viva64
viva64
El_programmer
3K posts
Blog about programming, coding, errors and other interesting articles from the world of technology
Don't wanna be here? Send us removal request.
viva64 · 7 years ago
Link
6 notes · View notes
viva64 · 7 years ago
Text
More than 1 potential vulnerability per 4000 lines of code in Android
Tumblr media
A year after writing the article about checking Tizen, developers of the PVS-Studio static analyzer checked the quality of the operating system code again, this time demonstrating the abilities of their product to detect errors and potential security vulnerabilities in the Android code.
Despite the fact that the Android code is of high quality and is well tested, and its development includes at least the use of Coverity static analyzer, PVS-Studio still managed to find a lot of interesting defects. Some errors are classified as CWE (Common Weakness Enumeration), which for a certain coincidence of circumstances can be used as vulnerability (CVE). That is why, if you want to protect your code from security vulnerabilities, you should find as many bugs as described in CWE and eliminate them.
According to developers, PVS-Studio is a tool for static application security testing (SAST) and can detect many potential vulnerabilities before they caused harm. This article describes examples of errors by the following categories:
- Pointless comparisons - Null pointer dereference - Private data is not cleared in memory - Unspecified/implementation-defined behavior - Incorrect memory control - Array index out of bounds - Broken loops and so on.
Thus, 490 CWE per 1855000 lines of code have been detected or more than 1 vulnerability per 4000 lines.
Development of large complex projects is impossible without the use of programming methodologies and tools to help monitor the quality of the code. First of all, this is a literate coding standard, code reviews, unit tests, static and dynamic code analyzers. All this helps to detect defects in code at the earliest stages of development. Use additional programs and methods to control the quality of your code and make your product secure!
Source - https://www.viva64.com/en/b/0579/
12 notes · View notes
viva64 · 7 years ago
Text
Amazon Lumberyard: A Scream of Anguish
Video games are among the most popular software products. Now a new game engine, Amazon Lumberyard, has joined this huge industry. The project is currently in the beta phase and still has time to get rid of the bugs and improve. Its authors have a lot of work to do to make sure they don't disappoint millions of gamers and game developers in the nearest future.
Tumblr media
Introduction
Amazon Lumberyard is a free cross-platform triple-A game engine developed by Amazon and based on the architecture of CryEngine, which was licensed from Crytek in 2015. I already checked CryEngine twice, in august 2016 and april 2017, and I'm sorry to say it, but the code quality had decreased since the first check. I was wondering the other day how Amazon had used the engine and took a look at the new product. I must admit they did make a great environment. The user documentation and environment deployment software are really awesome too. But the code is messed up again! I hope Amazon can afford to allocate much more resources for that project and will start caring about code quality at last. By writing this review I hope to draw their attention to this problem and persuade them to take a new approach to the development process. The code's current state is so bad that I had to change the title and the featured image of the article several times as I was going through the analysis report. The first version of the image was less emotional:
The source files under analysis refer to the latest Amazon Lumberyard version, 1.14.0.1, and were downloaded from the Github repository. Star Citizen is one of the first games to be built on the Lumberyard engine. If you are looking to play it, then welcome to take a peek under the hood with me.
Read more - https://www.viva64.com/en/b/0574/
3 notes · View notes
viva64 · 7 years ago
Text
Couple of words about development of a new static analyzer for Java code
Tumblr media
PVS-Studio static analyzer team, which until recently was searching for bugs and potential vulnerabilities only in C, C++, and C# code, has prepared a new version of their tool for Java code as well. Despite the fact that in the Java world there is already a number of static analysis tools, developers believe that their analyzer can be powerful and will be a good competition.
One of developers wrote in his article about the way how PVS-Studio for Java was created. First of all, it was necessary to figure out the development process of a syntax tree and semantic model. As these elements are basic, static analyzer is built around them.  In addition to them, the analyzer also requires data flow analysis, which enables you to calculate the possible values of variables and expressions in each point of the program and, thanks to that, find errors. Also the analyzer needs the annotation mechanism, diagnostic rules, integration, testing, and other techniques, explained in detail in the article.
Traditionally, the author gave examples of errors from different open source projects, that the Java analyzer has detected.  The author also noted that in the future articles with a more detailed report on each project will be available. So far you can review errors from the Hibernate, Hive, JavaParser, Jenkins projects and several others.
Besides that, when the first alpha version of the Java analyzer is available, developers suggest participating in its testing for those who would like to.  To do this, write to their support and they will contact you.
Full article - https://www.viva64.com/en/b/0572/
22 notes · View notes
viva64 · 7 years ago
Text
Static Analysis in Video Game Development: Top 10 Software Bugs
If you are a software developer working in the video game industry and wondering what else you could do to improve the quality of your product or make the development process easier and you don't use static analysis – it's just the right time to start doing so. You doubt that? OK, I'll try to convince you. And if you are just looking to see what coding mistakes are common with video-game and game-engine developers, then you're, again, at the right place: I have picked the most interesting ones for you.
Tumblr media
One of the best ways to prove that static analysis is a useful method is probably through examples showing it in action. That's what the PVS-Studio team does while checking open-source projects. After publishing of various articles, we compiled our top-10 mistakes from the program code in the video-game industry, and now we suggest you read this article - https://www.viva64.com/en/b/0570/
List of projects considered in the article:
X-Ray Engine
CryEngine V
Space Engineers
Quake III Arena GPL
Unity
Godot
Doom 3
Xenko
Unreal Engine 4
Although video-game development includes a lot of steps, coding remains one of the basic ones. Even if you don't write thousands of code lines, you have to use various tools whose quality determines how comfortable the process is and what the ultimate result will be. Static analysis is a very useful tool when developing, and one more option to help you improve the quality of your code (and thus of the final product).
14 notes · View notes
viva64 · 7 years ago
Text
PVS-Studio is now available on macOS: 64 weaknesses in the Apple's XNU Kernel
A new version of PVS-Studio analyzer 6.23 is working under macOS, which allows you to check the projects written in C and C++. With the release of the analyzer version for macOS, PVS-Studio can now be boldly called a cross-platform static code analyzer for C and C++ code.
Tumblr media
How to start demonstrating the abilities of PVS-Studio for macOS? No doubts, the check of the kernel of this system is the best variant! Although the XNU Kernel is relatively small, it's a challenge to study the analyzer warnings alone, which takes much time. False positives make the check more complicated, since you haven't performed the preliminary analyzer configuration.
In total, we noted 64 errors and decided to stop at this beautiful number. We have grouped the defects according to Common Weakness Enumeration, this classification is quite well-known and it will be easier to understand what errors are a question of this or that chapter. For more details check our article https://www.viva64.com/en/b/0566/.
Now you are able to detect errors and potential vulnerabilities in C, and C++. We invite everyone to try out our analyzer on your projects and to assess its abilities.
7 notes · View notes
viva64 · 7 years ago
Link
16 notes · View notes
viva64 · 7 years ago
Text
PVS-Studio: the Additional Insurance of the Medical Software
Software bugs can lead not only to material losses, but also can damage human's health. For example, actors on the stage of a theatre can get injured if suddenly one of the scenery begins to go down on the stage at the wrong time. However, the connection between the errors in code and the health damage of medical software is more obvious. Let's talk about this topic.
This article focuses on the teams of developers who create the programs for a medical equipment. I hope they will not stay indifferent and will check their code. Let's recall two famous cases where errors in programs, related to medicine, became the reason for bad news.
Tumblr media
Firstly, it is a series of tragic events caused by the errors in the Therac-25 device of radiation therapy. This device has caused at least six overdoses of radiation within the period from June 1985 to January 1987, some patients received doses of tens of thousands of rad. At least two people died directly from the radiation overdoses. Software bugs of the device were the reason of the tragedies and the main problem was the incorrect security strategy.
Tumblr media
Secondly, the software bugs can also cause harm indirectly. For example, the bugs in the software for MRI-scanners raise the questions about the 40 000 researches. For several decades, neuroscientists and cognitive psychologists has used statistical programs AFNI, SPM and FSL to analyze fMRI data. As it turned out, because of the incorrect algorithms, these programs might return up to 70% of false positive results instead of the projected 5%.
As you can see, the code errors can lead not only to troubles, such as a crash or a loss of data, but also to much more serious consequences, which influence the life and the health of many people throughout many years.
Moreover, the developer is responsible not only for his own code, but for the code of the used libraries. This situation is completely real, when the artifacts appear when creating an image/video due to an error from a third-party library and this will lead to confusion when diagnosing.
This is not an abstract theoretical problem. I myself faced a situation, in which when porting programs to 64-bit system an error causing incorrect handling of MRI data began to reveal itself. Fortunately, the error showed itself very clearly: a large fragment of the image was absent. However, the error might not be that noticeable and consist in the incorrect displaying of some details and it'll be much harder to detect it.
Tumblr media
More information about this error is available in the article "PVS-Studio project - 10 years of failures and successes". It is this and some other 64-bit errors that inspired the creation of the Viva64 tool, which then turned into a PVS-Studio static code analyzer.
It is impossible to predict where the errors can be and what errors can lead to trouble. The error can be complex and not necessarily spoil life, lurking in the algorithm of data processing and displaying. I can imagine a situation where because of an error in the comparison function, data of the wrong patient will be selected for processing, or the program, describing the condition of the patient, will not notice some differences in the data structure.
I invite all readers to start using the PVS-Studio static code analyzer. Yes, the analyzer, like any other tool, does not guarantee the absence of errors in your programs. However, it becomes an additional line of defense on the field of the battle against the bugs. It can help detect a lot of errors at the early stages of development and may help to save someone's health.
Read more - PVS-Studio: the Additional Insurance of the Medical Software
6 notes · View notes
viva64 · 7 years ago
Text
Why embedded developers should use static code analysis
I decided to briefly highlight 3 reasons why static analysis tools for program code may be useful for embedded developers.
Tumblr media
The first reason: no need to spend time on excruciating search for some specific errors
Static code analysis == cheapening the process of testing and device debugging. The earlier an error is detected, the less expensive it is to correct it. Static analysis allows to find bugs on the stage of writing the code, or at least during the night runs on the server. As a result, finding and correcting many of the errors is much cheaper.
Static analysis may be particularly useful when debugging embedded-systems. In such projects, developers deal not only with errors in programs, but also with errors in the device itself or with poor manufacturing layout (bad contact and etc.). As a result, the process of error detecting can be severely delayed because it is often not clear where to look for a bug. If a programmer supposes that code is written correctly, it can cause long searching involving designers and other colleagues, responsible for the hardware-part. So, it will be all the more unpleasant to return to the program code and finally discover a stupid typo. Stupendously inefficient consumption of time and efforts of a team. Sounds awesome, if a static analyzer finds such an error.
Here's such a situation that my friend once told me:
"Even still studying for master's degree, I started working in the company involved in customization of various small-scale devices. For example, automation of greenhouses or collecting information from sensors in the enterprise that nothing leaked or overheated nowhere.
I'm having another standard task which takes me just a couple of hours and I return it to two colleagues to firmware a device they created. Colleagues are surprised at how quickly everything was done, praising me, and I proudly declare, "Well, I'm kind of a professional in writing such things and generally everything is quite simple here". Colleagues leave with a flash drive where I recorded the binary file for microcontroller firmware.
And I forget about this task. There are other greater and more captivating challenges. Moreover, once they didn't come, then all is well.
But they came. But only a week later. Saying couldn't understand the matter. Tied themselves into knots. Our testing bench is not working. Rather, it works, but not quite as it should. We have already re-soldered it again and replaced the executive electromechanical parts. Does not work ... Maybe you'll have a look? May be, there is still something wrong in the program...
I open code and immediately see an error like this:
uchar A[3]; .... for (uchar i = 0; i != 4; i++)  average += A[i]; average /= 3;
I took another project as a base, and the code was written using a Copy-Paste method. In one place I forgot to replace 4 with 3. I was so ashamed that I made two people waste their working week".
The second reason: program updating is expensive, impossible or too late
Errors in embedded devices are extremely unpleasant that it is impossible or nearly impossible to fix them if the serial production started. If hundreds of thousands of washing machines have been already released and sent to shops, what should I do if in a certain mode, the machine is running inappropriately? Generally, it's a rhetorical question and here are two real options:
Forgive, forget and receive negative customer reviews on various sites, spoiling reputation. You can, of course, release and send application instructions "not to do so", but it's also a weak option.
Withdraw the series and do a firmware update. Costly affair.
Moreover, regardless whether the circulation is large or small, bugs fixing may be problematic or too late. The rocket fell, the error was detected, but too late. The patients died, the error was detected, but it will not return people. Antimissile weapons system begins to overshoot, the error was found, but there is nothing pleasant in this story. Cars didn't brake, errors were found, but there is no good for injured.
The conclusion is very simple. Code of embedded devices should be tested as thoroughly as possible, especially if the errors can lead to victims or serious material losses.
Static code analysis doesn't guarantee the absence of errors in code. However, you must use every opportunity to additionally verify the correctness of code. Static analyzers can point at lots of different bugs that manage to stay in the code even after several Code-Reviews.
If in your device there will be less errors thanks to static analysis, it is amazing. Perhaps, thanks to detecting these very errors, no one will die, or the company won't lose big sums of money or reputation because of client complaints.
The third reason: a developer may not know that he's doing something wrong
Errors in programs can be figuratively divided into two types. A programmer knows about the errors of first type and they appear in code accidentally, inadvertently. Errors of the second type occur when the programmer simply doesn't know that you cannot write code this or that way. In other words, he can read such code as much as he wants, but still won't find the bug.
Static analyzers have a knowledge base about the various patterns that in certain conditions cause an error. Therefore, they may indicate an error to the programmer, the existence of which he himself would hardly have guessed. An example would be using a 32-bit type time_t, which may result in malfunction of the device after 2038.
Another example is undefined behavior, which occurs because of incorrect use of shift operators <</>>. These operators are very widely used in code of microcontrollers. Unfortunately, programmers often use these operators very negligently, making the program unreliable and dependent on the version and compiler settings. Yet the program may work, but not because it is written correctly, but due to luck.
By using a static analyzer, programmers can hedge themselves against many unpleasant situations. Additionally, the analyzer can be used to monitor the quality of code in general, which is actual, when the number of project participants increases or changes. In other words, the tool helps to track, whether a novice started to write bad code.
Conclusion
There is one more reason to necessarily use a static code analyzer. This is when the project must meet a certain standard of software development of the language, such as MISRA C. However, rather, it refers to administrative measures, and is a bit away from the topic.
I wanted to show that the use of static analyzer is uniquely appropriate for any embedded project. Use this method and you will be able to:
Reduce time for searching and fixing bugs (example);
Reduce the likelihood of critical bugs;
Reduce the likelihood of necessity to update the firmware;
Monitor the overall code quality (we recommend to additionally look towards SonarQube);
Control the quality of the work of the new team members;
Monitor code quality of third-party modules/libraries.
There are no reasons not to use static code analysis, except laziness and illusion of superiority.
Tumblr media
Use static code analyzers! There are a lot of them.
Surely, we offer to pay attention to our PVS-Studio code analyzer, which has recently started to support a number of ARM-compilers.
6 notes · View notes
viva64 · 7 years ago
Text
Static Code Analyzer PVS-Studio 6.22 Now Supports ARM Compilers (Keil, IAR)
PVS-Studio is a static code analyzer detecting errors and potential vulnerabilities in the code of applications written in C, C++, and C#. We've been entertaining the readers of our blog for a long time by checking various open-source projects and commenting on the bugs found. Now our articles have every chance to become even more interesting because PVS-Studio can now check the code of embedded devices. We have added support for a few ARM compilers, which I talk about in detail below. Bugs in embedded devices and robots could be more of a spectacle than bugs in regular applications. When showing up in such devices, bugs don't simply cause a program to crash or hang, or display an image incorrectly; they make Wi-Fi kettles go mad and boil the water until it's all gone and the thermostat trips. That is, bugs tend to be more interesting and creepy in the world of embedded systems.
Tumblr media
My most spectacular bug
I've made a lot of coding mistakes over my programming career. Those errors were, however, somewhat dull. They just made programs misbehave or dereference a null pointer, and so on. Yes, those were true bugs that needed fixing. But the most impressive error I've ever made was when I was tinkering with my homemade robots.
I'm just a layman in robotics, and I've built all my machines just for the sake of fun and experiment. Among others, I've built four small remotely controlled robots that could play robot football and "catch the mouse". Without going into detail, they could do the following: move on their wheels, hit the ball, grasp with their claws, make sounds, and flash their LEDs. Here's a photo of one of those things as proof (click on the image to enlarge):
This bot is based on the ATmega8A microcontroller (8 Kbyte Flash, 512 byte EEPROM, 1 Kbyte RAM). In the first version of the firmware, one of the microcontroller timers would generate an interrupt whose handler was reading the commands transmitted from the remote control. A command received was written to a FIFO buffer from which it would then be retrieved and executed in the main program loop. Those commands were: move forward/backward; turn left/right; move forward turning slightly to the left; grasp the mouse; hit the ball; etc.
My implementation was actually too complicated. I got rid of the FIFO buffer later and rewrote the entire program in a simpler and neater form.
Now imagine me uploading the new firmware to the microcontroller, switching the robot on, and... The bot suddenly starts living on its own!
Here it is, moving across the floor chaotically, snapping its claw, hitting an invisible ball, flashing its lights. The funniest thing is that I don't even know why. There's simply no code in its firmware, I believe, that would make it do all these things.
It was the strongest impression of a software bug I've ever had over all my years as a programmer. It's one thing having a program crash because of a stack overflow, and quite another seeing a crazy robot rushing about, a robot built by you, without your having a slightest idea of how that could become possible. I wish I was smart enough at the time to take a video of the happening, with my facial expression in the background :).
It didn't take me long to figure out that I had made one of the most classic programming mistakes, namely forgetting to initialize the variable storing the number of unprocessed commands in the FIFO buffer. The robot started executing a random sequence of commands, reading the data from the buffer, as well as from beyond it.
Why am I telling you this? Well, I just wanted to show you that bugs in microcontroller firmware could be more dramatic than those in regular applications, and I hope you will also enjoy my other articles to come. Now, let's get back to the subject of this one, which is the release of the new PVS-Studio version.
PVS-Studio 6.22
In the new version of the analyzer, PVS-Studio 6.22, our team has improved its mechanics to enable it to check projects built with the following compilers:
ARM Compiler 5 and ARM Compiler 6 within the Keil uVision 5 environment.
ARM Compiler 5 and ARM Compiler 6 within the Keil DS-MDK environment.
IAR C/C++ Compiler for ARM within the IAR Embedded Workbench environment.
RT-Thread project
I needed an open-source project to demonstrate PVS-Studio's new capabilities, so I went for RT-Thread. This project can be built in the gcc/keil/iar modes. For the sake of additional testing, we checked it in both Keil and IAR modes. The logs were almost identical, so I don't even remember which I was working with when writing this article.
Now I should say a few words about the RT-Thread project itself.
RT-Thread is an open source IoT operating system from China, which has strong scalability: from a tiny kernel running on a tiny core, for example ARM Cortex-M0, or Cortex-M3/4/7, to a rich feature system running on MIPS32, ARM Cortex-A8, ARM Cortex-A9 DualCore etc.
Official website: rt-thread.org.
Source code: rt-thread.
I find the RT-Thread operating system a perfect candidate to be the first embedded system checked with PVS-Studio. 
❗  Read more - https://www.viva64.com/en/b/0561/
5 notes · View notes
viva64 · 7 years ago
Text
PVS-Studio analyzer for embedded-developers
Tumblr media
PVS-Studio is a static code analyzer that detects errors and potential vulnerabilities in programs written in C, C++, and C#.  In the new version of the PVS-Studio analyzer 6.22 our team finalized the infrastructure for checking the embedded projects of the following type:
1. Support of ARM Compiler 5 and ARM Compiler 6 was introduced as a part of the environment Keil uVision 5.
2. Support of ARM 5 and ARM 6 compilers was introduced as a part of the environment Keil DS-MDK.
3. And also IAR C/C++ Compiler for ARM as a part of the environment IAR Embedded Workbench.
You can download the demo version of PVS-Studio here.
We understand that many projects for embedded systems are small and it will prove to be impractical to buy a license. That’s why, we provide the option of free license, details of which can be found in the article "How to use PVS-Studio for Free”. The great advantage of our free license option is the ability to use it not only in open, but also in closed projects.
We think that many embedded developers are not familiar or almost unfamiliar with the PVS-Studio analyzer. Therefore, we offer them to get acquainted with our blog and examples of bugs that we found in demonstration purposes in the well-known open source projects.
6 notes · View notes
viva64 · 7 years ago
Text
Errors in Robots: Expectations VS Reality
You know, I don't think we are going to see the rise of the machines any time soon. I'm currently writing an article about how our team started adapting the PVS-Studio analyzer to the needs of embedded-software developers. As the first step, we supported KEIL and IAR. Examining the bugs found in some of the projects for embedded devices left me overwhelmed with emotions, which I'd like to share with you. The best way to do that, I suppose, is to show you a couple of pictures and bug examples.
Tumblr media
Now, what usually comes to our mind when we think about glitchy robots? A layperson's imagination typically paints the following picture:
Tumblr media
But when in the code of the RT-Thread operating system, I come across bugs like this, I don't believe any of that will come true.
When the Terminator pulls up at the police station to kill Sarah Connor, it'll end up like this:
Tumblr media
So, you can sleep peacefully for now.
.....
Oh, wait, I forgot to tell you that I'm going to write an article where I will show how PVS-Studio will be able to detect bugs like that... Oops!
4 notes · View notes
viva64 · 7 years ago
Link
13 notes · View notes
viva64 · 7 years ago
Text
Chromium: Typos
We present a series of articles where we share some tips on how to write high-quality code, using the bugs found in the Chromium project as examples. This is Part 4, where I talk about the problem of typos and writing code using the "Copy-Paste method".
Tumblr media
Nobody is safe from typos. They are found even in the code written by the most skilled programmers. Sadly, skill and experience don't protect you from accidentally writing a wrong variable name or omitting a few symbols. That's why typos have always been around, and always will be.
Writing code using the Copy-Paste method adds to the number of defects in source code. Unfortunately, it is a very effective technique, and there's nothing to be done about that. It takes much less time to copy a few lines and make slight changes in them than type the entire block of code from scratch. I'm not even going to bother trying to talk you out of using this technique, as I'm guilty of using it too. The annoying side effect of Copy-Paste is that you could easily forget to modify the code copied. Such mistakes are also sort of typos, as they have to do with forgetting to change the copied block of code or making wrong changes as a result of inattention.
Let's look at the typos that I found when examining the analysis report generated by PVS-Studio. As I mentioned in the introductory article, I only skimmed through it, so I may have missed some defects. In this article, I will be talking about the silliest and simplest mistakes, but that doesn't make any one of them any less of a mistake.
Null-pointer Dereference
The Common Weakness Enumeration classifies null-pointer dereference as CWE-476.
The examples below are taken from the source code of the Chromium project.
class Display : .... {  ....  std::unique_ptr<FocusController> focus_controller_;  .... } Display::~Display() {  ....  if (!focus_controller_) {    focus_controller_->RemoveObserver(this);    focus_controller_.reset();  }  .... }
The condition is incorrect: the pointer is dereferenced if null. The '!' character obviously shouldn't be here.
PVS-Studio diagnostic message: V522 CWE-476 Dereferencing of the null pointer 'focus_controller_' might take place. display.cc 52
The next error should be given the title "The classic of classics".
void AppViewGuest::CreateWebContents(....) {  ....  if (!guest_extension ||      !guest_extension->is_platform_app() ||      !embedder_extension |      !embedder_extension->is_platform_app()) {    callback.Run(nullptr);    return;  }  .... }
There's a typo here. The programmer accidentally wrote the '|' operator instead of '||'. As a result, the embedder_extension pointer is dereferenced, no matter if it's null or not.
Note. If you are only slightly familiar with the C++ language, I recommend reading the article "Short-circuit evaluation" to figure out why this is an error.
PVS-Studio diagnostic message: V522 CWE-476 Dereferencing of the null pointer 'embedder_extension' might take place. Check the bitwise operation. app_view_guest.cc 186
The next defect has to do with incomplete code. I think we should treat it as a typo too. The programmer intended to assign some value to a smart pointer but forgot to do so.
std::unique_ptr<base::ListValue> NetworkingPrivateServiceClient::GetEnabledNetworkTypes() {  std::unique_ptr<base::ListValue> network_list;  network_list->AppendString(::onc::network_type::kWiFi);  return network_list; }
The smart pointer is null by default. Since it doesn't change after declaration, we get null-pointer dereference.
PVS-Studio diagnostic message: V522 CWE-476 Dereferencing of the null pointer 'network_list' might take place. networking_private_service_client.cc 351
Now let's find a more complex case.
Response CSSAgent::getMatchedStylesForNode(int node_id,  Maybe<CSS::CSSStyle>* inline_style) {  UIElement* ui_element = dom_agent_->GetElementFromNodeId(node_id);  *inline_style = GetStylesForUIElement(ui_element);  if (!inline_style)    return NodeNotFoundError(node_id);  return Response::OK(); }
PVS-Studio diagnostic message: V595 CWE-476 The 'inline_style' pointer was utilized before it was verified against nullptr. Check lines: 142, 143. css_agent.cc 142
The inline_style pointer is dereferenced before being checked for nullptr. I guess this is because of a typo: the programmer simply forgot to add the asterisk character '*', in which case the correct version should look like this:
*inline_style = GetStylesForUIElement(ui_element); if (!*inline_style)  return NodeNotFoundError(node_id);
However, it could be the inline_style pointer that the programmer actually wanted to check. In that case, we're dealing with an error in function logic rather than a plain typo. To fix it, the check must be moved up so that it is executed prior to the call to the GetStylesForUIElement function. The function should then look like this:
Response CSSAgent::getMatchedStylesForNode(int node_id,  Maybe<CSS::CSSStyle>* inline_style) {  UIElement* ui_element = dom_agent_->GetElementFromNodeId(node_id);  if (!inline_style)    return NodeNotFoundError(node_id);  *inline_style = GetStylesForUIElement(ui_element);  return Response::OK(); }
That's all for null-pointer dereference errors in the code of Chromium, but there's one found in the V8 engine.
bool Object::IsSmi() const { return HAS_SMI_TAG(this); } bool IC::IsHandler(Object* object) {  return (object->IsSmi() && (object != nullptr)) ||         object->IsDataHandler() ||         object->IsWeakCell() ||         object->IsCode(); }
The object pointer is first dereferenced and only then checked for nullptr. Well, the entire expression looks odd, as if it was written in haste, which caused the typo: the programmer first wrote object->IsSmi(), then recalled that the object pointer should be checked for nullptr, and added the check. What they didn't do is pause and think it all over :).
Here PVS-Studio emits two warnings at once:
V522 CWE-628 Dereferencing of the null pointer 'object' might take place. The null pointer is passed into 'IsHandler' function. Inspect the first argument. Check lines: 'ic-inl.h:44', 'stub-cache.cc:19'. ic-inl.h 44
V713 CWE-476 The pointer object was utilized in the logical expression before it was verified against nullptr in the same logical expression. ic-inl.h 44
❗️ Read more - https://www.viva64.com/en/b/0556/
10 notes · View notes
viva64 · 7 years ago
Text
Chromium: Memory Leaks
We'd like to present the series of articles dealing with the recommendations on writing code of high quality using the examples of errors found in the Chromium project. This is the third part, which will be focused on memory leaks.
Tumblr media
I think the code of Chromium project and the libraries used in it is of very high quality. Sure, in the introductory article, I wrote about 250 errors, but actually, this is a very small number. In view of probability laws, no doubts that in a large project many errors will be found.
However, if we talk about memory leaks, there are not few of them. I suppose that what lets the Chromium developers down is that they give preference to dynamic code analyzers. Of course, these tools have a number of benefits. For instance, they don't issue false positives, once a dynamic analyzer has detected an error, we know for sure that an errors is really presented.
On the other hand, dynamic analysis also has weaknesses. If a code is not executed, an error will not be detected. But any developer realizes that it is very difficult to cover 100% of code with tests, or rather, this is impossible in practice. As a result, the number of errors remains in code and they are waiting for a favorable set of circumstances to reveal themselves.
Here static code analysis might come to aid. Yes, this is a hint for Google developers, that we will be glad, if they become our clients. Moreover, we are ready to get the additional work done on PVS-Studio adaptation and configuring for the specifications of the Chromium project. Our team is also ready to take on the correction of errors found. We already had similar experience (example).
But let's get back to memory leaks. As you will see, they hide in code that is rarely controlled. Basically, these are different error handlers. Static analyzers, unlike dynamic, are not always able to monitor the "future of a pointer" on the allocated memory and don't detect a lot of memory leaks. On the other hand, static analyzers check all code, regardless of the likelihood of its execution and notice errors. Thus, dynamic and static analyzers are complementary.
Let's see what I've noticed during studying the report issued by PVS-Studio. As I wrote in the introductory article, I skimmed through the report quite fluently, so there may be other, unnoticed errors. I would also like to note that memory leaks are extremely unpleasant for such a project as Chromium, so it will be exciting to talk about them. Such errors can be classified as CWE-401.
Read more - https://www.viva64.com/en/b/0555/
4 notes · View notes
viva64 · 7 years ago
Link
Ladys and gentlemen, we must do something about the memset function in C++ programs! Rather, it is clear what we must do at once - we have to stop using it. I wrote the article "The most dangerous function in the C/C++ world" at the time. I think it is easy to guess that this article will be exactly about memset.
However, I will not waste words, so I am going to demonstrate the danger of this function once again with the examples. The code of the Chromium project and the libraries used in it are of very high quality. Google developers pay much attention to the tests and the use of various tools for detecting defects. For instance, Google has developed such tools as AddressSanitizer, ThreadSanitizer and MemorySanitizer.
As a result, there are few errors related to memset function, but sadly, that they are still presented. Despite the errors, it is a very qualitative project!
Let's see what I noticed during studying the report issued by the PVS-Studio. As I wrote in the introductory article, I looked through the report quite fluently, so there may be other, unnoticed errors. However, the found defects will be enough for us to discuss the malloc function.
Read more - https://www.viva64.com/en/b/0553/
4 notes · View notes
viva64 · 7 years ago
Text
Chromium: the Sixth Project Check and 250 Bugs
This introduction begins a series of articles dealing with a recurrent check of a Chromium project using PVS-Studio static code analyzer. The articles include various patterns of errors and recommendations that reduce the likelihood of such errors appearing in code. However, to start with, some sort of an introduction should be presented, which will answer a number of questions in advance, and present all of the bugs discovered to the developers of Chromium, so that they can start fixing them without waiting for the end of this article series.
Tumblr media
Read more - https://www.viva64.com/en/b/0552/
6 notes · View notes