SlideShare a Scribd company logo
1 of 9
Download to read offline
Rechecking SharpDevelop: Any New Bugs?
Author: Sergey Khrenov
Date: 30.01.2017
PVS-Studio analyzer is continuously improving, and the C#-code analysis module is developing most
actively: ninety new diagnostic rules were added in 2016. However, the best way to estimate the
analyzer's efficiency is to look at the bugs it can catch. It's always interesting, as well as useful, to do
recurring checks of large open-source projects at certain intervals and compare their results. Today I will
talk about the results of the second analysis of SharpDevelop project.
Introduction
The previous article about the analysis results for SharpDevelop was written by Andrey Karpov in
November 2015. We were only going through the testing stage of our new C# analyzer then and were
preparing for its first release. However, with just the beta version on hand, Andrey successfully checked
SharpDeveloper and found a few interesting bugs there. After that, SharpDevelop was "laid on the shelf"
to be used with a number of other projects solely within our team for testing new diagnostics. Now the
time has come to check SharpDevelop once again but with the more "brawny" version, PVS-Studio 6.12.
I downloaded the latest version of SharpDevelop's source code from GitHub. The project contains about
one million lines of code in C#. At the end of the analysis, PVS-Studio output 809 warnings: 74 first-level,
508 second-level, and 227 third-level messages:
I will skip the Low-level warnings because there is a high rate of false positives among those. About 40%
of the Medium- and High-level warnings (582 in total) were found to be genuine errors or highly
suspicious constructs, which corresponds to 233 warnings. In other words, PVS-Studio found an average
of 0.23 errors per 1000 lines of code. This rate indicates a very high quality of SharpDevelop project's
code. Many of the other projects show much worse results.
The new check revealed some of the bugs found and described by Andrey in his previous article, but
most of the errors are new. The most interesting ones are discussed below.
Analysis results
Canonical Copy-Paste bug
This error deserves its own standard in the International Bureau of Weights and Measures. It is also a
vivid example of how useful static analysis is and how dangerous Copy-Paste can be.
PVS-Studio diagnostic message: V3102 Suspicious access to element of 'method.SequencePoints' object
by a constant index inside a loop. CodeCoverageMethodTreeNode.cs 52
public override void ActivateItem()
{
if (method != null && method.SequencePoints.Count > 0) {
CodeCoverageSequencePoint firstSequencePoint =
method.SequencePoints[0];
....
for (int i = 1; i < method.SequencePoints.Count; ++i) {
CodeCoverageSequencePoint sequencePoint =
method.SequencePoints[0]; // <=
....
}
....
}
....
}
The zero-index element of the collection is accessed at each iteration of the for loop. I included the code
fragment immediately following the condition of the if statement on purpose to show where the line
used in the loop body was copied from. The programmer changed the variable name firstSequencePoint
to sequencePoint but forgot to change the expression indexing into the elements. This is what the fixed
version of the construct looks like:
public override void ActivateItem()
{
if (method != null && method.SequencePoints.Count > 0) {
CodeCoverageSequencePoint firstSequencePoint =
method.SequencePoints[0];
....
for (int i = 1; i < method.SequencePoints.Count; ++i) {
CodeCoverageSequencePoint sequencePoint =
method.SequencePoints[i];
....
}
....
}
....
}
"Find the 10 differences", or another Copy-Paste
PVS-Studio diagnostic message: V3021 There are two 'if' statements with identical conditional
expressions. The first 'if' statement contains method return. This means that the second 'if' statement is
senseless NamespaceTreeNode.cs 87
public int Compare(SharpTreeNode x, SharpTreeNode y)
{
....
if (typeNameComparison == 0) {
if (x.Text.ToString().Length < y.Text.ToString().Length) // <=
return -1;
if (x.Text.ToString().Length < y.Text.ToString().Length) // <=
return 1;
}
....
}
Both if blocks use the same condition. I can't say for sure what exactly the correct version of the code
should look like in this case; it has to be decided by the program author.
Late null check
PVS-Studio diagnostic message: V3095 The 'position' object was used before it was verified against null.
Check lines: 204, 206. Task.cs 204
public void JumpToPosition()
{
if (hasLocation && !position.IsDeleted) // <=
....
else if (position != null)
....
}
The position variable is used without testing it for null. The check is done in another condition, in the
else block. This is what the fixed version could look like:
public void JumpToPosition()
{
if (hasLocation && position != null && !position.IsDeleted)
....
else if (position != null)
....
}
Skipped null check
PVS-Studio diagnostic message: V3125 The 'mainAssemblyList' object was used after it was verified
against null. Check lines: 304, 291. ClassBrowserPad.cs 304
void UpdateActiveWorkspace()
{
var mainAssemblyList = SD.ClassBrowser.MainAssemblyList;
if ((mainAssemblyList != null) && (activeWorkspace != null)) {
....
}
....
mainAssemblyList.Assemblies.Clear(); // <=
....
}
The mainAssemblyList variable is used without a prior null check, while such a check can be found in
another statement in this fragment. The fixed code:
void UpdateActiveWorkspace()
{
var mainAssemblyList = SD.ClassBrowser.MainAssemblyList;
if ((mainAssemblyList != null) && (activeWorkspace != null)) {
....
}
....
if (mainAssemblyList != null) {
mainAssemblyList.Assemblies.Clear();
}
....
}
Unexpected sorting result
PVS-Studio diagnostic message: V3078 Original sorting order will be lost after repetitive call to
'OrderBy' method. Use 'ThenBy' method to preserve the original sorting.
CodeCoverageMethodElement.cs 124
void Init()
{
....
this.SequencePoints.OrderBy(item => item.Line)
.OrderBy(item => item.Column); // <=
}
This code will sort the SequencePoints collection only by the Column field, which doesn't seem to be the
desired result. The problem with this code is that the second call to the OrderBy method will sort the
collection without taking into account the results of the previous sort. To fix this issue, method ThenBy
must be used instead of the second call to OrderBy:
void Init()
{
....
this.SequencePoints.OrderBy(item => item.Line)
.ThenBy(item => item.Column);
}
Possible division by zero
PVS-Studio diagnostic message: V3064 Potential division by zero. Consider inspecting denominator
'workAmount'. XamlSymbolSearch.cs 60
public XamlSymbolSearch(IProject project, ISymbol entity)
{
....
interestingFileNames = new List<FileName>();
....
foreach (var item in ....)
interestingFileNames.Add(item.FileName);
....
workAmount = interestingFileNames.Count;
workAmountInverse = 1.0 / workAmount; // <=
}
If the interestingFileNames collection is found to be empty, a division by zero will occur. I can't suggest a
ready solution for this code, but in any case, the authors need to improve the algorithm computing the
value of the workAmountInverse variable when the value of the workAmount variable is zero.
Repeated assignment
PVS-Studio diagnostic message: V3008 The 'ignoreDialogIdSelectedInTextEditor' variable is assigned
values twice successively. Perhaps this is a mistake. Check lines: 204, 201. WixDialogDesigner.cs 204
void OpenDesigner()
{
try {
ignoreDialogIdSelectedInTextEditor = true; // <=
WorkbenchWindow.ActiveViewContent = this;
} finally {
ignoreDialogIdSelectedInTextEditor = false; // <=
}
}
The ignoreDialogIdSelectedInTextEditor variable will be assigned with the value false regardless of the
result of executing the try block. Let's take a closer look at the variable declarations to make sure there
are no "pitfalls" there. This is the declaration of ignoreDialogIdSelectedInTextEditor:
bool ignoreDialogIdSelectedInTextEditor;
And here are the declarations of IWorkbenchWindow and ActiveViewContent:
public IWorkbenchWindow WorkbenchWindow {
get { return workbenchWindow; }
}
IViewContent ActiveViewContent {
get;
set;
}
As you can see, there are no legitimate reasons for assigning another value to the
ignoreDialogIdSelectedInTextEditor variable. Perhaps the correct version of this construct should use the
catch keyword instead of finally:
void OpenDesigner()
{
try {
ignoreDialogIdSelectedInTextEditor = true;
WorkbenchWindow.ActiveViewContent = this;
} catch {
ignoreDialogIdSelectedInTextEditor = false;
}
}
Incorrect search of a substring
PVS-Studio diagnostic message: V3053 An excessive expression. Examine the substrings '/debug' and
'/debugport'. NDebugger.cs 287
public bool IsKernelDebuggerEnabled {
get {
....
if (systemStartOptions.Contains("/debug") ||
systemStartOptions.Contains("/crashdebug") ||
systemStartOptions.Contains("/debugport") || // <=
systemStartOptions.Contains("/baudrate")) {
return true;
}
....
}
}
This code uses a serial search looking for the substring "/debug" or "/debugport" in the
systemStartOptions string. The problem with this fragment is that the "/debug" string is itself a substring
of "/debugport", so finding "/debug" makes further search of "/debugport" meaningless. It's not a bug,
but it won't harm to optimize the code:
public bool IsKernelDebuggerEnabled {
get {
....
if (systemStartOptions.Contains("/debug") ||
systemStartOptions.Contains("/crashdebug") ||
systemStartOptions.Contains("/baudrate")) {
return true;
}
....
}
}
Exception-handling error
PVS-Studio diagnostic message: V3052 The original exception object 'ex' was swallowed. Stack of
original exception could be lost. ReferenceFolderNodeCommands.cs 130
DiscoveryClientProtocol DiscoverWebServices(....)
{
try {
....
} catch (WebException ex) {
if (....) {
....
} else {
throw ex; // <=
}
}
....
}
Executing the throw ex call will result in overwriting the stack of the original exception, as the
intercepted exception will be generated anew. This is the fixed version:
DiscoveryClientProtocol DiscoverWebServices(....)
{
try {
....
} catch (WebException ex) {
if (....) {
....
} else {
throw;
}
}
....
}
Using an uninitialized field in a class constructor
PVS-Studio diagnostic message: V3128 The 'contentPanel' field is used before it is initialized in
constructor. SearchResultsPad.cs 66
Grid contentPanel;
public SearchResultsPad()
{
....
defaultToolbarItems = ToolBarService
.CreateToolBarItems(contentPanel, ....); // <=
....
contentPanel = new Grid {....};
....
}
The contentPanel field is passed as one of the arguments to the CreateToolBarItems method in the
constructor of the SearchResultsPad class. However, this field is not initialized until it has been used. It's
not necessarily an error, given that the possibility of the contentPanel variable with the value of null is
taken into account in the body of the CreateToolBarItems method and further on in the stack. This code
still looks very suspicious and needs to be examined by the authors.
As I have already said, this article discusses far not all the bugs found by PVS-Studio in this project but
only those that seemed interesting to me. The project authors are welcome to contact us to get a
temporary license key for a more thorough analysis of their code.
Conclusion
PVS-Studio did well again and revealed new interesting bugs during the second check of SharpDevelop
project. It means the analyzer knows how to do its job and can help make the world a bit better.
Remember that you, too, can join us at any time by taking the opportunity of checking your own
projects with the free version of PVS-Studio static analyzer.
You can download PVS-Studio at http://www.viva64.com/en/pvs-studio/
Please email us if you have any questions regarding the purchase of a commercial license. You can also
contact us to ask for a temporary license for deeper exploration of PVS-Studio without the limitations of
the demo version.

