SlideShare a Scribd company logo
The Little Unicorn That Could
Author: Andrey Karpov
Date: 22.06.2016
One of the Microsoft development teams already uses PVS-Studio analyzer in their work. It's great, but
it's not enough. That's why I keep demonstrating how static code analysis could benefit developers,
using Microsoft projects as examples. We scanned Casablanca project three years ago and found
nothing. As a tribute to its high quality, the project was awarded with a "bugless code" medal. As time
went by, Casablanca developed and grew. PVS-Studio's capabilities, too, have significantly improved,
and now I've finally got the opportunity to write an article about errors found by the analyzer in
Casablanca project (C++ REST SDK). These errors are few, but the fact that their number is still big
enough for me to make this article, does speak a lot in favor of PVS-Studio's effectiveness.
Casablanca
As I already said in the introduction, we have analyzed Casablanca project before; see the article "A
Small Post about Casablanca project" for the analysis results.
Casablanca (C++ REST SDK) is a small project written in Contemporary C++, by which I mean that the
project authors heavily use move semantics, lambdas, auto, and so forth. The new features of the C++
language allow programmers to write shorter and safer code. This assertion is supported by the fact that
collecting a decent number of bugs from this one is a difficult task, unlike other projects where we easily
catch lots of them.
For the analysis results for other Microsoft projects that we have scanned, see the following list of
articles: Xamarin.Forms, CNTK, Microsoft Edge, CoreCLR, Windows 8 Driver Samples, Visual C++ 2012 /
2013 library, CoreFX, Roslyn, Microsoft Code Contracts, WPF Samples (coming soon).
So, as we have found, Casablanca is a model of fine, high-quality code. Let's see what issues PVS-Studio
analyzer has managed to catch there.
Errors found
Fragment No. 1: typo
There is structure NumericHandValues with two members: low and high. This is how it is declared:
struct NumericHandValues
{
int low;
int high;
int Best() { return (high < 22) ? high : low; }
};
And this is how it is initialized in one of the fragments:
NumericHandValues GetNumericValues()
{
NumericHandValues res;
res.low = 0;
res.low = 0;
....
}
PVS-Studio diagnostic message: V519 The 'res.low' variable is assigned values twice successively.
Perhaps this is a mistake. Check lines: 130, 131. BlackJack_Client140 messagetypes.h 131
In this code, the programmer made a mistake and initialized the low member twice, leaving high
uninitialized. There's hardly any profound comment to make on this situation; it's just that nobody is
safe from typos.
Fragment No. 2: memory release error
void DealerTable::FillShoe(size_t decks)
{
std::shared_ptr<int> ss(new int[decks * 52]);
....
}
PVS-Studio diagnostic message: V554 Incorrect use of shared_ptr. The memory allocated with 'new []'
will be cleaned using 'delete'. BlackJack_Server140 table.cpp 471
When destroying an object, a smart pointer of type shared_ptr calls the delete operator by default
without brackets []. In this case, however, this behavior leads to an error.
To ensure correct object destruction, the code must be rewritten in the following way:
std::shared_ptr<int> ss(new int[decks * 52],
std::default_delete<int[]>());
Fragment No. 3: lost pointer
Static member s_server_api is a smart pointer and is declared in the following way:
std::unique_ptr<http_server>
http_server_api::s_server_api((http_server*)nullptr);
What doesn't look right is the following function code:
void http_server_api::unregister_server_api()
{
pplx::extensibility::scoped_critical_section_t lock(s_lock);
if (http_server_api::has_listener())
{
throw http_exception(_XPLATSTR("Server API ..... attached"));
}
s_server_api.release();
}
PVS-Studio diagnostic message: V530 The return value of function 'release' is required to be utilized.
cpprestsdk140 http_server_api.cpp 64
Note the line "s_server_api.release();". After calling the release function, a smart pointer does not own
the object anymore. Therefore, in our example, the pointer to the object is "lost", and the latter will
exist until the program terminates.
Again, it looks like we're dealing with a typo in this example: what the programmer must have intended
to call is function reset, not release.
Fragment No. 4: wrong enum
There are two enumerations, BJHandState and BJHandResult, which are declared in the following way:
enum BJHandState {
HR_Empty, HR_BlackJack, HR_Active, HR_Held, HR_Busted
};
enum BJHandResult {
HR_None, HR_PlayerBlackJack, HR_PlayerWin,
HR_ComputerWin, HR_Push
};
And this is a code fragment from function PayUp:
void DealerTable::PayUp(size_t idx)
{
....
if ( player.Hand.insurance > 0 &&
Players[0].Hand.state == HR_PlayerBlackJack )
{
player.Balance += player.Hand.insurance*3;
}
....
}
PVS-Studio diagnostic message: V556 The values of different enum types are compared. Types:
BJHandState, BJHandResult. BlackJack_Server140 table.cpp 336
The state variable is of type BJHandState, which means that the programmer mixed up the
enumerations. The code was more likely meant to look like this:
if ( player.Hand.insurance > 0 &&
Players[0].Hand.state == HR_BlackJack )
The funny thing is that this error doesn't affect the program execution in any way for now. Fortunately,
the constants HR_BlackJack and HR_PlayerBlackJack currently refer to the same value, 1. The reason is
that both constants occupy the same position in the corresponding enumerations. However, it may
change as the project develops, resulting in a strange, obscure error.
Fragment No. 5: strange break
web::json::value AsJSON() const
{
....
int idx = 0;
for (auto iter = cards.begin(); iter != cards.end();)
{
jCards[idx++] = iter->AsJSON();
break;
}
....
}
PVS-Studio diagnostic message: V612 An unconditional 'break' within a loop. BlackJack_Client140
messagetypes.h 213
The break statement looks very suspicious, as the loop can iterate only once at most. I can't tell for sure
what exactly this code is meant to do, but it doesn't look right in its present form.
Miscellaneous
Besides the issues that we have already discussed and could call errors, the analyzer found a few
fragments of untidy code - for example the ones where iterators are post-incremented.
inline web::json::value
TablesAsJSON(...., std::shared_ptr<BJTable>> &tables)
{
web::json::value result = web::json::value::array();
size_t idx = 0;
for (auto tbl = tables.begin(); tbl != tables.end(); tbl++)
{
result[idx++] = tbl->second->AsJSON();
}
return result;
}
PVS-Studio diagnostic message: V803 Decreased performance. In case 'tbl' is iterator it's more effective
to use prefix form of increment. Replace iterator++ with ++iterator. BlackJack_Client140 messagetypes.h
356
It's not an error, of course, but it is considered a good style to use a pre-increment instead: ++tbl. If you
feel unsure about this, please see the following articles:
1. Is it reasonable to use the prefix increment operator ++it instead of postfix operator it++ for
iterators? http://www.viva64.com/en/b/0093/
2. Pre vs. post increment operator - benchmark. http://silviuardelean.ro/2011/04/20/pre-vs-post-
increment-operator/
There are 10 more examples of post-incremented iterators found in the library's code, but I don't think
we need to discuss them here.
Another example of untidy code:
struct _acquire_protector
{
_acquire_protector(....);
~_acquire_protector();
size_t m_size;
private:
_acquire_protector& operator=(const _acquire_protector&);
uint8_t* m_ptr;
concurrency::streams::streambuf<uint8_t>& m_buffer;
};
PVS-Studio diagnostic message: V690 The '=' operator is declared as private in the '_acquire_protector'
class, but the default copy constructor will still be generated by compiler. It is dangerous to use such a
class. cpprestsdk140.uwp.staticlib fileio_winrt.cpp 825
As you can see, the programmer prohibited the use of the copy operator. However, the object can still
be copied using the copy constructor, which the compiler creates by default.
Conclusion
PVS-Studio analyzer has at last detected something to find fault with. The errors are few, but they are
still errors. It means that using static analysis regularly, not occasionally, like I did for this article, could
help prevent lots of bugs at the earliest stage. Fixing errors right after writing the code is better than
during the testing or debugging phase or, worst of all, when these errors are reported by end users.
References
1. The article title refers to the fairy-tale "The Little Engine That Could".
2. The following link will take you to the page where you can download PVS-Studio analyzer and
try it on one of your projects in C, C++, or C#: http://www.viva64.com/en/pvs-studio-download/

