Showing posts with label csharp. Show all posts
Showing posts with label csharp. Show all posts

Thursday, August 17, 2017

Use PVS-Studio to Find Errors in Your Colleagues' Code

by Andrey Karpov

We noticed that many people read our articles, dedicated to the abilities of PVS-Studio static code analyzer. Despite this, a small number of readers reach the download page with a distribution package. We would like to assure that downloading and trying PVS-Studio is very simple. On our site there is a demo version that you can download without filling in different forms and immediately begin detecting errors in code. To encourage our readers we decided to give an idea - to search errors in colleagues' code. This can become an interesting competition.
Рисунок 2
PVS-Studio performs static code analysis and generates warnings that help a programmer to find and fix bugs. We regularly demonstrate abilities of the analyzer in the articles, dedicated to the check of open source projects. Here are some recent publications:

The articles are really meaningful, people read them with great interest. At the same time we were disappointed by three messages, which we received last month. They had similar ideas such as:
For a year/two years I've been reading your articles with great interest. Finally, I decided to try your analyzer. I really liked it, but I have a question...
Aah! Why wait for 2 years? The analyzer is so simple to download and try. Very simple:
  • download;
  • install;
  • run;
  • study the warnings and ask yourself and others, how this code could actually work :)
So, I inspire not to postpone for years, just try it. You will like it! You will find a lot of interesting bugs both in your code and in code of your colleagues.
I suggest to have some fun! You find an error, and then show the related fragment to the author of the code. Let him try to find this error. It is a great way to appreciate the analyzer.
Download PVS-Studio and find errors.

Tuesday, August 15, 2017

Story of One Exception or This is How We Have to Debug Other People's Code