More Related Content

What's hot

Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
Rechecking TortoiseSVN with the PVS-Studio Code Analyzer
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerRechecking TortoiseSVN with the PVS-Studio Code Analyzer
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerAndrey Karpov
 
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 VirtualBoxPVS-Studio
 
Linux version of PVS-Studio couldn't help checking CodeLite
Linux version of PVS-Studio couldn't help checking CodeLiteLinux version of PVS-Studio couldn't help checking CodeLite
Linux version of PVS-Studio couldn't help checking CodeLitePVS-Studio
 
Checking WinMerge with PVS-Studio for the second time
Checking WinMerge with PVS-Studio for the second timeChecking WinMerge with PVS-Studio for the second time
Checking WinMerge with PVS-Studio for the second timePVS-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-StudioPVS-Studio
 
Documenting Bugs in Doxygen
Documenting Bugs in DoxygenDocumenting Bugs in Doxygen
Documenting Bugs in DoxygenPVS-Studio
 
Checking the code of Valgrind dynamic analyzer by a static analyzer
Checking the code of Valgrind dynamic analyzer by a static analyzerChecking the code of Valgrind dynamic analyzer by a static analyzer
Checking the code of Valgrind dynamic analyzer by a static analyzerPVS-Studio
 
Algoritmos sujei
Algoritmos sujeiAlgoritmos sujei
Algoritmos sujeigersonjack
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaDenilson Nastacio
 
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-xAndrey Karpov
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxDavid Rodenas
 
