The Chromium browser is developing very fast. When we checked the solution for the first time in 2011, it included 473 projects. Now it includes 1169 projects. We were curious to know if Google developers had managed to keep the highest quality of their code with Chromium developing at such a fast rate. Well, they had.
Heading for a Record: Chromium, the 5th CheckPVS-Studio
We checked Chromium more than once before, and those who follow our blog could reasonably ask, "Why another check? Weren't there enough of them?" Sure, Chromium's source code is particularly clean, which was shown by each of the previous checks, but new errors inevitably continue to appear. Repeated checks prove that the more often you use static analysis, the better. A good practice is to use the analyzer every day. An even better practice is to analyze the new code right after you finish writing it (automatic analysis of recently modified code).
OpenCV is a library of computer vision algorithms, picture processing algorithms, and general-purpose numerical algorithms. The library is written in C/C++ and is free both for academic and commercial use, as it is distributed under the BSD license. The time has come to check this library with the PVS-Studio code analyzer.
To measure the efficiency of our analyzer, and also to promote the methodology of static analysis, we regularly analyze open source projects for bugs and write articles about the results. 2016 was no exception. This year is especially important as it is the year of the "growth" of the C# analyzer. PVS-Studio has obtained a large number of new C# diagnostics, an improved virtual values mechanism (symbolic execution) and much more. Based on the results of our teamwork, I compiled a kind of chart of the most interesting bugs, found in various C# projects in 2016.
After hot discussions on the article about "The Big Calculator" I felt like checking some other projects related to scientific computations. The first program that came to hand was the open-source project OpenMS dealing with protein mass spectrometry. This project appeared to have been written in a very serious and responsible way. Developers use at least Cppcheck to analyze their project. That's why I didn't hope to find anything sensational left unnoticed by that tool. On the other hand, I was curious to see what bugs PVS-Studio would be able to find in the code after Cppcheck. If you want to know this too, follow me.
Date Processing Attracts Bugs or 77 Defects in Qt 6Andrey Karpov
The recent Qt 6 release compelled us to recheck the framework with PVS-Studio. In this article, we reviewed various interesting errors we found, for example, those related to processing dates. The errors we discovered prove that developers can greatly benefit from regularly checking their projects with tools like PVS-Studio.
One of the Microsoft development teams already uses PVS-Studio analyzer in their work. It's great, but it's not enough. That's why I keep demonstrating how static code analysis could benefit developers, using Microsoft projects as examples. We scanned Casablanca project three years ago and found nothing. As a tribute to its high quality, the project was awarded with a "bugless code" medal. As time went by, Casablanca developed and grew. PVS-Studio's capabilities, too, have significantly improved, and now I've finally got the opportunity to write an article about errors found by the analyzer in Casablanca project (C++ REST SDK). These errors are few, but the fact that their number is still big enough for me to make this article, does speak a lot in favor of PVS-Studio's effectiveness.
Source code of WPF samples by Microsoft was checkedPVS-Studio
To let people know about PVS-Studio, which is now able to check not only C++ projects, but C# as well, we decided to check the source code of WPF examples, offered by Microsoft.
We Continue Exploring Tizen: C# Components Proved to be of High QualityPVS-Studio
This time I go back again to the check of the Tizen project. In my recent post "Experiment of Bug Detection in the Code of C #Components of Tizen" in our blog, I analyzed the code of C# superficially and came to a conclusion that it makes sense to check the whole code of C# components of this project for errors using PVS-Studio and write the article about it. Right away, I would like to share with you the results of the work that I have done. I shall tell at once that PVS-Studio analyzer showed itself not on the bright side on C# code. Anyway, first things first: let's see what the analyzer found, and then we will deal with statistics and make conclusions.
Heading for a Record: Chromium, the 5th CheckPVS-Studio
We checked Chromium more than once before, and those who follow our blog could reasonably ask, "Why another check? Weren't there enough of them?" Sure, Chromium's source code is particularly clean, which was shown by each of the previous checks, but new errors inevitably continue to appear. Repeated checks prove that the more often you use static analysis, the better. A good practice is to use the analyzer every day. An even better practice is to analyze the new code right after you finish writing it (automatic analysis of recently modified code).
OpenCV is a library of computer vision algorithms, picture processing algorithms, and general-purpose numerical algorithms. The library is written in C/C++ and is free both for academic and commercial use, as it is distributed under the BSD license. The time has come to check this library with the PVS-Studio code analyzer.
To measure the efficiency of our analyzer, and also to promote the methodology of static analysis, we regularly analyze open source projects for bugs and write articles about the results. 2016 was no exception. This year is especially important as it is the year of the "growth" of the C# analyzer. PVS-Studio has obtained a large number of new C# diagnostics, an improved virtual values mechanism (symbolic execution) and much more. Based on the results of our teamwork, I compiled a kind of chart of the most interesting bugs, found in various C# projects in 2016.
After hot discussions on the article about "The Big Calculator" I felt like checking some other projects related to scientific computations. The first program that came to hand was the open-source project OpenMS dealing with protein mass spectrometry. This project appeared to have been written in a very serious and responsible way. Developers use at least Cppcheck to analyze their project. That's why I didn't hope to find anything sensational left unnoticed by that tool. On the other hand, I was curious to see what bugs PVS-Studio would be able to find in the code after Cppcheck. If you want to know this too, follow me.
Date Processing Attracts Bugs or 77 Defects in Qt 6Andrey Karpov
The recent Qt 6 release compelled us to recheck the framework with PVS-Studio. In this article, we reviewed various interesting errors we found, for example, those related to processing dates. The errors we discovered prove that developers can greatly benefit from regularly checking their projects with tools like PVS-Studio.
One of the Microsoft development teams already uses PVS-Studio analyzer in their work. It's great, but it's not enough. That's why I keep demonstrating how static code analysis could benefit developers, using Microsoft projects as examples. We scanned Casablanca project three years ago and found nothing. As a tribute to its high quality, the project was awarded with a "bugless code" medal. As time went by, Casablanca developed and grew. PVS-Studio's capabilities, too, have significantly improved, and now I've finally got the opportunity to write an article about errors found by the analyzer in Casablanca project (C++ REST SDK). These errors are few, but the fact that their number is still big enough for me to make this article, does speak a lot in favor of PVS-Studio's effectiveness.
Source code of WPF samples by Microsoft was checkedPVS-Studio
To let people know about PVS-Studio, which is now able to check not only C++ projects, but C# as well, we decided to check the source code of WPF examples, offered by Microsoft.
We Continue Exploring Tizen: C# Components Proved to be of High QualityPVS-Studio
This time I go back again to the check of the Tizen project. In my recent post "Experiment of Bug Detection in the Code of C #Components of Tizen" in our blog, I analyzed the code of C# superficially and came to a conclusion that it makes sense to check the whole code of C# components of this project for errors using PVS-Studio and write the article about it. Right away, I would like to share with you the results of the work that I have done. I shall tell at once that PVS-Studio analyzer showed itself not on the bright side on C# code. Anyway, first things first: let's see what the analyzer found, and then we will deal with statistics and make conclusions.
Virtual machines are important tools in the arsenal of a software developer. Being an active user of VirtualBox, and checking various open source projects with the help of it, I was personally interested in checking its source code. We did the first check of this project in 2014, and the description of 50 errors barely fit into two articles. With the release of Windows 10 and VirtualBox 5.0.XX the stability of the program got significantly worse, in my humble opinion. So, I decided to check the project again.
Dusting the globe: analysis of NASA World Wind projectPVS-Studio
Sometimes it is useful to look back to see how helpful the analyzer was to old projects, and which errors can be avoided in good time, if the analyzer is regularly used. This time our choice was NASA World Wind project, which was being developed on C# until 2007.
Every now and then, we have to write articles about how we've checked another fresh version of some compiler. That's not really much fun. However, as practice shows, if we stop doing that for a while, folks start doubting whether PVS-Studio is worth its title of a good catcher of bugs and vulnerabilities. What if the new compiler can do that too? Sure, compilers evolve, but so does PVS-Studio – and it proves, again and again, its ability to catch bugs even in high-quality projects such as compilers.
An Experiment with Checking the glibc LibraryAndrey Karpov
We have recently carried out an experiment with checking the glibc library by PVS-Studio. Its purpose was to study how good our analyzer is at checking Linux-projects. The basic conclusion is, not much good yet. Non-standard extensions used in such projects make the analyzer generate a huge pile of false positives. However, we have found some interesting bugs.
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerAndrey Karpov
We gave the TortoiseSVN developers a free registration key for some time so that they could check their project. While they haven't utilized it yet, I've decided to download the TortoiseSVN source codes and check it myself. My interest is obvious: I want to make another article to advertise PVS-Studio.
We already checked the TortoiseSVN project long ago. It was done at the same time as PVS-Studio 4.00 was released, which for the first time included diagnostic rules for general analysis.
Still Comparing "this" Pointer to Null?Andrey Karpov
This is a translation of an article written by Dmitry Meshcheryakov, an ABBYY employee and first published here: "ABBYY blog. Still Comparing "this" Pointer to Null?". Translation done and published with permission of the copyright holder.
PVS-Studio team is about to produce a technical breakthrough, but for now let...PVS-Studio
Static analysis is most useful when it is done on a regular basis. Especially when the project is rapidly developing, like the Blender project, for example. Now it's time to check it once more, and see what suspicious fragments we'll find this time.
The PVS-Studio developers' team has carried out comparison of the own static code analyzer PVS-Studio with the open-source Cppcheck static code analyzer. As a material for comparison, the source codes of the three open-source projects by id Software were chosen: Doom 3, Quake 3: Arena, Wolfenstein: Enemy Territory. The article describes the comparison methodology and lists of detected errors. The conclusions section at the end of the article contains "non-conclusions" actually, as we consciously avoid drawing any conclusions: you can reproduce our comparison and draw your own ones.
One of the programs, which allows you to solve the problem of data compression, is a popular file archiver 7-Zip, which I often use myself. Our readers have long asked us to check the code of this application. Well, it's time to look at its source code, and see what PVS-Studio is able to detect in this application.
How to Improve Visual C++ 2017 Libraries Using PVS-StudioPVS-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.
Miranda NG Project to Get the "Wild Pointers" Award (Part 1) Andrey Karpov
I have recently got to the Miranda NG project and checked it with the PVS-Studio code analyzer. And I'm afraid this is the worst project in regard to memory and pointers handling issues I've ever seen. Although I didn't study the analysis results too thoroughly, there still were so many errors that I had to split the material into 2 articles. The first of them is devoted to pointers and the second to all the rest stuff. Enjoy reading and don't forget your popcorn.
Top 10 bugs in C++ open source projects, checked in 2016PVS-Studio
While the world is discussing the 89th Ceremony of Oscar award and charts of actors and costumes, we've decided to write a review article about the IT-sphere. The article is going to cover the most interesting bugs, made in open source projects in 2016. This year was remarkable for our tool, as PVS-Studio has become available on Linux OS. The errors we present are hopefully, already fixed, but every reader can see how serious are the errors made by developers.
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' RequestPVS-Studio
In this article, I'd like to talk about the analysis of ReOpenLDAP project. It was developed to help solve issues that PAO (PJSC) MegaFon, Russia's largest mobile network operator, was faced with when employing OpenLDAP in their infrastructure. ReOpenLDAP is now successfully used in MegaFon affiliates all over Russia, so we thought it would be interesting to check such a high-load project as this one with our static analyzer PVS-Studio.
PVS-Studio delved into the FreeBSD kernelPVS-Studio
About a year ago we checked the Linux core. It was one of the most discussed articles at that time. We also got quite a number of requests to check FreeBSD, so finally we decided to take the time to do it.
Linux version of PVS-Studio couldn't help checking CodeLitePVS-Studio
As is already known to our readers, PVS-Studio static analyzer is exploring a new development direction - the Linux platform; as you may have noticed from the previous articles, it is doing well. This article shows how easily you can check a project with the help of the Linux version of the analyzer, because the simpler PVS-Studio for Linux is, the more supporters it will have. This time our choice was the CodeLite project. CodeLite was compiled and tested in Linux. Let's see what results we got.
Errors detected in the Visual C++ 2012 librariesPVS-Studio
Static code analysis is one of the error detection methodologies. We are glad that this methodology is becoming more and more popular nowadays. Visual Studio which includes static analysis as one of its many features contributes to this process to a large extent. This feature is easy to try and start using regularly. When one understands one likes static code analysis, we are glad to offer a professional analyzer PVS-Studio for the languages C/C++/C++11.
Orchard is a free, open source, community-focused Content Management System built on the ASP.NET MVC platform. Software IP management and project development governance are provided by Outercurve Foundation, a nonprofit fund.
Finding bugs in the code of LLVM project with the help of PVS-StudioPVS-Studio
About two months ago I wrote an article about the analysis of GCC using PVS-Studio. The idea of the article was as follows: GCC warnings are great, but they're not enough. It is necessary to use specialized tools for code analysis, for example, PVS-Studio. As proof of my words I showed errors that PVS-Studio was able to find the GCC code. A number of readers have noticed that the quality of the GCC code, and its diagnosis, aren't really great; while Clang compiler is up to date, of high quality, and fresh. In general Clang is awesome! Well, apparently, it's time to check LLVM project with the help of PVS-Studio.
64-bit computers have been around and well for a long time already. Most applications have 64-bit versions that can benefit from larger memory capacity and improved performance thanks to the architectural capabilities of 64-bit processors. Developing 64-bit application in C/C++ requires much attention from a programmer. There is a number of reasons for 32-bit code to fail to work properly when recompiled for the 64-bit platform. There are a lot of articles on this subject, so we will focus on some other thing. Let's find out if the new features introduced in C++11 have made 64-bit software programmers' life any better and easier.
Note. The article was originally published in Software Developer's Journal (April 25, 2014) and is published here by the editors' permission.
Virtual machines are important tools in the arsenal of a software developer. Being an active user of VirtualBox, and checking various open source projects with the help of it, I was personally interested in checking its source code. We did the first check of this project in 2014, and the description of 50 errors barely fit into two articles. With the release of Windows 10 and VirtualBox 5.0.XX the stability of the program got significantly worse, in my humble opinion. So, I decided to check the project again.
Dusting the globe: analysis of NASA World Wind projectPVS-Studio
Sometimes it is useful to look back to see how helpful the analyzer was to old projects, and which errors can be avoided in good time, if the analyzer is regularly used. This time our choice was NASA World Wind project, which was being developed on C# until 2007.
Every now and then, we have to write articles about how we've checked another fresh version of some compiler. That's not really much fun. However, as practice shows, if we stop doing that for a while, folks start doubting whether PVS-Studio is worth its title of a good catcher of bugs and vulnerabilities. What if the new compiler can do that too? Sure, compilers evolve, but so does PVS-Studio – and it proves, again and again, its ability to catch bugs even in high-quality projects such as compilers.
An Experiment with Checking the glibc LibraryAndrey Karpov
We have recently carried out an experiment with checking the glibc library by PVS-Studio. Its purpose was to study how good our analyzer is at checking Linux-projects. The basic conclusion is, not much good yet. Non-standard extensions used in such projects make the analyzer generate a huge pile of false positives. However, we have found some interesting bugs.
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerAndrey Karpov
We gave the TortoiseSVN developers a free registration key for some time so that they could check their project. While they haven't utilized it yet, I've decided to download the TortoiseSVN source codes and check it myself. My interest is obvious: I want to make another article to advertise PVS-Studio.
We already checked the TortoiseSVN project long ago. It was done at the same time as PVS-Studio 4.00 was released, which for the first time included diagnostic rules for general analysis.
Still Comparing "this" Pointer to Null?Andrey Karpov
This is a translation of an article written by Dmitry Meshcheryakov, an ABBYY employee and first published here: "ABBYY blog. Still Comparing "this" Pointer to Null?". Translation done and published with permission of the copyright holder.
PVS-Studio team is about to produce a technical breakthrough, but for now let...PVS-Studio
Static analysis is most useful when it is done on a regular basis. Especially when the project is rapidly developing, like the Blender project, for example. Now it's time to check it once more, and see what suspicious fragments we'll find this time.
The PVS-Studio developers' team has carried out comparison of the own static code analyzer PVS-Studio with the open-source Cppcheck static code analyzer. As a material for comparison, the source codes of the three open-source projects by id Software were chosen: Doom 3, Quake 3: Arena, Wolfenstein: Enemy Territory. The article describes the comparison methodology and lists of detected errors. The conclusions section at the end of the article contains "non-conclusions" actually, as we consciously avoid drawing any conclusions: you can reproduce our comparison and draw your own ones.
One of the programs, which allows you to solve the problem of data compression, is a popular file archiver 7-Zip, which I often use myself. Our readers have long asked us to check the code of this application. Well, it's time to look at its source code, and see what PVS-Studio is able to detect in this application.
How to Improve Visual C++ 2017 Libraries Using PVS-StudioPVS-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.
Miranda NG Project to Get the "Wild Pointers" Award (Part 1) Andrey Karpov
I have recently got to the Miranda NG project and checked it with the PVS-Studio code analyzer. And I'm afraid this is the worst project in regard to memory and pointers handling issues I've ever seen. Although I didn't study the analysis results too thoroughly, there still were so many errors that I had to split the material into 2 articles. The first of them is devoted to pointers and the second to all the rest stuff. Enjoy reading and don't forget your popcorn.
Top 10 bugs in C++ open source projects, checked in 2016PVS-Studio
While the world is discussing the 89th Ceremony of Oscar award and charts of actors and costumes, we've decided to write a review article about the IT-sphere. The article is going to cover the most interesting bugs, made in open source projects in 2016. This year was remarkable for our tool, as PVS-Studio has become available on Linux OS. The errors we present are hopefully, already fixed, but every reader can see how serious are the errors made by developers.
Checking the Code of LDAP-Server ReOpenLDAP on Our Readers' RequestPVS-Studio
In this article, I'd like to talk about the analysis of ReOpenLDAP project. It was developed to help solve issues that PAO (PJSC) MegaFon, Russia's largest mobile network operator, was faced with when employing OpenLDAP in their infrastructure. ReOpenLDAP is now successfully used in MegaFon affiliates all over Russia, so we thought it would be interesting to check such a high-load project as this one with our static analyzer PVS-Studio.
PVS-Studio delved into the FreeBSD kernelPVS-Studio
About a year ago we checked the Linux core. It was one of the most discussed articles at that time. We also got quite a number of requests to check FreeBSD, so finally we decided to take the time to do it.
Linux version of PVS-Studio couldn't help checking CodeLitePVS-Studio
As is already known to our readers, PVS-Studio static analyzer is exploring a new development direction - the Linux platform; as you may have noticed from the previous articles, it is doing well. This article shows how easily you can check a project with the help of the Linux version of the analyzer, because the simpler PVS-Studio for Linux is, the more supporters it will have. This time our choice was the CodeLite project. CodeLite was compiled and tested in Linux. Let's see what results we got.
Errors detected in the Visual C++ 2012 librariesPVS-Studio
Static code analysis is one of the error detection methodologies. We are glad that this methodology is becoming more and more popular nowadays. Visual Studio which includes static analysis as one of its many features contributes to this process to a large extent. This feature is easy to try and start using regularly. When one understands one likes static code analysis, we are glad to offer a professional analyzer PVS-Studio for the languages C/C++/C++11.
Orchard is a free, open source, community-focused Content Management System built on the ASP.NET MVC platform. Software IP management and project development governance are provided by Outercurve Foundation, a nonprofit fund.
Finding bugs in the code of LLVM project with the help of PVS-StudioPVS-Studio
About two months ago I wrote an article about the analysis of GCC using PVS-Studio. The idea of the article was as follows: GCC warnings are great, but they're not enough. It is necessary to use specialized tools for code analysis, for example, PVS-Studio. As proof of my words I showed errors that PVS-Studio was able to find the GCC code. A number of readers have noticed that the quality of the GCC code, and its diagnosis, aren't really great; while Clang compiler is up to date, of high quality, and fresh. In general Clang is awesome! Well, apparently, it's time to check LLVM project with the help of PVS-Studio.
64-bit computers have been around and well for a long time already. Most applications have 64-bit versions that can benefit from larger memory capacity and improved performance thanks to the architectural capabilities of 64-bit processors. Developing 64-bit application in C/C++ requires much attention from a programmer. There is a number of reasons for 32-bit code to fail to work properly when recompiled for the 64-bit platform. There are a lot of articles on this subject, so we will focus on some other thing. Let's find out if the new features introduced in C++11 have made 64-bit software programmers' life any better and easier.
Note. The article was originally published in Software Developer's Journal (April 25, 2014) and is published here by the editors' permission.
We thought of checking the Boost library long ago but were not sure if we would collect enough results to write an article. However, the wish remained. We tried to do that twice but gave up each time because we didn't know how to replace a compiler call with a PVS-Studio.exe call. Now we've got us new arms, and the third attempt has been successful. So, are there any bugs to be found in Boost?
Good has won this time. To be more exact, source codes of the Chromium project have won. Chromium is one of the best projects we have checked with PVS-Studio.
Good has won this time. To be more exact, source codes of the Chromium project have won. Chromium is one of the best projects we have checked with PVS-Studio.
We have checked the Windows 8 Driver Samples pack with our analyzer PVS-Studio and found various bugs in its samples. There is nothing horrible about it - bugs can be found everywhere, so the title of this article may sound a bit high-flown. But these particular errors may be really dangerous, as it is a usual practice for developers to use demo samples as a basis for their own projects or borrow code fragments from them.
Headache from using mathematical softwarePVS-Studio
It so happened that during some period of time I was discussing on the Internet, one would think, different topics: free alternatives of Matlab for universities and students, and finding errors in algorithms with the help of static code analysis. All these discussions were brought together by the terrible quality of the code of modern programs. In particular, it is about quality of software for mathematicians and scientists. Immediately there arises the question of the credibility to the calculations and studies conducted with the help of such programs. We will try to reflect on this topic and look for the errors.
Analyzing the Blender project with PVS-StudioPVS-Studio
We go on analyzing open source projects and making the software world better. This time we have checked the Blender 2.62 package intended for creating 3D computer graphics.
A new static analysis tool for C++ code CppCat was presented just recently. You probably heard a lot about the previous product (PVS-Studio) by the same authors. I was pretty doubtful about it then: on the one hand, static analysis is definitely a must-have methodology - things go better with than without it; on the other hand, PVS-Studio may scare users off with its hugeness, an enterprise-like character and the price, of course. I could imagine a project team of 50 developers buying it but wasn't sure about single developers or small teams of 5 developers. I remember suggesting to the PVS-Studio authors deploying "PVS as a cloud service" and sell access to it by time. But they chose to go their own way and created an abridged version at a relatively small price (which any company or even a single developer can afford).
Having checked ReactOS's code I managed to fulfill three of my wishes at once. Firstly, I had wanted for a long time to write an article on a common project. It's not interesting to check the source code of projects like Chromium: its quality is too high and a lot of resources are spent to maintain it, which are unavailable to common projects. Secondly, it's a good example to demonstrate the necessity of static analysis in a large project, especially when it is developed by a diverse and distributed team. Thirdly, I've got a confirmation that PVS-Studio is becoming even better and more useful.
We continue checking Microsoft projects: analysis of PowerShellPVS-Studio
It has become a "good tradition" for Microsoft to make their products open-source: CoreFX, .Net Compiler Platform (Roslyn), Code Contracts, MSBuild, and other projects. For us, the developers of PVS-Studio analyzer, it's an opportunity to check well-known projects, tell people (including the project authors themselves) about the bugs we find, and additionally test our analyzer. Today we are going to talk about the errors found in another project by Microsoft, PowerShell.
Re-checking the ReactOS project - a large reportPVS-Studio
The ReactOS project is rapidly developing. One of the developers participating in this project suggested that we re-analyzed the source code, as the code base is growing fast. We were glad to do that. We like this project, and we'll be happy if this article helps the developers to eliminate some bugs. Analysis was performed with the PVS-Studio 5.02 code analyzer.
Discussing Errors in Unity3D's Open-Source ComponentsPVS-Studio
Unity3D is one of the most promising and rapidly developing game engines to date. Every now and then, the developers upload new libraries and components to the official repository, many of which weren't available in as open-source projects until recently. Unfortunately, the Unity3D developer team allowed the public to dissect only some of the components, libraries, and demos employed by the project, while keeping the bulk of its code closed. In this article, we will try to find bugs and typos in those components with the help of PVS-Studio static analyzer.
An important event has taken place in the PVS-Studio analyzer's life: support of C#-code analysis was added in the latest version. As one of its developers, I couldn't but try it on some project. Reading about scanning small and little-known projects is not much interesting of course, so it had to be something popular, and I picked MonoDevelop.
The Ultimate Question of Programming, Refactoring, and EverythingAndrey Karpov
Yes, you've guessed correctly - the answer is "42". In this article you will find 42 recommendations about coding in C++ that can help a programmer avoid a lot of errors, save time and effort. The author is Andrey Karpov - technical director of "Program Verification Systems", a team of developers, working on PVS-Studio static code analyzer. Having checked a large number of open source projects, we have seen a large variety of ways to shoot yourself in the foot; there is definitely much to share with the readers. Every recommendation is given with a practical example, which proves the currentness of this question. These tips are intended for C/C++ programmers, but usually they are universal, and may be of interest for developers using other languages.
The Ultimate Question of Programming, Refactoring, and EverythingPVS-Studio
Yes, you've guessed correctly - the answer is "42". In this article you will find 42 recommendations about coding in C++ that can help a programmer avoid a lot of errors, save time and effort. The author is Andrey Karpov - technical director of "Program Verification Systems", a team of developers, working on PVS-Studio static code analyzer. Having checked a large number of open source projects, we have seen a large variety of ways to shoot yourself in the foot; there is definitely much to share with the readers. Every recommendation is given with a practical example, which proves the currentness of this question. These tips are intended for C/C++ programmers, but usually they are universal, and may be of interest for developers using other languages.
100 bugs in Open Source C/C++ projects Andrey Karpov
This article demonstrates capabilities of the static code analysis methodology. The readers are offered to study the samples of one hundred errors found in open-source projects in C/C++.
This is a second article, which focuses on usage of the PVS-Studio analyzer in cloud CI-systems. This time we'll consider the platform Azure DevOps - a cloud CI\CD solution from Microsoft. We'll be analyzing the ShareX project.
Errors that static code analysis does not find because it is not usedAndrey Karpov
Readers of our articles occasionally note that the PVS-Studio static code analyzer detects a large number of errors that are insignificant and don't affect the application. It is really so. For the most part, important bugs have already been fixed due to manual testing, user feedback, and other expensive methods. At the same time, many of these errors could have been found at the code writing stage and corrected with minimal loss of time, reputation and money. This article will provide several examples of real errors, which could have been immediately fixed, if project authors had used static code analysis.
A Check of the Open-Source Project WinSCP Developed in Embarcadero C++ BuilderAndrey Karpov
We regularly check open-source C/C++ projects, but what we check are mostly projects developed in the Visual Studio IDE. For some reason, we haven't paid much attention to the Embarcadero C++ Builder IDE. In order to improve this situation, we are going to discuss the WinSCP project I have checked recently.
P.S. C++ Builder support in PVS-Studio had been dropped after version 5.20. If you have any questions, feel free to contact our support.
In this article, we will speak about the static analysis of the doxygen documentation generator tool. This popular and widely used project, which, as its authors claim, not without reason, has become "the de facto standard tool for generating documentation from annotated C++ sources", has never been scanned by PVS-Studio before. Doxygen scans the program source code and generates the documentation relying on it. Now it's time for us to peep into its source files and see if PVS-Studio can find any interesting bugs there.
Linux Kernel, tested by the Linux-version of PVS-StudioPVS-Studio
Since the release of the publicly available Linux-version of PVS-Studio, it was just a matter of time until we would recheck the Linux kernel. It is quite a challenge for any static code analyzer to check a project written by professionals from all around the world, used by people in various fields, which is regularly checked and tested by different tools. So, what errors did we manage to find in such conditions?
The PVS-Studio team is now actively developing a static analyzer for C# code. The first version is expected by the end of 2015. And for now my task is to write a few articles to attract C# programmers' attention to our tool in advance. I've got an updated installer today, so we can now install PVS-Studio with C#-support enabled and even analyze some source code. Without further hesitation, I decided to scan whichever program I had at hand. This happened to be the Umbraco project. Of course we can't expect too much of the current version of the analyzer, but its functionality has been enough to allow me to write this small article.
Similar to PVS-Studio vs Chromium. 3-rd Check (20)
Здесь вы найдёте 60 вредных советов для программистов и пояснение, почему они вредные. Всё будет одновременно в шутку и серьёзно. Как бы глупо ни смотрелся вредный совет, он не выдуман, а подсмотрен в реальном мире программирования.
In this article, you're going to find 60 terrible coding tips — and explanations of why they are terrible. It's a fun and serious piece at the same time. No matter how terrible these tips look, they aren't fiction, they are real: we saw them all in the real programming world.
Ошибки, которые сложно заметить на code review, но которые находятся статичес...Andrey Karpov
Есть ошибки, которые легко прячутся от программистов на обзорах кода. Чаще всего они связаны с опечатками или недостаточным знанием тонких нюансах языка/библиотеки. Давайте посмотрим интересные примеры таких ошибок и как их можно выявить с помощью статического анализа. При этом анализаторы не конкурируют с обзорами кода или, например, юнит-тестами. Они отлично дополняют другие методологии борьбы с ошибками.
When should you start using PVS-Studio? What can PVS-Studio detect? Supported standards: MISRA, CWE, CERT, OWASP, AUTOSAR. What about analysis options? What about legacy code?
Двойное освобождение ресурсов. Недостижимый код. Некорректные операции сдвига. Неправильная работа с типами. Опечатки и copy-paste. Проблемы безопасности. Путаница с приоритетом операций.
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...Andrey Karpov
What is static analysis and what is it for? How does static analysis work? (Unreal Engine 4). How to introduce static analysis in your project: best practices.
Does static analysis need machine learning?Andrey Karpov
Introduction to static analysis. Existing solutions and approaches they implement. Problems and pitfalls when creating an analyzer. When learning «manually». When learning on a real large code base. Most promising approaches.
Typical errors in code on the example of C++, C#, and JavaAndrey Karpov
Objectives of this webinar
How we detected error patterns
Patterns themselves and how to avoid them:
3.1 Copy-paste and last line effect
3.2 if (A) {...} else if (A)
3.3 Errors in checks
3.4 Array index out of bounds
3.5 Operator precedence
3.6 Typos that are hard to spot
How to use static analysis properly
Conclusion
Q&A
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)Andrey Karpov
How to fight bugs in legacy code?
Should you do it at all?
What to do if there are hundreds or even thousands of errors?(that’s usually the case)
How to avoid spending a plethora of man-hours on this?
And still, how did you work with Unreal Engine?
C++ Code as Seen by a Hypercritical ReviewerAndrey Karpov
We all do code reviews. Who doesn't admit this – does it twice as often. C++ code reviewers look like a sapper. .. except that they can make a mistake more than once. But sometimes the consequences are painful . Brave code review world.
Static Code Analysis for Projects, Built on Unreal EngineAndrey Karpov
Why Do You Need Static Analysis? Detect errors early in the program development process. Get recommendations on code formatting. Check your spelling. Calculate various software metrics.
Are С and C++ Alive? Even More, IBM RPG Is! C and C++ Are Not Just for Old Systems. Are С and C++ Alive? Summary for C, C++. Embedded: C and С++ Are on the Rise.
Zero, one, two, Freddy's coming for youAndrey Karpov
This post continues the series of articles, which can well be called "horrors for developers". This time it will also touch upon a typical pattern of typos related to the usage of numbers 0, 1, 2. The language you're writing in doesn't really matter: it can be C, C++, C#, or Java. If you're using constants 0, 1, 2 or variables' names contain these numbers, most likely, Freddy will come to visit you at night. Go on, read and don't say we didn't warn you.
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
Tim Combridge from Sensible Giraffe and Salesforce Ben presents some important tips that all developers should know when dealing with Flows in Salesforce.
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?XfilesPro
Worried about document security while sharing them in Salesforce? Fret no more! Here are the top-notch security standards XfilesPro upholds to ensure strong security for your Salesforce documents while sharing with internal or external people.
To learn more, read the blog: https://www.xfilespro.com/how-does-xfilespro-make-document-sharing-secure-and-seamless-in-salesforce/
Strategies for Successful Data Migration Tools.pptxvarshanayak241
Data migration is a complex but essential task for organizations aiming to modernize their IT infrastructure and leverage new technologies. By understanding common challenges and implementing these strategies, businesses can achieve a successful migration with minimal disruption. Data Migration Tool like Ask On Data play a pivotal role in this journey, offering features that streamline the process, ensure data integrity, and maintain security. With the right approach and tools, organizations can turn the challenge of data migration into an opportunity for growth and innovation.
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Hivelance Technology
Cryptocurrency trading bots are computer programs designed to automate buying, selling, and managing cryptocurrency transactions. These bots utilize advanced algorithms and machine learning techniques to analyze market data, identify trading opportunities, and execute trades on behalf of their users. By automating the decision-making process, crypto trading bots can react to market changes faster than human traders
Hivelance, a leading provider of cryptocurrency trading bot development services, stands out as the premier choice for crypto traders and developers. Hivelance boasts a team of seasoned cryptocurrency experts and software engineers who deeply understand the crypto market and the latest trends in automated trading, Hivelance leverages the latest technologies and tools in the industry, including advanced AI and machine learning algorithms, to create highly efficient and adaptable crypto trading bots
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Modern design is crucial in today's digital environment, and this is especially true for SharePoint intranets. The design of these digital hubs is critical to user engagement and productivity enhancement. They are the cornerstone of internal collaboration and interaction within enterprises.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
PVS-Studio vs Chromium. 3-rd Check
1. PVS-Studio vs Chromium. 3-rd Check
Author: Andrey Karpov
Date: 12.08.2013
The Chromium browser is developing very fast. When we checked the solution for the first time in 2011, it
included 473 projects. Now it includes 1169 projects. We were curious to know if Google developers had
managed to keep the highest quality of their code with Chromium developing at such a fast rate. Well, they
had.
Chromium
Chromium is an open-source web browser developed by the Google company. It is used as a basis for the
Google Chrome browser. Visit the "Get the Code" page for information on downloading the solution source
codes.
Some General Information
We checked Chromium earlier and reported those checks in two articles: the first check (23.05.2011), the
second check (13.10.2011). Each time we managed to find a number of errors - this is a subtle hint about
the usefulness of code analyzers.
Currently (we downloaded the source codes in July 2013) Chromium consists of 1169 projects. The total size
of the C/C++ source code is 260 Mbytes plus 450 Mbytes more of the third-party libraries.
If you study our first analysis-report for Chromium of 2011, you will notice that the size of the third-party
libraries has not changed much since that. But the size of the project code itself has grown from 155 Mbytes
to 260 Mbytes.
Calculating the Cyclomatic Complexity Just from Curiosity
The PVS-Studio analyzer is capable of searching for functions with big cyclomatic complexity values. These
functions are usually the first candidates to be refactored. Having checked 1160 projects, I was naturally
curious to find out which of them held the record for having "the most complex function".
In Chromium, the function ValidateChunkAMD64() has the highest cyclomatic complexity (2782). However,
we had to disqualify it from the contest because it is located in the validator_x86_64.c file which is an
autogenerated one. That's a pity: it could have been an epic record-holder. I have never seen such a large
cyclomatic complexity value in my life.
Thus, the first three places go to the following functions:
1. The WebKit library. The HTMLTokenizer::nextToken() function in the file htmltokenizer.cpp.
Cyclomatic complexity is 1106.
2. 2. The Mesa library. The _mesa_glsl_lex() function in the file glsl_lexer.cc. Cyclomatic complexity is
1088.
3. The usrsctplib library (this player is unknown). The sctp_setopt() function in the file
htmltokenizer.cpp. Cyclomatic complexity is 1026.
If you have never come across cyclomatic complexity of 1000, you'd better never have to for your psychic
health's sake :). It's just too much, you know.
Code Quality
What can be said about the quality of the Chromium project's code? It is perfect as always. There are some
bugs indeed, just as in any other large project; but if you calculate their density (by dividing their number by
the code size) you'll see that it is very trifling. This is a very good code with pretty few bugs. So, we award a
medal to the Chromium developers for their clear code. The previous medal was awarded to the Casablanca
(C++ REST SDK) project by Microsoft.
Figure 1. A medal for the Chromium developers.
Along with the project code itself, I also checked the third-party libraries used by Chromium. However,
describing errors found in them is not very interesting, especially considering that I just glanced through the
report very quickly. You may think I'm a mean guy, but I'm not. I'd like to watch you studying carefully the
analysis report for all the 1169 projects. The bugs I did notice were added into our bug database. This article
describes only those errors that I found in Chromium itself (its plugins and so on).
The Chromium project being so perfect, what for should I describe its bugs at all? It's simple: I want to show
you how powerful the PVS-Studio analyzer is. Since it has managed to catch some bugs in Chromium with its
fine code, it is surely worth your attention.
The analyzer chewed up dozens of thousands of files with the total size 710 Mbytes and still survived.
Although the Chromium project is being developed by highly skilled developers and checked by various
verifying tools, PVS-Studio still managed to catch some defects. And that's an awesome achievement! And
the last thing: it took it a reasonable time (about 5 hours) to complete the analysis, as the check ran in
parallel (AMD FX-8320/3.50 GHz/eight-core processor, 16.0 GB RAM).
3. Selected Examples of Detected Bugs
I invite you to study selected code samples that caught my glance when looking through the analysis report.
I'm sure that a more thorough examination will have much more interesting results.
Noticed Bugs No. 1 - Misprints
Vector3dF
Matrix3F::SolveEigenproblem(Matrix3F* eigenvectors) const
{
// The matrix must be symmetric.
const float epsilon = std::numeric_limits<float>::epsilon();
if (std::abs(data_[M01] - data_[M10]) > epsilon ||
std::abs(data_[M02] - data_[M02]) > epsilon ||
std::abs(data_[M12] - data_[M21]) > epsilon) {
NOTREACHED();
return Vector3dF();
}
....
}
V501 There are identical sub-expressions to the left and to the right of the '-' operator: data_[M02] -
data_[M02] matrix3_f.cc 128
We need to check that a 3x3 matrix is symmetric.
Figure 2. 3x3 matrix.
To do that we should compare the following items:
• M01 and M10
• M02 and M20
• M12 and M21
The code must have been written with the use of the Copy-Paste technology, which resulted in M02 cell
being compared to itself. That's a funny matrix class.
4. Another plain misprint:
bool IsTextField(const FormFieldData& field) {
return
field.form_control_type == "text" ||
field.form_control_type == "search" ||
field.form_control_type == "tel" ||
field.form_control_type == "url" ||
field.form_control_type == "email" ||
field.form_control_type == "text";
}
V501 There are identical sub-expressions 'field.form_control_type == "text"' to the left and to the right of the
'||' operator. autocomplete_history_manager.cc 35
A comparison to the "text" string is executed twice, which is strange. One of these lines is not necessary or
there must be some other comparison instead.
Noticed Bugs No. 2 - Opposite Conditions
static void ParseRequestCookieLine(
const std::string& header_value,
ParsedRequestCookies* parsed_cookies)
{
std::string::const_iterator i = header_value.begin();
....
if (*i == '"') {
while (i != header_value.end() && *i != '"') ++i;
....
}
V637 Two opposite conditions were encountered. The second condition is always false. Check lines: 500, 501.
web_request_api_helpers.cc 500
I guess this code was intended to skip a text framed by double quotes. But it actually does nothing, as the
condition is false right away. I've written a small pseudo-code fragment to clarify the point:
5. if ( A == 'X' ) {
while ( .... && A != 'X' ) ....;
The programmer must have forgotten to move the pointer by one character, so the fixed code should look
like this:
if (*i == '"') {
++i;
while (i != header_value.end() && *i != '"') ++i;
Noticed Bugs No. 3 - Unsuccessfully Removed Items
void ShortcutsProvider::DeleteMatchesWithURLs(
const std::set<GURL>& urls)
{
std::remove_if(matches_.begin(),
matches_.end(),
RemoveMatchPredicate(urls));
listener_->OnProviderUpdate(true);
}
V530 The return value of function 'remove_if' is required to be utilized. shortcuts_provider.cc 136
To remove items from the container the function std::remove_if() is used, yet it is used incorrectly. The
function remove_if() actually removes nothing; it only shifts items to the beginning and moves the iterator
back to garbage which you need to remove manually by calling the erase() function of the container. See
also the Wikipedia-article "Erase-remove idiom" for details.
The fixed code:
matches_.erase(std::remove_if(.....), matches_.end());
Noticed Bugs No. 4 - This Eternal Mess-up with SOCKET
SOCKET in the Linux world is an integer SIGNED data type.
SOCKET in the Windows world is an integer UNSIGNED data type.
In Visual C++ header files, the SOCKET type is declared in this way:
6. typedef UINT_PTR SOCKET;
But programmers are constantly forgetting this and keep writing code like this:
class NET_EXPORT_PRIVATE TCPServerSocketWin {
....
SOCKET socket_;
....
};
int TCPServerSocketWin::Listen(....) {
....
socket_ = socket(address.GetSockAddrFamily(),
SOCK_STREAM, IPPROTO_TCP);
if (socket_ < 0) {
PLOG(ERROR) << "socket() returned an error";
return MapSystemError(WSAGetLastError());
}
....
}
V547 Expression 'socket_ < 0' is always false. Unsigned type value is never < 0. tcp_server_socket_win.cc 48
An unsigned variable is always above or equal to zero. It means that the 'socket_ < 0' check is meaningless.
If the socket fails to be opened while the program is running, this situation will be handled incorrectly.
Noticed Bugs No. 5 - Mess-up with operations ~ and !
enum FontStyle {
NORMAL = 0,
BOLD = 1,
ITALIC = 2,
UNDERLINE = 4,
};
7. void LabelButton::SetIsDefault(bool is_default) {
....
style = is_default ? style | gfx::Font::BOLD :
style & !gfx::Font::BOLD;
....
}
V564 The '&' operator is applied to bool type value. You've probably forgotten to include parentheses or
intended to use the '&&' operator. label_button.cc 131
I guess the code was intended to work in the following way:
• If the 'is_default' variable is true, the bit responsible for the BOLD type must always be set to 1.
• If the 'is_default' variable is false, the bit responsible for the BOLD type must always be set to 0.
The expression "style & !gfx::Font::BOLD", however, works quite differently than the programmer expects.
The result of the "!gfx::Font::BOLD" operation will be 'false', i.e. 0. The code above is equivalent to this one:
style = is_default ? style | gfx::Font::BOLD : 0;
For it to work correctly the '~' operation must be used:
style = is_default ? style | gfx::Font::BOLD :
style & ~gfx::Font::BOLD;
Noticed Bugs No. 6 - Temporary Objects Created in a Strange Way
base::win::ScopedComPtr<IDirect3DSurface9> scaler_scratch_surfaces_[2];
bool AcceleratedSurfaceTransformer::ResizeBilinear(
IDirect3DSurface9* src_surface, ....)
{
....
IDirect3DSurface9* read_buffer = (i == 0) ?
src_surface : scaler_scratch_surfaces_[read_buffer_index];
....
8. }
V623 Consider inspecting the '?:' operator. A temporary object of the 'ScopedComPtr' type is being created
and subsequently destroyed. Check second operand. accelerated_surface_transformer_win.cc 391
This code will hardly cause any bugs, but it is worth discussing: I suppose some programmers will discover a
new C++ trap they will find interesting.
It's all simple at first sight: depending on the condition, either the 'src_surface' pointer or one of the
'scaler_scratch_surfaces_' array's items is chosen. The array is comprised by objects of the
base::win::ScopedComPtr<IDirect3DSurface9> type which can be automatically cast to the pointer to
IDirect3DSurface9.
The devil is in the details.
The ternary operator '?:' cannot return different types depending on the conditions. Here is a simple
example to explain the point.
int A = 1;
auto X = v ? A : 2.0;
The ?: operator returns the 'double' type. Because of that, the 'X' variable will also be double. But it's not
the point. The point is that the 'A' variable will be implicitly extended to the 'double' type!
The trouble occurs if you write a thing like this:
CString s1(L"1");
wchar_t s2[] = L"2";
bool a = false;
const wchar_t *s = a ? s1 : s2;
Execution of this code fragment results in the 's' variable referring to data inside a temporary object of the
CString type. The problem is that this object will be immediately destroyed.
Now let's go back to Chromium's source code.
IDirect3DSurface9* read_buffer = (i == 0) ?
src_surface : scaler_scratch_surfaces_[read_buffer_index];
If the 'i == 0' condition is true, the next thing occurs:
• the pointer 'src_surface' is used to create a temporary object of the
base::win::ScopedComPtr<IDirect3DSurface9> type;
• the temporary object is implicitly cast to the pointer of the IDirect3DSurface9 type and put into the
read_buffer variable;
• the temporary object is destroyed.
9. I'm not familiar with the logic of the program and the ScopedComPtr class and I can't tell for sure if any
negative consequences will occur. The most probable thing is that the counter of the reference number will
be incremented in the constructor and decremented in the destructor. So, everything will be OK.
If not, you risk getting a non-valid pointer or broken reference counter.
So, even if there is no error in this particular case, I will be glad if anyone of the readers has learned
something new. As you can see, ternary operators are much more dangerous than one may think.
Here is one more suspicious fragment like the previous one:
typedef
GenericScopedHandle<HandleTraits, VerifierTraits> ScopedHandle;
DWORD HandlePolicy::DuplicateHandleProxyAction(....)
{
....
base::win::ScopedHandle remote_target_process;
....
HANDLE target_process =
remote_target_process.IsValid() ?
remote_target_process : ::GetCurrentProcess();
....
}
V623 Consider inspecting the '?:' operator. A temporary object of the 'GenericScopedHandle' type is being
created and subsequently destroyed. Check third operand. handle_policy.cc 81
Noticed Bugs No. 7 - Repeating Checks
string16 GetAccessString(HandleType handle_type,
ACCESS_MASK access) {
....
if (access & FILE_WRITE_ATTRIBUTES)
output.append(ASCIIToUTF16("tFILE_WRITE_ATTRIBUTESn"));
10. if (access & FILE_WRITE_DATA)
output.append(ASCIIToUTF16("tFILE_WRITE_DATAn"));
if (access & FILE_WRITE_EA)
output.append(ASCIIToUTF16("tFILE_WRITE_EAn"));
if (access & FILE_WRITE_EA)
output.append(ASCIIToUTF16("tFILE_WRITE_EAn"));
....
}
V581 The conditional expressions of the 'if' operators situated alongside each other are identical. Check
lines: 176, 178. handle_enumerator_win.cc 178
If the flag FILE_WRITE_EA is enabled, the string "tFILE_WRITE_EAn" will be added twice. That's very
strange.
A similar strange thing happens in the following fragment as well:
static bool PasswordFormComparator(const PasswordForm& pf1,
const PasswordForm& pf2) {
if (pf1.submit_element < pf2.submit_element)
return true;
if (pf1.username_element < pf2.username_element)
return true;
if (pf1.username_value < pf2.username_value)
return true;
if (pf1.username_value < pf2.username_value)
return true;
if (pf1.password_element < pf2.password_element)
return true;
if (pf1.password_value < pf2.password_value)
return true;
11. return false;
}
V581 The conditional expressions of the 'if' operators situated alongside each other are identical. Check
lines: 259, 261. profile_sync_service_password_unittest.cc 261
The check "pf1.username_value < pf2.username_value" is executed twice. Perhaps one string is just not
needed, but it's also probable that the programmer wanted to check something else and some different
condition is missing here.
Noticed Bugs No. 8 - One-Time Loops
ResourceProvider::ResourceId
PictureLayerImpl::ContentsResourceId() const
{
....
for (PictureLayerTilingSet::CoverageIterator iter(....);
iter;
++iter)
{
if (!*iter)
return 0;
const ManagedTileState::TileVersion& tile_version = ....;
if (....)
return 0;
if (iter.geometry_rect() != content_rect)
return 0;
return tile_version.get_resource_id();
12. }
return 0;
}
V612 An unconditional 'return' within a loop. picture_layer_impl.cc 638
Something is not right with this loop: it iterates only once. There is the unconditional operator return at the
end of the loop, which may be due to the following reasons:
• That was just the idea, which I doubt. What for did the programmer need to create a loop, an
iterator and so on?
• One of the 'return's must be replaced with 'continue'. But that's hardly as well.
• Most likely, some condition is missing before the last 'return'.
There are some other strange loops iterating only once:
scoped_ptr<ActionInfo> ActionInfo::Load(....)
{
....
for (base::ListValue::const_iterator iter = icons->begin();
iter != icons->end(); ++iter)
{
std::string path;
if (....);
return scoped_ptr<ActionInfo>();
}
result->default_icon.Add(....);
break;
}
....
}
V612 An unconditional 'break' within a loop. action_info.cc 76
13. const BluetoothServiceRecord* BluetoothDeviceWin::GetServiceRecord(
const std::string& uuid) const
{
for (ServiceRecordList::const_iterator iter =
service_record_list_.begin();
iter != service_record_list_.end();
++iter)
{
return *iter;
}
return NULL;
}
V612 An unconditional 'return' within a loop. bluetooth_device_win.cc 224
Noticed Bugs No. 9 - Uninitialized Variables
HRESULT IEEventSink::Attach(IWebBrowser2* browser) {
DCHECK(browser);
HRESULT result;
if (browser) {
web_browser2_ = browser;
FindIEProcessId();
result = DispEventAdvise(web_browser2_, &DIID_DWebBrowserEvents2);
}
return result;
}
V614 Potentially uninitialized variable 'result' used. ie_event_sink.cc 240
If the pointer 'browser' equals zero, the function will return an uninitialized variable.
14. Another code fragment:
void SavePackage::GetSaveInfo() {
....
bool skip_dir_check;
....
if (....) {
....->GetSaveDir(...., &skip_dir_check);
}
....
BrowserThread::PostTask(BrowserThread::FILE,
FROM_HERE,
base::Bind(..., skip_dir_check, ...));
}
V614 Potentially uninitialized variable 'skip_dir_check' used. Consider checking the fifth actual argument of
the 'Bind' function. save_package.cc 1326
The variable 'skip_dir_check' may remain uninitialized.
Noticed Bugs No. 10 - Code Alignment Does Not Correspond to Program Logic
void OnTraceNotification(int notification) {
if (notification & TraceLog::EVENT_WATCH_NOTIFICATION)
++event_watch_notification_;
notifications_received_ |= notification;
}
V640 The code's operational logic does not correspond with its formatting. The statement is indented to the
right, but it is always executed. It is possible that curly brackets are missing. trace_event_unittest.cc 57
When examining this code, you cannot understand whether or not curly brackets are missing here. Even if it
is correct, it should be changed a bit so that it doesn't confuse other programmers.
Here is a couple of fragments with a TOO strange code alignment:
15. • nss_memio.c 152
• nss_memio.c 184
Noticed Bugs No. 11 - Checking a Pointer after New
Many programs contain legacy code written in those old times when the 'new' operator did not throw an
exception in case of memory shortage. It used to return a null pointer instead.
Chromium is no exception in that aspect - it also has such checks. The trouble is not that these checks are
meaningless but that returning a null pointer implied performing some actions or returning certain values
by functions. Now the program logic is different because of the practice of exception generation: the code
that was given control in case of a memory allocation error now stays idle.
Have a look at this example:
static base::DictionaryValue* GetDictValueStats(
const webrtc::StatsReport& report)
{
....
DictionaryValue* dict = new base::DictionaryValue();
if (!dict)
return NULL;
dict->SetDouble("timestamp", report.timestamp);
base::ListValue* values = new base::ListValue();
if (!values) {
delete dict;
return NULL;
}
....
}
16. V668 There is no sense in testing the 'dict' pointer against null, as the memory was allocated using the 'new'
operator. The exception will be generated in the case of memory allocation error.
peer_connection_tracker.cc 164
V668 There is no sense in testing the 'values' pointer against null, as the memory was allocated using the
'new' operator. The exception will be generated in the case of memory allocation error.
peer_connection_tracker.cc 169
The first check "if (!dict) return NULL;" doesn't seem harmful. But the second check is not safe. If memory
fails to be allocated when the "new base::ListValue()" function creates an object, the exception
'std::bad_alloc' will be thrown and the GetDictValueStats() function will terminate.
As a result, this code:
if (!values) {
delete dict;
return NULL;
}
will never destroy the object whose address is stored in the 'dict' variable.
To fix the code we need to refactor it and use smart pointers.
Examine another code fragment:
bool Target::Init() {
{
....
ctx_ = new uint8_t[abi_->GetContextSize()];
if (NULL == ctx_) {
Destroy();
return false;
}
....
}
V668 There is no sense in testing the 'ctx_' pointer against null, as the memory was allocated using the
'new' operator. The exception will be generated in the case of memory allocation error. target.cc 73
17. In case of a memory allocation error, the function Destroy() won't be called.
I find this type of bugs not very much interesting to write about any further. Instead, I give you a list of other
fragments of that kind I've noticed:
• 'data' pointer. target.cc 109
• 'page_data' pointer. mock_printer.cc 229
• 'module' pointer. pepper_entrypoints.cc 39
• 'c_protocols' pointer. websocket.cc 44
• 'type_enum' pointer. pin_base_win.cc 96
• 'pin_enum' pointer. filter_base_win.cc 75
• 'port_data'. port_monitor.cc 388
• 'xcv_data' pointer. port_monitor.cc 552
• 'monitor_data'. port_monitor.cc 625
• 'sender_' pointer. crash_service.cc 221
• 'cache' pointer. crash_cache.cc 269
• 'current_browser' pointer. print_preview_dialog_controller.cc 403
• 'udp_socket' pointer. network_stats.cc 212
• 'popup_' pointer. try_chrome_dialog_view.cc 90
Noticed Bugs No. 12 - Bad Tests
Unit tests are a wonderful method of software quality enhancement. But tests themselves often have
errors, which results in their failure. Making tests for tests is just too much; so, static code analysis will be of
use in these cases. I discussed this idea in more detail in the article "How to complement TDD with static
analysis".
Below are some examples of errors I have found in tests for Chromium:
std::string TestAudioConfig::TestValidConfigs() {
....
static const uint32_t kRequestFrameCounts[] = {
PP_AUDIOMINSAMPLEFRAMECOUNT,
PP_AUDIOMAXSAMPLEFRAMECOUNT,
1024,
2048,
4096
};
18. ....
for (size_t j = 0;
j < sizeof(kRequestFrameCounts)/sizeof(kRequestFrameCounts);
j++) {
....
}
V501 There are identical sub-expressions 'sizeof (kRequestFrameCounts)' to the left and to the right of the '/'
operator. test_audio_config.cc 56
Only one test is executed in the loop. The error is this:
"sizeof(kRequestFrameCounts)/sizeof(kRequestFrameCounts)" equals one. The correct expression is
"sizeof(kRequestFrameCounts)/sizeof(kRequestFrameCounts[0])".
Another incorrect test:
void DiskCacheEntryTest::ExternalSyncIOBackground(....) {
....
scoped_refptr<net::IOBuffer> buffer1(new net::IOBuffer(kSize1));
scoped_refptr<net::IOBuffer> buffer2(new net::IOBuffer(kSize2));
....
EXPECT_EQ(0, memcmp(buffer2->data(), buffer2->data(), 10000));
....
}
V549 The first argument of 'memcmp' function is equal to the second argument. entry_unittest.cc 393
The function "memcmp()" compares the buffer to itself. This results in the test failing to perform the
necessary check. I guess the code should look like this:
EXPECT_EQ(0, memcmp(buffer1->data(), buffer2->data(), 10000));
And the next test is the one that may unexpectedly spoil the other tests:
static const int kNumPainters = 3;
static const struct {
19. const char* name;
GPUPainter* painter;
} painters[] = {
{ "CPU CSC + GPU Render", new CPUColorPainter() },
{ "GPU CSC/Render", new GPUColorWithLuminancePainter() },
};
int main(int argc, char** argv) {
....
// Run GPU painter tests.
for (int i = 0; i < kNumPainters; i++) {
scoped_ptr<GPUPainter> painter(painters[i].painter);
....
}
V557 Array overrun is possible. The value of 'i' index could reach 2. shader_bench.cc 152
The 'painters' array perhaps used to consist of three items earlier. Now it has only two, but the value of the
'kNumPainters' constant is still 3.
Here is a list of some other incorrect code fragments in tests which I find worth considering:
V579 The string function receives the pointer and its size as arguments. It is possibly a mistake. Inspect the
second argument. syncable_unittest.cc 1790
V579 The string function receives the pointer and its size as arguments. It is possibly a mistake. Inspect the
second argument. syncable_unittest.cc 1800
V579 The string function receives the pointer and its size as arguments. It is possibly a mistake. Inspect the
second argument. syncable_unittest.cc 1810
V595 The 'browser' pointer was utilized before it was verified against nullptr. Check lines: 5489, 5493.
testing_automation_provider.cc 5489
V595 The 'waiting_for_.get()' pointer was utilized before it was verified against nullptr. Check lines: 205,
222. downloads_api_unittest.cc 205
V595 The 'pNPWindow' pointer was utilized before it was verified against nullptr. Check lines: 34, 35.
plugin_windowed_test.cc 34
20. V595 The 'pNPWindow' pointer was utilized before it was verified against nullptr. Check lines: 16, 20.
plugin_window_size_test.cc 16
V595 The 'textfield_view_' pointer was utilized before it was verified against nullptr. Check lines: 182, 191.
native_textfield_views_unittest.cc 182
V595 The 'message_loop_' pointer was utilized before it was verified against nullptr. Check lines: 53, 55.
test_flash_message_loop.cc 53
Noticed Bugs No. 13 - Variadic Function
In any program many defects are found in code fragments responsible for handling errors and reacting to
incorrect input data. This is due to the fact that these fragments are difficult to test, so they are usually not.
Because of this, programs start behaving in a very intricate way, which was not planned by the programmer.
For example:
DWORD GetLastError(VOID);
void TryOpenFile(wchar_t *path, FILE *output) {
wchar_t path_expanded[MAX_PATH] = {0};
DWORD size = ::ExpandEnvironmentStrings(
path, path_expanded, MAX_PATH - 1);
if (!size) {
fprintf(output,
"[ERROR] Cannot expand "%S". Error %S.rn",
path, ::GetLastError());
}
....
}
V576 Incorrect format. Consider checking the fourth actual argument of the 'fprintf' function. The pointer to
string of wchar_t type symbols is expected. fs.cc 17
If the variable 'size' equals zero, the program tries to write a text message into a file. But this message will
most probably contain some abracadabra at the end. Moreover, this code may cause an access violation.
Writing is performed by the function fprintf() which cannot control the types of its arguments. It expects
that the last argument should be a pointer to a string. But the actual argument is a number (error code)
which will be converted into an address, and no one can predict how the program will behave after that.
21. Unnoticed Bugs
I remind you once again that I only looked through the list of warning messages and described in this article
only what caught my attention. What's more, I've shown just a part of what I've found. If I described all
those bugs, the article would become too big. And it's already big enough.
I decided not to mention many code fragments which I found of no interest to the readers. Here you are a
couple of examples to explain what I mean.
bool ManagedUserService::UserMayLoad(
const extensions::Extension* extension,
string16* error) const
{
if (extension_service &&
extension_service->GetInstalledExtension(extension->id()))
return true;
if (extension) {
bool was_installed_by_default =
extension->was_installed_by_default();
.....
}
}
V595 The 'extension' pointer was utilized before it was verified against nullptr. Check lines: 277, 280.
managed_user_service.cc 277
The pointer 'extension' gets dereferenced in the "extension->id()" expression in the beginning. After that it
is being checked for being a null pointer.
Such code fragments are usually harmless, for the pointer simply cannot be equal to zero, so the check is
meaningless. That's why I find it unreasonable to mention these fragments because I may be mistaken and
confuse a correct code for an incorrect one.
This is one more example of a diagnostic I preferred not to notice:
bool WebMClusterParser::ParseBlock(....)
{
22. int timecode = buf[1] << 8 | buf[2];
....
if (timecode & 0x8000)
timecode |= (-1 << 16);
....
}
V610 Undefined behavior. Check the shift operator '<<. The left operand '-1' is negative.
webm_cluster_parser.cc 217
Formally, a shift of a negative value leads to undefined behavior. But many compilers work stably and
behave the way the programmer expects them to. It results in the code working well and long, though it
shouldn't. I don't feel like fighting these troubles now, so I'll better skip such messages. Those of you who
want to study the issue in detail, see the article "Wade not in unknown waters - part three".
About False Positives
I am often asked the question:
You do it very cleverly citing samples of detected bugs in your articles without telling the total number of
warning messages produced by the tool. It's a usual thing with static analyzers to generate too many false
positives so that one has hard time trying to pick out real errors among them. How many false positives
does PVS-Studio generate?
I always hesitate to answer. You see, I have two opposite answers: the first is "many", the second is "few". It
all depends on how you approach to viewing the list of warning messages. I will try to explain this duality by
the example of Chromium.
The PVS-Studio analyzer has generated 3582 first-level warnings (the set of General Analysis rules) for this
project. This number is very big. Most of them are false positives. If you attack them frontally and start
examining each item of the list, you'll get bored very soon. Your impression of the tool will be awful: almost
all the warnings are false positives looking very alike. Nothing interesting. The tool is bad.
The typical mistake of a user who thinks like that is that he has not performed even minimum customization
of the tool. Yes, we try to make PVS-Studio such a tool that can be efficiently run immediately after the
setup. We try to make it in such a way that you don't have to customize anything; you just check your
project and study the list of warnings.
But sometimes it can't be done. That was the case with Chromium. It was the macro 'DVLOG' that triggered
so many false positives. This macro is responsible for logging something and is written in such a tricky way
that PVS-Studio believes it to have a bug. Since the macro is used very often in the program, I got quite
many false positives. In fact, the number of false warnings in the analysis report coincides with the number
23. of times the DVLOG macro is used; namely, it triggered about 2300 false positives under the "V501 There
are identical sub-expressions....." diagnostic.
You can suppress these warnings by adding the comment //-V:DVLOG:501 in the header file opposite to the
macro declaration.
This simple operation lets us subtract 2300 false positives from the total number of messages (3528). We
have at one instant eliminated 65% of messages. Now we don't have to waste time examining them.
It won't take you much time and effort to perform some more subtle customizations like that. As a result,
most of the false positives will be removed from the report. Customizing some diagnostics requires analysis
relaunch, while others don't. All this is described in detail in the documentation section "Suppression of
false alarms". In particular, analysis relaunch is required for diagnostics detecting errors in macros.
I hope you now understand why I have two opposite answers. It all depends on whether or not the
programmer is ready to spend just a bit of his time studying the product and ways to get rid of irrelevant
messages.
The Final Word to the Readers
Taking the opportunity, I want to send my best regards to my parents... Oh, sorry, I meant: taking the
opportunity, I want to send my best regards to programmers and remind them a few things:
• The answer to the question "Did you inform the developers about the errors found in their
project?" can be found in the post "FAQ for those who have read our articles".
• The best way to contact us and ask any questions you want is through the feedback form on our
website. Please don't use twitter for that purpose as well as comments to our articles on third-party
sites and so on.
• I invite you to follow us in twitter: @Code_Analysis. I regularly collect and post various links to
interesting materials in the area of programming and the C++ language.