This is the fourth post in which I want to share with you some useful observations on error patterns and the ways of fighting them. This time I will touch upon the subject of handling rare and emergency conditions in programs. While examining a number of applications, I came to a conclusion that the error handling code is one of the most unreliable parts in C/C++ programs' sources. What are the consequences of such defects? An application must generate the message "file X is not found" but instead it crashes and forces the user to make guesses about what he/she is doing wrong. A program handling a data base produces an incomprehensible message instead of telling the user that there is just a field filled in incorrectly. Let's try to fight against this type of errors that haunt our users.
Checking WinMerge with PVS-Studio for the second timePVS-Studio
The author analyzes the WinMerge project with the latest version of the PVS-Studio static code analyzer, finding several new errors compared to a previous analysis. Regular re-analysis is important as analyzers improve over time and new defects arise. Various logic errors are presented, such as unsigned integer comparisons that are always true, null pointer dereferences, and incorrect function argument types. The analyzer's ability to find new types of errors shows it continues advancing in correctly identifying defects.
About half a year ago we checked the Chromium project and wrote an article about it. The PVS-Studio analyzer naturally keeps developing, and in the new Chromium version we have found some errors undetected before. Many errors, of course, refer not to the Chromium project itself but to libraries it employs. But in this article I want to show you how the analyzer's capabilities have improved and not tell you about what we have found in this or that part of Chromium. That's why I will give messages together.
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...PVS-Studio
You probably already know that the Microsoft Corporation bought the Xamarin Company. Even though Microsoft has started gradually opening the source code of some of its products, the Xamarin.Forms code was a big surprise. I couldn't give it the go-by, and decided to check the code using a static code analyzer.
Tesseract. Recognizing Errors in Recognition SoftwareAndrey Karpov
Tesseract is a free software program for text recognition developed by Google. According to the project description, "Tesseract is probably the most accurate open source OCR engine available". And what if we try to catch some bugs there with the help of the CppCat analyzer?
More than a year has passed since we analyzed Notepad++ with PVS-Studio. We wanted to see how much better the PVS-Studio analyzer has become since then and which of the previous errors have been fixed in Notepad++.
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.
We are regularly asked to check various open-source projects with the PVS-Studio analyzer. If you want to offer some project for us to analyze too, please follow this link. Another project we have checked is Dolphin-emu.
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.
Checking WinMerge with PVS-Studio for the second timePVS-Studio
The author analyzes the WinMerge project with the latest version of the PVS-Studio static code analyzer, finding several new errors compared to a previous analysis. Regular re-analysis is important as analyzers improve over time and new defects arise. Various logic errors are presented, such as unsigned integer comparisons that are always true, null pointer dereferences, and incorrect function argument types. The analyzer's ability to find new types of errors shows it continues advancing in correctly identifying defects.
About half a year ago we checked the Chromium project and wrote an article about it. The PVS-Studio analyzer naturally keeps developing, and in the new Chromium version we have found some errors undetected before. Many errors, of course, refer not to the Chromium project itself but to libraries it employs. But in this article I want to show you how the analyzer's capabilities have improved and not tell you about what we have found in this or that part of Chromium. That's why I will give messages together.
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...PVS-Studio
You probably already know that the Microsoft Corporation bought the Xamarin Company. Even though Microsoft has started gradually opening the source code of some of its products, the Xamarin.Forms code was a big surprise. I couldn't give it the go-by, and decided to check the code using a static code analyzer.
Tesseract. Recognizing Errors in Recognition SoftwareAndrey Karpov
Tesseract is a free software program for text recognition developed by Google. According to the project description, "Tesseract is probably the most accurate open source OCR engine available". And what if we try to catch some bugs there with the help of the CppCat analyzer?
More than a year has passed since we analyzed Notepad++ with PVS-Studio. We wanted to see how much better the PVS-Studio analyzer has become since then and which of the previous errors have been fixed in Notepad++.
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.
We are regularly asked to check various open-source projects with the PVS-Studio analyzer. If you want to offer some project for us to analyze too, please follow this link. Another project we have checked is Dolphin-emu.
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.
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.
A new version of Firebird DBMS was released not so long ago. This release was one of the most significant in the project's history, as it marked substantial revision of the architecture, addition of multithreading support, and performance improvements. Such a significant update was a good occasion for us to scan Firebird one more time with PVS-Studio static code analyzer.
How to make fewer errors at the stage of code writing. Part N1.PVS-Studio
I've arrived at the source code of a widely know instant messenger Miranda IM. Together with various plugins, this is a rather large project whose size is about 950 thousand code lines in C and C++. And like any other considerable project with a long development history, it has rather many errors and misprints.
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...PVS-Studio
Microsoft have given open access to the source code of a tool kit that is used in the company to speed up the development of artificial intelligence: Computational Network Toolkit is now available at Github. The developers had to create their own custom solution, because the existing tools did not work fast enough.
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindPVS-Studio
Articles discussing the results of analysis of open-source projects are a good thing as they benefit everyone: some, including project authors themselves, can find out what bugs lurk in a project; others discover for themselves the static analysis technology and start using it to improve their code's quality. For us, it is a wonderful means to promote PVS-Studio analyzer, as well as to put it through some additional testing. This time I have analyzed Accord.Net framework and found lots of interesting issues in its code.
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.
Some of you may know that we have recently released version 6.00 of our analyzer, that now has C# support. The ability to scan C# projects increases the number of open-source projects we can analyze. This article is about one such check. This time it is a project, developed by Sony Computer Entertainment (SCEI).
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...PVS-Studio
The article demonstrates errors detected with the static code analyzer integrated into Visual Studio 2010. The research was performed on five open source projects. The same projects were also checked with PVS-Studio. Results of comparing these two tools are presented at the end of the article.
One of the main problems with C++ is having a huge number of constructions whose behavior is undefined, or is just unexpected for a programmer. We often come across them when using our static analyzer on various projects. But, as we all know, the best thing is to detect errors at the compilation stage. Let's see which techniques in modern C++ help writing not only simple and clear code, but make it safer and more reliable.
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.
I sometimes feel quite embarrassed when examining bugs in software projects. Many of these bugs inhabit the code for many years, and you just can't help wondering how the program still manages to run at all with a hundred mistakes and defects. And it does work somehow. And people do manage to use it. It holds true not only for code drawing a video game pockemon, but for math libraries too. Your guess is right - we'll speak about the math library Scilab and its analysis results in this article.
The document analyzes the source code of the Godot game engine using the PVS-Studio static code analyzer. It finds and discusses several types of errors identified by the analyzer, including duplicated comparisons, array overruns due to enum/array mismatches, incorrect data type checks, typos causing logic errors or infinite loops, and unsafe pointer usage. The analysis aims to both introduce readers to the Godot project and help its developers fix bugs and improve code quality.
Static Analysis of Mozilla Thunderbird's Code by PVS-StudioPVS-Studio
In this article, we will talk about the analysis of the Mozilla Thunderbird project by the PVS-Studio static analyzer. Being a Thunderbird user, I would occasionally run into hangs and strange behavior of the program. Hopefully our analysis will help to reveal at least some of the reasons behind it in the source code. So welcome to follow me to see what errors can be found in this popular project.
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1PVS-Studio
Operating systems are among the largest and most complicated software projects, and that means they perfectly suit the purpose of demonstrating static code analysis' capabilities. After the successful analysis of Linux Kernel, I felt inspired to try analyzing other open-source operating systems as well.
This document discusses C programming concepts including data types, variables, operators, conditional statements, loops, and functions. It contains code examples to find the size of different data types, if/else statements, for/while loops, break/continue statements, and switch statements. The key points covered are:
- Using the sizeof operator to determine the size of int, float, double, char, and other variable types.
- If/else and if/else ladder conditional statements for comparing values.
- For, while, and do-while loop structures for iteration.
- Break and continue statements for early loop termination or skipping iterations.
- Switch statement for multiple conditional comparisons using case labels.
Analyzing the Quake III Arena GPL projectPVS-Studio
As you know, the id Software company has laid out source codes of many of their games. We already checked some of these projects earlier. This time we decided to analyze the Quake III Arena GPL source code. Analysis was performed with PVS-Studio 4.54.
Analysis of the Trans-Proteomic Pipeline (TPP) projectPVS-Studio
To be honest, I don't know what the TPP project is intended for. As far as I understand, this is a set of tools to assist in research of proteins and their interaction in living organisms. However, that's not so much important. What is important is that their source codes are open. It means that I can check them with the PVS-Studio static analyzer. Which I'm very much fond of.
64-Bit Code in 2015: New in the Diagnostics of Possible IssuesPVS-Studio
64-bit issues are pretty hard to detect because they are like a timebomb: it may take quite a while before they show up. The PVS-Studio static analyzer makes it easier to find and fix such errors. But we have made even a few more steps forward: we have recently revised with more care the 64-bit diagnostics implemented in our tool, which resulted in changing their distribution among severity levels. In this article, I'm going to tell you about these changes and how it affected the tool handling and bug search. You will also find real-life examples of 64-bit errors.
Logical Expressions in C/C++. Mistakes Made by ProfessionalsPVS-Studio
In programming, a logical expression is a language construct that is evaluated as true or false. Many books that teach programming "from scratch" discuss possible operations on logical expressions familiar to every beginner. In this article, I won't be talking about the AND operator having higher precedence than OR. Instead, I will talk about common mistakes that programmers make in simple conditional expressions consisting of no more than three operators, and show how you can check your code using truth tables. Mistakes described here are the ones made by the developers of such well-known projects as FreeBSD, Microsoft ChakraCore, Mozilla Thunderbird, LibreOffice, and many others.
The document summarizes the results of analyzing the OpenCV computer vision library with the PVS-Studio code analyzer. Several real bugs were found in older versions of OpenCV and have since been fixed. New analysis of the current OpenCV version uncovered additional bugs, including copy-paste errors, meaningless loops, misprints in conditions, pointer errors, and poor test cases. The analysis demonstrates that static analysis is useful for finding real bugs in large, complex libraries like OpenCV during development.
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.
A new version of Firebird DBMS was released not so long ago. This release was one of the most significant in the project's history, as it marked substantial revision of the architecture, addition of multithreading support, and performance improvements. Such a significant update was a good occasion for us to scan Firebird one more time with PVS-Studio static code analyzer.
How to make fewer errors at the stage of code writing. Part N1.PVS-Studio
I've arrived at the source code of a widely know instant messenger Miranda IM. Together with various plugins, this is a rather large project whose size is about 950 thousand code lines in C and C++. And like any other considerable project with a long development history, it has rather many errors and misprints.
"Why is there no artificial intelligence yet?" Or, analysis of CNTK tool kit ...PVS-Studio
Microsoft have given open access to the source code of a tool kit that is used in the company to speed up the development of artificial intelligence: Computational Network Toolkit is now available at Github. The developers had to create their own custom solution, because the existing tools did not work fast enough.
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindPVS-Studio
Articles discussing the results of analysis of open-source projects are a good thing as they benefit everyone: some, including project authors themselves, can find out what bugs lurk in a project; others discover for themselves the static analysis technology and start using it to improve their code's quality. For us, it is a wonderful means to promote PVS-Studio analyzer, as well as to put it through some additional testing. This time I have analyzed Accord.Net framework and found lots of interesting issues in its code.
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.
Some of you may know that we have recently released version 6.00 of our analyzer, that now has C# support. The ability to scan C# projects increases the number of open-source projects we can analyze. This article is about one such check. This time it is a project, developed by Sony Computer Entertainment (SCEI).
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...PVS-Studio
The article demonstrates errors detected with the static code analyzer integrated into Visual Studio 2010. The research was performed on five open source projects. The same projects were also checked with PVS-Studio. Results of comparing these two tools are presented at the end of the article.
One of the main problems with C++ is having a huge number of constructions whose behavior is undefined, or is just unexpected for a programmer. We often come across them when using our static analyzer on various projects. But, as we all know, the best thing is to detect errors at the compilation stage. Let's see which techniques in modern C++ help writing not only simple and clear code, but make it safer and more reliable.
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.
I sometimes feel quite embarrassed when examining bugs in software projects. Many of these bugs inhabit the code for many years, and you just can't help wondering how the program still manages to run at all with a hundred mistakes and defects. And it does work somehow. And people do manage to use it. It holds true not only for code drawing a video game pockemon, but for math libraries too. Your guess is right - we'll speak about the math library Scilab and its analysis results in this article.
The document analyzes the source code of the Godot game engine using the PVS-Studio static code analyzer. It finds and discusses several types of errors identified by the analyzer, including duplicated comparisons, array overruns due to enum/array mismatches, incorrect data type checks, typos causing logic errors or infinite loops, and unsafe pointer usage. The analysis aims to both introduce readers to the Godot project and help its developers fix bugs and improve code quality.
Static Analysis of Mozilla Thunderbird's Code by PVS-StudioPVS-Studio
In this article, we will talk about the analysis of the Mozilla Thunderbird project by the PVS-Studio static analyzer. Being a Thunderbird user, I would occasionally run into hangs and strange behavior of the program. Hopefully our analysis will help to reveal at least some of the reasons behind it in the source code. So welcome to follow me to see what errors can be found in this popular project.
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1PVS-Studio
Operating systems are among the largest and most complicated software projects, and that means they perfectly suit the purpose of demonstrating static code analysis' capabilities. After the successful analysis of Linux Kernel, I felt inspired to try analyzing other open-source operating systems as well.
This document discusses C programming concepts including data types, variables, operators, conditional statements, loops, and functions. It contains code examples to find the size of different data types, if/else statements, for/while loops, break/continue statements, and switch statements. The key points covered are:
- Using the sizeof operator to determine the size of int, float, double, char, and other variable types.
- If/else and if/else ladder conditional statements for comparing values.
- For, while, and do-while loop structures for iteration.
- Break and continue statements for early loop termination or skipping iterations.
- Switch statement for multiple conditional comparisons using case labels.
Analyzing the Quake III Arena GPL projectPVS-Studio
As you know, the id Software company has laid out source codes of many of their games. We already checked some of these projects earlier. This time we decided to analyze the Quake III Arena GPL source code. Analysis was performed with PVS-Studio 4.54.
Analysis of the Trans-Proteomic Pipeline (TPP) projectPVS-Studio
To be honest, I don't know what the TPP project is intended for. As far as I understand, this is a set of tools to assist in research of proteins and their interaction in living organisms. However, that's not so much important. What is important is that their source codes are open. It means that I can check them with the PVS-Studio static analyzer. Which I'm very much fond of.
64-Bit Code in 2015: New in the Diagnostics of Possible IssuesPVS-Studio
64-bit issues are pretty hard to detect because they are like a timebomb: it may take quite a while before they show up. The PVS-Studio static analyzer makes it easier to find and fix such errors. But we have made even a few more steps forward: we have recently revised with more care the 64-bit diagnostics implemented in our tool, which resulted in changing their distribution among severity levels. In this article, I'm going to tell you about these changes and how it affected the tool handling and bug search. You will also find real-life examples of 64-bit errors.
Logical Expressions in C/C++. Mistakes Made by ProfessionalsPVS-Studio
In programming, a logical expression is a language construct that is evaluated as true or false. Many books that teach programming "from scratch" discuss possible operations on logical expressions familiar to every beginner. In this article, I won't be talking about the AND operator having higher precedence than OR. Instead, I will talk about common mistakes that programmers make in simple conditional expressions consisting of no more than three operators, and show how you can check your code using truth tables. Mistakes described here are the ones made by the developers of such well-known projects as FreeBSD, Microsoft ChakraCore, Mozilla Thunderbird, LibreOffice, and many others.
The document summarizes the results of analyzing the OpenCV computer vision library with the PVS-Studio code analyzer. Several real bugs were found in older versions of OpenCV and have since been fixed. New analysis of the current OpenCV version uncovered additional bugs, including copy-paste errors, meaningless loops, misprints in conditions, pointer errors, and poor test cases. The analysis demonstrates that static analysis is useful for finding real bugs in large, complex libraries like OpenCV during development.
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.
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.
The document discusses how programmers often wrongly blame compilers for errors in their own code. It provides examples from open source code where errors like using the wrong size argument in memset() and memcpy() led programmers to incorrectly accuse the compiler. The author advises thoroughly investigating one's own code before blaming compilers, to avoid looking silly and to more quickly find and fix real errors.
The article describes the testing technologies used when developing PVS-Studio static code analyzer. The developers of the tool for programmers talk about the principles of testing their own program product which can be interesting for the developers of similar packages for processing text data or source code.
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++. All the errors have been found with the PVS-Studio static code analyzer.
Visual Studio Automation Object Model. EnvDTE interfacesPVS-Studio
This article contains an overview of Visual Studio Automation Object Model. Model's overall structure and the means of obtaining access to its interfaces through DTE/DTE2 top level objects are examined. Several examples of utilizing elements of the model are provided. Also discussed are the issues of using model's interfaces within multithreaded applications; an example of implementing such mechanism for multithreaded interaction with COM interfaces in managed code is provided as well.
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.
In this article, I've collected a huge amount of links all of which could prove potentially useful to software developers who are getting acquainted with 64-bit world. In general, we will cover C/C++ languages, but I am sure, that developers from other languages will discover a lot of interesting stuff here as well.
1) The author conducted experiments to determine if PVS-Studio could analyze code without being tied to Visual Studio. Experiments showed that properly handling include paths and duplicate file names is difficult without a project file, and preprocessing is essential for quality static analysis.
2) Compilation switches had little impact on analysis, except include paths. Preprocessing provides necessary type and symbol information.
3) Checking all files in a folder led to analyzing unnecessary files and preprocessing errors. Project structure is important for proper static analysis.
This is a small note on the results of checking the OpenSSL project with the PVS-Studio analyzer. I analyzed the openssl-0.9.8-stable-SNAP-20121208 version.
Monitoring a program that monitors computer networksPVS-Studio
The document discusses several types of errors found using static analysis on the NetXMS open source project codebase. It describes 4 examples of 64-bit errors where pointers are incorrectly cast to 32-bit types. It also mentions errors handling unsigned types like sockets, half-cleared buffers due to misunderstanding string sizes, copy-paste errors, uninitialized variables, null pointer dereferences, and incorrect variable type usage with variadic functions. The author encourages the NetXMS developers to use the static analysis tool to find and address these kinds of issues in their code.
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.
This article covers the extension of Visual Studio by integrating into its 'Settings' dialog pages. Option page registration and integration into the IDE for different kinds of extension packages will be examined, as well as the means to display various standard and user-created components inside a custom settings page. Also covered are the ways of accessing environment settings through Visual Studio Automation model and preservation mechanism for option pages.
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.
How to make fewer errors at the stage of code writing. Part N3.PVS-Studio
This is the third article where I will tell you about a couple of new programming methods that can help you make your code simpler and safer. You may read the previous two posts here [1] and here [2]. This time we will take samples from the Qt project.
Regular use of static code analysis in team developmentPVS-Studio
Static code analysis technologies are used in companies with mature software development processes. However, there might be different levels of using and introducing code analysis tools into a development process: from manual launch of an analyzer "from time to time" or when searching for hard-to-find errors to everyday automatic launch or launch of a tool when adding new source code into the version control system.
This article deals with creation, utilization and handling of Visual Studio commands in its extension modules through automation object model APIs and IDE services. The relations between IDE commands and environment UI elements, such as user menus and toolbars, will also be examined.
How to complement TDD with static analysisPVS-Studio
TDD is one of the most popular software development techniques. I like this technology in general, and we employ it to some extent. The main thing is not to run to extremes when using it. One shouldn't fully rely on it alone forgetting other methods of software quality enhancement. In this article, I will show you how the static code analysis methodology can be used by programmers using TDD to additionally secure themselves against errors.
Static analysis is most efficient when being used regularly. We'll tell you w...PVS-Studio
The document discusses best practices for using static code analysis tools to maximize their effectiveness. It recommends: 1) Marking false positives to reduce future messages, 2) Using incremental analysis to check modified files, 3) Checking files modified in the last few days, and 4) Running analysis nightly on a build server. Following all recommendations provides the highest return on investment in static analysis by catching errors earlier in development.
Checking the code of Valgrind dynamic analyzer by a static analyzerPVS-Studio
This statement would be incorrect, as well as the reverse idea. The tools of static and dynamic analysis complement each other, they do not compete with each other. Both of these methods have strengths and weaknesses. Some errors cannot be detected by dynamic analyzers, some - by static ones. That's why I suggest treating this post as another demonstration of the abilities of PVS-Studio, not the comparison of two methodologies.
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...Andrey Karpov
The article demonstrates errors detected with the static code analyzer integrated into Visual Studio 2010. The research was performed on five open source projects. The same projects were also checked with PVS-Studio. Results of comparing these two tools are presented at the end of the article.
Comparing the general static analysis in Visual Studio 2010 and PVS-Studio by...PVS-Studio
The article demonstrates errors detected with the static code analyzer integrated into Visual Studio 2010. The research was performed on five open source projects. The same projects were also checked with PVS-Studio. Results of comparing these two tools are presented at the end of the article.
A Slipshod Check of the Visual C++ 2013 Library (update 3)Andrey Karpov
Someone suggested to me recently that I check the libraries from Visual Studio 2013. I haven't found
anything of much interest, just a few small errors and slip-ups. They wouldn't make an interesting,
attractive article, but I've still decided to describe all those defects. I just hope it will help make the
libraries a bit better and stimulate the authors to carry out a more thorough analysis. I don't have the
project files necessary to build the libraries, so my analysis had to be superficial and I could have missed
a lot.
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).
A Unicorn Seeking Extraterrestrial Life: Analyzing SETI@home's Source CodePVS-Studio
The document analyzes the source code of the SETI@home project using a static code analyzer. The analysis found relatively few errors, indicating high code quality. Some issues discussed include incorrect operator precedence leading to logic errors, empty methods that should return values, pointer dereferencing before checking for null, undefined behavior from negative number shifts, and inefficient string length calls in loops. Overall the review uncovered some minor defects but showed the code is generally well written.
Python and Ruby implementations compared by the error densityPVS-Studio
Which programming language to start learning? Python or Ruby? Which one is better? Django or Ruby on Rails? Such questions can often be found on IT forums around the world. I suggest comparing not the languages themselves, but their reference implementations: CPython and MRI. In this article, we are going to cover the errors that were found by PVS-Studio in these projects.
Rechecking TortoiseSVN with the PVS-Studio Code AnalyzerAndrey Karpov
The author downloaded and analyzed the source code of the TortoiseSVN project using the PVS-Studio static code analyzer. The analysis found several bugs, including identical comparisons, unsafe uses of formatting functions like printf(), and obsolete null checks after memory allocation. While many of the issues would not cause failures, some could lead to undefined behavior, especially in 64-bit systems where pointer sizes are larger than integer types. The author concludes by recommending regular use of static analysis to find bugs early.
A new version of Firebird DBMS was released not so long ago. This release was one of the most significant in the project's history, as it marked substantial revision of the architecture, addition of multithreading support, and performance improvements. Such a significant update was a good occasion for us to scan Firebird one more time with PVS-Studio static code analyzer.
Apache HTTP Server project continues to develop, and so does PVS-Studio analyzer, growing even more powerful with every new version. Let's see what we've got this time.
PVS-Studio analyzer is continuously improving, and the C#-code analysis module is developing most actively: ninety new diagnostic rules were added in 2016. However, the best way to estimate the analyzer's efficiency is to look at the bugs it can catch. It's always interesting, as well as useful, to do recurring checks of large open-source projects at certain intervals and compare their results. Today I will talk about the results of the second analysis of SharpDevelop project.
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.
Checking the World of Warcraft CMaNGOS open source serverPVS-Studio
In this article, I would like to share the results of our analysis of the open source implementation of the World of Warcraft server, CMaNGOS, as done by the PVS-Studio static analyzer.
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.
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.
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.
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.
Similar to How to make fewer errors at the stage of code writing. Part N4. (18)
Essentials of Automations: Exploring Attributes & Automation ParametersSafe Software
Building automations in FME Flow can save time, money, and help businesses scale by eliminating data silos and providing data to stakeholders in real-time. One essential component to orchestrating complex automations is the use of attributes & automation parameters (both formerly known as “keys”). In fact, it’s unlikely you’ll ever build an Automation without using these components, but what exactly are they?
Attributes & automation parameters enable the automation author to pass data values from one automation component to the next. During this webinar, our FME Flow Specialists will cover leveraging the three types of these output attributes & parameters in FME Flow: Event, Custom, and Automation. As a bonus, they’ll also be making use of the Split-Merge Block functionality.
You’ll leave this webinar with a better understanding of how to maximize the potential of automations by making use of attributes & automation parameters, with the ultimate goal of setting your enterprise integration workflows up on autopilot.
QA or the Highway - Component Testing: Bridging the gap between frontend appl...zjhamm304
These are the slides for the presentation, "Component Testing: Bridging the gap between frontend applications" that was presented at QA or the Highway 2024 in Columbus, OH by Zachary Hamm.
In the realm of cybersecurity, offensive security practices act as a critical shield. By simulating real-world attacks in a controlled environment, these techniques expose vulnerabilities before malicious actors can exploit them. This proactive approach allows manufacturers to identify and fix weaknesses, significantly enhancing system security.
This presentation delves into the development of a system designed to mimic Galileo's Open Service signal using software-defined radio (SDR) technology. We'll begin with a foundational overview of both Global Navigation Satellite Systems (GNSS) and the intricacies of digital signal processing.
The presentation culminates in a live demonstration. We'll showcase the manipulation of Galileo's Open Service pilot signal, simulating an attack on various software and hardware systems. This practical demonstration serves to highlight the potential consequences of unaddressed vulnerabilities, emphasizing the importance of offensive security practices in safeguarding critical infrastructure.
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...GlobalLogic Ukraine
Під час доповіді відповімо на питання, навіщо потрібно підвищувати продуктивність аплікації і які є найефективніші способи для цього. А також поговоримо про те, що таке кеш, які його види бувають та, основне — як знайти performance bottleneck?
Відео та деталі заходу: https://bit.ly/45tILxj
"What does it really mean for your system to be available, or how to define w...Fwdays
We will talk about system monitoring from a few different angles. We will start by covering the basics, then discuss SLOs, how to define them, and why understanding the business well is crucial for success in this exercise.
From Natural Language to Structured Solr Queries using LLMsSease
This talk draws on experimentation to enable AI applications with Solr. One important use case is to use AI for better accessibility and discoverability of the data: while User eXperience techniques, lexical search improvements, and data harmonization can take organizations to a good level of accessibility, a structural (or “cognitive” gap) remains between the data user needs and the data producer constraints.
That is where AI – and most importantly, Natural Language Processing and Large Language Model techniques – could make a difference. This natural language, conversational engine could facilitate access and usage of the data leveraging the semantics of any data source.
The objective of the presentation is to propose a technical approach and a way forward to achieve this goal.
The key concept is to enable users to express their search queries in natural language, which the LLM then enriches, interprets, and translates into structured queries based on the Solr index’s metadata.
This approach leverages the LLM’s ability to understand the nuances of natural language and the structure of documents within Apache Solr.
The LLM acts as an intermediary agent, offering a transparent experience to users automatically and potentially uncovering relevant documents that conventional search methods might overlook. The presentation will include the results of this experimental work, lessons learned, best practices, and the scope of future work that should improve the approach and make it production-ready.
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...DanBrown980551
This LF Energy webinar took place June 20, 2024. It featured:
-Alex Thornton, LF Energy
-Hallie Cramer, Google
-Daniel Roesler, UtilityAPI
-Henry Richardson, WattTime
In response to the urgency and scale required to effectively address climate change, open source solutions offer significant potential for driving innovation and progress. Currently, there is a growing demand for standardization and interoperability in energy data and modeling. Open source standards and specifications within the energy sector can also alleviate challenges associated with data fragmentation, transparency, and accessibility. At the same time, it is crucial to consider privacy and security concerns throughout the development of open source platforms.
This webinar will delve into the motivations behind establishing LF Energy’s Carbon Data Specification Consortium. It will provide an overview of the draft specifications and the ongoing progress made by the respective working groups.
Three primary specifications will be discussed:
-Discovery and client registration, emphasizing transparent processes and secure and private access
-Customer data, centering around customer tariffs, bills, energy usage, and full consumption disclosure
-Power systems data, focusing on grid data, inclusive of transmission and distribution networks, generation, intergrid power flows, and market settlement data
AI in the Workplace Reskilling, Upskilling, and Future Work.pptxSunil Jagani
Discover how AI is transforming the workplace and learn strategies for reskilling and upskilling employees to stay ahead. This comprehensive guide covers the impact of AI on jobs, essential skills for the future, and successful case studies from industry leaders. Embrace AI-driven changes, foster continuous learning, and build a future-ready workforce.
Read More - https://bit.ly/3VKly70
MySQL InnoDB Storage Engine: Deep Dive - MydbopsMydbops
This presentation, titled "MySQL - InnoDB" and delivered by Mayank Prasad at the Mydbops Open Source Database Meetup 16 on June 8th, 2024, covers dynamic configuration of REDO logs and instant ADD/DROP columns in InnoDB.
This presentation dives deep into the world of InnoDB, exploring two ground-breaking features introduced in MySQL 8.0:
• Dynamic Configuration of REDO Logs: Enhance your database's performance and flexibility with on-the-fly adjustments to REDO log capacity. Unleash the power of the snake metaphor to visualize how InnoDB manages REDO log files.
• Instant ADD/DROP Columns: Say goodbye to costly table rebuilds! This presentation unveils how InnoDB now enables seamless addition and removal of columns without compromising data integrity or incurring downtime.
Key Learnings:
• Grasp the concept of REDO logs and their significance in InnoDB's transaction management.
• Discover the advantages of dynamic REDO log configuration and how to leverage it for optimal performance.
• Understand the inner workings of instant ADD/DROP columns and their impact on database operations.
• Gain valuable insights into the row versioning mechanism that empowers instant column modifications.
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor IvaniukFwdays
At this talk we will discuss DDoS protection tools and best practices, discuss network architectures and what AWS has to offer. Also, we will look into one of the largest DDoS attacks on Ukrainian infrastructure that happened in February 2022. We'll see, what techniques helped to keep the web resources available for Ukrainians and how AWS improved DDoS protection for all customers based on Ukraine experience
AppSec PNW: Android and iOS Application Security with MobSFAjin Abraham
Mobile Security Framework - MobSF is a free and open source automated mobile application security testing environment designed to help security engineers, researchers, developers, and penetration testers to identify security vulnerabilities, malicious behaviours and privacy concerns in mobile applications using static and dynamic analysis. It supports all the popular mobile application binaries and source code formats built for Android and iOS devices. In addition to automated security assessment, it also offers an interactive testing environment to build and execute scenario based test/fuzz cases against the application.
This talk covers:
Using MobSF for static analysis of mobile applications.
Interactive dynamic security assessment of Android and iOS applications.
Solving Mobile app CTF challenges.
Reverse engineering and runtime analysis of Mobile malware.
How to shift left and integrate MobSF/mobsfscan SAST and DAST in your build pipeline.
Must Know Postgres Extension for DBA and Developer during MigrationMydbops
Mydbops Opensource Database Meetup 16
Topic: Must-Know PostgreSQL Extensions for Developers and DBAs During Migration
Speaker: Deepak Mahto, Founder of DataCloudGaze Consulting
Date & Time: 8th June | 10 AM - 1 PM IST
Venue: Bangalore International Centre, Bangalore
Abstract: Discover how PostgreSQL extensions can be your secret weapon! This talk explores how key extensions enhance database capabilities and streamline the migration process for users moving from other relational databases like Oracle.
Key Takeaways:
* Learn about crucial extensions like oracle_fdw, pgtt, and pg_audit that ease migration complexities.
* Gain valuable strategies for implementing these extensions in PostgreSQL to achieve license freedom.
* Discover how these key extensions can empower both developers and DBAs during the migration process.
* Don't miss this chance to gain practical knowledge from an industry expert and stay updated on the latest open-source database trends.
Mydbops Managed Services specializes in taking the pain out of database management while optimizing performance. Since 2015, we have been providing top-notch support and assistance for the top three open-source databases: MySQL, MongoDB, and PostgreSQL.
Our team offers a wide range of services, including assistance, support, consulting, 24/7 operations, and expertise in all relevant technologies. We help organizations improve their database's performance, scalability, efficiency, and availability.
Contact us: info@mydbops.com
Visit: https://www.mydbops.com/
Follow us on LinkedIn: https://in.linkedin.com/company/mydbops
For more details and updates, please follow up the below links.
Meetup Page : https://www.meetup.com/mydbops-databa...
Twitter: https://twitter.com/mydbopsofficial
Blogs: https://www.mydbops.com/blog/
Facebook(Meta): https://www.facebook.com/mydbops/
How to make fewer errors at the stage of code writing. Part N4.
1. How to make fewer errors at the stage of
code writing. Part N4.
Author: Andrey Karpov
Date: 14.12.2011
Abstract
This is the fourth post in which I want to share with you some useful observations on error patterns and
the ways of fighting them. This time I will touch upon the subject of handling rare and emergency
conditions in programs. While examining a number of applications, I came to a conclusion that the error
handling code is one of the most unreliable parts in C/C++ programs' sources. What are the
consequences of such defects? An application must generate the message "file X is not found" but
instead it crashes and forces the user to make guesses about what he/she is doing wrong. A program
handling a data base produces an incomprehensible message instead of telling the user that there is just
a field filled in incorrectly. Let's try to fight against this type of errors that haunt our users.
Introduction
Firstly, here is the information for those readers who are not familiar with my previous posts. You can
find them here:
• Post N1 [Miranda IM];
• Post N2 [Chromium, Return to Castle Wolfenstein, etc];
• Post N3 [Qt SDK].
As usual, I won't go into abstract speculations but instead will start with examples. This time I decided to
take them from the open source Firefox project. I will try to show you that even in high-quality and
popular application things are not very good in the code intended for error handling. All the defects
have been found with the PVS-Studio 4.50 analyzer.
2. Error samples
Example N1. Incomplete verification for table integrity
int AffixMgr::parse_convtable(..., const char * keyword)
{
...
if (strncmp(piece, keyword, sizeof(keyword)) != 0) {
HUNSPELL_WARNING(stderr,
"error: line %d: table is corruptn",
af->getlinenum());
delete *rl;
*rl = NULL;
return 1;
}
...
}
PVS-Studio diagnostic message: V579 The strncmp function receives the pointer and its size as
arguments. It is possibly a mistake. Inspect the third argument. affixmgr.cpp 3708
The programmer tried to verify the table integrity here. Unfortunately, this check may both work and
fail. To calculate the length of the key word the sizeof() operator is used, which is certainly incorrect. As
a result, whether or not the code works will depend on pure luck (at certain values of the key word and
'keyword' pointer's size in the current data model).
Example 2. Invalid verification for file reading operation
int PatchFile::LoadSourceFile(FILE* ofile)
{
...
size_t c = fread(rb, 1, r, ofile);
if (c < 0) {
LOG(("LoadSourceFile: "
"error reading destination file: " LOG_S "n",
mFile));
3. return READ_ERROR;
}
...
}
PVS-Studio diagnostic message: V547 Expression 'c < 0' is always false. Unsigned type value is never < 0.
updater.cpp 1179
This is an example when the code of error handling was written with the "just letting it to be" approach.
The programmer didn't even bother to think over what he/she had written and how it would work. Such
a verification is an incorrect one: the fread() function uses an unsigned type to return the number of
bytes read. This is the function's prototype:
size_t fread(
void *buffer,
size_t size,
size_t count,
FILE *stream
);
The 'c' variable having the size_t type is naturally used to store the result. Consequently, the result of
the (c < 0) check is always false.
This is a good example. It seems at the first glance that there is some checking here but we find out that
it's absolutely useless.
The same error can be found in other places as well:
V547 Expression 'c < 0' is always false. Unsigned type value is never < 0. updater.cpp 2373
V547 Expression 'c < 0' is always false. Unsigned type value is never < 0. bspatch.cpp 107
Example 3. Checking a pointer for NULL only after it had been used
nsresult
nsFrameSelection::MoveCaret(...)
{
...
mShell->FlushPendingNotifications(Flush_Layout);
if (!mShell) {
return NS_OK;
4. }
...
}
PVS-Studio diagnostic message: V595 The 'mShell' pointer was utilized before it was verified against
nullptr. Check lines: 1107, 1109. nsselection.cpp 1107
If the pointer is equal to null, we must handle this special occasion and return NS_OK from the function.
What confuses me is that the mShell pointer has already been used before this moment.
Probably, this code must is operational only because the mShell pointer never equals to NULL. I cite this
example to demonstrate that one can easily make a mistake even in the simplest of checks. We have it
but still it is useless.
Example 4. Checking a pointer for NULL only after it had been used
CompileStatus
mjit::Compiler::performCompilation(JITScript **jitp)
{
...
JaegerSpew(JSpew_Scripts,
"successfully compiled (code "%p") (size "%u")n",
(*jitp)->code.m_code.executableAddress(),
unsigned((*jitp)->code.m_size));
if (!*jitp)
return Compile_Abort;
...
}
PVS-Studio diagnostic message: V595 The '* jitp' pointer was utilized before it was verified against
nullptr. Check lines: 547, 549. compiler.cpp 547
By the way, using a pointer before checking it is a wide-spread error. This was one more example of this
kind.
Example 5. Incomplete checking of input values
PRBool
5. nsStyleAnimation::AddWeighted(...)
{
...
if (unit[0] == eCSSUnit_Null || unit[1] == eCSSUnit_Null ||
unit[0] == eCSSUnit_Null || unit[0] == eCSSUnit_URL) {
return PR_FALSE;
}
...
}
PVS-Studio diagnostic message: V501 There are identical sub-expressions 'unit [0] == eCSSUnit_Null' to
the left and to the right of the '||' operator. nsstyleanimation.cpp 1767
It seems to me that this code fragment contains 2 misprints simultaneously. I cannot tell for sure how
exactly the code should look, but the developers most likely intended it to be written as follows:
if (unit[0] == eCSSUnit_Null || unit[1] == eCSSUnit_Null ||
unit[0] == eCSSUnit_URL || unit[1] == eCSSUnit_URL) {
The misprints may cause the function to process incorrect input values.
Example 6. Incomplete checking of input values
nsresult PresShell::SetResolution(float aXResolution, float
aYResolution)
{
if (!(aXResolution > 0.0 && aXResolution > 0.0)) {
return NS_ERROR_ILLEGAL_VALUE;
}
...
}
PVS-Studio diagnostic message: V501 There are identical sub-expressions to the left and to the right of
the '&&' operator: aXResolution > 0.0 && aXResolution > 0.0 nspresshell.cpp 5114
And here was one more example of invalid input parameters verification. This time, a misprint doesn't
allow the program to check the aYResolution argument's value.
6. Example 7. A non-dereferenced pointer
nsresult
SVGNumberList::SetValueFromString(const nsAString& aValue)
{
...
const char *token = str.get();
if (token == '0') {
return NS_ERROR_DOM_SYNTAX_ERR; // nothing between commas
}
...
}
PVS-Studio diagnostic message: V528 It is odd that pointer to 'char' type is compared with the '0' value.
Probably meant: *token == '0'. svgnumberlist.cpp 96
The code checking that there's nothing between the commas does not work. To find out whether or not
the string is empty, we can compare the first character to '0'. But it is the pointer which is compared to
null instead of the first character. This pointer is never equal to zero. This is the correct check: (*token
== '0').
Example 8. Incorrect type for storing the index
PRBool
nsIEProfileMigrator::TestForIE7()
{
...
PRUint32 index = ieVersion.FindChar('.', 0);
if (index < 0)
return PR_FALSE;
...
}
PVS-Studio diagnostic message: V547 Expression 'index < 0' is always false. Unsigned type value is never
< 0. nsieprofilemigrator.cpp 622
7. The function won't return PR_FALSE if there is no dot in the string and will continue handling incorrect
data. The error here is that an unsigned data type was used for the 'index' variable. Checking that (index
< 0) is meaningless.
Example 9. Forming a wrong error message
cairo_status_t
_cairo_win32_print_gdi_error (const char *context)
{
...
fwprintf(stderr, L"%s: %S", context, (wchar_t *)lpMsgBuf);
...
}
PVS-Studio diagnostic message: V576 Incorrect format. Consider checking the third actual argument of
the 'fwprintf' function. The pointer to string of wchar_t type symbols is expected. cairo-win32-surface.c
129
Even if an error was successfully detected, it should be processed correctly. And since nobody tests error
handlers either, we may find many interesting things there.
The _cairo_win32_print_gdi_error() function will print some trash. The fwprintf() function awaits a
pointer to a unicode-string as the third argument, but instead it gets a string with the 'const char *'
format.
Example 10. Dumping error
bool ExceptionHandler::WriteMinidumpForChild(...)
{
...
DWORD last_suspend_cnt = -1;
...
// this thread may have died already, so not opening
// the handle is a non-fatal error
if (NULL != child_thread_handle) {
if (0 <= (last_suspend_cnt =
SuspendThread(child_thread_handle))) {
...
8. }
PVS-Studio diagnostic message: V547 Expression is always true. Unsigned type value is always >= 0.
exception_handler.cc 846
This is another example in the error handler. The result returned by the SuspendThread function is
processed incorrectly here. The last_suspend_cnt variable has the DWORD type and therefore is always
greater or equal to 0.
About other errors in Firefox
Let me digress from the central topic a bit and tell you about the results of checking Firefox in general.
The project is of a very high quality, and PVS-Studio had found quite a few errors in it. However, since
it's huge one, there is rather big number of errors in a quantitative relation. Unfortunately, I was not
able to study the report generated by the PVS-Studio tool thoroughly. The project was analyzed with the
console version of PVS-Studio called from the make-file. It is possible to review all the diagnostic
messages with opening of the report in Visual Studio. But as there is no project for Visual Studio, it
doesn't prompt you what variables and where are defined and doesn't allow you to navigate to
fragments where macros are defined and so on. As a result, analysis of an unknown project is quite
labor-intensive, and I managed to study only a fraction of the messages.
The errors are diverse. For example, there are array overruns:
class nsBaseStatis : public nsStatis {
public:
...
PRUint32 mLWordLen[10];
...
nsBaseStatis::nsBaseStatis(...)
{
...
for(PRUint32 i = 0; i < 20; i++)
mLWordLen[i] = 0;
...
}
...
};
PVS-Studio diagnostic message: V557 Array overrun is possible. The value of 'i' index could reach 19.
detectcharset.cpp 89
9. Although this error and other similar errors are interesting, they are not related to the subject of our
article. So, if you want to see some other errors, download this file: mozilla-test.txt.
Let's go back to errors in error handlers
I decided to cite 10 examples instead of just a couple to convince you that defects in error handlers are a
wide-spread issue. Of course, error handlers are not the most crucial and important fragments of a
program. But programmers write them, so they hope to improve the program behavior with their help.
Unfortunately, my observations convince me that checks and error handlers often fail to work correctly.
You see, I had just one project to show you those many errors of this kind.
What should we do with them, what recommendations can we give?
The first recommendation
We must admit that one might make a mistake even in a simple check. This is the most difficult and
important thing to understand. It is because error handlers are considered as simple code fragments
that they contain so many misprints and other defects. Error handlers are not tested and checked.
Nobody writes tests for them.
Of course, it's difficult and often unreasonable from the economic viewpoint to write tests for error
handlers. But if programmers at least know about the danger, it's already a progress. When you are
aware of something, you are already armed to deal with it. There is also an analogy to error handlers
that we can refer to.
Statistics tell us that mountain climbers most often fall at the end of ascension. It happens not because
of tiredness, but because the person thinks that he/she will soon finish the ascension - he/she relaxes,
loses attention and therefore makes more mistakes. Something like that happens to a programmer
when he is writing a program. He/she spends much effort and attention on creating an algorithm but
does not concentrate much on writing various checks because he/she is sure that he/she in no way can
make a mistake there.
So, now you are aware. And I'm sure this thing alone is already good.
If you say that only students and novice programmers make such silly mistakes, you are wrong.
Everyone makes misprints. Please read a small post on this topic: "The second myth - expert developers
do not make silly mistakes". I can confirm the idea by many examples from various projects. But I think
the ones cited here will be enough to make you think it over.
The second recommendation
The dumping mechanisms, logging functions and other similar auxiliary mechanisms do deserve creating
unit-tests for them.
An inefficient dumping mechanism is not only useless; it only pretends to be able to help you in an
emergency situation. If a user sends you a corrupted dump-file, it will not only be unable to help you but
will also mislead you and you will spend much more time searching for errors than if the dump-file had
never existed at all.
10. The recommendation looks simple and obvious. But do many of you reading this post have unit-tests to
check the WriteMyDump class?
The third recommendation
Use static code analyzers. The capability of finding defects in error handlers is one of the strong points
of the static analysis methodology. Static analysis covers all the code branches regardless of how often
they are used while an application is running. It can detect errors which reveal themselves quite rare.
In other words, code coverage with static analysis is 100%. It's almost impossible to reach the same code
coverage using other types of testing. Code coverage with unit-tests and regression testing usually is less
than 80%. The remaining 20% are very difficult to test. These 20% include most error handlers and rare
conditions.
The fourth recommendation
You may try to use the methodology of Fault injection. The point is that some functions start to return
various error codes from time to time, and the program must handle them correctly. For instance, you
can write your own function malloc() that will return NULL from time to time even when there is some
memory left. It will allow you to know how the application will behave when memory really runs out.
The same approach can be applied to such functions as fopen(), CoCreateInstance(), CreateDC(), etc.
There are special programs that allow you to automate this process and do it without manually writing
your own functions for causing random failures. Unfortunately, I never dealt with such systems, so I
cannot tell you about them in every detail.
Conclusion
Defects in error handlers are very frequent. Unfortunately, I'm not sure that the above given
recommendations are enough to avoid them. But I do hope that now this issue is of interest for you and
you will invent means to make defects in your programs fewer. I, as the other readers as well, will also
appreciate if you could share your ideas and methods with us on how to avoid errors of the type we
have discussed in this article.