by Paul Eremeev and Sergey Vasiliev 
Using third-party libraries allows you to get the functionality you want, without wasting time on the development of the corresponding logic. Take and use it! Of course, such an approach doesn't include only the merits, that's why it has another "dark" side. One of the problems inherent to using third-party libraries is the lack of control over things that are going on inside. It all started with a user who wrote about an unhandled exception, appearing when checking C# project...
Before moving to a debriefing session, one has to understand at least approximately about interacting between PVS-Studio, Roslyn and MSBuild. To keep it short - to open C++ and C# projects, PVS-Studio uses MSBuild libraries, and for C# projects Roslyn libraries are additionally used (which, in turn, uses MSBuild as well). If you would like to get more details about the interaction of these components, you can find them in the article: "Support of Visual Studio 2017 and Roslyn 2.0 in PVS-Studio: sometimes it's not that easy to use ready-made solutions as it may seem".
As I've already said it all started with a crash with this warning:
Unhandled Exception: System.IO.FileNotFoundException: Could not load 
file or assembly 'Microsoft.Build.Framework, Version=15.1.0.0, 
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its 
dependencies. The system cannot find the file specified. ---> 
System.IO.FileNotFoundException: Could not load file or assembly
'Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The 
system cannot find the file specified.
The most interesting thing here is that PVS-Studio is not mentioned in the error message, that made us think that we are not directly related to the crash. That's good. But when verifying the project, PVS-Studio still crashes, which is bad. Moreover, the exception was thrown in a way, that it couldn't be caught and handled properly on our side. So, we had to investigate and dig deep, e.g. configure debug projects to explore source code of Roslyn and MSBuild libraries.
It was clear at once that the exception is coming from within the Roslyn, while trying to open a project, but the Antlr4.Build.Tasks mention gave the idea, that the problem is more specific.
Gradually, exploring the code and making a way in the wilds of third-party dependencies connected with PVS-Studio, this call chain was reconstructed:
PVS-Studio -> Roslyn -> MSBuild -> Antlr4
It should be explained how Antlr4 dependencies got here, if PVS-Studio does not use them. The project file, parsing of which had generated an exception, utilizes the Antlr4 code generatortask, which is a user-defined MSBuild task. Such a task can be imported into any standard MSBuild project and it can be called as a separate build step. Thus, to open the project, in addition to Roslyn and MSBuild, we find ourselves tied by such third party components necessary for a build. Since the Roslyn, in addition to its evaluation, runs various build steps to open the project, code from Antlr4 is also executed inside the process of our analyzer.
Task's source code, throwing an exception, is available as an open source at GitHub. This allowed us to rebuild a task's .dll with debug symbols and see what was going on inside.
The most interesting (and useful for us) from what was inside, was a way in which an external process is launched - it took place in another application domain. During the instantiation of a type containing a method for processing the stdout of the aforementioned external process, the task requested the Microsoft.Build.Framework.dll library. Here comes the most interesting part. This library is already loaded by the process of our analyzer - it is needed both by us (for MSBuild files parsing) and by Roslyn. However, as you may remember, we are now in another AppDomain and the library is not loaded into it yet. The crash occurs while attempting to load this very library.
A careful reader may immediately have a question - why there is a problem with loading this library now, if in the main AppDomain it was just fine? The answer is how this AppDomain was created. A directory, passed to its constructor as base one, was the one containing the task's dll, but not a directory with the executable PVS-Studio_Cmd.exe file. This, in turn, led to a change in the behavior of the Fusion subsystem, which is responsible for finding and loading dependent .NET assemblies. Fusion searches for the assembly in the directory of the executable file (which is usually an exe file) and in the Global Assembly Cache. Creation of an AppDomain with another base directory made Fusion search for dll file in another directory, but not in the directory of executable PVS-Studio_Cmd.exe file. Yes, it is worth noting that PVS-Studio in its distribution has a significant number of MSBuild libraries (including the one which we are talking about) - the reason why it happened so can also be found in the article about our support of Visual Studio 2017, the link to which is given above. At the same time, starting with MSBuild version 15, its libraries are not registered at GAC. These two reasons (lack of a library in the GAC and change of the AppDomain base directory, in which Fusion looks for dependencies) led to the crash of the program.
As the exception occurred in another AppDomain, it is not possible to catch and handle it in analyzer application domain. More precisely, it is possible, but the application will still crash. The most we can do is to undertake actions for a softer crash, for example, inform about the source of the problem (what we did).
By the way, the same error occurs in the Microsoft Visual Studio 2017 development environment when trying to build this project. Most likely, it has existed in the Antlr4 task, but remained unnoticed because previous versions of MSBuild registered its dependencies in GAC, and Fusion found them there. At the moment, the bug is fixed in the Antlr4 repository. Do you know what decision did Antlr4 task developers made to fix this problem? Not to create a separate AppDomain, and do all necessary operations in the default one. Why it was necessary to complicate logic from the very beginning is an open question.
Overall, it turned out to be very ironic. The AppDomain technology, created with the aim of increasing the fault tolerance of the applications by creating isolated areas of execution, eventually led to the inability to protect ourselves in this situation. Of course, it is clear that such a situation could arise in case of an unhandled exception in a thread created in a third-party library as well, even when this thread is created in the default domain.
Anyway, we can learn several lessons from this situation:
  • There is no need to reinvent the bicycle. The more complex code, the more likely you will make a mistake.
  • Get ready to pay a certain price for the use of third-party libraries. Sometimes it can be quite huge.
  • Even if the problem is not in your code, but in some of the dependencies, the problem will automatically be your headache when it reveals itself.
  • The world is not perfect - unfortunately, there are things out of our control. For example, the exceptions, thrown from other application domains or threads.

Friday, July 21, 2017

We Continue Exploring Tizen: C# Components Proved to be of High Quality

by Sergey Khrenov 

This time I go back again to the check of the Tizen project. In my recent post "Experiment of Bug Detection in the Code of C #Components of Tizen" in our blog, I analyzed the code of C# superficially and came to a conclusion that it makes sense to check the whole code of C# components of this project for errors using PVS-Studio and write the article about it. Right away, I would like to share with you the results of the work that I have done. I shall tell at once that PVS-Studio analyzer showed itself not on the bright side on C# code. Anyway, first things first: let's see what the analyzer found, and then we will deal with statistics and make conclusions.
Picture 1

Introduction

Recently, my colleague Andrey Karpov has published two epic articles about the code analysis of Tizen project, written in C and C++:

