Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Products Showcase (http://www.go4expert.com/articles/products-showcase/)
-   -   PVS-Studio Tutorial (http://www.go4expert.com/articles/pvs-studio-tutorial-t18708/)

Karpov2007 27Jul2009 11:33

PVS-Studio Tutorial
 
Abstract
Introduction
Purpose, abilities and system requirements of PVS-Studio
Installation of PVS-Studio
Getting acquainted with PVS-Studio
Correction of errors
Working with the list of diagnostic warnings
Should all the potential errors detected by the analyzer be corrected?
References

Abstract



The article is a tutorial on operating PVS-Studio code analyzer. You will learn about the basic abilities of PVS-Studio, the principles of working with the tool and also about the peculiarities of analyzing the code of applications of some types.

Introduction



PVS-Studio is a static code analyzer intended for developers of modern resource-intensive C and C++ applications. By modern applications we understand 64-bit and/or parallel applications. Development of such programs involves some difficulties different from the problems you face when developing conventional programs. For besides usual errors known to everybody like uninitialized pointers, access out of an array's limits and other code defects, which are detected by any compiler, there are new types of problems.

http://www.go4expert.com/images/arti...utorial/01.png
Figure 1 - PVS-Studio code analyzer's logo

We speak about the errors in programs which occur when porting 32-bit applications on 64-bit platforms or paralleling the code to provide support of multi-processor or multi-core mode. It is rather difficult to develop such applications because of lack of tools which could simplify creation of 64-bit and parallel programs. PVS-Studio analyzer is quite a tool for this purpose!
Although PVS-Studio code analyzer is in itself rather simple, still you should understand the principles and technology of static code analysis to use it more efficiently. After reading this article and examining the examples described in it, you will be able to use PVS-Studio in your everyday work.

Purpose, abilities and system requirements of PVS-Studio



The static code analyzer PVS-Studio is intended for developers of modern resource-intensive C and C++ applications. At present, PVS-Studio includes two units:
  • Viva64 is a subsystem of diagnosing errors characteristic of 64-bit systems;
  • VivaMP is a subsystem of diagnosing errors in parallel programs built on OpenMP technology.

With the help of these two units PVS-Studio allows you to detect in the source code of C and C++ programs the following types of defects:
  • errors of migration of 32-bit applications on 64-bit systems
  • errors occurring when developing new 64-bit applications
  • non-optimal use of memory in 64-bit programs due to alignment peculiarities;
  • errors in parallel programs relating to insufficient knowledge of OpenMP directives' syntax;
  • errors in parallel programs relating to insufficient knowledge of the principles of paralleling code using OpenMP technology;
  • errors of incorrect memory operation in parallel code (unprotected main memory access, absence of synchronization, incorrect mode of access to variables etc)

PVS-Studio analyzer is intended for working on Windows-platform. It integrates into Microsoft Visual Studio 2005/2008 development environment. The system requirements to the analyzer coincide with the requirements to Microsoft Visual Studio:
  • Operation System: Windows 2000/XP/2003/Vista/2008 x86 or x64. Attention: to analyze 64-bit applications it is not necessary to have a 64-bit operation system.
  • Development environment: Microsoft Visual Studio 2005/2008 (Standard Edition, Professional Edition, Team Systems). To analyze 64-bit applications you must have a component of Visual Studio "X64 Compilers and Tools" installed. It is included into all the listed versions of Visual Studio and can be installed through Visual Studio Setup. Pay attention that PVS-Studio cannot operate Visual C++ Express Edition for this system does not support extension units.
  • Hardware: PVS-Studio operates on systems with no less than 1 Gb of main memory (it is recommended that you have 2 Gb and more); the analyzer can work at several cores (the more cores, the faster code analysis).

Installation of PVS-Studio



After getting PVS-Studio installation package you can begin installing the program. Fortunately, this is quite a simple procedure and the installer asks no tricky questions.

http://www.go4expert.com/images/arti...utorial/02.png
Figure 2 - Installation of PVS-Studio

During installation, the code analyzer will integrate into Microsoft Visual Studio. In case you have only one version of Microsoft Visual Studio (for example, only 2005 or 2008) installed on your computer the analyzer will integrate only into it. If you have several versions, it will integrate into all of them. It is detected automatically.

Besides, PVS-Studio Help system will integrate into MSDN. PVS-Studio has a very good Help system which contains descriptions of all the diagnostic warnings of the analyzer with examples of code defects and ways to correct them. Besides, it also describes all the settings with the help of which you can achieve better diagnosis in PVS-Studio.

When installation of PVS-Studio is complete you can make sure that it has been installed correctly. For this launch Microsoft Visual Studio and in the start window you will see the logo of PVS-Studio (Figure 3).

http://www.go4expert.com/images/arti...utorial/03.png
Figure 3 - Microsoft Visual Studio start window with PVS-Studio logo

Although you can begin working at once, we recommend that you install two additional examples of source codes PortSample and ParallelSample (Figure 4) from PVS-Studio\Issues Examples menu.

http://www.go4expert.com/images/arti...utorial/04.png
Figure 4 - Installation of additional examples of errors PortSample and ParallelSample

With the help of these examples you can get acquainted in practice with the defects which are characteristic of modern software. PortSample contains examples of problems occurring when porting software from 32-bit systems on 64-bit ones. ParallelSample allows you to see in practice what you can expect from parallel programs containing "parallel" errors.

These examples (PortSample and ParallelSample) should be installed because the further description in this article will be based on them.

Getting acquainted with PVS-Studio



After installing the examples PortSample and ParallelSample you can start examining PVS-Studio. Open PortSample (vs2008) project in Microsoft Visual Studio 2008 although you can do the same in Microsoft Visual Studio 2005 (Figure 5).

http://www.go4expert.com/images/arti...utorial/05.png
Figure 5 - Selection of PortSample demo-project

You should begin working with PVS-Studio with one of our demo-projects due to some reasons:
  • firstly, they cover all the code defects diagnosed by PVS-Studio;
  • secondly, you can watch behavior of an application with an error in a real example;
  • thirdly, PVS-Studio demo-version shows location only of some of the defects and errors in the code (although it detects them all). But for PortSample and ParallelSample we have made an exception - for them all the defects are shown.

So, open PortSample project, select 64-bit configuration x64 to check presence of defects in 64-bit code, with the help of PVS-Studio command bar select analysis of 64-bit problems - Viva64 unit "64-bit issues (Viva64)" and launch analysis of the whole solution by the command "Check Solution". All this is shown on Figure 6.

http://www.go4expert.com/images/arti...utorial/06.png
Figure 6 - Check of PortSample solution on presence of 64-bit problems

x64 configuration is chosen deliberately. You can check only the 64-bit configuration on 64-bit code problems. The point is that the project's settings in the 64-bit configuration are different from those of the 32-bit one. So you cannot perform check of 64-bit code in the 32-bit configuration.

After launching analysis, you will see a progress indicator with Pause (pause analysis) and Stop (stop analysis) buttons on the screen. Potentially unsafe constructions detected during analysis will be printed in the window of detected defects (Figure 7).

http://www.go4expert.com/images/arti...utorial/07.png
Figure 7 - Analysis of the project - problems detected in the code are printed in the window at once

The term "potentially unsafe construction" means that the analyzer considered some particular code line a defect. But only the programmer who knows the application can determine if this line is really a defect of the application or not. This principle of working with code analyzers must be understood correctly. Generally, no tool can replace a programmer completely when solving the task of correcting errors in programs. Only a programmer can do it relying on his knowledge. But a tool can and must help the programmer in this task. That's why a code analyzer's task is to reduce the number of places in the code which the programmer must look through and investigate.

But let's return to PVS-Studio analyzer. Analysis of the whole code is complete and now you can start looking through the messages. By the way, if you have a multi-core processor analysis will be performed faster for all the cores will be used.

Correction of errors



After getting a list of diagnostic warnings from the code analyzer, you can study it. Let's consider the first error:
Code: cpp

V101: Implicit assignment type conversion to memsize type. v1xx.cpp 34

Here is its code:
Code: cpp

size_t bufferSize = imageWidth * imageHeght *
                      bytePerPixel * maxFrameCountInBuffer;

The problem here is that the resulting size of the buffer (bufferSize variable) has the right size size_t but the variables participating in the expression (imageWidth, imageHeight, bytePerPixel and maxFrameCountInBuffer) have int type. The result of multiplication of these variables has also int type. It is not crucial for values less than 2 Gb for type conversion takes place. But if you get a result more than 2 Gb it will be cut to 2 Gb despite that bufferSize variable has a right type. To correct this error you should change the type of the variables participating in the expression. You can do this in a preciding code section. Instead of:
Code: cpp

unsigned imageWidth = 1000;
  unsigned imageHeght = 1000;
  unsigned bytePerPixel = 3;
  unsigned maxFrameCountInBuffer;

let's write:
Code: cpp

size_t imageWidth = 1000;
  size_t imageHeght = 1000;
  size_t bytePerPixel = 3;
  size_t maxFrameCountInBuffer;

You can learn about this correction from the Help system. After pressing F1 (with mouse or F4 button) when studying a new error, the MSDN window will open with the description of the error:

http://www.go4expert.com/images/arti...utorial/08.png
Figure 8 - Detailed description of the error and the ways to correct it are given in MSDN

After correcting the used data types let's relaunch analysis. You will see that the number of diagnostic warnings is less in one. It means that the problem is corrected. In the same way you should deal with all the diagnostic warnings and correct those places in the code where there are possible problems.

Working with the list of diagnostic warnings



Of course, in large real projects there will be not some tens of diagnostic warnings, but hundreds or even thousands of them. And looking through all of them is not a simple task. To simplify it PVS-Studio has several mechanisms. The first is filtration of warnings by the code of an error. The second is filtration by the content of the text of a diagnostic warning. The third is filtration by the paths to files. Let's consider the examples of using filtration systems.

Suppose you be sure that diagnostic messages with V112 code (using magic numbers) are not relevant to your application. In this case you may turn off showing of these diagnostic warnings with the help of the code analyzer's settings:

http://www.go4expert.com/images/arti...utorial/09.png
Figure 9 - Turning off some diagnostic warnings by the code

After that all the warnings with V112 code will disappear from the list of warnings. And you do not need to relaunch analysis for this. If you turn on these warnings they will appear in the list again without relaunching analysis.

Now let's consider another variant of filtration on the basis of the text of diagnostic warnings. Let's get back to PortSample example. One of the errors in this example is access to the array 'array' using an index of int type:
Code: cpp

V108: Incorrect index type for "array". Use memsize type instead.  v1xx.cpp 183

Here is the code:
Code: cpp

volatile int index = 0;
  for (size_t i = 0; i != n; ++i) {
    array[index++] = 1; // error
    if (array[i] != 1)
      throw CString("x64 portability issues");
  }

Of course, you may just change the type of index variable from unsigned to size_t and the problem will disappear. But if there are a lot of code sections with access to array variable and you are sure that there are not more than 2 billions of items in array, you may "ask" the code analyzer not to show the warnings whose text contains the word 'array'. You can do this with the help of the settings on MessageSupression page:

http://www.go4expert.com/images/arti...utorial/10.png
Figure 10 - Turning off some diagnostic warnings by the text

After that all the diagnostic warnings whose text contains the word 'array' will disappear from the list without relaunching the code analyzer. You can get them back by simply removing the word 'array' from the filter.

The last mechanism of reducing the number of diagnostic warnings is filtration on the basis of the paths to the project's files.

Suppose your project use Boost library. Of course, the analyzer will warn about potential problems in this library as well. But if you are sure that these warnings should not be considered you may simply add the path to the folder with Boost on ExcludeFromAnalysis page:

http://www.go4expert.com/images/arti...utorial/11.png
Figure 11 - Setting filtration of messages by files' names

After that the diagnostic warnings relating to the files in this folder will not be shown. This option requires relaunching the code analyzer.

There are also many other means to handle diagnostic warnings to be shown by setting the code analyzer but they lay beyond consideration in this document. We recommend that you refer to the documentation on the code analyzer's settings.

Should all the potential errors detected by the analyzer be corrected?



Having looked through all the warnings shown by the code analyzer you will find both real errors in programs and constructions that are not errors. The point is that the analyzer cannot detect all the errors in programs 100% accurately without the so called "false responses". Only the programmer who knows and understands the program can determine if there is an error in a particular place. The code analyzer can only significantly reduce the number of sections which must be looked through by the developer.

Thus, of course, there is no sense in trying to correct all the potential problems detected by the code analyzer.

But you should try to correct as many code sections as you can. It is especially relevant when the static analyzer is used not once just to verify an application when, for example, porting it on a 64-bit system, but regularly with the purpose to detect new errors and insufficient constructions. In this case correction of sections which are actually not errors, and also setting of the analyzer to suppress some types of errors will allow you to significantly save on time when using the analyzer next time.

References


  1. Andrey Karpov, Evgeniy Ryzhkov. 20 issues of porting C++ code on the 64-bit platform. http://www.viva64.com/art-1-2-599168895.html
  2. Alexey Kolosov, Andrey Karpov, Evgeniy Ryzhkov. 32 OpenMP traps for C++ developers. http://www.viva64.com/art-3-2-1023467288.html
  3. Andrey Karpov. Optimization of 64-bit programs. http://www.viva64.com/art-1-2-1756520624.html
  4. Andrey Karpov. Seven Steps of Migrating a Program to a 64-bit System. http://www.viva64.com/art-1-2-850243650.html
  5. Andrey Karpov. Parallel Lint. http://www.viva64.com/art-3-2-809480710.html


All times are GMT +5.5. The time now is 11:34.