PVS-Studio vs Chromium - Continuation
PVS-Studio vs Chromium - ContinuationPVS-Studio vs Chromium - Continuation
PVS-Studio vs Chromium - ContinuationPVS-Studio
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsPVS-Studio
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
 
Simulado java se 7 programmer
Simulado java se 7 programmerSimulado java se 7 programmer
Simulado java se 7 programmerMiguel Vilaca
 
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 2016PVS-Studio
 
The Little Unicorn That Could
The Little Unicorn That CouldThe Little Unicorn That Could
The Little Unicorn That CouldPVS-Studio
 

What's hot (20)

Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Rechecking TortoiseSVN with the PVS-Studio Code Analyzer
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerRechecking TortoiseSVN with the PVS-Studio Code Analyzer
Rechecking TortoiseSVN with the PVS-Studio Code Analyzer
 
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
 
Linux version of PVS-Studio couldn't help checking CodeLite
Linux version of PVS-Studio couldn't help checking CodeLiteLinux version of PVS-Studio couldn't help checking CodeLite
Linux version of PVS-Studio couldn't help checking CodeLite
 
Checking WinMerge with PVS-Studio for the second time
Checking WinMerge with PVS-Studio for the second timeChecking WinMerge with PVS-Studio for the second time
Checking WinMerge with PVS-Studio for the second time
 
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
 