When I noticed that the Tizen project includes the code in C#, I felt like doing a similar article on the checking of components written in this language. Unfortunately, this time the analyzer missed a chance to show us the outstanding achievements, but let us take it slow and examine the issue in detail.

Selecting Test Data

The open-source code is available for download by this link. The repository contains about 1 000 projects, each of them consists of the archive with the source code and the supporting files. It is not always possible to understand what is inside by the archive filenames or by the description. Therefore, a download, an extract and a review of archives had to be done for the entire repository.
In a previous article I gave the total number of C# source code files (4 929, excluding *.Designer.cs) and lines of code in them (about 691 000), that contained in the Tizen project. Now we need a more detailed analysis. For starters, we shall try to find the files with the .sln or .csproj extension. The availability of these files will allow us to undertake an analysis in IDE Visual Studio, making the work easier.
So, while searching, 227 solutions (*.sln) and 166 projects C# (*.csproj) were found. From the solutions files I chose the ones, which included C# projects. There were only three appropriate solutions:
  • Tizen.Xamarin.Forms.Extension.sln
  • Xamarin.Forms.Tizen.sln
  • Xamarin.Forms.sln
The first two solutions are the Tizen extension of the third-party component Xamarin.Forms, and the third one contains the component itself. Just over a year ago, we wrote the article about the check of Xamarin.Forms. In my work I will take into account these results and try to find new bugs.
Further on, after deleting files of the (*.csproj) projects, included in these solutions, I got 107 C# projects, that have not been connected with any solutions. Almost all of them are in top-level folders with the names of "csapi-*" type. After deleting 11 test projects as well as 9 projects, that had unsupported Visual Studio format from this number, I had got 87 projects left. I tested each of them separately.
For fairness of research I decided to separate the results, obtained for the internal C# components (those 87 projects), from the results of the check of components based on Xamarin.Forms. At first, I did not want to consider Xamarin.Forms, but, on reflection, I concluded, that once Tizen uses this component to its goals, then Xamarin.Forms bugs could influence Tizen.
I also will not describe the errors that I have already given in the previous article.
Picture 6

Analysis Results

Internal C# Tizen Components

During the check of this part of Tizen project the PVS-Studio analyzer generated 356 warnings, 18 of which are of High level of certainty, 157- of Medium level of certainty and 181 - of Low level of certainty. Approximately 325 000 lines of code were analyzed.
I did not consider the warnings of the Low level of certainty, as the percentage of false positives at this level is usually very large. Unfortunately, this time many false positives are not only at the Low level. Among 175 warnings of High and Medium levels, I found just 12 errors. Let's have a look at the most interesting of the detected errors.
PVS-Studio warning: V3008 The '_scanData' variable is assigned values twice successively. Perhaps, this is a mistake. Check lines: 138, 137. Tizen.Network.Bluetooth BluetoothLeAdapter.cs 138
CWE-563. Assignment to Variable without Use ('Unused Variable')
internal BluetoothLeDevice(BluetoothLeScanData scanData)
{
  _scanData = new BluetoothLeScanData ();
  _scanData = scanData;
  ....
}
The field _scanData is assigned a value twice. It looks very strange. Just in case, we will have a look at the BluetoothLeScanData class declaration and its constructor. Perhaps, the call of the constructor contains some additional actions. The class is small, so I will write it in one piece after formatting the original code:
internal class BluetoothLeScanData
{
  internal string RemoteAddress { get; set; }
  internal BluetoothLeDeviceAddressType AddressType { get; set; }
  internal int Rssi { get; set; }
  internal int AdvDataLength { get; set; }
  internal byte[] AdvData { get; set; }
  internal int ScanDataLength { get; set; }
  internal byte[] ScanData { get; set; }
}
As we can see, the class does not contain the explicitly defined default constructor, apparently, the double value assignment to the field _scanData is an error.
PVS-Studio warning: V3009 It's odd that this method always returns one and the same value of '0'. Tizen.Applications.WidgetApplication WidgetType.cs 47
CWE-393. Return of Wrong Status Code
private int OnCreate(....)
{
  WidgetBase b = Activator.CreateInstance(ClassType) as WidgetBase;
  ....  
  if (b == null)
    return 0;
  ....  
  return 0;
}
The method always returns 0, regardless of the result of its work. Probably, the error can be corrected, for example, like this:
private int OnCreate(....)
{
  WidgetBase b = Activator.CreateInstance(ClassType) as WidgetBase;
  ....  
  if (b == null)
    return 0;
  ....  
  return 1;
}
PVS-Studio warnings:
  • V3022 Expression '!LeftBoundIsForward' is always false. clipper_library clipper.cs 838
  • V3022 Expression '!LeftBoundIsForward' is always true. clipper_library clipper.cs 863