More Related Content

What's hot

Checking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzerChecking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzer
PVS-Studio
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggy
PVS-Studio
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
PVS-Studio
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Andrey Karpov
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
PVS-Studio
 
Picking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckPicking Mushrooms after Cppcheck
Picking Mushrooms after Cppcheck
Andrey Karpov
 
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' RequestChecking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
PVS-Studio
 
Top 10 C# projects errors found in 2016
Top 10 C# projects errors found in 2016Top 10 C# projects errors found in 2016
Top 10 C# projects errors found in 2016
PVS-Studio
 
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
Andrey Karpov
 
Checking OpenCV with PVS-Studio
Checking OpenCV with PVS-StudioChecking OpenCV with PVS-Studio
Checking OpenCV with PVS-Studio
PVS-Studio
 
A fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBoxA fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBox
PVS-Studio
 
Checking Notepad++: five years later
Checking Notepad++: five years laterChecking Notepad++: five years later
Checking Notepad++: five years later
PVS-Studio
 
Reanalyzing the Notepad++ project
Reanalyzing the Notepad++ projectReanalyzing the Notepad++ project
Reanalyzing the Notepad++ project
PVS-Studio
 
Analyzing the Blender project with PVS-Studio
Analyzing the Blender project with PVS-StudioAnalyzing the Blender project with PVS-Studio
Analyzing the Blender project with PVS-Studio
PVS-Studio
 
