Showing posts with label article. Show all posts
Showing posts with label article. Show all posts

Wednesday, May 3, 2017

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

In this article I would like to tell about several issues that PVS-Studio developers had to face when working on support of new Visual Studio version. Besides that, I will try to answer a question: why is the support of our C# analyzer, based on a "ready-made solution" (Roslyn, in this case) is in some situations more expensive than our "self-written" C++ analyzer.
Picture 2
With the release of new Visual Studio - 2017, Microsoft provides a large amount of innovations for its "flagship" IDE. These include:

  • support of C# 7.0;
  • support of new versions of .NET Core / .NET Standard;
  • support of new features of C++11 and C++14 standards;
  • improvements in IntelliSense for a lot of the supported languages;
  • "lightweight" download of projects and new methods to monitor the performance of IDE extensions;
  • a new component-based installer and much more.
PVS-Studio 6.14, supporting Visual Studio 2017, was released 10 days after the release of the IDE. The work on the support of new support of Visual Studio began much earlier - at the end of the last year. Certainly, not all the innovations in Visual Studio are connected with the work of PVS-Studio, however, the latest release of this IDE turned out to be especially labor intensive in terms of its support in all the components of our product. The most affected was not our "traditional" C++ analyzer (we managed to support the new version of Visual C++ quite fast), but were the components responsible for the interaction with MSBuild and Roslyn platform (that our C# analyzer is based on).
Also the new version of Visual Studio became the first since the moment when we created C# analyzer in PVS-Studio (that we released in parallel with the first release of Roslyn in Visual Studio 2015), and C++ analyzer for Windows was more tightly integrated with MSBuild. Therefore, due to the difficulties encountered when updating these components, the support of the new VS became the most time-consuming in the history of our product.

Microsoft solutions used in PVS-Studio

Chances are, you know that PVS-Studio is a static analyzer for C/C++/C#, running on Windows and Linux. What is inside PVS-Studio? First of all this is, of course, a cross-platform C++ analyzer and also (mostly) cross-platform utilities for its integration into various build systems.
However, the majority of our users on Windows platform use the stack of technologies for the software development by Microsoft, i.e. Visual C++/C#, Visual Studio, MSBuild and so on. For such users we have the means to work with the analyzer from Visual Studio (IDE plugin) and the command line utility to check C++/C#/MSBuild projects. The same utility is used by our VS plugin "under the hood". This utility for analyzing the structure of projects directly utilizes MSBuild API. Our C# analyzer is based on the .NET Compiler Platform (Roslyn), and so far it is only available for Windows users.
So, we see that on Windows platform PVS-Studio uses "native" Microsoft tools for integration into Visual Studio, the analysis of the build system and of C# code. With the release of a new version of Visual Studio, all of these components have also been updated.

Changes for our product with the release of Visual Studio 2017

Besides the updates of MSBuild and Roslyn, Visual Studio got a number of new features that greatly affected our product. Coincidentally, several of our components ceased working; those were used without any changes for several previous releases of Visual Studio, several of them have been working since Visual Studio 2005 (which we are not supporting anymore). Let's take a closer look at these changes.

A new installation routine of Visual Studio 2017

A new component-based system of installation, allowing the user to choose only the necessary components, was completely "untied" from the Windows system registry. Theoretically, it made the IDE more "portable" and allowed installing several versions of Visual Studio on one system. 
However, this also affected the developers of the extensions, because the whole code that allowed detecting the presence of the IDE or it's individual components, stopped working.
Figure 1 - the new Visual Studio Installer
Figure 1 - the new Visual Studio Installer
Now the developers are offered COM interfaces, in particular ISetupConfiguration, to be used for getting the information about the installed versions of Visual Studio. I think many would agree that the convenience of using COM interfaces is not that great as compared to reading from the registry. And if for the C# code, there are wrappers of these interfaces, we have to work quite hard on the adaptation of our installer based on InnoSetup. In the end, Microsoft replaced the use of one Windows-specific technology with another one. In my opinion, the benefit of such a transition is rather questionable, more so because Visual Studio could not fully abandon using the registry. At least in this version.
A more significant consequence of such a transition, besides a quite subjective matter of convenience of use, was that it indirectly influenced the work of MSBuild 15 libraries and their backward compatibility with previous versions of MSBuild. The reason of this is that new version of MSBuild also ceased using the registry. We had to update all the MSBuild components that we use, because Roslyn directly depends on them. I will give more details about the consequences of these changes a little later.

Changes in the C++ infrastructure of MSBuild

By saying the MSBuild infrastructure for C++, I primarily mean the layer that is responsible for the direct compiler invocation when building Visual C++ projects. This layer is called PlatformToolset in MSBuild and is responsible for the preparation of the execution environment for C++ compiler. The system of PlatformToolsets also provides backward compatibility with the previous versions of Visual C++ compilers. It allows working with the latest version of MSBuild to build projects, which use the previous versions of the visual C++ compiler.
For example you can build a project that uses a C++ compiler from Visual Studio 2015 in MSBuild 15/Visual Studio 2017, if this version of the compiler is installed in the system. This can be rather useful because it allows using the new version of IDE on the project immediately, without prior porting of the project to a new version of the compiler (which is sometimes not a simple task).
PVS-Studio fully supports the PlatformToolsets and uses the "native" MSBuild APIs to prepare the environment of C++ analyzer, allowing the analyzer to check the source code as close to how it is compiled as possible.
Such close integration with MSBuild allowed us to fairly easily support the new versions of C++ compiler from Microsoft. Or, to be more precise, to support its build environment, as the support of new compiler capabilities (for example, new syntax and header files, that use this syntax) are not in the scope of this article. We just added a new PlatformToolset to the list of the supported ones.
In the new version of Visual C++, the procedure of configuring the compiler environment underwent considerable changes which again "broke" our code, that was previously working for all versions starting with Visual Studio 2010. Although, the platform toolsets from the previous compiler versions are still working, we had to write a separate code branch to support the new toolset. Coincidentally (or perhaps not) MSBuild developers also changed the pattern of naming C++ toolsets: v100, v110, v120, v140 for the previous versions and v141 for the latest version (at the same time Visual Studio 2017 is still version 15.0).
In the new version, the structure of vcvars scripts, for which the deployment of the compiler environment relies upon, was changed completely. These scripts set up the environment variables necessary for the compiler, append the PATH variable with paths to the binary directories and system C++ libraries, and so on. The analyzer requires the identical environment, in particular for the preprocessing of the source files before the start of analysis.
It can be said that this new version of deployment scripts is in some way made more "tidy" and most likely it is easier to support and expand it (perhaps, the updating of these scripts was caused by the inclusion of clang as the compiler in the new version of Visual C++), but from the point of view of the developers of C++ analyzer, this added the workload for us.

PVS-Studio C# analyzer

Together with Visual Studio 2017, there was a release of Roslyn 2.0 and MSBuild 15. It may seem that to support these new versions in PVS-Studio C#, it would be enough to upgrade the Nuget packages in the projects that use them. After that, all the "goodies" of the new versions will become available to our analyzer, such as the support of C# 7.0, new types of .NET Core projects and so on.
Indeed, it was quite easy to update the packages we use and to rebuild the C# analyzer. However, the very first run of the new version on our tests showed that "everything got broken". The further experiments showed that the C# analyzer works correctly only in the system that has Visual Studio 2017/MSBuild 15 installed. It wasn't enough that our distribution kit contains the necessary versions of the Roslyn/MSBuild libraries. The release of the new C# version of the analyzer "as is" would cause the deterioration of the analysis results for the users who work with the previous versions of C# compilers.
When we were creating the first version of C# analyzer that used Roslyn 1.0, we tried to make our analyzer an "independent" solution, not requiring any third-party installed components. The main requirement for the user system is the compilability of the project to be analyzed - if the project can be built, it can be checked by the analyzer. It is obvious that to build Visual C# projects (csproj) on Windows one need to have at least MSBuild and a C# compiler.
We decided to immediately drop the idea to obligate our users to install the latest versions of MSBuild and Visual C# together with the C# analyzer. If the project gets built normally in Visual Studio 2013 (that uses MSBuild 12 its turn), the requirement to install MSBuild 15 will look like a redundant one. We, on the contrary, try to lower the "threshold" to start using our analyzer.
Microsoft web installers turned out to be quite demanding to the size of the necessary downloads - while our distribution is about 50 megabytes, the installer for Visual C++, for instance (that is also necessary for the C++ analyzer) estimated the volume of data for download as 3 Gigabytes. In the end, as we found our later, these components would still be not enough for the fully correct work of the C# analyzer.

The way PVS-Studio interacts with Roslyn

When we were only beginning to develop our C# analyzer, we had 2 ways to work with Roslyn platform.
The first one was to use Diagnostics API, which was especially designed for the development of .NET analyzers. This API provides a possibility to implement your own "diagnostics" by inheriting from the abstract DiagnosticAnalyzer class. With the help of CodeFixProvider class, the users could implement the automatic fixing of such warnings.
The absolute advantage of such an approach is the power of the existing infrastructure of Roslyn. The diagnostic rules become available in the Visual Studio code editor and can be applied while editing the code in the IDE, or when running the project rebuild. This approach doesn't oblige the analyzer developer to open project and source files manually - everything will be done in the scope of the "native" compiler, based on Roslyn. If we had chosen this way, we would probably not have had any issues with the updating to the new Roslyn, at least in the form as it is now.
The second option was to implement a completely standalone analyzer, by the analogy with PVS-Studio C++. This variant seemed better to us, as we decided to make the infrastructure of the C# analyzer as close to the existing C/C++ one as possible. This allowed adapting the existing C++ diagnostics rather fast (of course, not all of them, but those that were relevant for C#), as well as more "advanced" analysis methods.
Roslyn provides the facilities necessary for such an approach: we open Visual C# project files ourselves, build syntax trees from the source code and implement our own mechanism for their parsing. It can all be done using MSBuild and Roslyn APIs. Thus, we got the full control over all the phases of analysis, independent of the compiler work or the IDE.
No matter how tempting may seem the "free" integration with the editor of Visual Studio code, we preferred using our own IDE interface, as it provides more abilities than a standard Error List (where such warnings will be issued). The use of Diagnostics API would also limit us to the versions of the compiler which are based on Roslyn, i.e. the ones included in Visual Studio 2015 and 2017, while the standalone analyzer would let us support all the previous versions.
During the creation of the C# analyzer, we saw that Roslyn turned out to be very tightly tied with MSBuild. Of course I am speaking here about the Windows version of Roslyn, because we didn't have a chance to work with Linux version yet, so I cannot say exactly how it is going on there.
I should say right away that Roslyn's API to work with MSBuild projects remains fairly incomplete even in version 2.0. When writing a C# analyzer, we had to use a lot of "duct taping", as Roslyn was doing several things incorrectly (incorrectly means not in the way MSBuild would do it when building the same projects), which naturally led to false positives and errors during the analysis of the source files.
Exactly these close ties of Roslyn and MSBuild led to those issues that we faced before the update to Visual Studio 2017.

Roslyn and MSBuild

For the analyzer to work, we need to get two entities from Roslyn: a syntax tree of the checked code and a semantic model of the tree, i.e the semantics of syntax constructions representing its nodes - the types of class fields, return values, signatures of methods and so on. And if it is enough to have just a source code file to get the syntax tree with Roslyn, then to generate a semantic model of this file, it's necessary to compile a project which it includes.
The update of Roslyn to 2.0 led to the appearance of errors in the semantic model on our tests (V051 analyzer message is pointing to that). Such errors usually manifest in the result of the analysis results as false positive/negative warnings, i.e. a part of useful warnings disappear and wrong warnings appear.
For obtaining a semantic model, Roslyn provides to its users the so-called Workspace API that can open .NET MSBuild projects (in our case it is csproj and vbproj) and get the "compilations" of such projects. In this context, we are going to speak about an object of a helper Compilation class in Roslyn that abstracts the preparation and call of the C# compiler. We can get a semantic model from such a "compilation". Compilation errors lead to the errors in the semantic model.
Now let's see how Roslyn interacts with MSBuild to get a "compilation" of a project. Below here is a diagram illustrating the interaction in the simplified form:
Figure 2 - Scheme of the interaction between Roslyn and MSBuild
Figure 2 - Scheme of the interaction between Roslyn and MSBuild
The chart is divided into 2 segments - PVS-Studio and Build Tools. PVS-Studio segment contains components included in the distribution with our analyzer - MSBuild and Roslyn libraries, implementing the APIs that we utilize. The Build Tools segment includes the infrastructure of the build system that should be present in the system for the correct work of these APIs.
After the analyzer has requested the compilation object from the Workspace API (to get the semantic model), Roslyn starts building the project, or according to MSBuild terminology - perform the build task csc. After starting the build, control passes to MSBuild, which performs all of the preparatory steps in accordance with the build scripts.
It should be noted that this is not a "normal" build (it will not lead to the generation of binary files), but the so-called 'design' mode one. The ultimate goal of this step is for Roslyn to obtain all the information that would be available to the compiler during the "real" build. If the build is tied to the execution of any pre-build steps (for example, start of the scripts to auto-generate some of the source files), all such actions will also be performed by MSBuild, as if it were a normal build.
Having received the control, MSBuild, or the library included with PVS-Studio, to be exact, will start looking for the installed build toolsets in the system. Having found the appropriate toolset, it will try to instantiate the steps from the build scripts. The toolsets correspond to the installed instances of MSBuild present in the system. For example, MSBuild 14 (Visual Studio 2015), installs the toolset 14.0, MSBuild 12-12.0 and so on.
The toolset contains all the standard build scripts of MSBuild projects. The project file (for example, csproj) usually contains just the list of input build files (for example, the files with the source code). The toolset contains all the steps that should be performed over these files: from the compilation and linking to the publishing of the build results. Let's not speak too much about the way MSBuild works; it's just important to understand that one project file and the parser of this project (i.e. that MSBuild library, included in PVS-Studio) are not enough to do a full build.
Let's move to the segment of the Build Tools diagram. We are interested in the build step csc. MSBuild will need to find a library where this step is implemented directly, and the tasks file from the selected toolset will be used for that. A tasks file is an xml file, containing paths to the libraries, implementing standard build tasks. In accordance with this file, the appropriate library, containing the implementation of the csc task, will be found and loaded. The csc task will prepare everything for the call of the compiler itself (usually it is a separate command line utility csc.exe). As we remember, we have a "fake" build, and so when everything is ready, the compiler call will not happen. Roslyn has all the necessary information to get the semantic model now - all the references to other projects and libraries are expanded (as analyzed source code could contain types declared in these dependencies); all the prebuild steps are performed, all the dependencies are restored/copied and so on.
Fortunately, if something went wrong on one of these steps, Roslyn has a reserve mechanism to prepare a semantic model, based on the information available before the start of the compilation, i.e. before the moment when the control was passed to MSBuild Execution API. Typically, this information is gathered from the evaluation of project file (which admittedly is also conducted by a separate MSBuild Evaluation API). Often this information is insufficient to build a complete semantic model. The best example here is a new format of .NET Core projects, where the project file itself doesn't contain anything - even a list of source files, not to mention the dependencies. But even in "normal" .csproj files, we saw the loss of the paths to the dependencies and symbols of conditional compilation (defines) after the failed compilation, although their values were directly written in the project file itself.

Something went wrong

Now, as I hope it became a little more clear what happens "inside" PVS-Studio when checking the C# project, let's see what happened after the update of Roslyn and MSBuild. The chart above clearly shows that the Build Tools part from the PVS-Studio point of view is located in the "external environment" and accordingly is not controlled by the analyzer. As described previously, we abandoned the idea to put the whole MSBuild in the distribution, that's why we'll have to rely on what will be installed in the user's system. There can be many variants, as we support the work with all the Visual C# versions, starting with Visual Studio 2010. At the same time, Roslyn became a basis for the C# compiler starting with the previous version of Visual Studio - 2015.
Let's consider the situation when the system where the analyzer is run, doesn't have MSBuild 15 installed. The analyzer is run to check the project under Visual Studio 2015 (MSBuild 14). And now, we see the first flaw of Roslyn - when opening MSBuild project it doesn't specify the correct toolset. If the toolset isn't specified, MSBuild starts using the default toolset - in accordance with the version of the MSBuild library that is used. And since Roslyn 2.0 is compiled with the MSBuild 15 dependence, the library chooses this toolset version.
Due to the fact that this toolset is missing in the system, MSBuild instantiate this toolset incorrectly - we get a "mixture" of non-existent and incorrect paths, pointing to the toolset of the version 4. Why 4? Because this toolset, together with 4-th version of MSBuild is always available in the system as a part of the .NET Framework 4 (in later versions of MSBuild, it was untied from the framework). The result is the selection of an incorrect targets file, incorrect csc task and ultimately, errors in the compilation of the semantic model.
Why haven't we seen such an error on the old version of Roslyn? Firstly, according to the usage statistics of our analyzer, the majority of our users have Visual Studio 2015, i.e. the correct (for Roslyn 1.0) version of MSBuild is already installed.
Secondly, the new version of MSBuild, as I mentioned earlier, no longer uses the registry for storing the configurations, and, in particular, information about the installed toolset. And if all previous versions of MSBuild kept their toolsets in the registry, MSBuild 15 now stores it in config file next to MSBuild.exe. The new MSBuild changed "permanent address" - previous versions were uniformly in c:\Program Files (x 86) \MSBuild\%VersionNumber%, and the new version now is being deployed by default to the installation directory of Visual Studio (which also changed in comparison with previous versions).
This fact sometimes "concealed" wrongly selected toolset in previous versions - semantic model was generated correctly with such an incorrect toolset. Moreover, even if the required new toolset is present in the system, the library we use may not even find - now it is located in app.config file of MSBuild.exe, and not in the registry, and the library is loaded not from the MSBuild.exe process, but from PVS-Studio_Cmd.exe. The new MSBuild has a reserve mechanism for this case. If the system has a COM server installed, where the ISetupConfiguration is implemented, MSBuild will try to find the toolset in the installation directory of Visual Studio. However, the standalone installer of MSBuild, of course, does not register this COM interface - that is done only by the Visual Studio installer.
And finally, the third case, and probably the most important reason was, unfortunately, insufficient testing of our analyzer on various supported configurations, that did not allow us to identify the problem earlier. It occured that on all of the machines for everyday testing we have Visual Studio 2015 \ MSBuild 14 installed. Fortunately, we were able to identify and fix the problem before our clients would have reported it to us.
Once we understood why Roslyn did not work, we decided to try specifying the correct toolset upon the opening of the project. It is a separate question, which toolset should be considered "correct"? We were thinking about this when we started using the same MSBuild APIs to open C++ projects for our C++ analyzer. Since we can devote a whole article to this issue, we will not now dwell on it. Unfortunately, Roslyn does not provide a way to specify which toolset will be used, so we had to modify its own code (additional inconvenience for us, because it won't be possible to just take the ready-to-use Nuget packages). After that, issues disappeared in several projects from our test base. However, we got problems in a bigger number of projects. What went wrong now?
We should note here that all the processes described in the diagram above, occur within a single process of the operating system - PVS-Studio_Cmd.exe. It turned out that when choosing a correct toolset there was a conflict when loading dll modules. Our test version uses Roslyn 2.0, which includes a library Microsoft.CodeAnalysis.dll that also has the version 2.0. At the beginning of the project analysis, the library is already loaded into the memory of the process PVS-Studio_Cmd.exe (our C# analyzer). As we check Visual Studio 2015, we specify a toolset 14.0 when opening the project. Further on, MSBuild finds the correct tasks file and starts the compilation. Since the C# compiler in this toolset (remind you that we are using Visual Studio 2015) uses Roslyn 1.3, so MSBuild attempts to load Microsoft.CodeAnalysis.dll of version 1.3 into the memory of the process. Which it fails to do, as the module of a higher version is already loaded.
What can we do in this situation? Should we try to get the semantic model in a separate process or AppDomain? But to get the model, we need Roslyn (i.e. all those libraries that cause the conflict), but to transfer the model from one process/domain to another can be a non-trivial task, as this object contains references to the compilations and workspaces, from which it was obtained.
A better option would be to move the C# analyzer to a separate backend process from our solution parser that is common fro the C++ and C# analyzers, and to make two versions of such backends using Roslyn 1.0 and 2.0, respectively. But this decision also has some significant disadvantages:
  • the necessity to implement it in the code (which means additional expenses to the development and delay in the release of the new analyzer version);
  • more complex development of the code for diagnostic rules (we'll have to use idefs in the code to support new syntax from C# 7.0);
  • and, probably the most important one - this approach does not protect us from releasing new interim versions of Roslyn.
Let me explain the last point in more detail. During the existence of Visual Studio 2015, there were 3 updates, in each of them the Roslyn compiler was updated too - from 1.0 to 1.3. In case of an update to the version 2.1, for example, we'll have to create separate versions of the analyzer backend in case of every minor update of the studio, or the possibilty of the repetition of the version conflict error will remain for the users that have not the latest version of Visual Studio.
I should note that the compilation failed also in those cases when we tried to work with the toolsets not using Roslyn, for example, version 12.0 (Visual Studio 2013). There was a different reason, but we did not dig deeper, because the problems we already saw were enough to reject this solution.

How we solved the problem of backward compatibility of the analyzer with the old C# projects

After digging into the causes of these errors, we saw the need to "provide" the toolset of the version 15.0 with the analyzer. It saves us from the problems with the version conflict between the Roslyn components and allows checking projects for all the previous versions of Visual Studio (the latest version of the compiler is backwards compatible with all the previous versions of C# language). A little earlier, I have already described, why we decided not to pull in our installer a "full-fledged" MSBuild 15:
  • a large download size in the web installer of MSBuild;
  • potential version conflicts after the updates in Visual Studio 2017;
  • inability of MSBuild libraries to find their own installation directory (with the toolset), if there is no Visual Studio 2017.
However, when investigating the problems that appeared in Roslyn during the compilation of the projects, we understood that our distribution already contained all the necessary libraries of Roslyn and MSBuild (I should remind that Roslyn performs "a fake" compilation, that's why the compiler csc.exe was not necessary). In fact, for a full-fledged toolset, we were lacking several props and targets files, in which this toolset is described. And these are simple xml files in the formats of MSBuild projects, that take only several megabytes as a whole - we don't have any problem to include these files into the distribution.
The main problem was factually the necessity "to deceive" MSBuild libraries and make them take "our" toolset as a native one. This is a comment in the MSBuild code: Running without any defined toolsets. Most functionality limited. Likely will not be able to build or evaluate a project. (e.g. reference to Microsoft.*.dll without a toolset definition or Visual Studio instance installed). This comment describes the mode in which an MSBuild library works when it is added to a project just as a reference, and it is not used from MSBuild.exe. And this comment doesn't sound much encouraging, especially the "Likely will not be able to build or evaluate a project." part.
So, how can we make the MSBuild 15 libraries use a third-party toolset? Let me remind you that this toolset is declared in the app.config of the MSBuild.exe file. It turned out that you can add the contents of the config to the config of our application (PVS-Studio_Cmd.exe) and set the environment variable MSBUILD_EXE_PATH for our process with the path to our executable file. And this method worked! At that moment the latest version of MSBuild was at Release Candidate 4. Just in case, we decided to see how things were going in the master branch of MSBuild on Github. And as if by the Murphy's law, in the master branch in the code of the toolset selection was added a check - to take a toolset from the appconfig only in case when the name of the executable file is MSBuild.exe. Thus, in our distribution there appeared a file 0 bytes, with the name MSBuild.exe, that the environment variable MSBUILD_EXE_PATH of the process PVS-Studio_Cmd.exe points to.
That was not the end of our troubles with MSBuild. It turned out that the toolset itself is not enough for the projects that are using MSBuild extensions - these are additional build steps. For example, these types of projects include WebApplication, Portable .NET's Core projects. When installing the corresponding component in Visual Studio, these extensions are defined in a separate directory next to MSBuild. In our "installation" of MSBuild it was not present. We found the solution due to the ability to easily modify "our own" toolset. To do this, we bound the search paths (the property MSBuildExtensionsPath) of our toolset to a special environment variable, which PVS-Studio_Cmd.exe process specifies according to the type of the checked project. For example, if we have a WebApplication project for Visual Studio 2015, we (supposing that the user's project is compilable) search for the extensions for the toolset version 14.0 and specify the path to them in our special environment variable. These paths are needed to MSBuild only to include additional props\targets to the build scenario, that's why the problems with the version conflicts did not arise.
As a result, the C# analyzer can work on the system with any of the supported versions of Visual Studio, regardless of MSBuild version present. A potential issues would be the presence of the custom user modifications of MSBuild build scenarios, but thanks to the independence of our toolset, these modifications can be made in PVS-Studio provided toolset if necessary.

PVS-Studio plugin, Lightweight Solution Load

One of the new features of Visual Studio 2017, allowing to optimize the work with the solutions, containing a large amount of projects, was a mode of a delayed load - "lightweight solution load".
Figure 3 - lightweight solution load
Figure 3 - lightweight solution load
This mode can be enabled in the IDE for a separate solution, and for all the opened solutions. The peculiarity of using the mode "lightweight solution load" is showing only the tree of the projects (without load the projects) in the Visual Studio explorer. The load of the chosen project (the expansion of its inner structure and load of the files in the project) is performed only by request: after the corresponding action of the user (the expansion of the project node in the tree), or programmatically. The detailed description of the lightweight solution load is given in the documentation.
However, we faced several issues, creating the support of this mode:
  • obvious questions related to the lack of information about the files contained in the project until the project is loaded in the IDE;
  • the necessity of using new methods to get the information mentioned above;
  • a number of "pitfalls" due the fact that we started the work on the support of PVS-Studio plugin in Visual Studio 2017 long before its release.
In this regard, I would like to mention insufficient amount of technical documentation about the use of the lightweight solution load. In fact all the documentation, showing the peculiarities of internal mechanisms of work with new possibilities of VIsual Studio 2017 related to the "lightweight solution load" is limited just to one article.
Speaking about those "pitfalls", while the RC Visual Studio was being refined, the Microsoft didn't only eliminate the defects, but also renamed some methods in the newly added interfaces that we were also using. As a result, we needed to correct the working mechanism of the support of the lightweight solution load after the release of PVS-Studio.
Why in the release version? The thing is that one of the interfaces we use turned out to be declared in the library that is included in Visual Studio two times - one in the main installation of Visual Studio and the second - as a part of Visual Studio SDK package (a package to develop the Visual Studio extensions). For some reason, the Visual Studio SDK developers haven't updated RC version of this library in the release of Visual Studio 2017. As we had SDK installed on practically all the machines (also on the machine running the night builds - it is also used as a build server), we didn't have any issues during the compilation and work. Unfortunately, this bug was fixed after the release of PVS-Studio, when we got a bug report from a user. As for the article, which I wrote about earlier, the mentions of this interface still have the old name by the moment of posting this text.

Conclusion

The release of Visual Studio 2017 became the most "expensive" for PVS-Studio since the moment of its creation. This was caused by several factors - significant changes in the work of MSBuild\Visual Studio, the inclusion of C# analyzer as a part of PVS-Studio (that also needs to be supported now).
When we started working on the static analyzer for C#, we expected Roslyn to allow doing it very quickly. These expectations ware, for the most part, fulfilled - the release of the first version of the analyzer occured after only 4 months. We also thought that, in comparison with our C++ analyzer, the use of a third-party solution would allow us to save on the support of the new capabilities of the C# language appearing during its subsequent evolution. This expectation was also confirmed. Despite all this, the use of a ready-made platform for static analysis wasn't as "painless", as we see now from our experience of the support of new versions of Roslyn/Visual Studio. Solving the questions about the compatibility with the new C# capabilities, Roslyn creates difficulties in completely other spheres due to the fact that it is bound with third - party components (MSBuild and Visual Studio, to be more exact). The bound between Roslyn and MSBuild significantly hinders its use in the standalone static code analyzer.

We are often asked, why don't we "rewrite" our C++ analyzer on the basis of some ready-made solution, Clang, for example. Indeed, this would allow us to remove a number of present day problems in our C++ core. However, apart from the necessity to rewrite the existing mechanisms and diagnostics, we should not also forget that using a third-party solution, there will always be "pitfalls" that will be impossible to foresee.

Tuesday, May 2, 2017

How to Improve Visual C++ 2017 Libraries Using PVS-Studio

The title of this article is a hint for the Visual Studio developers that they could benefit from the use of PVS-Studio static code analyzer. The article discusses the analysis results of the libraries in the recent Visual C++ 2017 release and gives advice on how to improve them and eliminate the bugs found. Read on to find out how the developers of Visual C++ Libraries shoot themselves in the foot: it's going to be interesting and informative.
Picture 2

A bit of history

This is not my first experiment on checking Visual C++ libraries. To see the results of the previous checks, see the following articles:

There was a long pause after these checks, and I never wrote an article about checking VS2015, as there were lots of interesting projects waiting to be checked. Well, frankly, I just forgot to write that article. Luckily, I remembered about VS2017 thanks to the tweet by one of the Visual C++ developers (@MalwareMinigun):
I'm surprised we don't have people yelling at us all the time for stuff you folks find in standard library headers.
Picture 1
Indeed, I didn't tell the world about the bugs in Visual Studio 2017 libraries! Well then, challenge accepted!
As you can see, it's been a month since the tweet (March 31-st), so I admit I've been dragging my feet over the reply, but now I'm going to mend that.

What was checked and how it was checked

I did this check using the latest currently available version of PVS-Studio analyzer (6.15).
What I was checking were the C++ libraries that come with the recently released Visual Studio 2017 version. The version of the libraries that I had on my computer at the time was dated 12.04.2017. However, the version number doesn't matter that much because it's an article popularizing static analysis in general and PVS-Studio analyzer in particular, rather than a bug report.
I confess that I didn't bother to perform proper, full-fledged analysis, as it's a complicated task for me.
Firstly, I had to make copies of all the libraries and put them in another folder; otherwise, the analyzer wouldn't have been able to produce diagnostic messages for them because it doesn't do that for system libraries. By copying files into another folder I trick PVS-Studio into generating the warnings I need.
By the way, this also explains the absence of feedback from Visual C++ users on warnings in the libraries as mentioned in the tweet quoted above. There's no point in generating such warnings by default, as they would only distract people. Besides, it helps us speed up the analysis process a little, as the analyzer doesn't have to perform full-fledged parsing and analysis of inline functions' bodies.
Secondly, I didn't try to build the projects in an honest way. I just started a new solution and added the files from the libraries to it. Because of that, PVS-Studio failed to check some of the files, but it doesn't matter much from the viewpoint of my goal, which was to write the article. I got enough material anyway. A more thorough and correct check is something that the Visual C++ developers should do themselves, and I'm ready to help them with that.

False positives

I'm afraid I can't give you concrete figures on false positives this time.
I just can tell you that there were:
  • 433 general-analysis (GA) warnings of High certainty level.
  • 743 general-analysis (GA) warnings of Medium certainty level.
However, you can't use these figures to make any interpretations or draw any conclusions!
Remember, I checked only part of the files, and did it in an unconventional way. Besides, there is one peculiar thing about the libraries. You see, the analyzer issued lots of warnings that were totally correct yet completely false. There is an explanation to this paradox.
It's bad and dangerous to declare system data types manually. For example:
typedef unsigned long       DWORD;
PVS-Studio analyzer issues the following warning for this: V677 Custom declaration of a standard 'DWORD' type. The system header file should be used: #include <WinDef.h>.
The analyzer is totally correct in saying so. You should include the corresponding header rather than declare the type manually.
As you understand, this diagnostic doesn't apply to Visual C++ libraries, for they are just the place to contain the declarations of such types. There were more than 250 warnings like that.
Here's another interesting example. PVS-Studio analyzer is right in criticizing code that checks the this pointer for NULL. As specified by the modern C++ standard, this cannot equal NULL.
Yet Visual C++ has big problems with that. It seems it's never going to meet the standard as far as this matter is concerned, or at least not any time soon. The reason is that the architecture of the libraries (for example MFC) is such that this being equal to NULL is an ordinary thing there.
There are many functions in the libraries' code that check the this pointer. Here are two examples:
_AFXWIN_INLINE CDC::operator HDC() const
{ return this == NULL ? NULL : m_hDC; }
_AFXWIN_INLINE HDC CDC::GetSafeHdc() const
{ return this == NULL ? NULL : m_hDC; }
Naturally, these functions trigger the following PVS-Studio analyzer warnings:
  • V704 'this == 0' expression should be avoided - this expression is always false on newer compilers, because 'this' pointer can never be NULL. afxwin1.inl 314
  • V704 'this == 0' expression should be avoided - this expression is always false on newer compilers, because 'this' pointer can never be NULL. afxwin1.inl 316
There are over 40 warnings like that and, of course, they are all useless. You can treat them as false positives in the next few years.
As you can see from the examples with the messages V677 and V704, not all diagnostics apply to the Visual C++ libraries. It's not a problem, of course - you can simply turn them off and thus reduce the number of warnings by 300 at once.
I'm writing all this to show you just one more time that discussing the false positives rate makes no sense without prior customization of the analyzer.
So, no rate this time, sorry. If you want to know my personal opinion, there aren't many false positives.

Interesting findings

I'm going to move from harmless to horrible. We'll start with recommendations on minor fixes, then move to mild errors, and finally discuss what I think to be the "creepy" ones. In other words, I'll be raising the tension. Here we go, saving the software world from bugs!
Picture 5

Microoptimizations

The analyzer suggested applying a number of microoptimizations. It means every example in this section is code with a potential for small improvements rather than a bug.
We'll start with the V808 warning, which warns us about an object being created but never used. We'll examine this situation in two functions as examples.
void CMFCToolBarComboBoxButton::AdjustRect()
{
  ....
  if (m_pWndEdit != NULL)
  {
    CRect rectEdit = m_rect;

    const int iBorderOffset = 3;

    m_pWndEdit->SetWindowPos(
      NULL, m_rect.left + nHorzMargin + iBorderOffset,
      m_rect.top + iBorderOffset,
      m_rect.Width() - 2 * nHorzMargin - m_rectButton.Width() -
        iBorderOffset - 3,
      m_rectCombo.Height() - 2 * iBorderOffset,
      SWP_NOZORDER | SWP_NOACTIVATE);
  }
  ....
}
PVS-Studio diagnostic message: V808 'rectEdit' object of 'CRect' type was created but was not utilized. afxtoolbarcomboboxbutton.cpp 607
After the rectEdit object has been created and initialized, it's not used anywhere. It's just an extra object and can be removed without any hesitation. This will make the code a bit shorter.
The other example:
BOOL CALLBACK AFX_EXPORT
CMFCToolBarFontComboBox::EnumFamPrinterCallBackEx(....)
{
  ....
  CString strName = pelf->elfLogFont.lfFaceName;

  pCombo->AddFont((ENUMLOGFONT*)pelf, FontType,
                  CString(pelf->elfScript));
  return 1;
}
V808 'strName' object of 'CStringT' type was created but was not utilized. afxtoolbarfontcombobox.cpp 138
An object of type CString is created and initialized but not used anywhere. I don't know if the compiler is smart enough to throw away the unnecessary code that performs string creation and initialization, but it might well fail to do so since CStirng is a complex class. It doesn't matter, though; the strName object should be removed anyway to make the code shorter.
There are just tons of unnecessary objects like that. In addition to what we have already discussed, the analyzer issued 50 more messages. In order not to clutter up the text, I've made a separate list: vs2017_V808.txt.
Now it's time for unnecessary checks.
TaskStack::~TaskStack()
{
  if (m_pStack)
    delete [] m_pStack;
}
PVS-Studio diagnostic message: V809 Verifying that a pointer value is not NULL is not required. The 'if (m_pStack)' check can be removed. taskcollection.cpp 29
You can safely use nullptr as input for the delete operator, so the check is unnecessary and the code can be simplified:
TaskStack::~TaskStack()
{
  delete [] m_pStack;
}
Checks like that are also numerous. All 68 messages can be found in the file vs2017_V809.txt.
The next small improvement is about replacing iterators' postfix increments with prefix ones. For example:
size_type count(const key_type& _Keyval) const
{
  size_type _Count = 0;
  const_iterator _It = _Find(_Keyval);
  for (;_It != end() && !this->_M_comparator(....); _It++)
  {
    _Count++;
  }
  return _Count;
}
PVS-Studio diagnostic message: V803 Decreased performance. In case '_It' is iterator it's more effective to use prefix form of increment. Replace iterator++ with ++iterator. internal_concurrent_hash.h 509
The code would become a bit better if you wrote:
for (;_It != end() && !this->_M_comparator(....); ++_It)
The question if there is any use in doing such refactoring was discussed in the article "Is it reasonable to use the prefix increment operator ++it instead of postfix operator it++ for iterators?". In brief, the answer is yes, though not much.
Should the library developers decide these fixes are worth applying, here's the file with the other 26 warnings of this type: vs2017_V803.txt.
One more microoptimization. It is better to clear a string by calling to str.Empty() rather than assigning it the value _T(""). The class doesn't have prior knowledge about how much memory to allocate for a string, so it starts wasting time computing the string length, which is just an unnecessary operation.
CString m_strRegSection;

CFullScreenImpl::CFullScreenImpl(CFrameImpl* pFrameImpl)
{
  m_pImpl = pFrameImpl;
  m_pwndFullScreenBar = NULL;
  m_bFullScreen = FALSE;
  m_bShowMenu = TRUE;
  m_bTabsArea = TRUE;
  m_uiFullScreenID = (UINT)-1;
  m_strRegSection = _T("");
}
PVS-Studio diagnostic message: V815 Decreased performance. Consider replacing the expression 'm_strRegSection = L""' with 'm_strRegSection.Empty()'. afxfullscreenimpl.cpp 52
In this code, it's better to replace the line
m_strRegSection = _T("");
with
m_strRegSection.Empty();
It's just a small improvement, but it would surely please a perfectionist.
Note. In general, this string can be removed, as this code is in the constructor and the string is empty anyway.
The other 27 warnings of this kind: vs2017_V815.txt.
One more example:
HRESULT  GetPropertyInfo(....)
{
  ....
  for(ul=0; ul<m_cPropSetDex; ul++)
  {
    ....
    for(ULONG ulProp=0; ....)
    {
      ....
      pDescBuffer += (wcslen(L"UNKNOWN") + 1);
  ....
}
PVS-Studio diagnostic message: V814 Decreased performance. The 'wcslen' function was called multiple times inside the body of a loop. atldb.h 2374
Note that the wcslen function will be called multiple times, as it is written inside nested loops. A more logical solution would be to compute the length of the L"UNKNOWN" string in advance and remember it.
The last message in this section: V814 Decreased performance. The 'wcslen' function was called multiple times inside the body of a loop. atldb.h 2438
We've finished with microoptimizations. Let's move on to more interesting things.

Small and medium bugs

Compiler warnings are turned off in header files in an incorrect way. Here's one example of this error:
#ifdef _MSC_VER
#pragma warning(disable:4200)
#endif

typedef struct adpcmwaveformat_tag {
        WAVEFORMATEX    wfx;
        WORD            wSamplesPerBlock;
        WORD            wNumCoef;
#if defined( _MSC_VER )        
        ADPCMCOEFSET    aCoef[];
#else
        ADPCMCOEFSET    aCoef[1];
#endif        
} ADPCMWAVEFORMAT;
typedef ADPCMWAVEFORMAT       *PADPCMWAVEFORMAT;
typedef ADPCMWAVEFORMAT NEAR *NPADPCMWAVEFORMAT;
typedef ADPCMWAVEFORMAT FAR  *LPADPCMWAVEFORMAT;

#ifdef _MSC_VER
#pragma warning(default:4200)
#endif
PVS-Studio diagnostic message: V665 Possibly, the usage of '#pragma warning(default: X)' is incorrect in this context. The '#pragma warning(push/pop)' should be used instead. Check lines: 2610, 2628. mmreg.h 2628
I know it's not easy to figure out what the error is actually about, so here are the key lines:
#pragma warning(disable:4200)
....
#pragma warning(default:4200)
Compiler warning 4200 is turned off and then its state is set to default. You can't do it that way. Suppose some user has the 4200 diagnostic turned off completely for one of their files and writes the following line in that file, unaware of the harm it could do:
#include <mmreg.h>
As a result, this line will enable the warning again to be triggered by the user's code.
The correct solution is to save the current state and then return the previous one:
#pragma warning(push)
#pragma warning(disable:4200)
....
#pragma warning(pop)
Here's a list of other cases of incorrect use of pragma warnings in headers:
  • V665 Possibly, the usage of '#pragma warning(default: X)' is incorrect in this context. The '#pragma warning(push/pop)' should be used instead. Check lines: 586, 601. workstealingqueue.h 601
  • V665 Possibly, the usage of '#pragma warning(default: X)' is incorrect in this context. The '#pragma warning(push/pop)' should be used instead. Check lines: 1669, 1697. usbioctl.h 1697
  • V665 Possibly, the usage of '#pragma warning(default: X)' is incorrect in this context. The '#pragma warning(push/pop)' should be used instead. Check lines: 1631, 1646. usbioctl.h 1646
  • V665 Possibly, the usage of '#pragma warning(default: X)' is incorrect in this context. The '#pragma warning(push/pop)' should be used instead. Check lines: 1490, 1518. usbioctl.h 1518
  • V665 Possibly, the usage of '#pragma warning(default: X)' is incorrect in this context. The '#pragma warning(push/pop)' should be used instead. Check lines: 986, 1002. usbioctl.h 1002
  • V665 Possibly, the usage of '#pragma warning(default: X)' is incorrect in this context. The '#pragma warning(push/pop)' should be used instead. Check lines: 960, 978. usbioctl.h 978
  • V665 Possibly, the usage of '#pragma warning(default: X)' is incorrect in this context. The '#pragma warning(push/pop)' should be used instead. Check lines: 913, 925. usbioctl.h 925
  • V665 Possibly, the usage of '#pragma warning(default: X)' is incorrect in this context. The '#pragma warning(push/pop)' should be used instead. Check lines: 861, 876. usbioctl.h 876
  • V665 Possibly, the usage of '#pragma warning(default: X)' is incorrect in this context. The '#pragma warning(push/pop)' should be used instead. Check lines: 860, 875. usbioctl.h 875
Errors of this kind are found in *.cpp files as well, but I didn't write them down as they don't pose any threat to the code of Visual C++ users. It is desirable, however, to fix those tooNevertheless,.
Now let's talk about the new operator.
inline HRESULT CreatePhraseFromWordArray(....)
{
  ....
  SPPHRASEELEMENT *pPhraseElement = new SPPHRASEELEMENT[cWords];
  if(pPhraseElement == NULL)
  {
    ::CoTaskMemFree(pStringPtrArray);
    return E_OUTOFMEMORY;
  }
  memset(pPhraseElement, 0, sizeof(SPPHRASEELEMENT) * cWords);
  ....
}
PVS-Studio diagnostic message: V668 There is no sense in testing the 'pPhraseElement' pointer against null, as the memory was allocated using the 'new' operator. The exception will be generated in the case of memory allocation error. sphelper.h 2973
This code is technically faulty. If a memory allocation error occurs, the new operator must throw an exception, thus preventing the flow of execution from getting into the body of the if statement and calling the CoTaskMemFree function. The program's behavior will no longer follow the author's design.
I'm not sure this is a real error, though. This project might be linked with nothrownew.obj, in which case the new operator will not throw the exception. It is a common practice to use this feature among driver developers, for example. To learn more, see: new and delete operators. So, if these are false warnings, you can simply turn off the V668 warning.
However, another scenario is also possible: the code in question dates back to the ancient times when the new operator used to return the value of NULL in case of an error. If that is the case, then it's really bad, since I got 112 warnings of that kind: vs2017_V668.txt.
Let's move on. The analyzer issued multiple V730 warnings that tell us about some of constructor members left uninitialized. Here are two examples to illustrate this.
We'll examine class CMFCScanliner first. It has the following declared members:
class CMFCScanliner
{
  ....
  private:
  LPBYTE  m_line;
  LPBYTE  m_line_begin;
  LPBYTE  m_line_end;
  size_t  m_pitch;
  DWORD   m_start_row;
  DWORD   m_start_col;
  DWORD   m_rows;
  DWORD   m_cols;
  long    m_offset;
  BYTE    m_channels;
  size_t  m_height;
};
Now look at the constructor:
CMFCScanliner()
{
  empty();
}
Actually, there's nothing to look at here. We should go to the empty function:
void empty()
{
  m_line      = NULL;
  m_pitch     = 0;
  m_start_row = 0;
  m_start_col = 0;
  m_rows      = 0;
  m_cols      = 0;
  m_offset    = 0;
  m_height    = 0;
  m_line_begin = NULL;
  m_line_end   = NULL;
}
PVS-Studio diagnostic message: V730 It is possible that not all members of a class are initialized inside the constructor. Consider inspecting: m_channels. afxtoolbarimages.cpp 510
Every member except m_channels has been initialized. It looks strange, doesn't it? There is nothing special about this member. So, it really looks like an error, though I can't say for sure since I don't know how exactly this class should work.
Now let's examine structure AFX_EVENT.
struct AFX_EVENT
{
  enum 
  {
    event, propRequest, propChanged, propDSCNotify
  };

  AFX_EVENT(int eventKind);

  AFX_EVENT(int eventKind, DISPID dispid, ....);

  int m_eventKind;
  DISPID m_dispid;
  DISPPARAMS* m_pDispParams;
  EXCEPINFO* m_pExcepInfo;
  UINT* m_puArgError;
  BOOL m_bPropChanged;
  HRESULT m_hResult;
  DSCSTATE m_nDSCState;
  DSCREASON m_nDSCReason;
};

AFX_INLINE AFX_EVENT::AFX_EVENT(int eventKind)
{
  m_eventKind = eventKind;
  m_dispid = DISPID_UNKNOWN;
  m_pDispParams = NULL;
  m_pExcepInfo = NULL;
  m_puArgError = NULL;
  m_hResult = NOERROR;
  m_nDSCState = dscNoState;
  m_nDSCReason = dscNoReason;
}
PVS-Studio diagnostic message: V730 Not all members of a class are initialized inside the constructor. Consider inspecting: m_bPropChanged. afxpriv2.h 104
This time, it is the variable m_bPropChanged that was left uninitialized.
In both cases, I can't say for sure if these variables must be initialized. I leave it to the developers to examine this and other suspicious cases pointed out by PVS-Studio analyzer. The file vs2017_V730.txt contains 183 more warnings of that type. I'm sure some of them will prove to be genuine. Had I been sure that those members must be initialized, I'd have included them all into the next section instead. Uninitialized variables are very tricky because they lead to rare and irregular errors.
The next warnings deal with pointless checks: such checks should either be removed or replaced with appropriate ones.
HRESULT
SetDpiCompensatedEffectInput(....)
{
  ....
  hr = deviceContext->CreateEffect(CLSID_D2D1DpiCompensation,
                                   &dpiCompensationEffect);
  if (SUCCEEDED(hr))
  {
    if (SUCCEEDED(hr))
    {
  ....
}
PVS-Studio diagnostic message: V571 Recurring check. The 'if (((HRESULT)(hr)) >= 0)' condition was already verified in line 881. d2d1_1helper.h 883
The value of the variable hr is checked twice in a row. It's either duplicate code or some typo, in which case the second condition needs to be changed.
void Append(_In_reads_(nLength) PCXSTR pszSrc, _In_ int nLength)
{
  // See comment in SetString() about why we do this
  UINT_PTR nOffset = pszSrc-GetString();

  UINT nOldLength = GetLength();
  if (nOldLength < 0)
  {
    // protects from underflow
    nOldLength = 0;
  }
  ....
}
PVS-Studio diagnostic message: V547 Expression 'nOldLength < 0' is always false. Unsigned type value is never < 0. atlsimpstr.h 392
The nOldLength variable is of type unsigned UINT and therefore can't be less than zero.
Now let's talk about the function FreeLibrary.
extern "C"
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID)
{
  ....
  ::FreeLibrary(pState->m_appLangDLL);
  ....
}
PVS-Studio diagnostic message: V718 The 'FreeLibrary' function should not be called from 'DllMain' function. dllinit.cpp 639
This is what MSDN says about this function: It is not safe to call FreeLibrary from DllMain. For more information, see the Remarks section in DllMain.
It's pure luck this code works as intended, but it's still bad and must be reviewed.
As the last example in this section, I'd like you to look at the following template function:
template<class _FwdIt>
  string_type transform_primary(_FwdIt _First, _FwdIt _Last) const
{  // apply locale-specific case-insensitive transformation
  string_type _Res;

  if (_First != _Last)
    {  // non-empty string, transform it
    vector<_Elem> _Temp(_First, _Last);

    _Getctype()->tolower(&*_Temp.begin(),
      &*_Temp.begin() + _Temp.size());
    _Res = _Getcoll()->transform(&*_Temp.begin(),
      &*_Temp.begin() + _Temp.size());
    }
  return (_Res);
}
PVS-Studio diagnostic message: V530 The return value of function 'tolower' is required to be utilized. regex 319
It's the first time I see this code, and I'm not sure how to treat it. I don't know if the analyzer is right in pointing out the call of the tolower function. The return value of the tolower function typically must be used, but I don't know what version of it exactly is called here. So, I'm just pointing this code out to the developers for them to check it.

Hardcore

This is where, I believe, the most interesting things start.
Picture 7
_AFXCMN_INLINE int CToolBarCtrl::GetString(
  _In_ int nString,
  _Out_writes_to_(cchMaxLen, return + 1) LPTSTR lpstrString,
  _In_ size_t cchMaxLen) const
{
  ASSERT(::IsWindow(m_hWnd));
  return (int) ::SendMessage(m_hWnd, ...., (LPARAM)lpstrString);
  lpstrString[cchMaxLen]=_T('\0');
}
PVS-Studio diagnostic message: V779 Unreachable code detected. It is possible that an error is present. afxcmn2.inl 111
This is an obvious bug: the last line of the function never executes.
The next fragment contains a highly suspicious call of the return statement inside a loop body:
HRESULT GetIndexOfPropertyInSet(
  _In_ const GUID* pPropSet,
  _In_ DBPROPID dwPropertyId,
  _Out_ ULONG* piCurPropId,
  _Out_ ULONG* piCurSet)
{
  HRESULT hr = GetIndexofPropSet(pPropSet, piCurSet);
  if (hr == S_FALSE)
    return hr;
  UPROPINFO* pUPropInfo = m_pUPropSet[*piCurSet].pUPropInfo;
  for(ULONG ul=0; ul<m_pUPropSet[*piCurSet].cUPropInfo; ul++)
  {
    if( dwPropertyId == pUPropInfo[ul].dwPropId )
      *piCurPropId = ul;
    return S_OK;
  }

  return S_FALSE;
}
PVS-Studio diagnostic message: V612 An unconditional 'return' within a loop. atldb.h 4837
Why implement a loop if it can't iterate more than once anyway? The code looks like it could be simplified, but I suspect it needs some bug fixing instead. It seems that there are braces missing here and the function should actually look as follows:
HRESULT GetIndexOfPropertyInSet(
  _In_ const GUID* pPropSet,
  _In_ DBPROPID dwPropertyId,
  _Out_ ULONG* piCurPropId,
  _Out_ ULONG* piCurSet)
{
  HRESULT hr = GetIndexofPropSet(pPropSet, piCurSet);
  if (hr == S_FALSE)
    return hr;
  UPROPINFO* pUPropInfo = m_pUPropSet[*piCurSet].pUPropInfo;
  for(ULONG ul=0; ul<m_pUPropSet[*piCurSet].cUPropInfo; ul++)
  {
    if( dwPropertyId == pUPropInfo[ul].dwPropId )
    {
      *piCurPropId = ul;
      return S_OK;
    }
  }
  return S_FALSE;
}
Besides that loop discussed above, there are a couple of break statements breaking loops all the time:
  • V612 An unconditional 'break' within a loop. viewprev.cpp 476
  • V612 An unconditional 'break' within a loop. iomanip 489
Now let's talk about Copy-Paste. One can't write a big software project without making a heap of mistakes dealing with text copy-and-pasting.
Try to spot the bug in the example below by yourself, without reading my comment.
void CPaneContainerManager::RemoveAllPanesAndPaneDividers()
{
  ASSERT_VALID(this);
  POSITION pos = NULL;

  for (pos = m_lstControlBars.GetHeadPosition(); pos != NULL;)
  {
    POSITION posSave = pos;
    CBasePane* pWnd = DYNAMIC_DOWNCAST(
      CBasePane, m_lstControlBars.GetNext(pos));
    ASSERT_VALID(pWnd);

    if (pWnd->IsPaneVisible())
    {
      m_lstControlBars.RemoveAt(posSave);
    }
  }

  for (pos = m_lstSliders.GetHeadPosition(); pos != NULL;)
  {
    POSITION posSave = pos;
    CBasePane* pWnd = DYNAMIC_DOWNCAST(
      CBasePane, m_lstControlBars.GetNext(pos));
    ASSERT_VALID(pWnd);

    if (pWnd->IsPaneVisible())
    {
      m_lstSliders.RemoveAt(posSave);
    }
  }
}
Picture 3
Have you found it?
I bet many of you gave up and scrolled on. It's a nice example of why static analyzers are so important and needed: they never get lazy or tired.
PVS-Studio diagnostic message: V778 Two similar code fragments were found. Perhaps, this is a typo and 'm_lstSliders' variable should be used instead of 'm_lstControlBars'. afxpanecontainermanager.cpp 1645
However, finding the bug hasn't become much easier even after reading the analyzer's warning. Here's an abridged version with only the key lines left:
for (... m_lstControlBars ...)
{
  CBasePane* pWnd = ... m_lstControlBars ...
  m_lstControlBars.RemoveAt();
}

for (... m_lstSliders ...)
{
  CBasePane* pWnd = ... m_lstControlBars ...
  m_lstSliders.RemoveAt();
}
Container m_lstControlBars is handled in the first loop, and container m_lstSliders, in the second.
There's almost no doubt that the second loop was written using the Copy-Paste technique: the programmer took the first loop, copied it, and then changed all the instances of the name m_lstControlBars to m_lstSliders. All but one!
The mistake is here: CBasePane* pWnd = ... m_lstControlBars ...
It's a nice bug but the next one is just as cool. Let's check how increment/decrement operators are implemented in the CMFCScanliner class:
class CMFCScanliner
{
  ....
  inline  const CMFCScanliner& operator ++ ()
  {
    m_line += m_offset;
    return *this;
  }

  inline  const CMFCScanliner& operator ++ (int)
  {
    m_line += m_offset;
    return *this;
  }

  inline  const CMFCScanliner& operator -- ()
  {
    m_line -= m_offset;
    return *this;
  }

  inline  const CMFCScanliner& operator -- (int)
  {
    m_line += m_offset;
    return *this;
  }
  ....
};
PVS-Studio diagnostic message: V524 It is odd that the body of '--' function is fully equivalent to the body of '++' function. afxtoolbarimages.cpp 656
Note how the very last operator is implemented: the programmer forgot to change += to -=. It's a classic! It's the "last line effect" in all its glory!
The analyzer found three spots where leaks might occur. This is one of them:
CSpinButtonCtrl* CMFCPropertyGridProperty::CreateSpinControl(
  CRect rectSpin)
{
  ASSERT_VALID(this);
  ASSERT_VALID(m_pWndList);

  CSpinButtonCtrl* pWndSpin = new CMFCSpinButtonCtrl;

  if (!pWndSpin->Create(WS_CHILD | WS_VISIBLE | UDS_ARROWKEYS |
                        UDS_SETBUDDYINT | UDS_NOTHOUSANDS,
                        rectSpin, m_pWndList,
                        AFX_PROPLIST_ID_INPLACE))
  {
    return NULL;
  }
  ....
}
PVS-Studio diagnostic message: V773 The function was exited without releasing the 'pWndSpin' pointer. A memory leak is possible. afxpropertygridctrl.cpp 1490
If an error occurs while executing the Create function, the object the pointer to which is stored in the pWndSpin variable won't be deleted.
The other cases:
  • V773 The function was exited without releasing the 'pList' pointer. A memory leak is possible. afxribboncombobox.cpp 461
  • V773 The function was exited without releasing the 'pButton' pointer. A memory leak is possible. afxvslistbox.cpp 222
As specified by the C++ standard, calling the delete operator on a pointer of type void* is undefined behavior. As you have already guessed, that's what happens in the Visual C++ libraries:
typedef void *PVOID;
typedef PVOID PSECURITY_DESCRIPTOR;

class CSecurityDescriptor
{
  ....
  PSECURITY_DESCRIPTOR m_pSD;
  ....
};

inline CSecurityDescriptor::~CSecurityDescriptor()
{
  delete m_pSD;        // <= void *m_pSD;
  free(m_pOwner);
  free(m_pGroup);
  free(m_pDACL);
  free(m_pSACL);
}
PVS-Studio diagnostic message: V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. atlcom.h 1039
Other defects of this kind:
  • V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. atlcom.h 1048
  • V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. atlcom.h 1070
  • V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. atlcom.h 1667
  • V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. afxstate.cpp 265
  • V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. dbcore.cpp 1240
  • V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. dbcore.cpp 1250
  • V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. doccore.cpp 1654
  • V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. dockstat.cpp 343
  • V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. filefind.cpp 43
  • V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. filefind.cpp 49
  • V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. sockcore.cpp 541
  • V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. winfrm.cpp 145
  • V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. winfrm.cpp 465
  • V772 Calling a 'delete' operator for a void pointer will cause undefined behavior. mapiunicodehelp.h 168
The CMFCReBar::CalcFixedLayout function gets the bStretch parameter but doesn't use it. To be more exact, 1 is explicitly written to bStretch before using it for the first time. To prove that I haven't misunderstood or missed anything, here's this function in full.
CSize CMFCReBar::CalcFixedLayout(BOOL bStretch, BOOL bHorz)
{
  ASSERT_VALID(this);
  ENSURE(::IsWindow(m_hWnd));

  // the union of the band rectangles is the total bounding rect
  int nCount = (int) DefWindowProc(RB_GETBANDCOUNT, 0, 0);
  REBARBANDINFO rbBand;
  rbBand.cbSize = m_nReBarBandInfoSize;
  int nTemp;

  // sync up hidden state of the bands
  for (nTemp = nCount; nTemp--; )
  {
    rbBand.fMask = RBBIM_CHILD|RBBIM_STYLE;
    VERIFY(DefWindowProc(RB_GETBANDINFO, nTemp,
                         (LPARAM)&rbBand));
    CPane* pBar = DYNAMIC_DOWNCAST(
      CPane, CWnd::FromHandlePermanent(rbBand.hwndChild));
    BOOL bWindowVisible;
    if (pBar != NULL)
      bWindowVisible = pBar->IsVisible();
    else
      bWindowVisible = (::GetWindowLong(
        rbBand.hwndChild, GWL_STYLE) & WS_VISIBLE) != 0;
    BOOL bBandVisible = (rbBand.fStyle & RBBS_HIDDEN) == 0;
    if (bWindowVisible != bBandVisible)
      VERIFY(DefWindowProc(RB_SHOWBAND, nTemp, bWindowVisible));
  }

  // determine bounding rect of all visible bands
  CRect rectBound; rectBound.SetRectEmpty();
  for (nTemp = nCount; nTemp--; )
  {
    rbBand.fMask = RBBIM_STYLE;
    VERIFY(DefWindowProc(RB_GETBANDINFO, nTemp,
                         (LPARAM)&rbBand));
    if ((rbBand.fStyle & RBBS_HIDDEN) == 0)
    {
      CRect rect;
      VERIFY(DefWindowProc(RB_GETRECT, nTemp, (LPARAM)&rect));
      rectBound |= rect;
    }
  }

  // add borders as part of bounding rect
  if (!rectBound.IsRectEmpty())
  {
    CRect rect; rect.SetRectEmpty();
    CalcInsideRect(rect, bHorz);
    rectBound.right -= rect.Width();
    rectBound.bottom -= rect.Height();
  }
  bStretch = 1;
  return CSize((bHorz && bStretch) ? 32767 : rectBound.Width(),
    (!bHorz && bStretch) ? 32767 : rectBound.Height());
}
PVS-Studio diagnostic message: V763 Parameter 'bStretch' is always rewritten in function body before being used. afxrebar.cpp 209
The line "bStretch = 1;" looks like someone added it for debugging purposes and forgot to delete it when it was no longer needed. Perhaps this is exactly what happened. The authors should check this strange code.
Look at the declaration of the AdjustDockingLayout function in the classes CBasePane and CDockSite.
class CBasePane : public CWnd
{
  ....
  virtual void AdjustDockingLayout(HDWP hdwp = NULL);
  ....
};

class CDockSite : public CBasePane
{
  ....
  virtual void AdjustDockingLayout();
  ....
};
PVS-Studio diagnostic message: V762 It is possible a virtual function was overridden incorrectly. See first argument of function 'AdjustDockingLayout' in derived class 'CDockSite' and base class 'CBasePane'. afxdocksite.h 94
It looks like the programmer added the argument hdwp to the function declaration in the base class at some point but forgot to do the same in the derived class. As a result, these two are different functions now.
Similar cases:
  • V762 It is possible a virtual function was overridden incorrectly. See first argument of function 'CopyState' in derived class 'CPane' and base class 'CBasePane'. afxpane.h 96
  • V762 It is possible a virtual function was overridden incorrectly. See first argument of function 'CopyState' in derived class 'CDockablePane' and base class 'CPane'. afxdockablepane.h 184
  • V762 It is possible a virtual function was overridden incorrectly. See second argument of function 'SizeToContent' in derived class 'CMFCLinkCtrl' and base class 'CMFCButton'. afxlinkctrl.h 50
  • V762 It is possible a virtual function was overridden incorrectly. See first argument of function 'RecalcLayout' in derived class 'CMFCTasksPane' and base class 'CPane'. afxtaskspane.h 287
Since we started talking about functions in classes, let's talk about virtual destructors, or more exactly, missing virtual destructors. We'll start with the CAccessToken class:
class CAccessToken
{
  ....
  mutable CRevert *m_pRevert;
};

inline bool
CAccessToken::ImpersonateLoggedOnUser() const throw(...)
{
  ....
  delete m_pRevert;
  m_pRevert = _ATL_NEW CRevertToSelf;
  ....
}
The analyzer issues the following warning: V599 The virtual destructor is not present, although the 'CRevert' class contains virtual functions. atlsecurity.h 5252
Let's figure out why it does that. We are interested in the m_pRevert member, which is a pointer to an object of type CRevert. The class is used polymorphically judging by the following code line:
m_pRevert = _ATL_NEW CRevertToSelf;
The CRevertToSelf class is derived from CRevert. Now let's look into these classes:
class CRevert
{
public:
  virtual bool Revert() throw() = 0;
};

class CRevertToSelf : public CRevert
{
public:
  bool Revert() throw()
  {
    return 0 != ::RevertToSelf();
  }
};
What is missing in this CRevert class? A virtual destructor.
We do not only add new diagnostics to PVS-Studio analyzer but also improve existing ones. For example, the V611 diagnostic has recently learned how to detect memory release issues in the cases when memory allocation and freeing are performed in different functions. This is how it works in practice.
template <class TAccessor>
class CBulkRowset : public CRowset<TAccessor>
{
  ....
  void SetRows(_In_ DBROWCOUNT nRows) throw()
  {
    if (nRows == 0)
      nRows = 10;
    if (nRows != m_nRows)
    {
      delete m_phRow;
      m_phRow = NULL;
      m_nRows = nRows;
    }
  }

  HRESULT BindFinished() throw()
  {
    m_nCurrentRows = 0;
    m_nCurrentRow  = 0;
    m_hr = S_OK;

    if (m_phRow == NULL)
    {
      m_phRow = _ATL_NEW HROW[m_nRows];
      if (m_phRow == NULL)
        return E_OUTOFMEMORY;
    }

    return S_OK;
  }
  ....
  HROW*   m_phRow;
  ....
}
PVS-Studio diagnostic message: V611 The memory was allocated using 'new T[]' operator but was released using the 'delete' operator. Consider inspecting this code. It's probably better to use 'delete [] m_phRow;'. atldbcli.h 5689
Memory is allocated in the function BindFinished using the new [] operator:
m_phRow = _ATL_NEW HROW[m_nRows];
and released in the function SetRows using the delete operator:
delete m_phRow;
The result is undefined behavior.
Now, here's a very suspicious call to the memset function. However, before we examine the faulty code, let's see how a call to that function is used in correct code.
Normal code:
void CToolTipCtrl::FillInToolInfo(TOOLINFO& ti, ....) const
{
  memset(&ti, 0, sizeof(AFX_OLDTOOLINFO));
  ti.cbSize = sizeof(AFX_OLDTOOLINFO);
  ....
}
It's a typical situation. All the structure members are cleared (filled with zeroes) by calling the memset function. After that, the size of the structure is written to it. It's a usual practice for WinAPI - this is how functions figure out which version (format) of the structure they are dealing with.
The code above is logical. The size of the structure AFX_OLDTOOLINFO is computed. Then this size is used to call the memset function, and the same size is written to the structure.
Now, here's abnormal code:
BOOL CControlBar::PreTranslateMessage(MSG* pMsg)
{
  ....
  TOOLINFO ti; memset(&ti, 0, sizeof(AFX_OLDTOOLINFO));
  ti.cbSize = sizeof(TOOLINFO);
  ....
}
PVS-Studio diagnostic message: V512 A call of the 'memset' function will lead to underflow of the buffer '& ti'. barcore.cpp 384
The structure is of type TOOLINFO, and it is the size of the TOOLINFO structure that gets written to it: ti.cbSize = sizeof(TOOLINFO);.
However, the structure is cleared only partially since the number of bytes to be cleared is computed according to the sizeof(AFX_OLDTOOLINFO) expression.
As a result, some members of the structure remain uninitialized.
There is one more case of a structure incompletely filled by memset.
GUID m_Id;
void zInternalStart()
{
  ....
  // Zero the activity id in case we end up logging the stop.
  ZeroMemory(&m_Id, sizeof(&m_Id));
  ....
}
PVS-Studio diagnostic message: V512 A call of the 'memset' function will lead to underflow of the buffer '& m_Id'. traceloggingactivity.h 656
Computing the pointer size instead of the structure size is a classic bug, which leads to clearing only the first 4 or 8 bytes depending on whether the application is compiled as 32-bit or 64-bit, while the GUID structure's size is 16 bytes (128 bits).
Fixed version:
ZeroMemory(&m_Id, sizeof(m_Id));
There were a few V595 warnings too, which is not surprising since this diagnostic detects one of the most widespread bugs in C and C++ programs. However, those written in C# are not perfect either.
This error is about a pointer being dereferenced before the check.
Look at the following code fragment.
HRESULT CBasePane::get_accHelp(VARIANT varChild, BSTR *pszHelp)
{
  if ((varChild.vt == VT_I4) && (varChild.lVal == CHILDID_SELF))
  {
    *pszHelp = SysAllocString(L"ControlPane");
    return S_OK;
  }

  if (((varChild.vt != VT_I4) && (varChild.lVal != CHILDID_SELF))
      || (NULL == pszHelp))
  {
    return E_INVALIDARG;
  }
  ....
}
PVS-Studio diagnostic message: V595 The 'pszHelp' pointer was utilized before it was verified against nullptr. Check lines: 1324, 1328. afxbasepane.cpp 1324
If you call the function in the following way:
VARIANT foo;
foo.vt = VT_I4;
foo.lVal = CHILDID_SELF;
get_accHelp(foo, NULL);
it must return the E_INVALIDARG status, but a null pointer deference will occur instead.
This is the way of the analyzer's "thought". "The pointer is dereferenced, but it is checked for NULL later. Since there is such a check, the pointer might be null. If it really is, that's bad. Aha, I should warn about this!"
As I have already said, this error is found in many applications, and the Visual C++ libraries are no exception. Here are 17 more fragments that need refactoring: vs2017_V595.txt.
The last bug I'd like to discuss deals with mixing up the constants FALSE and S_FALSE.
BOOL CMFCRibbonPanel::OnSetAccData (long lVal)
{
  ....
  if (nIndex < 0 || nIndex >= arElements.GetSize())
  {
    return FALSE;
  }

  if (GetParentWnd()->GetSafeHwnd() == NULL)
  {
    return S_FALSE;
  }

  ASSERT_VALID(arElements[nIndex]);
  return arElements[nIndex]->SetACCData(GetParentWnd(), m_AccData);
}
PVS-Studio diagnostic message: V716 Suspicious type conversion in return statement: returned HRESULT, but function actually returns BOOL. afxribbonpanel.cpp 4107
The function returns the type BOOL. For the case when HWND can't be obtained from the parent window, the programmer wanted the function to return the value FALSE but made a typo and wrote S_FALSE instead, which drastically changes the statement's meaning.
This is how the S_FALSE constant is declared:
#define S_FALSE ((HRESULT)1L)
You've probably guessed already what happens, but I shall explain just in case.
Writing "return S_FALSE;" is the same thing as writing "return TRUE;". Epic fail.
This error is not alone, it has a few friends:
  • V716 Suspicious type conversion in return statement: returned HRESULT, but function actually returns BOOL. afxribbonbar.cpp 5623
  • V716 Suspicious type conversion in return statement: returned HRESULT, but function actually returns BOOL. afxribbonbar.cpp 5627
  • V716 Suspicious type conversion in return statement: returned HRESULT, but function actually returns BOOL. ctlnownd.cpp 349
  • V716 Suspicious type conversion in return statement: returned HRESULT, but function actually returns BOOL. olecli2.cpp 548

Note

As I already said in the beginning, not all of the files were checked. More than that, I could have missed something among those warnings the analyzer did issue. So, I'm asking the developers not to view this paper as a manual on fixing some of the bugs. It would be much better if you checked the libraries yourselves and closely examined the analyzer warnings.

Conclusion

Picture 4
This is just one more time that I managed to demonstrate how useful static analysis tools can be.
Please beware of one mistake. I hear every now and then that some programmers run static analyzers on their code before releasing. If you know someone who does that and finds it normal, know that they are very, very wrong, so please set them back on the right track. It's the most erroneous way of using static analyzers. It's just like keeping all compiler warnings disabled while working on a project and enabling them just before the release.
You are all welcome to download PVS-Studio demo version and try it on your projects.
Supported languages and compilers:
  • Windows. Visual Studio 2017 C, C++, C++/CLI, C++/CX (WinRT), C#
  • Windows. Visual Studio 2015 C, C++, C++/CLI, C++/CX (WinRT), C#
  • Windows. Visual Studio 2013 C, C++, C++/CLI, C++/CX (WinRT), C#
  • Windows. Visual Studio 2012 C, C++, C++/CLI, C++/CX (WinRT), C#
  • Windows. Visual Studio 2010 C, C++, C++/CLI, C#
  • Windows. MinGW C, C++
  • Windows/Linux. Clang C, C++
  • Linux. GCC C, C++

Thanks for reading; follow me on Twitter: @Code_Analysis.