To get a trial key
fill out the form below
Team License (a basic version)
Enterprise License (an extended version)
* By clicking this button you agree to our Privacy Policy statement

Request our prices
New License
License Renewal
--Select currency--
USD
EUR
GBP
RUB
* By clicking this button you agree to our Privacy Policy statement

Free PVS-Studio license for Microsoft MVP specialists
* By clicking this button you agree to our Privacy Policy statement

To get the licence for your open-source project, please fill out this form
* By clicking this button you agree to our Privacy Policy statement

I am interested to try it on the platforms:
* By clicking this button you agree to our Privacy Policy statement

Message submitted.

Your message has been sent. We will email you at


If you haven't received our response, please do the following:
check your Spam/Junk folder and click the "Not Spam" button for our message.
This way, you won't miss messages from our team in the future.

>
>
>
Christmas Analysis of .NET Core Librari…

Christmas Analysis of .NET Core Libraries (CoreFX)

Dec 28 2015

About a year ago Microsoft made the CoreCLR and CoreFX source code open. The latter project wasn't of a big interest to us until recently, as it was written in C#, not in C++. But with the release of a new version of PVS-Studio 6.00 that now supports C# I decided to go back to the CoreFX and write an article about its analysis.

0365_CoreFX/image1.png

Introduction

.NET Core is a modular runtime and library implementation that includes a subset of the .NET Framework.NET Core consists of a set of libraries, called "CoreFX", and a small, optimized runtime, called "CoreCLR".

.NET Core is open source software that is available at GitHub:

These are large-scale Microsoft products that are very well written, but still we managed to find some suspicious code fragments.

The article about CoreCLR analysis can be found here: PVS-Studio: 25 Suspicious Code Fragments in CoreCLR.

CoreFX project that we are going to discuss in this article was checked with the help of a static code analyzer PVS-Studio 6.00 that now has C# support.

Analysis results

Preparing an article about the check of an open source project, we report only about a certain number of all of the warnings issued by the analyzer. Therefore we recommend the authors of the project to run the analyzer on their code themselves and study the complete analysis results.

The most dangerous code fragments

V3027 The variable 'start.BaseMapping' was utilized in the logical expression before it was verified against null in the same logical expression. Mappings.cs 598

internal void SetSequence()
{
  if (TypeDesc.IsRoot)
      return;

  StructMapping start = this;

  // find first mapping that does not have the sequence set
  while (!start.BaseMapping.IsSequence &&          // <=
          start.BaseMapping != null    &&          // <=???
         !start.BaseMapping.TypeDesc.IsRoot)
      start = start.BaseMapping;
  ....
}

We see a serious logical error here! An object with the 'start' name in the body of the loop gets changed during every iteration and the loop executes while the object is in a particular state. BUT the check of the "start.BaseMapping != null" condition is done only after the access to "start.BaseMapping.IsSequence", which can lead to the dereference of the null reference.

V3019 Possibly an incorrect variable is compared to null after type conversion using 'as' keyword. Check variables 'comparand', 'comparedCredentialKey'. CredentialCache.cs 4007