We Continue Exploring Tizen: C# Components Proved to be of High Quality
We Continue Exploring Tizen: C# Components Proved to be of High QualityWe Continue Exploring Tizen: C# Components Proved to be of High Quality
We Continue Exploring Tizen: C# Components Proved to be of High Quality
PVS-Studio
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-x
Andrey Karpov
 
Checking the Source Code of FlashDevelop with PVS-Studio
Checking the Source Code of FlashDevelop with PVS-StudioChecking the Source Code of FlashDevelop with PVS-Studio
Checking the Source Code of FlashDevelop with PVS-Studio
PVS-Studio
 
Re-checking the ReactOS project - a large report
Re-checking the ReactOS project - a large reportRe-checking the ReactOS project - a large report
Re-checking the ReactOS project - a large report
PVS-Studio
 
Source code of WPF samples by Microsoft was checked
Source code of WPF samples by Microsoft was checkedSource code of WPF samples by Microsoft was checked
Source code of WPF samples by Microsoft was checked
PVS-Studio
 
Waiting for the Linux-version: Checking the Code of Inkscape Graphics Editor
Waiting for the Linux-version: Checking the Code of Inkscape Graphics EditorWaiting for the Linux-version: Checking the Code of Inkscape Graphics Editor
Waiting for the Linux-version: Checking the Code of Inkscape Graphics Editor
PVS-Studio
 

What's hot (20)

Checking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzerChecking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzer
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggy
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
 
Picking Mushrooms after Cppcheck
Picking Mushrooms after CppcheckPicking Mushrooms after Cppcheck
Picking Mushrooms after Cppcheck
 
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' RequestChecking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' Request
 
Top 10 C# projects errors found in 2016
Top 10 C# projects errors found in 2016Top 10 C# projects errors found in 2016
Top 10 C# projects errors found in 2016
 
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
PVS-Studio. Static code analyzer. Windows/Linux, C/C++/C#. 2017
 
Checking OpenCV with PVS-Studio
Checking OpenCV with PVS-StudioChecking OpenCV with PVS-Studio
Checking OpenCV with PVS-Studio
 
A fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBoxA fresh eye on Oracle VM VirtualBox
A fresh eye on Oracle VM VirtualBox
 
Checking Notepad++: five years later
Checking Notepad++: five years laterChecking Notepad++: five years later
Checking Notepad++: five years later
 
Reanalyzing the Notepad++ project
Reanalyzing the Notepad++ projectReanalyzing the Notepad++ project
Reanalyzing the Notepad++ project
 
Analyzing the Blender project with PVS-Studio
Analyzing the Blender project with PVS-StudioAnalyzing the Blender project with PVS-Studio
Analyzing the Blender project with PVS-Studio
 