CWE-570/CWE-571 Expression is Always False/True
private TEdge ProcessBound(TEdge E, bool LeftBoundIsForward)
{
  ....
  if (LeftBoundIsForward)
  {
    ....
    if (!LeftBoundIsForward) Result = Horz.Prev;
    ....
  }
  else
  {
    ....
    if (!LeftBoundIsForward) Result = Horz.Next;
    ....
  }
  ....
}
This fragment of code contains two similar verifications at once. At the same time, in the first case the variable Result will never get the value Horz.Prev, and in the second case the same variable Result will always get the value Horz.Next. The author must carefully review the code and fix the bug himself.
PVS-Studio warning: V3022 Expression 'e.OutIdx >= 0' is always true. clipper_library clipper.cs 3144
CWE-571 Expression is Always True
private void DoMaxima(TEdge e)
{
  ....
  if(....)
  {
    ....
  } else if( e.OutIdx >= 0 && eMaxPair.OutIdx >= 0 )
  {
    if (e.OutIdx >= 0) AddLocalMaxPoly(e, eMaxPair, e.Top);
    ....
  }
  ....
}
Another fragment of code with an erroneous check. Perhaps, if in the condition e.OutIdx >= 0 && eMaxPair.OutIdx >= 0 the operator "||" was used, the check of e.OutIdx >= 0 in the attached block if, would make sense. Now it looks suspicious.
PVS-Studio warning: V3110 Possible infinite recursion inside 'InsertBefore' method. ElmSharp Toolbar.cs 288
CWE-674 Uncontrolled Recursion
public ToolbarItem InsertBefore(ToolbarItem before, string label)
{
  return InsertBefore(before, label);
}
The call of the InsertBefore method generates an infinite recursion. Probably, a bug appeared due to a call of the wrong overload of the method. In the code there is another InsertBefore method:
public ToolbarItem InsertBefore(ToolbarItem before, string label,
  string icon)
{
  ....
}
Perhaps, these are all the interesting bugs in this section. There are also several suspicious fragments of code, but I will not dwell on them. Code from Samsung Electronics, written in C#, shows good quality. Why am I so sure that the checked code has authorship of Samsung? Because each of the scanned files contained "Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved" in its header comment.

Tizen Components on the Xamarin.Forms Base