public override bool Equals(object comparand)
{
  CredentialHostKey comparedCredentialKey =
                                  comparand as CredentialHostKey;

  if (comparand == null)
  {
    // This covers also the compared == null case
    return false;
  }

  bool equals = string.Equals(AuthenticationType,
        comparedCredentialKey.AuthenticationType, ....
  ....
}

Object of any type or null can be passed to the function. If the null gets passed, this case will be handled incorrectly. If it is an object of a type that cannot be converted to "CredentialHostKey" type, then there will be an error accessing the "comparedCredentialKey.AuthenticationType", because the variable "comparedCredentialKey" can be null.

Most likely the code meant to look like this:

CredentialHostKey comparedCredentialKey =
                                  comparand as CredentialHostKey;
if (comparedCredentialKey == null)
{
  return false;
}

A similar fragment in the code:

  • V3019 Possibly an incorrect variable is compared to null after type conversion using 'as' keyword. Check variables 'comparand', 'comparedCredentialKey'. CredentialCache.cs 497

V3008 The 'HResult' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 169, 166. WebSocketException.cs 169

private void SetErrorCodeOnError(int nativeError)
{
    if (!Succeeded(nativeError))
    {
        HResult = nativeError;
    }

    HResult = nativeError;  // <=???
}

Somehow, regardless of the conditions, the variable "HResult" always gets the same value. Most likely the function should be implemented in a different way.

V3008 The 'ResPrec' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 1735, 1731. SQLDecimal.cs 1735

public static SqlDecimal operator /(SqlDecimal x, SqlDecimal y)
{
  int ResPrec;
  ....
  ResPrec = ResScale + x.m_bPrec + y.m_bPrec + 1;     // <=
  MinScale = Math.Min(ResScale, s_cNumeDivScaleMin);

  ResInteger = Math.Min(ResInteger, s_NUMERIC_MAX_PRECISION);
  ResPrec = ResInteger + ResScale;                    // <=

  if (ResPrec > s_NUMERIC_MAX_PRECISION)
      ResPrec = s_NUMERIC_MAX_PRECISION;
  ....
}

It is very suspicious, that the value of the "ResPrec" variable is evaluated according to some formula and then it is just replaced with another value.

V3020 An unconditional 'return' within a loop. Enumerable.cs 517

public override bool MoveNext()
{
  switch (state)
  {
    case 1:
      _enumerator = _source.GetEnumerator();
      state = 2;
      goto case 2;
    case 2:
      while (_enumerator.MoveNext())
      {
        current = _selector(_enumerator.Current);
        return true;
      }
      Dispose();
      break;
  }
  return false;
}

It's strange, that in the body of the "while" loop, the function exists without any condition. Perhaps there is an issue in the code.

Another similar loop:

  • V3020 An unconditional 'return' within a loop. JsonDataContract.cs 128

V3008 The 'prefix' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 953, 952. XmlSerializationWriter.cs 953

protected void WriteAttribute(string localName, string ns, ....)
{
  ....
  string prefix = localName.Substring(0, colon);
  prefix = _w.LookupPrefix(ns);
  _w.WriteStartAttribute(prefix,
                         localName.Substring(colon + 1), ns);
  ....
}

A substring from the 'localName', that has a "colon" length, is saved into the 'prefix' variable and then the value is replaced with a different one. Further on we see that the remaining substring from the 'localName' is still used while the first part is lost. A very questionable code fragment.

V3030 Recurring check. The 'baseTableRowCounts == null' condition was already verified in line 68. MetadataAggregator.cs 70

private MetadataAggregator(....)
{
  ....
  if (baseTableRowCounts == null)                           // <=
  {
    if (baseReader == null)
    {
      throw new ArgumentNullException("deltaReaders");
    }

    if (baseReader.GetTableRowCount(TableIndex.EncMap) != 0)
    {
      throw new ArgumentException("....", "baseReader");
    }

    CalculateBaseCounts(baseReader, out baseTableRowCounts, // <=
                                    out baseHeapSizes);
  }
  else
  {
    if (baseTableRowCounts == null)                      // <=???
    {
      throw new ArgumentNullException("baseTableRowCounts");
    }

    ....
  }
  ....
}

The analyzer detected a condition that has already been checked. If you look at the code fragment, the last check in the 'else' - "baseTableRowCounts == null" makes no sense. You may also see that if the "baseTableRowCounts" variable is null, the programmer tries to change its value by calling the CalculateBaseCounts() function. Most likely an extra "baseTableRowCounts == null" check is missing after this function. I.e. the code was probably meant to look like this:

private MetadataAggregator(....)
{
  ....
  if (baseTableRowCounts == null)
  {
    if (baseReader == null)
    {
      throw new ArgumentNullException("deltaReaders");
    }

    if (baseReader.GetTableRowCount(TableIndex.EncMap) != 0)
    {
      throw new ArgumentException("....", "baseReader");
    }

    CalculateBaseCounts(baseReader, out baseTableRowCounts,
                                    out baseHeapSizes);
    if (baseTableRowCounts == null)
    {
      throw new ArgumentNullException("baseTableRowCounts");
    }

  }
  else
  {
    ....
  }
  ....
}

Other warnings

V3022 Expression 'readercount >= 0' is always true. Unsigned type value is always >= 0. ReaderWriterLockSlim.cs 977

private void ExitAndWakeUpAppropriateWaitersPreferringWriters()
{
  ....
  uint readercount = GetNumReaders();
  ....
  
  if (readercount == 1 && _numWriteUpgradeWaiters > 0)
  {
    ....
  }
  else if (readercount == 0 && _numWriteWaiters > 0)
  {
    ExitMyLock();
    _writeEvent.Set();
  }
  else if (readercount >= 0)
  {
    ....
  }
  else
    ExitMyLock();
  ....
}

The variable "readercount" has an unsigned type, so the condition "readercount >= 0" is meaningless. Perhaps it is used to be a signed type variable, so there was some chance for the ExitMyLOck() function to execute in the last 'else'. Now this code never gets control. This fragment has to be rewritten.

V3014 It is likely that a wrong variable is being incremented inside the 'for' operator. Consider reviewing 'i'. RegexCharClass.cs 1094

private void Canonicalize()
{
  ....
  for (i = 1, j = 0; ; i++)
  {
    for (last = _rangelist[j]._last; ; i++)
    {
      if (i == _rangelist.Count || last == LastChar)
      {
        done = true;
        break;
      }

      if ((CurrentRange = _rangelist[i])._first > last + 1)
        break;

      if (last < CurrentRange._last)
        last = CurrentRange._last;
    }

    _rangelist[j] = new SingleRange(_rangelist[j]._first, last);

    j++;

    if (done)
      break;

    if (j < i)
      _rangelist[j] = _rangelist[i];
  }
  _rangelist.RemoveRange(j, _rangelist.Count - j);
  ....
}

The analyzer detected a change of one loop counter in a different loop. It is difficult to say whether there is an error in this function, but the code is written not very clearly. It is quite possible to make a mistake somewhere in the index when accessing the array, because it's difficult to monitor the changes of one counter in several loops.

V3004 The 'then' statement is equivalent to the 'else' statement. XmlSerializationWriterILGen.cs 1213

private void WriteMember(...., TypeDesc memberTypeDesc, ....)
{
  ....
  if (memberTypeDesc.IsArray)
  {
    LocalBuilder localI = ilg.DeclareOrGetLocal(...., iVar);
    ilg.For(localI, 0, ilg.GetLocal(aVar));
  }
  else
  {
    LocalBuilder localI = ilg.DeclareOrGetLocal(...., iVar);
    ilg.For(localI, 0, ilg.GetLocal(aVar));
  }
  ....
}

The condition that doesn't affect anything as only one code type will be executed. It' classic Copy-Paste.

V3004 The 'then' statement is equivalent to the 'else' statement. SqlUtil.cs 93

internal static void ContinueTask(....)
{
  ....
  if (connectionToDoom != null || connectionToAbort != null)
  {
    try
    {
      onSuccess();
    }
    catch (Exception e)
    {
      completion.SetException(e);
    }
  }
  else
  { // no connection to doom - reliability section not required
    try
    {
      onSuccess();
    }
    catch (Exception e)
    {
      completion.SetException(e);
    }
  }
  ....
}

There are also too many similar code fragments, although in the commentary it is written that the situations are different.

Conclusion

Here it is - another Microsoft project analysis. The code is rather qualitative, taking into account the considerable size of the project. But the programmers can still make errors. This article gives only an overview of the bugs found and the list of the warnings provided here is far from being complete.

Two main factors that facilitate safe and high-quality code:

  • Regular, not casual static analysis;
  • Review of the analyzer warnings should be done by the authors of the corresponding fragments.

We hope you enjoyed this article. In the future there will be more articles about the checks of the projects written in C/C++ and C#.

Thank you for your attention. We wish you bug free code in the coming new year!

Popular related articles
Static analysis as part of the development process in Unreal Engine

Date: Jun 27 2017

Author: Andrey Karpov

Unreal Engine continues to develop as new code is added and previously written code is changed. What is the inevitable consequence of ongoing development in a project? The emergence of new bugs in th…
Characteristics of PVS-Studio Analyzer by the Example of EFL Core Libraries, 10-15% of False Positives

Date: Jul 31 2017

Author: Andrey Karpov

After I wrote quite a big article about the analysis of the Tizen OS code, I received a large number of questions concerning the percentage of false positives and the density of errors (how many erro…
Free PVS-Studio for those who develops open source projects

Date: Dec 22 2018

Author: Andrey Karpov

On the New 2019 year's eve, a PVS-Studio team decided to make a nice gift for all contributors of open-source projects hosted on GitHub, GitLab or Bitbucket. They are given free usage of PVS-Studio s…
Technologies used in the PVS-Studio code analyzer for finding bugs and potential vulnerabilities

Date: Nov 21 2018

Author: Andrey Karpov

A brief description of technologies used in the PVS-Studio tool, which let us effectively detect a large number of error patterns and potential vulnerabilities. The article describes the implementati…
How PVS-Studio Proved to Be More Attentive Than Three and a Half Programmers

Date: Oct 22 2018

Author: Andrey Karpov

Just like other static analyzers, PVS-Studio often produces false positives. What you are about to read is a short story where I'll tell you how PVS-Studio proved, just one more time, to be more atte…
PVS-Studio ROI

Date: Jan 30 2019

Author: Andrey Karpov

Occasionally, we're asked a question, what monetary value the company will receive from using PVS-Studio. We decided to draw up a response in the form of an article and provide tables, which will sho…
The Last Line Effect

Date: May 31 2014

Author: Andrey Karpov

I have studied many errors caused by the use of the Copy-Paste method, and can assure you that programmers most often tend to make mistakes in the last fragment of a homogeneous code block. I have ne…
PVS-Studio for Java

Date: Jan 17 2019

Author: Andrey Karpov

In the seventh version of the PVS-Studio static analyzer, we added support of the Java language. It's time for a brief story of how we've started making support of the Java language, how far we've co…
Appreciate Static Code Analysis!

Date: Oct 16 2017

Author: Andrey Karpov

I am really astonished by the capabilities of static code analysis even though I am one of the developers of PVS-Studio analyzer myself. The tool surprised me the other day as it turned out to be sma…
The way static analyzers fight against false positives, and why they do it

Date: Mar 20 2017

Author: Andrey Karpov

In my previous article I wrote that I don't like the approach of evaluating the efficiency of static analyzers with the help of synthetic tests. In that article, I give the example of a code fragment…

Comments (0)

Next comments
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site.
Learn More →
Accept