Documenting Bugs in Doxygen
Documenting Bugs in DoxygenDocumenting Bugs in Doxygen
Documenting Bugs in Doxygen
 
Checking the code of Valgrind dynamic analyzer by a static analyzer
Checking the code of Valgrind dynamic analyzer by a static analyzerChecking the code of Valgrind dynamic analyzer by a static analyzer
Checking the code of Valgrind dynamic analyzer by a static analyzer
 
Algoritmos sujei
Algoritmos sujeiAlgoritmos sujei
Algoritmos sujei
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
 
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
 
Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicox
 
PVS-Studio vs Chromium - Continuation
PVS-Studio vs Chromium - ContinuationPVS-Studio vs Chromium - Continuation
PVS-Studio vs Chromium - Continuation
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code Contracts
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
Simulado java se 7 programmer
Simulado java se 7 programmerSimulado java se 7 programmer
Simulado java se 7 programmer
 
Mock your way with Mockito
Mock your way with MockitoMock your way with Mockito
Mock your way with Mockito
 
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
 
The Little Unicorn That Could
The Little Unicorn That CouldThe Little Unicorn That Could
The Little Unicorn That Could
 

Viewers also liked

How to capture a variable in C# and not to shoot yourself in the foot
How to capture a variable in C# and not to shoot yourself in the footHow to capture a variable in C# and not to shoot yourself in the foot
How to capture a variable in C# and not to shoot yourself in the footPVS-Studio
 
1st European Scholar TimeBanking Association Logo Contest
1st European Scholar TimeBanking Association Logo Contest1st European Scholar TimeBanking Association Logo Contest
1st European Scholar TimeBanking Association Logo Contestjosepbofilllamiquela
 
Esperanto, Loglan and Dothraki: Why do people construct new languages?
Esperanto, Loglan and Dothraki: Why do people construct new languages?Esperanto, Loglan and Dothraki: Why do people construct new languages?
Esperanto, Loglan and Dothraki: Why do people construct new languages?Melanie JI Mueller
 
Bezpieczenstwo w czasie_ferii(5)
Bezpieczenstwo w czasie_ferii(5)Bezpieczenstwo w czasie_ferii(5)
Bezpieczenstwo w czasie_ferii(5)dorotax
 
Why, How, and WIIFM - Sensible Social Media
Why, How, and WIIFM - Sensible Social MediaWhy, How, and WIIFM - Sensible Social Media
Why, How, and WIIFM - Sensible Social MediaSheila Scarborough
 