The extension of Xamarin.Forms used in Tizen, contains approximately 242 000 lines of code. During its check the PVS-Studio analyzer generated 163 warnings, 10 of them of High level of certainty, 46 - of Medium level, and 107 - of Low level (not considered).
As promised, I will try to find errors that have not been described in the previous article about the check of Xamarin.Forms. By the way, some of the errors described in the article, were not found during a new check. Apparently, they were corrected after the authors' acquaintance with the article.
Despite the small number of generated warnings, I managed to find some new bugs.
PVS-Studio warning: V3095 The 'context' object was used before it was verified against null. Check lines: 16, 18. Xamarin.Forms.Xaml XamlServiceProvider.cs 16
CWE-476 NULL Pointer Dereference
internal XamlServiceProvider(INode node, HydratationContext context)
{
  ....
  if (node != null && node.Parent != null
    && context.Values.TryGetValue(node.Parent,  // <=
    out targetObject))
    IProvideValueTarget = new XamlValueTargetProvider(....);
  if (context != null)  // <=
    IRootObjectProvider =
    new XamlRootObjectProvider(context.RootElement);
  ....
}
The variable context is firstly used, and then verified against null.
PVS-Studio warning: V3095 The 'type' object was used before it was verified against null. Check lines: 147, 149. Xamarin.Forms.Xaml ExpandMarkupsVisitor.cs 147
CWE-476 NULL Pointer Dereference
public INode Parse(....)
{
  ....
  var xmltype = new XmlType(namespaceuri, type.Name, null);  // <=
  
  if (type == null)
    throw new NotSupportedException();
  ....
}
Another example of a possible throwing of NullReferenceException exception. The variable type is used to create the instance of the XmlType class, and then is verified against null.
Other similar errors:
  • V3095 The 'e.NewElement' object was used before it was verified against null. Check lines: 32, 46. Xamarin.Forms.Platform.Tizen MasterDetailPageRenderer.cs 32
  • V3095 The 'e.NewItems' object was used before it was verified against null. Check lines: 557, 567. Xamarin.Forms.Core Element.cs 557
  • V3095 The 'e.OldItems' object was used before it was verified against null. Check lines: 561, 574. Xamarin.Forms.Core Element.cs 561
  • V3095 The 'part' object was used before it was verified against null. Check lines: 135, 156. Xamarin.Forms.Core BindingExpression.cs 135
PVS-Studio warning: V3125 The 'e.NewItems' object was used after it was verified against null. Check lines: 999, 986. Xamarin.Forms.Core TemplatedItemsList.cs 999
CWE-476 NULL Pointer Dereference
void OnProxyCollectionChanged(....)
{
  ....
  if (e.NewStartingIndex >= 0 && e.NewItems != null)  // <=
    maxindex = Math.Max(maxindex, e.NewStartingIndex +
      e.NewItems.Count);
  ....
  for (int i = e.NewStartingIndex; i < _templatedObjects.Count; i++)
    SetIndex(_templatedObjects[i], i + e.NewItems.Count);  // <=
  ....
}
Here is a reverse situation. The variable e.NewItems is verified against null before using for the first time. However, during the second use one forgot to do it.

Statistics

As my colleague, Andrey Karpov, wrote in one of the previous articles, the PVS-Studio analyzer detects about 0.4 errors on 1000 lines of C/C++ code in Tizen project. Let's calculate what we get for C# code.
In total, 567 000 lines of code in C# were checked.
In my opinion, only 15 fragments of code were found, about which one can say that that they contain errors.
It turns out that PVS-Studio detects 0.02 errors on 1000 lines of code. Or, in other words, it finds 1 error on 50 000 lines of code. It is not too much.
Picture 11
We have to admit that in this case the analyzer was unable to demonstrate its usefulness. It is hard to say why it happened so. When checking for other open source projects the analyzer often showed good results. For example, when checking the open-sourced Unity3D components, the density of detected bugs was 0.5 errors on 1000 lines of code, i.e. it was 25 times better.
Perhaps, the checked components now are of high quality or the analyzer cannot find these types of errors, inherent to this project. Maybe the reason for it is the complicated inner architecture of Tizen. Very often the verified projects do not contain all the necessary environment and many links are missing, which does not allow some diagnostics to work out. Some projects cannot be verified at all.

Conclusions

So, the result of the test was not such as I expected for this size of code. Frankly speaking: I intended to find at least a few hundred errors but I found only about fifteen.
However, it is important to say, that the PVS-Studio analyzer coped with the task to analyze the C# code of Tizen project. Therefore, it may be useful, if not now, then later, when new components, written using C#, will appear in Tizen. Potential benefit is confirmed by the huge number of errors that the analyzer has already found in other open source projects (see list of articles).
Moreover, as we are not tired of repeating, the single checks using the analyzer are not optimal, as bugs have already been laid in the version control system, which is bad. It is much more efficient to use the static analyzer regularly, which will correct errors when coding, before falling into a version control system, because in such case, the cost and complexity of fixing them is much lower.
Picture 17

Download and try PVS-Studio: https://www.viva64.com/en/pvs-studio-download/?win

Friday, June 30, 2017

Experiment of Bug Detection in the Code of C# Tizen Components