We Continue Exploring Tizen: C# Components Proved to be of High Quality
We Continue Exploring Tizen: C# Components Proved to be of High QualityWe Continue Exploring Tizen: C# Components Proved to be of High Quality
We Continue Exploring Tizen: C# Components Proved to be of High Quality
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-x
 
Checking the Source Code of FlashDevelop with PVS-Studio
Checking the Source Code of FlashDevelop with PVS-StudioChecking the Source Code of FlashDevelop with PVS-Studio
Checking the Source Code of FlashDevelop with PVS-Studio
 
Re-checking the ReactOS project - a large report
Re-checking the ReactOS project - a large reportRe-checking the ReactOS project - a large report
Re-checking the ReactOS project - a large report
 
Source code of WPF samples by Microsoft was checked
Source code of WPF samples by Microsoft was checkedSource code of WPF samples by Microsoft was checked
Source code of WPF samples by Microsoft was checked
 
Waiting for the Linux-version: Checking the Code of Inkscape Graphics Editor
Waiting for the Linux-version: Checking the Code of Inkscape Graphics EditorWaiting for the Linux-version: Checking the Code of Inkscape Graphics Editor
Waiting for the Linux-version: Checking the Code of Inkscape Graphics Editor
 

Viewers also liked

Grupo nº-5
Grupo nº-5Grupo nº-5
Grupo nº-5
santiago ruiz
 
Qrops seminar pattaya 2011
Qrops seminar pattaya 2011Qrops seminar pattaya 2011
Qrops seminar pattaya 2011AcornCapital
 
Era vargas
Era vargasEra vargas
Era vargas
Alan Silva
 
Digital Art - Arte Digital
Digital Art - Arte DigitalDigital Art - Arte Digital
Digital Art - Arte DigitalVivian Terra
 
Qrops seminar pattaya 2011
Qrops seminar pattaya 2011Qrops seminar pattaya 2011
Qrops seminar pattaya 2011AcornCapital
 
Coca Cola Mobile Marketing
Coca Cola Mobile MarketingCoca Cola Mobile Marketing
Coca Cola Mobile Marketing
KMTO
 
PRS Technology India
PRS Technology IndiaPRS Technology India
PRS Technology Indiasunil bind
 
Volgraph compare chart
Volgraph compare chartVolgraph compare chart
Expansão ultramarina
Expansão ultramarinaExpansão ultramarina
Expansão ultramarina
Solange Vavassori
 
Ativ 03anaclaudia
Ativ 03anaclaudiaAtiv 03anaclaudia
Ativ 03anaclaudiaburanatc
 
Worxmate
WorxmateWorxmate

Viewers also liked (13)

Grupo nº-5
Grupo nº-5Grupo nº-5
Grupo nº-5
 
Zeba_Naz
Zeba_NazZeba_Naz
Zeba_Naz
 
Qrops seminar pattaya 2011
Qrops seminar pattaya 2011Qrops seminar pattaya 2011
Qrops seminar pattaya 2011
 
Era vargas
Era vargasEra vargas
Era vargas
 
Digital Art - Arte Digital
Digital Art - Arte DigitalDigital Art - Arte Digital
Digital Art - Arte Digital
 
Qrops seminar pattaya 2011
Qrops seminar pattaya 2011Qrops seminar pattaya 2011
Qrops seminar pattaya 2011
 
Galeria
GaleriaGaleria
Galeria
 
Coca Cola Mobile Marketing
Coca Cola Mobile MarketingCoca Cola Mobile Marketing
Coca Cola Mobile Marketing
 
PRS Technology India
PRS Technology IndiaPRS Technology India
PRS Technology India
 
Volgraph compare chart
Volgraph compare chartVolgraph compare chart
Volgraph compare chart
 
Expansão ultramarina
Expansão ultramarinaExpansão ultramarina
Expansão ultramarina
 
Ativ 03anaclaudia
Ativ 03anaclaudiaAtiv 03anaclaudia
Ativ 03anaclaudia
 
Worxmate
WorxmateWorxmate
Worxmate
 

Similar to The Little Unicorn That Could

LibRaw, Coverity SCAN, PVS-Studio
LibRaw, Coverity SCAN, PVS-StudioLibRaw, Coverity SCAN, PVS-Studio
LibRaw, Coverity SCAN, PVS-Studio
Andrey Karpov
 
PVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd CheckPVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd Check
Andrey Karpov
 
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ BuilderA Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
Andrey Karpov
 
Linux Kernel, tested by the Linux-version of PVS-Studio
Linux Kernel, tested by the Linux-version of PVS-StudioLinux Kernel, tested by the Linux-version of PVS-Studio
Linux Kernel, tested by the Linux-version of PVS-Studio
PVS-Studio
 
Heading for a Record: Chromium, the 5th Check
Heading for a Record: Chromium, the 5th CheckHeading for a Record: Chromium, the 5th Check
Heading for a Record: Chromium, the 5th Check
PVS-Studio
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
Andrey Karpov
 
PVS-Studio delved into the FreeBSD kernel
PVS-Studio delved into the FreeBSD kernelPVS-Studio delved into the FreeBSD kernel
PVS-Studio delved into the FreeBSD kernel
PVS-Studio
 
PVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's code
PVS-Studio
 
Looking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopLooking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelop
PVS-Studio
 
How to Improve Visual C++ 2017 Libraries Using PVS-Studio
How to Improve Visual C++ 2017 Libraries Using PVS-StudioHow to Improve Visual C++ 2017 Libraries Using PVS-Studio
How to Improve Visual C++ 2017 Libraries Using PVS-Studio
PVS-Studio
 
Errors that static code analysis does not find because it is not used
Errors that static code analysis does not find because it is not usedErrors that static code analysis does not find because it is not used
Errors that static code analysis does not find because it is not used
Andrey Karpov
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
PVS-Studio
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Andrey Karpov
 
The Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and EverythingThe Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and Everything
Andrey Karpov
 
The Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and EverythingThe Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and Everything
PVS-Studio
 
We continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellWe continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShell
PVS-Studio
 
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft EdgeChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
PVS-Studio
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects
Andrey Karpov
 
Analysis of bugs in Orchard CMS
Analysis of bugs in Orchard CMSAnalysis of bugs in Orchard CMS
Analysis of bugs in Orchard CMS
PVS-Studio
 

Similar to The Little Unicorn That Could (19)

LibRaw, Coverity SCAN, PVS-Studio
LibRaw, Coverity SCAN, PVS-StudioLibRaw, Coverity SCAN, PVS-Studio
LibRaw, Coverity SCAN, PVS-Studio
 
PVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd CheckPVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd Check
 
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ BuilderA Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ Builder
 
Linux Kernel, tested by the Linux-version of PVS-Studio
Linux Kernel, tested by the Linux-version of PVS-StudioLinux Kernel, tested by the Linux-version of PVS-Studio
Linux Kernel, tested by the Linux-version of PVS-Studio
 
Heading for a Record: Chromium, the 5th Check
Heading for a Record: Chromium, the 5th CheckHeading for a Record: Chromium, the 5th Check
Heading for a Record: Chromium, the 5th Check
 
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
PVS-Studio and Continuous Integration: TeamCity. Analysis of the Open RollerC...
 
PVS-Studio delved into the FreeBSD kernel
PVS-Studio delved into the FreeBSD kernelPVS-Studio delved into the FreeBSD kernel
PVS-Studio delved into the FreeBSD kernel
 
PVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's codePVS-Studio: analyzing ReactOS's code
PVS-Studio: analyzing ReactOS's code
 
Looking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopLooking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelop
 
How to Improve Visual C++ 2017 Libraries Using PVS-Studio
How to Improve Visual C++ 2017 Libraries Using PVS-StudioHow to Improve Visual C++ 2017 Libraries Using PVS-Studio
How to Improve Visual C++ 2017 Libraries Using PVS-Studio
 
Errors that static code analysis does not find because it is not used
Errors that static code analysis does not find because it is not usedErrors that static code analysis does not find because it is not used
Errors that static code analysis does not find because it is not used
 
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...
 
The Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and EverythingThe Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and Everything
 
The Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and EverythingThe Ultimate Question of Programming, Refactoring, and Everything
The Ultimate Question of Programming, Refactoring, and Everything
 
We continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellWe continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShell
 
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft EdgeChakraCore: analysis of JavaScript-engine for Microsoft Edge
ChakraCore: analysis of JavaScript-engine for Microsoft Edge
 