Ольга Нерода: Тренды в дизайне Email-рассылок
Ольга Нерода: Тренды в дизайне Email-рассылокОльга Нерода: Тренды в дизайне Email-рассылок
Ольга Нерода: Тренды в дизайне Email-рассылокAlexander Rys
 

Viewers also liked (10)

How to capture a variable in C# and not to shoot yourself in the foot
How to capture a variable in C# and not to shoot yourself in the footHow to capture a variable in C# and not to shoot yourself in the foot
How to capture a variable in C# and not to shoot yourself in the foot
 
1st European Scholar TimeBanking Association Logo Contest
1st European Scholar TimeBanking Association Logo Contest1st European Scholar TimeBanking Association Logo Contest
1st European Scholar TimeBanking Association Logo Contest
 
Esperanto, Loglan and Dothraki: Why do people construct new languages?
Esperanto, Loglan and Dothraki: Why do people construct new languages?Esperanto, Loglan and Dothraki: Why do people construct new languages?
Esperanto, Loglan and Dothraki: Why do people construct new languages?
 
Nami ppt eng v3.3.1
Nami ppt eng v3.3.1Nami ppt eng v3.3.1
Nami ppt eng v3.3.1
 
Bezpieczenstwo w czasie_ferii(5)
Bezpieczenstwo w czasie_ferii(5)Bezpieczenstwo w czasie_ferii(5)
Bezpieczenstwo w czasie_ferii(5)
 
Why, How, and WIIFM - Sensible Social Media
Why, How, and WIIFM - Sensible Social MediaWhy, How, and WIIFM - Sensible Social Media
Why, How, and WIIFM - Sensible Social Media
 
Metaprogramming with javascript
Metaprogramming with javascriptMetaprogramming with javascript
Metaprogramming with javascript
 
Ольга Нерода: Тренды в дизайне Email-рассылок
Ольга Нерода: Тренды в дизайне Email-рассылокОльга Нерода: Тренды в дизайне Email-рассылок
Ольга Нерода: Тренды в дизайне Email-рассылок
 
Android
AndroidAndroid
Android
 
театр
театртеатр
театр
 

Similar to Rechecking SharpDevelop: Any New Bugs?

The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project AnalyzedPVS-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
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindPVS-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 checkedPVS-Studio
 
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...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 reportPVS-Studio
 
Looking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopLooking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopPVS-Studio
 
Comparing PVS-Studio for C# and a built-in Visual Studio analyzer, using the ...
Comparing PVS-Studio for C# and a built-in Visual Studio analyzer, using the ...Comparing PVS-Studio for C# and a built-in Visual Studio analyzer, using the ...
Comparing PVS-Studio for C# and a built-in Visual Studio analyzer, using the ...Ekaterina Milovidova
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?PVS-Studio
 
How to make fewer errors at the stage of code writing. Part N4.
How to make fewer errors at the stage of code writing. Part N4.How to make fewer errors at the stage of code writing. Part N4.
How to make fewer errors at the stage of code writing. Part N4.PVS-Studio
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggyPVS-Studio
 
Still Comparing "this" Pointer to Null?
Still Comparing "this" Pointer to Null?Still Comparing "this" Pointer to Null?
Still Comparing "this" Pointer to Null?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
 
A Slipshod Check of the Visual C++ 2013 Library (update 3)
A Slipshod Check of the Visual C++ 2013 Library (update 3)A Slipshod Check of the Visual C++ 2013 Library (update 3)
A Slipshod Check of the Visual C++ 2013 Library (update 3)Andrey Karpov
 
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 QualityPVS-Studio
 
LibRaw, Coverity SCAN, PVS-Studio
LibRaw, Coverity SCAN, PVS-StudioLibRaw, Coverity SCAN, PVS-Studio
LibRaw, Coverity SCAN, PVS-StudioAndrey Karpov
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionAndrey Karpov
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionPVS-Studio
 
Analyzing ReactOS One More Time
Analyzing ReactOS One More TimeAnalyzing ReactOS One More Time
Analyzing ReactOS One More TimePVS-Studio
 

Similar to Rechecking SharpDevelop: Any New Bugs? (20)

The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
 
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...
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
 
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
 
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
 
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
 
Looking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopLooking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelop
 