By Sergey Khrenov 
Recently, my colleague Andrey Karpov asked me to find 3-4 bugs in one of the Tizen components, written in C#.He has also done the analysis of Tizen, searching for bugs in the C/C++ code and is now writing several articles on this topic.Inspired by his example, I did an experiment on finding bugs in C# components of Tizen.I should say that it was quite a successful venture, soon I will write a big article ob this topic, now I would like to share the results of a trial test.
Рисунок 2
For a start, I decided not to do a complex in-depth analysis of the whole Tizen codebase, but chose just a couple of projects in C# that do not require much effort. The purpose of this experiment is to try to understand whether we need to work in this direction.

The result of such a superficial analysis showed that I managed to find several real bugs, which suggests that there is a lot of work for PVS-Studio here. In this article I will give just a short description of these errors, leaving a detailed examination of this question for the future.
According to my calculations, the Tizen code has 4 929 files of the source code with the extension cs, with about 691 000 lines of code. The source code is rather large and its full-fledged analysis will take some time. Later, by the results of this work, I will write a detailed article.
In the meantime, I will give a description of the three bugs, detected at this stage of work. For simplicity I will specify the name of the top-level folder in the hierarchy of Tizen projects, which has a file with an error.
xamarin-forms-tizen
PVS-Studio: V3001 There are identical sub-expressions 'RwWait' to the left and to the right of the '|' operator. Xamarin.Forms.Platform.WP8 SplitOrderedList.cs 458
struct SimpleRwLock
{
  const int RwWait = 1;
  const int RwWrite = 2;
  const int RwRead = 4;
  ....
  public void EnterReadLock()
  {
    var sw = new SpinWait();
    do
    {
      while ((_rwlock & (RwWrite | RwWait)) > 0)
        sw.SpinOnce();

      if ((Interlocked.Add(ref _rwlock, RwRead)
          & (RwWait | RwWait)) == 0)                // <=
        return;

      Interlocked.Add(ref _rwlock, -RwRead);
    } while (true);
  }
  ....
}
Perhaps, there is a typo in the condition of the if block, related to the fact that RwWait and RwWrite are spelled very similarly, which led to RwWait being mistakenly used twice. The condition in the while block above proves my suspicious, as the combination RwWrite | RwWait is used correctly there.
PVS-Studio: V3095 The 'type' object was used before it was verified against null. Check lines: 147, 149. Xamarin.Forms.Xaml ExpandMarkupsVisitor.cs 147
CWE-476 NULL Pointer Dereference
public class MarkupExpansionParser : 
  MarkupExpressionParser, IExpressionParser<INode>
{
  ....
  public INode Parse(....)
  {
    ....
    Type type;
    ....
    var xmltype = new XmlType(namespaceuri, type.Name, null); // <=
   
    if (type == null)
      throw new NotSupportedException();
    ....
  }
  ....
}
The variable type is first used to access type.Name and then it is verified against null. As a result, an exception NullReferenceException is possible.
csapi-location
PVS-Studio. V3110 Possible infinite recursion inside 'Timestamp' property. Tizen.Location Location.cs 186
CWE-674 Uncontrolled Recursion
public class Location
{
  ....
  internal int _timestamp;
  ....
  public DateTime Timestamp
  {
    get
    {
        return Interop.ConvertDateTime(_timestamp);
    }
    internal set
    {
        Timestamp = value;             // <=
    }
  }  
  ....
}
This code contains an error, inevitably resulting in the exhaustion of the stack (infinite recursion) upon the attempt to access the Timestamp property. At the same time there are no visible signs if a typo. The field _timestamp is very different from Timestamp, so it's not really likely that they were confused. Besides that, _timestamp has an int type, which makes it impossible to assign with the value of the DateTime type. It would requite type conversion, such as the one implemented in the get section. I think, only the author would be able to correct this error.
That's it for a start, I'll save the remaining errors for my big article.
What we can surely say is that PVS-Studio analyzer can be used not only to check the C and C++ code, but C# components as well.
Download and try PVS-Studio: https://www.viva64.com/en/pvs-studio-download/?win