100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects 100 bugs in Open Source C/C++ projects
100 bugs in Open Source C/C++ projects
 
Analysis of bugs in Orchard CMS
Analysis of bugs in Orchard CMSAnalysis of bugs in Orchard CMS
Analysis of bugs in Orchard CMS
 

Recently uploaded

In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 

Recently uploaded (20)

In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 

The Little Unicorn That Could

  • 1. The Little Unicorn That Could Author: Andrey Karpov Date: 22.06.2016 One of the Microsoft development teams already uses PVS-Studio analyzer in their work. It's great, but it's not enough. That's why I keep demonstrating how static code analysis could benefit developers, using Microsoft projects as examples. We scanned Casablanca project three years ago and found nothing. As a tribute to its high quality, the project was awarded with a "bugless code" medal. As time went by, Casablanca developed and grew. PVS-Studio's capabilities, too, have significantly improved, and now I've finally got the opportunity to write an article about errors found by the analyzer in Casablanca project (C++ REST SDK). These errors are few, but the fact that their number is still big enough for me to make this article, does speak a lot in favor of PVS-Studio's effectiveness. Casablanca As I already said in the introduction, we have analyzed Casablanca project before; see the article "A Small Post about Casablanca project" for the analysis results. Casablanca (C++ REST SDK) is a small project written in Contemporary C++, by which I mean that the project authors heavily use move semantics, lambdas, auto, and so forth. The new features of the C++ language allow programmers to write shorter and safer code. This assertion is supported by the fact that collecting a decent number of bugs from this one is a difficult task, unlike other projects where we easily catch lots of them. For the analysis results for other Microsoft projects that we have scanned, see the following list of articles: Xamarin.Forms, CNTK, Microsoft Edge, CoreCLR, Windows 8 Driver Samples, Visual C++ 2012 / 2013 library, CoreFX, Roslyn, Microsoft Code Contracts, WPF Samples (coming soon). So, as we have found, Casablanca is a model of fine, high-quality code. Let's see what issues PVS-Studio analyzer has managed to catch there. Errors found Fragment No. 1: typo There is structure NumericHandValues with two members: low and high. This is how it is declared: struct NumericHandValues { int low;
  • 2. int high; int Best() { return (high < 22) ? high : low; } }; And this is how it is initialized in one of the fragments: NumericHandValues GetNumericValues() { NumericHandValues res; res.low = 0; res.low = 0; .... } PVS-Studio diagnostic message: V519 The 'res.low' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 130, 131. BlackJack_Client140 messagetypes.h 131 In this code, the programmer made a mistake and initialized the low member twice, leaving high uninitialized. There's hardly any profound comment to make on this situation; it's just that nobody is safe from typos. Fragment No. 2: memory release error void DealerTable::FillShoe(size_t decks) { std::shared_ptr<int> ss(new int[decks * 52]); .... } PVS-Studio diagnostic message: V554 Incorrect use of shared_ptr. The memory allocated with 'new []' will be cleaned using 'delete'. BlackJack_Server140 table.cpp 471 When destroying an object, a smart pointer of type shared_ptr calls the delete operator by default without brackets []. In this case, however, this behavior leads to an error. To ensure correct object destruction, the code must be rewritten in the following way: std::shared_ptr<int> ss(new int[decks * 52], std::default_delete<int[]>()); Fragment No. 3: lost pointer Static member s_server_api is a smart pointer and is declared in the following way: std::unique_ptr<http_server> http_server_api::s_server_api((http_server*)nullptr); What doesn't look right is the following function code:
  • 3. void http_server_api::unregister_server_api() { pplx::extensibility::scoped_critical_section_t lock(s_lock); if (http_server_api::has_listener()) { throw http_exception(_XPLATSTR("Server API ..... attached")); } s_server_api.release(); } PVS-Studio diagnostic message: V530 The return value of function 'release' is required to be utilized. cpprestsdk140 http_server_api.cpp 64 Note the line "s_server_api.release();". After calling the release function, a smart pointer does not own the object anymore. Therefore, in our example, the pointer to the object is "lost", and the latter will exist until the program terminates. Again, it looks like we're dealing with a typo in this example: what the programmer must have intended to call is function reset, not release. Fragment No. 4: wrong enum There are two enumerations, BJHandState and BJHandResult, which are declared in the following way: enum BJHandState { HR_Empty, HR_BlackJack, HR_Active, HR_Held, HR_Busted }; enum BJHandResult { HR_None, HR_PlayerBlackJack, HR_PlayerWin, HR_ComputerWin, HR_Push }; And this is a code fragment from function PayUp: void DealerTable::PayUp(size_t idx) { .... if ( player.Hand.insurance > 0 && Players[0].Hand.state == HR_PlayerBlackJack ) { player.Balance += player.Hand.insurance*3;
  • 4. } .... } PVS-Studio diagnostic message: V556 The values of different enum types are compared. Types: BJHandState, BJHandResult. BlackJack_Server140 table.cpp 336 The state variable is of type BJHandState, which means that the programmer mixed up the enumerations. The code was more likely meant to look like this: if ( player.Hand.insurance > 0 && Players[0].Hand.state == HR_BlackJack ) The funny thing is that this error doesn't affect the program execution in any way for now. Fortunately, the constants HR_BlackJack and HR_PlayerBlackJack currently refer to the same value, 1. The reason is that both constants occupy the same position in the corresponding enumerations. However, it may change as the project develops, resulting in a strange, obscure error. Fragment No. 5: strange break web::json::value AsJSON() const { .... int idx = 0; for (auto iter = cards.begin(); iter != cards.end();) { jCards[idx++] = iter->AsJSON(); break; } .... } PVS-Studio diagnostic message: V612 An unconditional 'break' within a loop. BlackJack_Client140 messagetypes.h 213 The break statement looks very suspicious, as the loop can iterate only once at most. I can't tell for sure what exactly this code is meant to do, but it doesn't look right in its present form. Miscellaneous Besides the issues that we have already discussed and could call errors, the analyzer found a few fragments of untidy code - for example the ones where iterators are post-incremented. inline web::json::value TablesAsJSON(...., std::shared_ptr<BJTable>> &tables) { web::json::value result = web::json::value::array();
  • 5. size_t idx = 0; for (auto tbl = tables.begin(); tbl != tables.end(); tbl++) { result[idx++] = tbl->second->AsJSON(); } return result; } PVS-Studio diagnostic message: V803 Decreased performance. In case 'tbl' is iterator it's more effective to use prefix form of increment. Replace iterator++ with ++iterator. BlackJack_Client140 messagetypes.h 356 It's not an error, of course, but it is considered a good style to use a pre-increment instead: ++tbl. If you feel unsure about this, please see the following articles: 1. Is it reasonable to use the prefix increment operator ++it instead of postfix operator it++ for iterators? http://www.viva64.com/en/b/0093/ 2. Pre vs. post increment operator - benchmark. http://silviuardelean.ro/2011/04/20/pre-vs-post- increment-operator/ There are 10 more examples of post-incremented iterators found in the library's code, but I don't think we need to discuss them here. Another example of untidy code: struct _acquire_protector { _acquire_protector(....); ~_acquire_protector(); size_t m_size; private: _acquire_protector& operator=(const _acquire_protector&); uint8_t* m_ptr; concurrency::streams::streambuf<uint8_t>& m_buffer; }; PVS-Studio diagnostic message: V690 The '=' operator is declared as private in the '_acquire_protector' class, but the default copy constructor will still be generated by compiler. It is dangerous to use such a class. cpprestsdk140.uwp.staticlib fileio_winrt.cpp 825 As you can see, the programmer prohibited the use of the copy operator. However, the object can still be copied using the copy constructor, which the compiler creates by default.
  • 6. Conclusion PVS-Studio analyzer has at last detected something to find fault with. The errors are few, but they are still errors. It means that using static analysis regularly, not occasionally, like I did for this article, could help prevent lots of bugs at the earliest stage. Fixing errors right after writing the code is better than during the testing or debugging phase or, worst of all, when these errors are reported by end users. References 1. The article title refers to the fairy-tale "The Little Engine That Could". 2. The following link will take you to the page where you can download PVS-Studio analyzer and try it on one of your projects in C, C++, or C#: http://www.viva64.com/en/pvs-studio-download/