Comparing PVS-Studio for C# and a built-in Visual Studio analyzer, using the ...
Comparing PVS-Studio for C# and a built-in Visual Studio analyzer, using the ...Comparing PVS-Studio for C# and a built-in Visual Studio analyzer, using the ...
Comparing PVS-Studio for C# and a built-in Visual Studio analyzer, using the ...
 
Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?
 
How to make fewer errors at the stage of code writing. Part N4.
How to make fewer errors at the stage of code writing. Part N4.How to make fewer errors at the stage of code writing. Part N4.
How to make fewer errors at the stage of code writing. Part N4.
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggy
 
Still Comparing "this" Pointer to Null?
Still Comparing "this" Pointer to Null?Still Comparing "this" Pointer to Null?
Still Comparing "this" Pointer to Null?
 
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...
 
A Slipshod Check of the Visual C++ 2013 Library (update 3)
A Slipshod Check of the Visual C++ 2013 Library (update 3)A Slipshod Check of the Visual C++ 2013 Library (update 3)
A Slipshod Check of the Visual C++ 2013 Library (update 3)
 
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
 
LibRaw, Coverity SCAN, PVS-Studio
LibRaw, Coverity SCAN, PVS-StudioLibRaw, Coverity SCAN, PVS-Studio
LibRaw, Coverity SCAN, PVS-Studio
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
Intel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correctionIntel IPP Samples for Windows - error correction
Intel IPP Samples for Windows - error correction
 
Analyzing ReactOS One More Time
Analyzing ReactOS One More TimeAnalyzing ReactOS One More Time
Analyzing ReactOS One More Time
 

Recently uploaded

Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 

Recently uploaded (20)

Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 

Rechecking SharpDevelop: Any New Bugs?

  • 1. Rechecking SharpDevelop: Any New Bugs? Author: Sergey Khrenov Date: 30.01.2017 PVS-Studio analyzer is continuously improving, and the C#-code analysis module is developing most actively: ninety new diagnostic rules were added in 2016. However, the best way to estimate the analyzer's efficiency is to look at the bugs it can catch. It's always interesting, as well as useful, to do recurring checks of large open-source projects at certain intervals and compare their results. Today I will talk about the results of the second analysis of SharpDevelop project. Introduction The previous article about the analysis results for SharpDevelop was written by Andrey Karpov in November 2015. We were only going through the testing stage of our new C# analyzer then and were preparing for its first release. However, with just the beta version on hand, Andrey successfully checked SharpDeveloper and found a few interesting bugs there. After that, SharpDevelop was "laid on the shelf" to be used with a number of other projects solely within our team for testing new diagnostics. Now the time has come to check SharpDevelop once again but with the more "brawny" version, PVS-Studio 6.12. I downloaded the latest version of SharpDevelop's source code from GitHub. The project contains about one million lines of code in C#. At the end of the analysis, PVS-Studio output 809 warnings: 74 first-level, 508 second-level, and 227 third-level messages:
  • 2. I will skip the Low-level warnings because there is a high rate of false positives among those. About 40% of the Medium- and High-level warnings (582 in total) were found to be genuine errors or highly suspicious constructs, which corresponds to 233 warnings. In other words, PVS-Studio found an average of 0.23 errors per 1000 lines of code. This rate indicates a very high quality of SharpDevelop project's code. Many of the other projects show much worse results. The new check revealed some of the bugs found and described by Andrey in his previous article, but most of the errors are new. The most interesting ones are discussed below. Analysis results Canonical Copy-Paste bug This error deserves its own standard in the International Bureau of Weights and Measures. It is also a vivid example of how useful static analysis is and how dangerous Copy-Paste can be. PVS-Studio diagnostic message: V3102 Suspicious access to element of 'method.SequencePoints' object by a constant index inside a loop. CodeCoverageMethodTreeNode.cs 52 public override void ActivateItem() { if (method != null && method.SequencePoints.Count > 0) { CodeCoverageSequencePoint firstSequencePoint = method.SequencePoints[0]; .... for (int i = 1; i < method.SequencePoints.Count; ++i) { CodeCoverageSequencePoint sequencePoint = method.SequencePoints[0]; // <= .... } ....
  • 3. } .... } The zero-index element of the collection is accessed at each iteration of the for loop. I included the code fragment immediately following the condition of the if statement on purpose to show where the line used in the loop body was copied from. The programmer changed the variable name firstSequencePoint to sequencePoint but forgot to change the expression indexing into the elements. This is what the fixed version of the construct looks like: public override void ActivateItem() { if (method != null && method.SequencePoints.Count > 0) { CodeCoverageSequencePoint firstSequencePoint = method.SequencePoints[0]; .... for (int i = 1; i < method.SequencePoints.Count; ++i) { CodeCoverageSequencePoint sequencePoint = method.SequencePoints[i]; .... } .... } .... } "Find the 10 differences", or another Copy-Paste PVS-Studio diagnostic message: V3021 There are two 'if' statements with identical conditional expressions. The first 'if' statement contains method return. This means that the second 'if' statement is senseless NamespaceTreeNode.cs 87 public int Compare(SharpTreeNode x, SharpTreeNode y) { .... if (typeNameComparison == 0) { if (x.Text.ToString().Length < y.Text.ToString().Length) // <= return -1; if (x.Text.ToString().Length < y.Text.ToString().Length) // <= return 1; }
  • 4. .... } Both if blocks use the same condition. I can't say for sure what exactly the correct version of the code should look like in this case; it has to be decided by the program author. Late null check PVS-Studio diagnostic message: V3095 The 'position' object was used before it was verified against null. Check lines: 204, 206. Task.cs 204 public void JumpToPosition() { if (hasLocation && !position.IsDeleted) // <= .... else if (position != null) .... } The position variable is used without testing it for null. The check is done in another condition, in the else block. This is what the fixed version could look like: public void JumpToPosition() { if (hasLocation && position != null && !position.IsDeleted) .... else if (position != null) .... } Skipped null check PVS-Studio diagnostic message: V3125 The 'mainAssemblyList' object was used after it was verified against null. Check lines: 304, 291. ClassBrowserPad.cs 304 void UpdateActiveWorkspace() { var mainAssemblyList = SD.ClassBrowser.MainAssemblyList; if ((mainAssemblyList != null) && (activeWorkspace != null)) { .... } .... mainAssemblyList.Assemblies.Clear(); // <= ....
  • 5. } The mainAssemblyList variable is used without a prior null check, while such a check can be found in another statement in this fragment. The fixed code: void UpdateActiveWorkspace() { var mainAssemblyList = SD.ClassBrowser.MainAssemblyList; if ((mainAssemblyList != null) && (activeWorkspace != null)) { .... } .... if (mainAssemblyList != null) { mainAssemblyList.Assemblies.Clear(); } .... } Unexpected sorting result PVS-Studio diagnostic message: V3078 Original sorting order will be lost after repetitive call to 'OrderBy' method. Use 'ThenBy' method to preserve the original sorting. CodeCoverageMethodElement.cs 124 void Init() { .... this.SequencePoints.OrderBy(item => item.Line) .OrderBy(item => item.Column); // <= } This code will sort the SequencePoints collection only by the Column field, which doesn't seem to be the desired result. The problem with this code is that the second call to the OrderBy method will sort the collection without taking into account the results of the previous sort. To fix this issue, method ThenBy must be used instead of the second call to OrderBy: void Init() { .... this.SequencePoints.OrderBy(item => item.Line) .ThenBy(item => item.Column); } Possible division by zero
  • 6. PVS-Studio diagnostic message: V3064 Potential division by zero. Consider inspecting denominator 'workAmount'. XamlSymbolSearch.cs 60 public XamlSymbolSearch(IProject project, ISymbol entity) { .... interestingFileNames = new List<FileName>(); .... foreach (var item in ....) interestingFileNames.Add(item.FileName); .... workAmount = interestingFileNames.Count; workAmountInverse = 1.0 / workAmount; // <= } If the interestingFileNames collection is found to be empty, a division by zero will occur. I can't suggest a ready solution for this code, but in any case, the authors need to improve the algorithm computing the value of the workAmountInverse variable when the value of the workAmount variable is zero. Repeated assignment PVS-Studio diagnostic message: V3008 The 'ignoreDialogIdSelectedInTextEditor' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 204, 201. WixDialogDesigner.cs 204 void OpenDesigner() { try { ignoreDialogIdSelectedInTextEditor = true; // <= WorkbenchWindow.ActiveViewContent = this; } finally { ignoreDialogIdSelectedInTextEditor = false; // <= } } The ignoreDialogIdSelectedInTextEditor variable will be assigned with the value false regardless of the result of executing the try block. Let's take a closer look at the variable declarations to make sure there are no "pitfalls" there. This is the declaration of ignoreDialogIdSelectedInTextEditor: bool ignoreDialogIdSelectedInTextEditor; And here are the declarations of IWorkbenchWindow and ActiveViewContent: public IWorkbenchWindow WorkbenchWindow { get { return workbenchWindow; } }
  • 7. IViewContent ActiveViewContent { get; set; } As you can see, there are no legitimate reasons for assigning another value to the ignoreDialogIdSelectedInTextEditor variable. Perhaps the correct version of this construct should use the catch keyword instead of finally: void OpenDesigner() { try { ignoreDialogIdSelectedInTextEditor = true; WorkbenchWindow.ActiveViewContent = this; } catch { ignoreDialogIdSelectedInTextEditor = false; } } Incorrect search of a substring PVS-Studio diagnostic message: V3053 An excessive expression. Examine the substrings '/debug' and '/debugport'. NDebugger.cs 287 public bool IsKernelDebuggerEnabled { get { .... if (systemStartOptions.Contains("/debug") || systemStartOptions.Contains("/crashdebug") || systemStartOptions.Contains("/debugport") || // <= systemStartOptions.Contains("/baudrate")) { return true; } .... } } This code uses a serial search looking for the substring "/debug" or "/debugport" in the systemStartOptions string. The problem with this fragment is that the "/debug" string is itself a substring of "/debugport", so finding "/debug" makes further search of "/debugport" meaningless. It's not a bug, but it won't harm to optimize the code: public bool IsKernelDebuggerEnabled {
  • 8. get { .... if (systemStartOptions.Contains("/debug") || systemStartOptions.Contains("/crashdebug") || systemStartOptions.Contains("/baudrate")) { return true; } .... } } Exception-handling error PVS-Studio diagnostic message: V3052 The original exception object 'ex' was swallowed. Stack of original exception could be lost. ReferenceFolderNodeCommands.cs 130 DiscoveryClientProtocol DiscoverWebServices(....) { try { .... } catch (WebException ex) { if (....) { .... } else { throw ex; // <= } } .... } Executing the throw ex call will result in overwriting the stack of the original exception, as the intercepted exception will be generated anew. This is the fixed version: DiscoveryClientProtocol DiscoverWebServices(....) { try { .... } catch (WebException ex) { if (....) {
  • 9. .... } else { throw; } } .... } Using an uninitialized field in a class constructor PVS-Studio diagnostic message: V3128 The 'contentPanel' field is used before it is initialized in constructor. SearchResultsPad.cs 66 Grid contentPanel; public SearchResultsPad() { .... defaultToolbarItems = ToolBarService .CreateToolBarItems(contentPanel, ....); // <= .... contentPanel = new Grid {....}; .... } The contentPanel field is passed as one of the arguments to the CreateToolBarItems method in the constructor of the SearchResultsPad class. However, this field is not initialized until it has been used. It's not necessarily an error, given that the possibility of the contentPanel variable with the value of null is taken into account in the body of the CreateToolBarItems method and further on in the stack. This code still looks very suspicious and needs to be examined by the authors. As I have already said, this article discusses far not all the bugs found by PVS-Studio in this project but only those that seemed interesting to me. The project authors are welcome to contact us to get a temporary license key for a more thorough analysis of their code. Conclusion PVS-Studio did well again and revealed new interesting bugs during the second check of SharpDevelop project. It means the analyzer knows how to do its job and can help make the world a bit better. Remember that you, too, can join us at any time by taking the opportunity of checking your own projects with the free version of PVS-Studio static analyzer. You can download PVS-Studio at http://www.viva64.com/en/pvs-studio/ Please email us if you have any questions regarding the purchase of a commercial license. You can also contact us to ask for a temporary license for deeper exploration of PVS-Studio without the limitations of the demo version.