<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Emma Brown on Medium]]></title>
        <description><![CDATA[Stories by Emma Brown on Medium]]></description>
        <link>https://medium.com/@emma_programmer?source=rss-d2ed7cc547b4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Emma Brown on Medium</title>
            <link>https://medium.com/@emma_programmer?source=rss-d2ed7cc547b4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:19:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emma_programmer/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Recent interesting content from the PVS-Studio Team]]></title>
            <link>https://medium.com/@emma_programmer/recent-interesting-content-from-the-pvs-studio-team-d98fcd3bb2b5?source=rss-d2ed7cc547b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d98fcd3bb2b5</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pvs-studio]]></category>
            <dc:creator><![CDATA[Emma Brown]]></dc:creator>
            <pubDate>Mon, 16 Jan 2017 12:25:56 GMT</pubDate>
            <atom:updated>2017-01-16T12:25:56.199Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*GTwCScJhUgi6NokJTOKdyw.png" /></figure><p>Recently we have published several articles which many a man can find not just interesting but also useful. We understand that far from everyone keep tabs on our publications, and someone could have missed some important points. We decided to post here links to the most valuable articles we have published recently.</p><p>1. We introduced a new license which allows a free usage of PVS-Studio if you meet certain conditions. For more details refer to <a href="http://www.viva64.com/en/b/0457/">How to use PVS-Studio for Free</a>. After we have published this article, two enthusiasts described how to embed PVS-Studio into <a href="http://www.viva64.com/en/b/0459/">Anjuta DevStudio</a> and <a href="http://www.viva64.com/en/b/0458/">Eclipse CDT</a>.</p><p>2. We wrote an <a href="http://www.viva64.com/en/b/0466/">article</a> that describes the inner workings of the PVS-Studio analyzer and the technologies we use to detect errors.</p><p>3. We published quite an interesting article where we summarize progress in development of PVS-Studio analyzer. The fact is, we started our journey 10 years ago. More details are available here: <a href="http://www.viva64.com/en/b/0465/">http://www.viva64.com/en/b/0465/</a>. At the same time we <a href="http://www.viva64.com/en/b/0464/">described</a> how we created a new version of our site.</p><p>Furthermore recently we have checked (or re-checked) some open-source projects to demonstrate power of the PVS-Studio static code analyzer:</p><p>1. <a href="http://www.viva64.com/en/b/0425/">GCC</a></p><p>2. <a href="http://www.viva64.com/en/b/0446/">LLVM</a></p><p>3. <a href="http://www.viva64.com/en/b/0460/">Linux Kernel</a></p><p>I hope I provided you with an interesting reading for the evening.</p><p>If you have any questions regarding the PVS-Studio static code analyzer or its licensing terms, please contact me at <a href="/service/mailto:xxx@viva64.com">fateeva@viva64.com</a>. I’ll be happy to assist you with running the analyzer on your project and setting it up. If capabilities of a demo version are insufficient for you, I’ll generate a temporary license key so that you can discover all the features of our analyzer in detail. Anyway, do not hesitate to contact me. To solve any technical questions, I’ll involve experienced programmers from our team. Together we can solve any difficulties.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d98fcd3bb2b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How PVS-Studio does the bug search: methods and technologies]]></title>
            <link>https://medium.com/@emma_programmer/how-pvs-studio-does-the-bug-search-methods-and-technologies-8438978d6e1e?source=rss-d2ed7cc547b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8438978d6e1e</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[static-code-analysis]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Emma Brown]]></dc:creator>
            <pubDate>Thu, 12 Jan 2017 12:12:52 GMT</pubDate>
            <atom:updated>2017-01-12T12:12:52.817Z</atom:updated>
            <content:encoded><![CDATA[<p>PVS-Studio is a static code analyzer, that searches for errors and vulnerabilities in programs written in C, C++ and C#. In this article, I am going to uncover the technologies that we use in PVS-Studio analyzer. In addition to the general theoretical information, I will show practical examples of how certain technology allows the detection of bugs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*YsL-yz3xjw8uBXfl.png" /></figure><h3>Introduction</h3><p>The reason for writing this article, was my report on the open conference ISPRAS OPEN 2016 that took place in the beginning of December, in the main building of the Russian Academy of Sciences. The subject of the report: “The operation principles of PVS-Studio static code analyzer” (<a href="https://yadi.sk/i/BUr5G_Yx38YFpU">presentation in the pptx format</a>)</p><p>Unfortunately, the time for the report was very limited, so I had to come up with a very short presentation, and I couldn’t cover all the topics I wanted to cover. And so I decided to write this article, where I will give more details on the approaches and algorithms that we use in the development of the PVS-Studio analyzer.</p><p>At the moment, PVS-Studio is, in fact, two separate analyzers, one for C++ and another for C#. Moreover, they are written in different languages; we develop the kernel of C++ analyzer in C++, and the C# kernel — in C#.</p><p>However, developing these two kernels, we use similar approaches. Besides this, a number of employees participate in the development of both C++ and C # diagnostics at the same time. This is why I won’t separate these analyzers any further in this article. The description of the mechanisms will be the same for both analyzers. Of course, there are some differences, but they are quite insignificant for the analyzer overview. If there is a need to specify the analyzer, I will say if I am talking about the C++ analyzer or C#.</p><h3>The team</h3><p>Before I get into the description of the analyzer, I will say a couple of words about our company, and our team.</p><p>The PVS-Studio analyzer is developed by the Russian company — OOO “Program Verification Systems”. The company is growing and developing solely on profit gained from product sales. The company office is located in Tula, 200 km to the south of Moscow.</p><p>The site: <a href="http://www.viva64.com/en/pvs-studio/">http://www.viva64.com/en/pvs-studio/</a>.</p><p>At the time of writing this article, the company has 24 employees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/0*1KLqXs3EQPtaF6nt.png" /></figure><p>To some people it may seem that one person would be enough to create the analyzer. However, the job is much more complicated and requires a lot of work-years. The maintenance and further development of the product requires even more work-years.</p><p>We see our mission in the promoting the methodology of static code analysis. And of course, to get financial reward, developing a powerful tool that allows the detection of a large number of bugs at the earliest stages of development.</p><h3>Our achievements</h3><p>To spread the word about PVS-Studio, we regularly check open source projects, and describe the findings in our <a href="http://www.viva64.com/en/inspections/">articles</a>. At the moment, we have checked about 270projects.</p><p>Since the moment we started writing articles we have found <a href="http://www.viva64.com/en/examples/">more than 10 000 errors</a>, and reported them to the authors of the projects. We are quite proud of this, and I should explain why.</p><p>If we divide the number of bugs found by the number of projects, we get quite an unimpressive number: 40 errors per project. So I want to highlight an important point; these 10000 bugs are a side effect. We have never had the goal to find as many errors as possible. Quite often, we stop when we find enough errors for an article.</p><p>This shows quite well the convenience, and the abilities, of the analyzer. We are proud that we can simply take different projects and start searching for bugs immediately, almost without the need to set up the analyzer. If it weren’t so, we wouldn’t be able to detect 10000 bugs just as a side effect of writing the articles.</p><h3>PVS-Studio</h3><p>Briefly, <a href="http://www.viva64.com/en/pvs-studio/">PVS-Studio</a> is:</p><ul><li>More than 340 diagnostics for C, C++</li><li>More than 120 diagnostics for C#</li><li>Windows;</li><li>Linux;</li><li>Plugin for Visual Studio</li><li>Quick Start (compilation monitoring)</li><li>Various additional abilities, integration with SonarQube and IncrediBuild for example.</li></ul><h3>Why C and C++</h3><p>The C and C++ languages are extremely effective and graceful. But in return they require a lot of attention, and deep knowledge of the subject. This is why static analyzers are so popular among C and C++ developers. Despite the fact that the compilers and development tools are also evolving, nothing really changes. I will explain what I mean by that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*B-8WRmAWmykMrz7I.png" /></figure><p>We did a check of the first Cfront compiler, written in 1985 in honor of the 30-year anniversary. If you are interested, you may find more details in the article: “<a href="http://www.viva64.com/en/b/0355/">Celebrating the 30-th anniversary of the first C++ compiler: let’s find the bugs in it</a>”.</p><p>There, we found the following bug:</p><pre>Pexpr expr::typ(Ptable tbl)<br>{<br>  ....<br>  Pclass cl;<br>  ....<br>  cl = (Pclass) nn-&gt;tp;<br>  cl-&gt;permanent=1;                                    // &lt;= use<br>  <strong>if</strong> (cl == 0) error(&#39;i&#39;,&quot;%k %s&#39;sT missing&quot;,CLASS,s); // &lt;= test<br>  ....</pre><p>First, the pointer <em>cl</em> is dereferenced, and only then it is verified against NULL.</p><p>30 years passed.</p><p>Here is the modern Clang compiler, not Cfront. And here is what PVS-Studio detects in it:</p><pre>....<br>Value *StrippedPtr = PtrOp-&gt;stripPointerCasts();<br>PointerType *StrippedPtrTy = <br>  dyn_cast&lt;PointerType&gt;(StrippedPtr-&gt;getType());  // &lt;= use<br><strong>if</strong> (!StrippedPtr)                                 // &lt;= test<br>  <strong>return</strong> 0;<br>....</pre><p>There is a saying: “Bugs. C++ bugs never change”. The pointer <em>StrippedPtr </em>is dereferenced first, and then verified against NULL.</p><p>The analyzers are extremely helpful for C and C++ languages. This is why we started developing PVS-Studio analyzer for these languages, and will continue doing so. There is a high probability that PVS-Studio won’t have less job in the future, as these languages are really popular, and dangerous, at the same time.</p><h3>Why C #</h3><p>Of course, in some regard, C# is more thought-out, and safer than C++. Still, it is not perfect and it also causes a lot of hassle for programmers. I’ll give only one example, because it is a topic for a separate article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/0*nB9xhtyz4NPV7zOC.png" /></figure><p>Here is our old good buddy — the error we described before. A fragment from the project PowerShell:</p><pre>....<br>_parameters = <strong>new</strong> Dictionary&lt;string, ParameterMetadata&gt;(<br>  other.Parameters.Count,                          // &lt;= use<br>  StringComparer.OrdinalIgnoreCase); <br><strong>if</strong> (other.Parameters != null)                      // &lt;= test<br>....</pre><p>First, the reference <em>other.Parameters </em>is<em> </em>used to get the property <em>Count</em>, and only then verified against <em>null</em>.</p><p>As you can see, in C# the pointers are now called references, but it didn’t really help. If we touch upon the topic of typos, they are made everywhere, regardless of the language. In general, there is a lot to do in C#, so we continue developing this direction.</p><h3>What’s next?</h3><p>For now we don’t have exact plans on what language we want to support next. We have two candidates: Objective-C and Java. We are leaning more towards Java, but it is not decided yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/0*afU8MBOZeA_vjtkG.png" /></figure><h3>Technologies we do not use in PVS-Studio</h3><p>Before speaking about the inner structure of PVS-Studio, I should briefly state what you won’t find there.</p><p>PVS-Studio has nothing to do with the Prototype Verification System (<a href="http://pvs.csl.sri.com/">PVS</a>). It’s just a coincidence. PVS-Studio is a contraction of ‘Program Verification Systems’ (OOO “Program Verification Systems”).</p><p>PVS-Studio does not use formal grammar for the bug search. The analyzer works on a higher level. The analysis is done on the basis of the <a href="http://www.viva64.com/en/t/0039/">derivation tree</a>.</p><p>PVS-Studio does not use the Clang compiler to analyze C/C++ code; we use Clang to do the preprocessing. More details can be found in the article: “<a href="http://www.viva64.com/en/b/0186/">A few words about interaction between PVS-Studio and Clang</a>”. To build the derivation tree, we use our own parser that was based on the OpenC++ library, which has been quite forgotten now in the programming world. Actually there is almost nothing left from this library and we implement the support of new constructions ourselves.</p><p>When working with C# code we take <a href="http://www.viva64.com/en/b/0399/">Roslyn</a> as the basis. The C# analyzer of PVS-Studio checks the source code of a program, which increases the quality of the analysis compared with binary code analysis (Common Intermediate Language).</p><p>PVS-Studio does not use the string matching and regular expressions. This way, is a dead-end. This approach has so many disadvantages that it’s impossible to create a more or less qualitative analyzer based on it, and some diagnostics cannot be implemented at all. This topic is covered in more details in the article “<a href="http://www.viva64.com/en/b/0087/">Static analysis and regular expressions</a>”.</p><h3>Technologies we use in PVS-Studio</h3><p>To ensure high quality in our static analysis results, we use advanced methods of source code analysis for the program and its control flow graph: let’s see what they are.</p><p><strong>Note. </strong>Further on, we’ll have a look at several diagnostics, and take a look at the principles of their work. It is important to note that I deliberately omit the description of those cases when the diagnostic should not issue warnings, so as not to overload this article with details. I have written this note for those who didn’t have any experience in the development of an analyzer: don’t think that it’s as simple as it may seem after reading the material below. It is only 5% of the task to create the diagnostic. It’s not hard for the analyzer to complain about suspicious code, it’s much harder to not complain about the correct code. We spend 95% of our time “teaching” the analyzer to detect various programming techniques, which may seem suspicious for the diagnostic, but in reality they are correct.</p><h3>Pattern-based analysis</h3><p>Pattern-based analysis is used to search for fragments in the source code that are similar to known error containing code. The number of patterns is huge, and the complexity of their detection varies greatly.<br>Moreover, in some cases, the diagnostics use empirical algorithms to detect typos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/0*h0VVuwEQyZX6uFyG.png" /></figure><p>For now, let’s consider two <strong>simplest cases</strong> that are detected with the help of the pattern-based analysis. The first simple case:</p><pre><strong>if</strong> ((*path)[0]-&gt;e-&gt;dest-&gt;loop_father != path-&gt;last()-&gt;e-&gt;....)<br>{<br>  delete_jump_thread_path (path);<br>  e-&gt;aux = NULL;<br>  ei_next (&amp;ei;);<br>}<br><strong>else</strong><br>{<br>  delete_jump_thread_path (path);<br>  e-&gt;aux = NULL;<br>  ei_next (&amp;ei;);<br>}</pre><p>PVS-Studio warning: V523 The ‘then’ statement is equivalent to the ‘else’ statement. tree-ssa-threadupdate.c 2596</p><p>The same set of actions is performed regardless of the condition. I think everything is so simple that it requires no special explanation. By the way, this code fragment is not taken from a student’s coursework, but from the code of the GCC compiler. The article “<a href="http://www.viva64.com/en/b/0425/">Finding bugs in the code of GCC compiler with the help of PVS-Studio</a>” describes those bugs we found in GCC.</p><p>Here is the second simple case (the code is taken from the FCEUX project):</p><pre><strong>if</strong>((t=(<strong>char</strong> *)realloc(next-&gt;name,strlen(name+1))))</pre><p>PVS-Studio warning: V518 The ‘realloc’ function allocates strange amount of memory calculated by ‘strlen(expr)’. Perhaps the correct variant is ‘strlen(expr) + 1’. fceux cheat.cpp 609</p><p>The following erroneous pattern gets analyzed. Programmers know that when they allocate memory to store a string, it is necessary to allocate the memory for a character, where the end of line character will be stored (<a href="http://www.viva64.com/en/t/0088/">terminal null</a>). In other words, programmers know that they must add +1 or +sizeof(TCHAR). But sometimes they do it rather carelessly. As a result, they add 1 not to the value, which returns the <em>strlen </em>function, but to a pointer.</p><p>This is exactly what happened in our case. <em>strlen(name)+1 </em>should be written instead of <em>strlen(name+1).</em></p><p>There will be less memory allocated than is necessary, because of such an error. Then we’ll have the access out of the allocated buffer bound, and the consequences will be unpredictable. Moreover, the program can pretend that it works correctly, if the two bytes after the allocated buffer aren’t used thanks to mere luck. With a worse-case scenario, this defect can cause induced errors that will show up in a completely different place.</p><p>Now let’s have a look at the analysis of the <strong>medium complexity level</strong>.</p><p>The diagnostic is formulated like this: we warn that after using the <em>as</em> operator, the original object is verified against <em>null</em> instead of the result of the <em>as</em> operator.</p><p>Let’s take a look at a code fragment taken from CodeContracts:</p><pre><strong>public</strong> override Predicate <strong>JoinWith</strong>(Predicate other)<br>{<br>  var right = other as PredicateNullness;<br>  <strong>if</strong> (other != null)<br>  {<br>    <strong>if</strong> (<strong>this</strong>.value == right.value)<br>    {</pre><p>PVS-Studio warning: V3019 Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘other’, ‘right’. CallerInvariant.cs 189</p><p>Pay attention, that the variable <em>other </em>gets verified against null, not the <em>right</em> variable. This is clearly a mistake, because further the program works with the <em>right</em> variable.</p><p>And in the end — here is a <strong>complex pattern</strong>, related to the usage of macros.</p><p>The macro is defined in such a way that the operation precedence inside the macro is higher than the priority outside of the macro. Example:</p><pre>#<strong>define</strong> RShift(a) a &gt;&gt; 3<br>....<br>RShift(a &amp; 0xFFF) // a &amp; 0xFFF &gt;&gt; 3</pre><p>To solve this problem we should enclose the <em>a </em>argument in the parenthesis in the macro (it would be better to enclose entire macro too), then it will be like this:</p><pre>#<strong>define</strong> RShift(a) ((a) &gt;&gt; 3),</pre><p>Then the macro will be correctly expanded into:</p><pre>RShift(a &amp; 0xFFF) // ((a &amp; 0xFFF) &gt;&gt; 3)</pre><p>The definition of the pattern looks quite simple, but in practice the implementation of the diagnostic is quite complicated. It’s not enough just to analyze only “#define RShift(a) a &gt;&gt; 3”. If warnings are issued for all strings of this kind, there will be too many of them. We should have a look at the way the macro expands in every particular case, and try to define the situations where it was done intentionally, and when the brackets are really missing.</p><p>Let’s have a look at this bug in a real project; FreeBSD:</p><pre>#<strong>define</strong>  ICB2400_VPINFO_PORT_OFF(chan) \<br>  (ICB2400_VPINFO_OFF +                \<br>   sizeof (isp_icb_2400_vpinfo_t) +    \<br>  (chan * ICB2400_VPOPT_WRITE_SIZE))<br>....<br>off += ICB2400_VPINFO_PORT_OFF(chan - 1);</pre><p>PVS-Studio warning: V733 It is possible that macro expansion resulted in incorrect evaluation order. Check expression: chan — 1 * 20. isp.c 2301</p><h3>Type inference</h3><p>The type inference based on the semantic model of the program, allows the analyzer to have full information about all variables and statements in the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/0*B-wXdp0s413flEhp.png" /></figure><p>In other words, the analyzer has to know if the token <em>Foo</em> is a variable name, or the class name or a function. The analyzer repeats the work of the compiler, which also needs to know the type of an object and all additional information about the type: the size, signed/unsigned type; if it is a class, then how is it inherited and so on.</p><p>This is why PVS-Studio needs to preprocess the *.c/*.cpp files. The analyzer can get the information about the types only by analyzing the preprocessed file. Without having such information, it would be impossible to implement many diagnostics, or, they will issue too many false positives.</p><p><strong>Note.</strong> If someone claims that their analyzer can check *.c/*.cpp files as a text document, without complete preprocessing, then it’s just playing around. Yes, such an analyzer is able to find something, but in general it’s a mere toy to play with.</p><p>So, information about the types is necessary both to detect errors, and also so as not to issue false positives. The information about classes is especially important.</p><p>Let’s take a look at some examples of how information about the types is used.</p><p>The first example demonstrates that information about the type is needed to detect an error when working with the <em>fprintf </em>function (the code is taken from the Cocos2d-x project):</p><pre>WCHAR *<strong>gai_strerrorW</strong>(<strong>int</strong> ecode);<br>....<br>#<strong>define</strong> gai_strerror gai_strerrorW<br>....<br>fprintf(stderr, &quot;net_listen error for %s: %s&quot;,<br>        serv, gai_strerror(n));</pre><p>PVS-Studio warning: V576 Incorrect format. Consider checking the fourth actual argument of the ‘fprintf’ function. The pointer to string of char type symbols is expected. ccconsole.cpp 341</p><p>The function <em>frintf </em>receives the pointer of the <em>char * </em>type as the fourth argument. It accidentally happened so that the actual argument is a string of the <em>wchar_t * type.</em></p><p>To detect this error, we need to know the type that is returned by the function <em>gai_strerrorW</em>. If there is no such information, it will be impossible to detect the error.</p><p>Now let’s examine an example where data about the type helps to avoid a false positive.</p><p>The code “*A = *A;” will be definitely considered suspicious. However, they analyzer will be silent if it sees the following:</p><pre><strong>volatile</strong> <strong>char</strong> *ptr;<br>....<br>*ptr = *ptr;  // &lt;= No V570 warning</pre><p>The <em>volatile</em> specifier gives a hint that it is not a bug, but the deliberate action of a programmer. The developer has to “touch” this memory cell. Why is it needed? It’s hard to say, but if he does it, then there is a reason for it, and the analyzer shouldn’t issue a warning.</p><p>Let’s take a look at an example of how we can detect a bug, based on knowledge about the class.</p><p>The fragment is taken from the <strong>CoreCLR</strong> project.</p><pre><strong>struct</strong> GCStatistics : <strong>public</strong> StatisticsBase {<br>....<br><strong>virtual</strong> <strong>void</strong> <strong>Initialize</strong>();<br><strong>virtual</strong> <strong>void</strong> <strong>DisplayAndUpdate</strong>();<br>.... <br>GCStatistics g_LastGCStatistics;<br>....<br>memcpy(&amp;g_LastGCStatistics, <strong>this</strong>, <strong>sizeof</strong>(g_LastGCStatistics));</pre><p>PVS-Studio warning: V598 The ‘memcpy’ function is used to copy the fields of ‘GCStatistics’ class. Virtual table pointer will be damaged by this. cee_wks gc.cpp 287.</p><p>It’s acceptable to copy one object into another using the <em>memcpy</em> function, if the objects are POD-structures. However, there are virtual methods in the class, which means that there is pointer to a virtual methods table. It’s very dangerous to copy this pointer from one object to another.</p><p>So, this diagnostic is possible due to the fact that we know that the variable of the <em>g_LastGCStatistics </em>is a class instance, and that this class isn’t a POD-type.</p><h3>Symbolic execution</h3><p>Symbolic execution allows the evaluation of variable values that can lead to errors, and perform range checking of values. Sometimes we call this a mechanism of virtual values evaluation: see the article “<a href="http://www.viva64.com/en/b/0394/">Searching for errors by means of virtual values evaluation</a>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/0*r4RzZvOi4PmB3AK4.png" /></figure><p>Knowing the probable values of the variables, we can detect errors such as:</p><ul><li>memory leaks;</li><li>overflows;</li><li>array index out of bounds;</li><li>null pointer dereference in C++/access by a null reference in C#;</li><li>meaningless conditions;</li><li>division by zero;</li><li>and so on.</li></ul><p>Let’s see how we can find various errors, knowing the probable values of the variables. Let’s start with a code fragment taken from the QuantLib project:</p><pre>Handle&lt;YieldTermStructure&gt; md0Yts() {<br>  <strong>double</strong> q6mh[] = {<br>    0.0001,0.0001,0.0001,0.0003,0.00055,0.0009,0.0014,0.0019,<br>    0.0025,0.0031,0.00325,0.00313,0.0031,0.00307,0.00309,<br>    ........................................................<br>    0.02336,0.02407,0.0245 };               // 60 elements<br>  ....<br>  <strong>for</strong>(<strong>int</strong> i=0;i&lt;10+18+37;i++) {             // i &lt; 65   <br>    q6m.push_back(<br>      boost::shared_ptr&lt;Quote&gt;(<strong>new</strong> SimpleQuote(q6mh[i])));</pre><p>PVS-Studio warning: V557 Array overrun is possible. The value of ‘i’ index could reach 64. markovfunctional.cpp 176</p><p>Here the analyzer has the following data:</p><ul><li>the array <em>q6mh </em>contains 60 items;</li><li>the array counter <em>i </em>will have values [0..64]</li></ul><p>Having this data, the V557 diagnostic detects the array index out of bounds during the execution of the <em>q6mh[i] </em>operation.</p><p>Now let’s look at a situation where we have division by 0. This code is taken from the Thunderbird project.</p><pre><strong>static</strong> <strong>inline</strong> size_t <strong>UnboxedTypeSize</strong>(JSValueType type)<br>{<br>  <strong>switch</strong> (type) {<br>  .......<br>  <strong>default</strong>: <strong>return</strong> 0;<br>  }<br>}<br>Minstruction *<strong>loadUnboxedProperty</strong>(<strong>size_t</strong> offset, ....)<br>{<br>  <strong>size_t</strong> index = offset / UnboxedTypeSize(unboxedType);</pre><p>PVS-Studio warning: V609 Divide by zero. Denominator range [0..8]. ionbuilder.cpp 10922</p><p>The <em>UnboxedTypeSize </em>function returns various values, including 0. Without checking that the result of the function may be 0, it is used as the denominator. This can potentially lead to division of the <em>offset </em>variable by zero.</p><p>The previous examples were about the range of integer values. However, the analyzer handles values of other data types, for example, strings and pointers.</p><p>Let’s look at an example of incorrect handling of the strings. In this case, the analyzer stores the information that the whole string was converted to lower or uppercase. This allows us to detect the following situations:</p><pre>string lowerValue = value.ToLower();<br>....<br><strong>bool</strong> insensitiveOverride = lowerValue == lowerValue.ToUpper();</pre><p>PVS-Studio warning: V3122 The ‘lowerValue’ lowercase string is compared with the ‘lowerValue.ToUpper()’ uppercase string. ServerModeCore.cs 2208</p><p>The programmer wanted to check if all the string characters are uppercase. The code definitely has some logical error, because all the characters of this string were previously converted to lowercase.</p><p>So, we can talk on and on about the diagnostics, based on the data of the variable values. I’ll give just one more example related to the pointers and memory leaks.</p><p>The code is taken from the WinMerge project:</p><pre>CMainFrame* pMainFrame = <strong>new</strong> CMainFrame;<br><strong>if</strong> (!pMainFrame-&gt;LoadFrame(IDR_MAINFRAME))<br>{<br>  <strong>if</strong> (hMutex)<br>  {<br>    ReleaseMutex(hMutex);<br>    CloseHandle(hMutex);<br>  }<br>  <strong>return</strong> FALSE;<br>}<br>m_pMainWnd = pMainFrame;</pre><p>PVS-Studio warning: V773 The function was exited without releasing the ‘pMainFrame’ pointer. A memory leak is possible. Merge merge.cpp 353</p><p>If the frame could not be loaded, the function exits. At the same time, the object, whose pointer is stored in the <em>pMainFrame </em>variable, doesn’t get destroyed.</p><p>The diagnostics work as follows. The analyzer remembers that the pointer <em>pMainFrame </em>stores the object address, created with the <em>new</em> operator. Analyzing the control flow graph, the analyzer sees a <em>return</em> statement. At the same time, the object wasn’t destroyed and the pointer continues referring to a created object. Which means that we have a memory leak in this fragment.</p><h3>Method annotations</h3><p>Method annotations provides more information about the used methods than can be obtained by analyzing only their signatures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*maErt3etCmbuVPM8.png" /></figure><p>We have done a lot in annotating the functions:</p><ul><li>C/C++. By this moment we have annotated 6570 functions (standard C and C++ libraries, POSIX, MFC, Qt, ZLib and so on).</li><li>C#. At the moment we have annotated 920 functions.</li></ul><p>Let’s see how a <em>memcmp </em>function is annotated in the C++ analyzer kernel:</p><pre>C_&quot;int memcmp(const void *buf1, const void *buf2, size_t count);&quot;<br>ADD(REENTERABLE | RET_USE | F_MEMCMP | STRCMP | HARD_TEST |<br>    INT_STATUS, nullptr, nullptr, &quot;memcmp&quot;,<br>    POINTER_1, POINTER_2, BYTE_COUNT);</pre><p>A brief explanation of the annotation:</p><ul><li><strong>C_</strong>- an auxiliary control mechanism of annotations (unit tests);</li><li><strong>REENTERABLE</strong> — repetitive call with the same arguments will give the same result</li><li><strong>RET_USE</strong> — the result should be used</li><li><strong>F_MEMCMP</strong> — launch of certain checks for buffer index out of bounds</li><li><strong>STR_CMP — </strong>the function returns 0 in case of equality</li><li><strong>HARD_TEST</strong> — a special function. Some programmers define their own functions in their own namespace. Ignore namespace.</li><li><strong>INT_STATUS</strong> — the result cannot be explicitly compared with 1 or -1;</li><li><strong>POINTER_1, POINTER_2 </strong>— the pointers must be non-zero and different;</li><li><strong>BYTE_COUNT </strong>— this parameter specifies the number of bytes and must be greater than 0.</li></ul><p>The annotations data is used by many diagnostics. Let’s take a look at some of the errors that we found in the code of applications, thanks to the annotation for the <em>memcmp</em> function.</p><p>An example of using the <strong>INT_STATUS </strong>annotation. The CoreCLR project</p><pre><strong>bool</strong> <strong>operator</strong>()(<strong>const</strong> GUID&amp; _Key1, <strong>const</strong> GUID&amp; _Key2) <strong>const</strong><br>{<br>  <strong>return</strong> memcmp(&amp;_Key1, &amp;_Key2, <strong>sizeof</strong>(GUID)) == -1;<br>}</pre><p>V698 Expression ‘memcmp(….) == -1’ is incorrect. This function can return not only the value ‘-1’, but any negative value. Consider using ‘memcmp(….) &lt; 0’ instead. sos util.cpp 142</p><p>This code may work well, but in general, it is incorrect. The function <em>memcmp </em>returns values 0, greater and less than 0. Important:</p><ul><li>“greater than zero” is not necessarily 1</li><li>“less than zero” is not necessarily -1</li></ul><p>Thus, there is no guarantee that such code is well-behaved. At any moment the comparison may start working incorrectly. This may happen during the change of the compiler, changes in the optimization settings, and so on.</p><p>The flag INT_STATUS helps to detect one more kind of an error. The code of Firebird project:</p><pre>SSHORT TextType::compare(ULONG len1, <strong>const</strong> UCHAR* str1,<br>ULONG len2, <strong>const</strong> UCHAR* str2)<br>{<br>  ....<br>  SSHORT cmp = memcmp(str1, str2, MIN(len1, len2));<br>  <strong>if</strong> (cmp == 0)<br>    cmp = (len1 &lt; len2 ? -1 : (len1 &gt; len2 ? 1 : 0));<br>  <strong>return</strong> cmp;<br>}</pre><p>PVS-Studio. V642 Saving the ‘memcmp’ function result inside the ‘short’ type variable is inappropriate. The significant bits could be lost breaking the program’s logic. texttype.cpp 3</p><p>Again, the programmer works inaccurately, with the return result of the <em>memcmp</em> function. The error, is that the type size is truncated; the result is placed into a variable of the <em>short</em> type.</p><p>Some may think that we are just too picky. Not in the least. Such sloppy code can easily create a real vulnerability.</p><p>One such mistake, was the root of a serious vulnerability in MySQL/MariaDB in versions earlier than 5.1.61, 5.2.11, 5.3.5, 5.5.22. The reason for this was the following code in the file ‘sql/password.c’:</p><pre><strong>typedef</strong> <strong>char</strong> my_bool;<br>....<br>my_bool <strong>check</strong>(...) {<br>  <strong>return</strong> memcmp(...);<br>}</pre><p>The thing is, that when a user connects to MySQL/MariaDB, the code evaluates a token (SHA from the password and hash) that is then compared with the expected value of <em>memcmp</em> function. But on some platforms the return value can go beyond the range [-128..127] As a result, in 1 out of 256 cases the procedure of comparing hash with an expected value always returns <em>true</em>, regardless of the hash. Therefore, a simple command on bash gives a hacker root access to the volatile MySQL server, even if the person doesn’t know the password. A more detailed description of this issue can be found here: <a href="http://seclists.org/oss-sec/2012/q2/493">Security vulnerability in MySQL/MariaDB</a>.</p><p>An example of using the <strong>BYTE_COUNT </strong>annotation. The GLG3D project</p><pre><strong>bool</strong> Matrix4::<strong>operator</strong>==(<strong>const</strong> Matrix4&amp; other) <strong>const</strong> {<br>  <strong>if</strong> (memcmp(<strong>this</strong>, &amp;other, <strong>sizeof</strong>(Matrix4) == 0)) {<br>    <strong>return</strong> true;<br>  }<br>  ....<br>}</pre><p>PVS-Studio warning: V575 The ‘memcmp’ function processes ‘0’ elements. Inspect the ‘third’ argument. graphics3D matrix4.cpp 269</p><p>The third argument of the <em>memcmp</em> function is marked as <em>BYTE_COUNT</em>. It is supposed that such an argument should not be zero. In the given example the third actual parameter is exactly 0.</p><p>The error is that the bracket is misplaced there. As a result, the third argument is the expression <em>sizeof(Matrix4) == 0</em>. The result of the expression is false, i.e. 0.</p><p>An example of using the markup <strong>POINTER_1 </strong>and<strong> POINTER_2</strong>. The GDB Project:</p><pre><strong>static</strong> <strong>int</strong><br><strong>psymbol_compare</strong> (<strong>const</strong> <strong>void</strong> *addr1, <strong>const</strong> <strong>void</strong> *addr2,<br><strong>int</strong> length)<br>{<br>  <strong>struct</strong> partial_symbol *sym1 = (<strong>struct</strong> partial_symbol *) addr1;<br>  <strong>struct</strong> partial_symbol *sym2 = (<strong>struct</strong> partial_symbol *) addr2;<br>  <strong>return</strong> (memcmp (&amp;sym1-&gt;ginfo.value, &amp;sym1-&gt;ginfo.value,<br><strong>sizeof</strong> (sym1-&gt;ginfo.value)) == 0<br>          &amp;&amp; .......</pre><p>PVS-Studio warning: V549 The first argument of ‘memcmp’ function is equal to the second argument. psymtab.c 1580</p><p>The first and second arguments are marked as POINTER_1 and POINTER_2. Firstly, this means that they must not be NULL. But in this case, we are interested in the second property of the markup: these pointers must not be the same, the suffixes _1 and _2 show that.</p><p>Because of a typo in the code, the buffer <em>&amp;sym1-&gt;ginfo.</em>value is compared with itself. Relying on the markup, PVS-Studio easily detects this error.</p><p>An example of using the <strong>F_MEMCMP </strong>markup.</p><p>This markup includes a number of special diagnostics for such functions as<em>memcmp</em> and <em>__builtin_memcmp</em>. As a result, the following error was detected in the Haiku project:</p><pre>dst_s_read_private_key_file(....)<br>{<br>  ....<br>  <strong>if</strong> (memcmp(in_buff, &quot;Private-key-format: v&quot;, 20) != 0)<br>    <strong>goto</strong> fail;<br>  ....<br>}</pre><p>PVS-Studio warning: V512 A call of the ‘memcmp’ function will lead to underflow of the buffer ‘“Private-key-format: v”’. dst_api.c 858</p><p>The string “Private-key-format: v” has 21 symbols, not 20. Thus, a smaller amount of bytes is compared than should be.</p><p>Here is an example of using the <strong>REENTERABLE </strong>markup. Frankly speaking, the word “reenterable” does not entirely depict the essence of this flag. However, all our developers are quite used to it, and don’t want to change it for the sake of some beauty.</p><p>The essence of the markup is in the following. The function doesn’t have any state, or any side effects; it doesn’t change the memory, doesn’t print anything, does not remove the files on the disc. That’s how the analyzer can distinguish between correct and incorrect constructions. For example, code such as the following is quite workable:</p><pre><strong>if</strong> (fprintf(f, &quot;1&quot;) == 1 &amp;&amp; fprintf(f, &quot;1&quot;) == 1)</pre><p>The analyzer will not issue any warnings. We are writing two items to the file, and the code cannot be contracted to:</p><pre><strong>if</strong> (fprintf(f, &quot;1&quot;) == 1) // incorrect</pre><p>But this code is redundant, and the analyzer will be suspicious about it, as the function <em>cosf </em>doesn’t have any state and doesn’t write anything:</p><pre><strong>if</strong> (cosf(a) &gt; 0.1f &amp;&amp; cosf(a) &gt; 0.1f)</pre><p>Now let’s go back to the <em>memcmp</em> function, and see which error we managed to find in PHP with the help of the markup we spoke of earlier:</p><pre><strong>if</strong> ((len == 4) /* sizeof (none|auto|pass) */ &amp;&amp;<br>    (!memcmp(&quot;pass&quot;, charset_hint, 4) ||<br>     !memcmp(&quot;auto&quot;, charset_hint, 4) ||<br>     !memcmp(&quot;auto&quot;, charset_hint, 4)))</pre><p>PVS-Studio warning: V501 There are identical sub-expressions ‘!memcmp(“auto”, charset_hint, 4)’ to the left and to the right of the ‘||’ operator. html.c 396</p><p>It is checked twice that the buffer has the “auto” word. This code is redundant, and the analyzer assumes it has an error. Indeed, the comment tells us that comparison with the string “none” is missing here.</p><p>As you can see, using the markup, you can find a lot of interesting bugs. Quite often, the analyzers provide the possibility of annotating the functions themselves. In PVS-Studio, these opportunities are quite weak. It has only several diagnostics that you can use to annotate something. For example, the diagnostic <a href="http://www.viva64.com/en/w/v576/">V576</a> to look for bugs in the usage of the format output functions (printf, sprintf, wprintf, and so on).</p><p>We deliberately don’t develop the mechanism of user annotations. There are two reasons for this:</p><ul><li>Nobody would spend time doing the markup of functions in a large project. It’s simply impossible if you have 10 million lines of code, and the PVS-Studio analyzer is meant for medium and large projects.</li><li>If some functions from a well-known library aren’t marked up, it’s best to write to us, and we’ll annotate them. Firstly, we’ll do it better and faster; secondly, the results of the markup will be available to all our users.</li></ul><h3>Once more — brief facts about the technologies</h3><p>I’ll briefly summarize the information about the technologies we use. PVS-Studio uses:</p><ul><li>Pattern-based analysis on the basis of an abstract syntax tree: it is used to look for fragments in the source code that are similar to the known code patterns with an error.</li><li>Type inference based on the semantic model of the program: it allows the analyzer to have full information on all variables and statements in the code.</li><li>Symbolic execution: this allows evaluating variable values that can lead to errors, perform range checking of values.</li><li>Data-flow analysis: this is used to evaluate limitations that are imposed on the variable values when processing various language constructs. For example, values that a variable can take inside if/else blocks.</li><li>Method annotations: this provides more information about the used methods than can be obtained by analyzing only their signatures.</li></ul><p>Based on these technologies the analyzer can identify the following classes of bugs in C, C++ and C# programs:</p><ul><li>64-bit errors;</li><li>address of the local function is returned from the function by the reference;</li><li>arithmetic overflow, underflow;</li><li>array index out of bounds;</li><li>double release of resources;</li><li>dead code;</li><li>micro optimizations;</li><li>unreachable code;</li><li>uninitialized variables;</li><li>unused variables;</li><li>incorrect shift operations;</li><li>undefined/unspecified behavior;</li><li>incorrect handling of types (HRESULT, BSTR, BOOL, VARIANT_BOOL);</li><li>misconceptions about the work of a function/class;</li><li>typos;</li><li>absence of a virtual destructor;</li><li>code formatting not corresponding with the logic of its work;</li><li>errors due to Copy-Paste;</li><li>exception handling errors;</li><li>buffer overflow;</li><li>security issues;</li><li>confusion with the operation precedence;</li><li>null pointer/reference dereference;</li><li>dereferencing parameters without a prior check;</li><li>synchronization errors;</li><li>errors when using WPF;</li><li>memory leaks;</li><li>integer division by zero;</li><li>diagnostics, made by the user requests</li></ul><p>Conclusion. PVS-Studio is a powerful tool in the search for bugs, which uses an up-to-date arsenal of methods for detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*SwbaIrKei0l83YmB.png" /></figure><p>Yes, PVS-Studio is like a superhero in the world of programs.</p><h3>Testing PVS-Studio</h3><p>The development of an analyzer is impossible without constant testing of it. We use 7 various testing techniques in the development of PVS-Studio:</p><ul><li>Static code analysis on the machines of our developers. Every developer has PVS-Studio installed. New code fragments and the edits made in the existing code are instantly checked by means of incremental analysis. We check C++ and C# code.</li><li>Static code analysis during the nightly builds. If the warning wasn’t catered for, it will show up during the overnight build on the server. PVS-Studio scans C# and C++ code. Besides that we also use the Clang compiler to check C++ code.</li><li>Unit-tests of class, method, function levels. This approach isn’t very well-devloped, as there are moments that are hard to test because of the necessity to prepare a large amount of input data for the test. We mostly rely on high-level tests.</li><li>Functional tests for specially prepared and marked up files with errors. This is our alternative to the classical unit testing.</li><li>Functional tests proving that we are parsing the main system header files correctly.</li><li>Regression tests of individual third-party projects and solutions. This is the most important and useful way of testing for us. Comparing the old and new analysis results we check that we haven’t broken anything; it also provides an opportunity to polish new diagnostic messages. To do this, we regularly check open source projects. The C++ analyzer is tested on 120 projects under Windows (Visual C++), and additionally on 24 projects under Linux (GCC). The test base of the C# analyzer is slightly smaller. It has only 54 projects.</li><li>Functional tests of the user interface — the add-on, integrated in the Visual Studio environment.</li></ul><h3>Conclusion</h3><p>This article was written in order to promote the methodology of static analysis. I think that readers might be interested to know not just about the results of the analyzer work, but also about the inner workings. I’ll try writing articles on this topic from time to time.</p><p>Additionally, we plan to take part in various programming events, such as conferences and seminars. We will be glad to receive invitations to various events, especially those that are in Moscow and St. Petersburg. For example, if there is a programmer meeting in your institute or a company, where people share their experience, we can come and make a report on an interesting topic. For instance, about modern C++; or about the way we develop analyzers, about typical errors of programmers and how to avoid them by adding a coding standard, and so on. Please, send the invitations to my e-mail: karpov [@] viva64.com.</p><p>Finally, here are some links:</p><ul><li><a href="http://www.viva64.com/en/pvs-studio/">Download PVS-Studio for Windows</a></li><li><a href="http://www.viva64.com/en/pvs-studio-download-linux/">Download PVS-Studio for Linux</a></li><li><a href="http://www.viva64.com/en/b/0457/">A free version of the license for PVS-Studio</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8438978d6e1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stories about Christmas and New Year Bugs]]></title>
            <link>https://medium.com/@emma_programmer/stories-about-christmas-and-new-year-bugs-e1a90a114c6?source=rss-d2ed7cc547b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1a90a114c6</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[christmas]]></category>
            <category><![CDATA[amazon]]></category>
            <dc:creator><![CDATA[Emma Brown]]></dc:creator>
            <pubDate>Fri, 23 Dec 2016 13:08:04 GMT</pubDate>
            <atom:updated>2016-12-23T13:08:04.461Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you believe in magic? Of course not — it’s just against logic! Programmers are serious-minded and well-educated people of a realistic outlook. Well, you didn’t favor fairy tales as a child either, did you? OK, I’m not going to answer for you. Just please make yourself a cup of tea, peel a tangerine, look at the snowflakes falling outside the window, and only then go on to read this Story.</p><p>What you are about to read is a story about an Evil Bug and its multiple attempts to spoil Christmas Eve and New Year’s Eve. It did manage to fulfill its sinister plans a number of times, but, fortunately, in every true fairy tale, evil is always opposed by good.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*4lAl5uPyMf2ziJvT.png" /></figure><h3>Christmas-tree virus</h3><p>On December 17, 1987, a student at the Clausthal University of Technology, former West Germany, a beginner programmer at the time, had a bright idea of an ingenious Christmas greeting for his friends. He sent them a Christmas tree! Of course, he hadn’t cut it down in a forest, nor had he even bought it in a store. He was a programmer, remember? He just wrote a program in the scripting language <a href="https://ru.wikipedia.org/wiki/REXX">REXX</a> for <a href="https://en.wikipedia.org/wiki/VM_(operating_system)">VM/CMS</a> that would draw a nice Christmas tree on the screen and print a few warm words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*Bvcyepk9zTH6MR4D.png" /></figure><p>The hero of our story surely meant well, but Evil Bug interfered, overloading the network and exploiting the self-replicating Christmas program to paralyze private email network IBM Vnet all over the world for two days (the chain was this: university network — EARN — BitNet — IBM Vnet). The hero was suspected to be an anti-hero and his touching greeting, a worm. The programmer’s malicious intent was never proved, but Evil Bug was surely involved in that story.</p><h3>Unprecedented-generosity show</h3><p>People traditionally exchange presents on Christmas Eve and New Year’s Eve. Beautifully packed boxes under the Christmas tree or cute souvenirs in Christmas stockings hung by the fireplace — this is what traditional Christmas and New Year presents look like. However, surprises are particularly pleasant.</p><p><a href="https://www.amazon.com/">Amazon</a> was one of the first Internet services with dozens of thousands of goods of all kinds sold and bought daily. A perfect place to pick presents! That’s what site visitors were doing on December 12, 2014. Huge excitement was caused by the fact that thousands of goods were selling for the wonderful price of just 1 penny (<a href="https://www.theguardian.com/technology/2014/dec/15/amazon-sellers-discounted-glitch-pricing">source</a>). Infinitely grateful to Amazon for such a gorgeous Christmas present, the buyers were enthusiastically filling their carts. Meanwhile, Evil Bug was watching and smirking, anticipating the reaction of the sellers who knew nothing yet about the huge losses they had suffered.</p><p>The bug was hiding in <a href="https://www.repricerexpress.com/">RepricerExpress</a> software responsible for synching prices in online stores. This software facilitates competition by enabling sellers to respond promptly to price fluctuations for like products.</p><p>What did Evil Bug do? It sneaked into RepricerExpress when it was only going through development and testing, but never showed up until… one of the sellers, caught in the pre-holiday turmoil, accidentally set a single price — 1 penny — for all of their stock. The software took that value as a minimum price and cut the prices for other sellers’ like products accordingly.</p><p>That behavior had to do with the fact that when developing the UI, the software authors had not implemented a feature to allow sellers to specify individual minimum prices. More than that, the prices would automatically update within certain intervals. The bug was fixed in the subsequent versions of the software.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*wRzfyZErmaq9JUKv.png" /></figure><p>The day when the bug revealed itself will be remembered for long by the Amazon sellers. That day, they lost thousands of dollars and many nearly went bankrupt (<a href="https://www.theguardian.com/technology/2014/dec/15/amazon-sellers-discounted-glitch-pricing">source</a>). But for the prompt action taken by Amazon, which managed to cancel the majority of orders placed on the affected items, the largest online store’s reputation would have been severely damaged.</p><p>The RepricerExpress developers apologized for the bug in a statement posted on their <a href="https://www.repricerexpress.com/statement/">official blog</a>.</p><h3>Apple VS New Year</h3><p>Remember the film “<a href="https://en.wikipedia.org/wiki/Dr._Seuss%27_How_the_Grinch_Stole_Christmas_(2000_film)">How the Grinch Stole Christmas</a>”? It seems that the Evil Bug took it as a source of inspiration when thinking up a plan of attacking Apple devices. In February 2016, Apple users discovered an interesting bug. There was a legend going around on <a href="https://www.reddit.com/r/jailbreak/comments/458ao3/discussion_changing_time_date_settings_to_jan_1/">social networks</a> saying that if you changed the date to January 1, 1970, on your iPhone or iPad and restarted it, the system would completely crash leaving you with a brick with an Apple logo on it. The procedure was claimed to be irreversible. The bug was reported to be found on devices that employed 64-bit processors, such as Apple A7, A8, A8X, A9, and A9X: iPhone 5S and newer, iPad Air and iPad Mini 2 and newer, and the 6th generation iPod Touch. The operating system’s version number did not matter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*cBxyjEztfBWrnM34.png" /></figure><p>Did anyone try it? Sure! A wave of Apple-gadget killings swept through the world. Fortunately, some handymen found a way to bring the “bricks” back to life. Apple never revealed the official cause of the bug, but they did confirm it could occur when manually changing the date to May 1970 or earlier on an iOS device.</p><p>Users carried out their own investigation and came up with the following explanation: the bug could have been caused by a negative-value variable used to store time in UNIX format. How could the value become negative?</p><p><strong>Version 1.</strong> Since time was stored in UNIX-format, timing would start with January 1, 1970, that is, this date was a zero value. When changing time zones, the value could decrement below zero.</p><p><strong>Version 2.</strong> The bug was typical of 64-bit devices, so perhaps the 32-bit time mark was computed first and then, after changing time zones, would be cast to the pointer size, causing the most significant bits to be filled incorrectly and… Welcome to the XXII century!</p><h3>Sleep long with iPhone</h3><p>Long, long sleep not interrupted by an alarm clock — isn’t it what most of us dream of? Though not Gasprom, iPhones do make their owners’ dreams come true! All those who were planning to start the first day of 2013 fresh and early and set up an alarm on their devices to January 1, “happily” overslept. Evil Bug obviously meant to turn a huge number of users into “sleeping beauties”, as the iPhone alarm clock wouldn’t work until January 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/0*nIA-FEoLhwkJU9DF.png" /></figure><p>Apple preferred to keep silent again. However, rumors about the possible cause of the bug spread anyway. Apple uses the <a href="https://en.wikipedia.org/wiki/ISO_week_date">ISO week date</a> standard, which is widely used by finance companies, as it enables convenient fiscal year planning. What is special about this standard is that a new year is considered as such only starting with the week the first Thursday of the year falls on. The ISO week date calendar contains 52 or 53 weeks (364 or 371 days), so it turned out iPhones were still living in the previous year and stepped into the new one (2013) on January 7, when the first week of the year began.</p><p>There was also an alternative explanation, where Steve Jobs himself took on the role of Evil Bug. The Apple founder was allegedly fond of sleeping in, hence that “feature”. It’s just a joke of course, but the consequences of that seemingly harmless bug were far from funny: the people were late for work, failed to get to important meetings in time, and lost money (<a href="http://www.dailymail.co.uk/news/article-1343430/IPhone-alarm-working-glitch-leaves-thousands-dozing-New-Year.html">source</a>).</p><h3>Flight cancelled</h3><p>The price of a software bug is the factor that developers should never ignore. Here is another Christmas bug story to support this statement.</p><p>On December 12, 2014, the UK’s air traffic control center of National Air Traffic Services (NATS) was faced with a software glitch, which brought the work of some of the airports, including such heavily loaded giants as Heathrow, Gatwick, Stansted, Birmingham, Cardiff, and Glasgow, to a halt. The problem was aggravated by the time that Evil Bug chose for the attack. It was a Friday afternoon, Christmas Eve.</p><p>The fault persisted for a little longer than half an hour — 36 minutes — but the price of the error behind it was steep, as illustrated by the following figures, which Evil Bug can be proud of:</p><ul><li>92 flights cancelled</li><li>170 flights suspended</li><li>10 planes re-routed to alternate airports</li><li>125,000 passengers experiencing inconvenience</li><li>623 million pounds of losses suffered</li></ul><p>A situation like that could not pass unnoticed. An investigation was carried out. In their final <a href="http://www.nats.aero/wp-content/uploads/2015/05/Independent-Enquiry-Final-Report-2.0.pdf">report</a>, the Civil Aviation Authority (CAA) and <a href="http://www.nats.aero/">NATS</a> described a bug found in the software of the System Flight Server (SFS). The SFS is responsible for real-time delivery of data to the Controllers of workstations within the NATS management system. There are two identical SFSs: primary and secondary. Both compute the same data. When the primary SFS shuts down, the secondary one comes into operation. The system did provide for hardware faults but for some reason lacked any protection against software exceptions.</p><p>The maximum permitted number of operational workstations (i.e. terminals from which traffic control and monitoring are carried out) running at a time was 193 — well, in theory at least. In reality, the SFS’s code checked for another value, 151. That’s why when 153 workstations attempted to connect simultaneously, the system reset with a subsequent crash. It was found later that the “latent software fault” had been present since as early as 1990. It’s a wonder that it hadn’t shown earlier.</p><h3>The Year 2000 and Year 2038 problems</h3><p>The New Year of 2000 was one of the most anticipated ones. As some experts of all sorts believed, the turn of the millennium was definitely going to be accompanied by the Apocalypse or, which is no less terrifying, rise of the machines.</p><p>What arguments did they give for their fear of Terminators? Logic! The first computers were slow, so programmers, unwilling to waste precious performance on trifles, decided to use two digits to represent the year in dates. For example, March 23, 1991, was represented as 23.03.91. This notation is nice and normal to the eye. However, from computers’ viewpoint, it’s not that simple. The years 2000 and 1900 were encoded by the same pair of digits, 00, so when the New Year of 2000 began, their internal clock would be set back to the year 1900.</p><p>People could not help visualizing the dreadful effects of such a terrible fault: software crashes, spontaneous missile launches, the financial market collapse. The most horrible things were expected to happen in Russia as a country worst prepared for the new millennium.</p><p>Well, 2017 is approaching, which means the Apocalypse never happened.</p><p>That said, certain bugs did show when the new millennium came:</p><ul><li>British Telecom’s computer networks were paralyzed and engineers had to analyze about a million of code lines to bring them back to life. It cost British Telecom quite a big sum of about 0.5 billion dollars.</li><li>In Spain, emergency conditions were observed at 9 nuclear plants — fortunately, without any serious consequences.</li><li>In Mongolia, the “Year 2000 problem” affected railway operation and ticket offices.</li></ul><p>Some of the bugs were quite amusing:</p><ul><li>Terms of imprisonment in one Spanish prison were stretched/cut by 100 years</li><li>In some Greek stores, buyers would get sales slips dated 1900</li><li>In a South Korean hospital, the patient monitoring software declared a one-year-old baby an old man of 99</li><li>The citizens of a small US town got electricity bills overdue by 100 years</li></ul><p>The “Year 2000 problem” is a striking example of the profound effect that mass media have on humankind. The next wave of mass panic for a similar reason is expected in 2038. On January 19, 2038, at 03:14:07, Greenwich, computers and other devices using 32-bit operating systems will no longer be able to measure time properly. In many devices, system time is measured in seconds starting with January 1, 1970. The seconds are stored in a 32-bit value of type <em>signed int</em> (32-bit signed integer). Soon after the beginning of 2038, the counter will update with the 2,147,483,648th second, which the system will not be able to store, and switch to a negative value.</p><p>How to avoid a system error that will follow? Replace all 32-bit processors with 64-bit ones.</p><h3>How to help Good?</h3><p>Traditionally, Good always defeats Evil, but the struggle doesn’t stop for a moment. Is there any chance to exterminate all Evil Bugs for good? That’s unlikely, but we definitely have every chance to deal massive damage to their troops. To do that, programmers fighting on Good’s side, i.e. for quality code, should wisely pick tools to help them in the fight. Arm yourself with PVS-Studio static analyzer! And be sure to check this <a href="https://www.youtube.com/watch?v=m7_xqta_rkE&amp;t=4s">short horror film</a> about Unicorn PVS-Studio saving Penguin Linux from Evil Bug.</p><p>Feel inspired? Then let’s help Good together! The PVS-Studio team has already made a big step forward by offering you the <a href="http://www.viva64.com/en/b/0457/">free version of our analyzer</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*Ikl2c3O-jCIWB16Y.png" /></figure><p>Dear programmers, good luck with your projects, and may Good always win in your evil-bug stories! Merry Christmas and a Happy New Year!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1a90a114c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The First Bug on Mars]]></title>
            <link>https://medium.com/@emma_programmer/the-first-bug-on-mars-961c9f8cff4f?source=rss-d2ed7cc547b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/961c9f8cff4f</guid>
            <category><![CDATA[mars]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[space]]></category>
            <dc:creator><![CDATA[Emma Brown]]></dc:creator>
            <pubDate>Tue, 20 Dec 2016 12:59:25 GMT</pubDate>
            <atom:updated>2016-12-20T12:59:25.120Z</atom:updated>
            <content:encoded><![CDATA[<p>In 1971, the USSR delivered the first planetary rovers on skis to Mars, whose task was to puncture the surface with a rod (housing a dynamic penetrometer and a radiation densitometer) to see if Mars was solid or liquid dusty. The first probe crashed on November 27; the second soft-landed on December 2 but didn’t manage to get out of the “shell” of the lander, so that attempt didn’t count.</p><p><strong>25 years later</strong></p><p>On July 4, 1997, the U.S. probe arrived at Mars and brought a “sojourner” with the first bug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*PUhJhy0XcYLI0sMv.png" /></figure><p><em>Image from sci-fi film “The Martian”. The main character is carrying the Sojourner rover</em></p><p>The mission was at risk, but the powerful debugging functionality provided by the operating system, and professionalism of the programmers back on Earth (the guys did know their subject) enabled NASA to fix the bug in a short time.</p><h3>Sojourner</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*QyFU29w7aJQWpptD.png" /></figure><p>The mission’s cost was relatively small — $265 million.</p><p>The rover operated for 83 sols.</p><p>The rover’s name, “Sojourner”, originates from the Bible, where it means “traveler”, and was selected in an essay contest won by V. Ambroise, a 12-year-old from U.S. state of Connecticut. It is named for abolitionist and women’s rights activist Sojourner Truth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*ikaHREL2Th3_RnQ3.png" /></figure><p>Mission results:</p><ul><li>2.3 billion bits of information</li><li>16,500 images taken by the lander</li><li>550 images taken by the rover</li><li>15 chemical analyses of rocks and soil</li><li>plenty of meteorological data</li><li>food for thought for software testers</li></ul><p>More <a href="http://www.viva64.com/en/b/0462/">info</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=961c9f8cff4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Re-analysis of Umbraco code]]></title>
            <link>https://medium.com/@emma_programmer/re-analysis-of-umbraco-code-eabfd2a308a4?source=rss-d2ed7cc547b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/eabfd2a308a4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[umbraco]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Emma Brown]]></dc:creator>
            <pubDate>Tue, 20 Dec 2016 12:57:58 GMT</pubDate>
            <atom:updated>2016-12-20T12:57:58.694Z</atom:updated>
            <content:encoded><![CDATA[<p>Time passes inexorably. It feels that just recently we announced the release of the C# static code analyzer, checked the first projects, and started writing articles about it. But a whole year has passed since that moment. It was a year of painstaking and hard work on diagnostic improvements, adding new diagnostic rules, gathering statistics on false positives and eliminating their causes, communicating with users, and tackling a great deal of other issues. It was a year of both small and large successes on this hard, but incredibly interesting, path we have chosen. Now it’s time for a re-analysis of the Umbraco project that we checked right after the release of our C# analyzer a year ago.</p><h3>Introduction</h3><p>The first <a href="http://www.viva64.com/en/b/0357/">article</a> about the <a href="https://umbraco.com/">Umbraco</a> analysis was written by my colleague Andrey Karpov. This year the project continued development, and so far it contains about 3340 files with the extension “.cs”, which is approximately 425 KLOC (at the time of the first check, the project had 3200 files with the extension “.cs”, and 400 KLOC respectively).</p><p>On the first check, the analyzer found a relatively small number of errors, which were nevertheless quite interesting to write an article on, and to draw first conclusions about the work of the C# analyzer from. It is far more interesting doing the check now, when the analyzer has obtained dozens of new diagnostic rules, and improved it’s mechanisms of searching for bugs; it’s also quite amusing to compare the results of the present time check with the one we did a year ago. To do the analysis, I used the latest version of Umbraco source code, which is also available at <a href="https://github.com/umbraco/Umbraco-CMS">GitHub</a>, and also the latest version of <a href="http://www.viva64.com/en/pvs-studio-download/">PVS-Studio 6.11</a>.</p><p>In the results of the check, we got 508 warnings. 71 warnings were first level, 358 — second level, 79 — third level.</p><p>The overall coefficient of issues density (the number of warnings per KLOC) was 1.12. This is a good indicator which corresponds to approximately one warning per a thousand lines of code. But warnings do not necessarily mean real errors. It’s normal for any static analyzer to have a certain percentage of false positives. Quite often, the warnings look like real bugs, but later after inspection, it turns out that it’s not so. Therefore, I won’t be discussing the low level warnings, as the percentage of false positives is usually quite high there.</p><p>I have reviewed the warnings issued by PVS-Studio, and detected approximately 56% false positives at High and Meduim levels. The remaining warnings contain quite suspicious constructs that require additional review, as well as real errors in the code.</p><p>What can be said about the quality of the analyzer work, in comparison with 2015? The first thing that caught our eye is that there were none of the warnings present, which had been described in the previous article. It seems (or at least we want to believe) that the Umbraco developers paid attention to Andrey’s article, and fixed the errors described in it. Although the project is of course in continuous development, and the bugs could be fixed anyway, during daily work. Anyway — there are almost no old mistakes. Still, there are a lot of new ones! I’ll go through the most interesting bugs here.</p><h3>The analysis results</h3><p><strong>Potential division by zero</strong></p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v3064/">V3064</a> Potential division by zero. Consider inspecting denominator ‘maxWidthHeight’. ImageHelper.cs 154</p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v3064/">V3064</a> Potential division by zero. Consider inspecting denominator ‘maxWidthHeight’. ImageHelper.cs 155</p><pre><strong>private</strong> <strong>static</strong> ResizedImage <strong>GenerateThumbnail</strong>(....)<br>{<br>  ....<br>  <strong>if</strong> (maxWidthHeight &gt;= 0)<br>  {<br>    var fx = (<strong>float</strong>)image.Size.Width / maxWidthHeight;  // &lt;=<br>    var fy = (<strong>float</strong>)image.Size.Height / maxWidthHeight;  // &lt;=<br>    ....<br>  }<br>  ....<br>}</pre><p>The provided code fragment has two possible errors, although the second one will never be executed. The condition of the <em>if</em> block allows the <em>maxWidthHeight</em> variable to be equal to zero, which acts as a divisor inside the block. In general, this code can work normally for quite a long period of time, and this is the biggest danger in it. Looking at the name of the <em>maxWidthHeight</em>,<em> </em>we can conclude that it’s value is most likely not equal to zero. Well, what if it is zero at some point of the execution? The correct version of this construction is as follows:</p><pre><strong>private</strong> <strong>static</strong> ResizedImage <strong>GenerateThumbnail</strong>(....)<br>{<br>  ....<br>  <strong>if</strong> (maxWidthHeight &gt; 0)<br>  {<br>    var fx = (<strong>float</strong>)image.Size.Width / maxWidthHeight;<br>    var fy = (<strong>float</strong>)image.Size.Height / maxWidthHeight;<br>    ....<br>  }<br>  ....<br>}</pre><p>The case where the variable <em>maxWidthHeight</em> is zero, should be inspected separately.</p><p><strong>A vexatious typo</strong></p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v3080/">V3080</a> Possible null dereference. Consider inspecting ‘context.Request’. StateHelper.cs 369</p><pre><strong>public</strong> <strong>static</strong> <strong>bool</strong> HasCookies<br>{<br>  get<br>  {<br>    var context = HttpContext;<br>    <strong>return</strong> context != null &amp;&amp; context.Request != null &amp;  // &lt;=<br>           context.Request.Cookies != null &amp;&amp;<br>           context.Response != null &amp;&amp;<br>           context.Response.Cookies != null;<br>  }<br>}</pre><p>There is a typo: the <em>&amp;</em> operator is used instead of <em>&amp;&amp;</em>.<em> </em>The condition <em>context.Request.Cookies != null </em>will be checked regardless of the result from the check of the previous condition <em>context.Request != null</em>. This will inevitably lead to access by a zero reference in case the variable <em>context.Request </em>is null. The correct version of this construction is as follows:</p><pre><strong>public</strong> <strong>static</strong> <strong>bool</strong> HasCookies<br>{<br>  get<br>  {<br>    var context = HttpContext;<br>    <strong>return</strong> context != null &amp;&amp; context.Request != null &amp;&amp;<br>           context.Request.Cookies != null &amp;&amp;<br>           context.Response != null &amp;&amp;<br>           context.Response.Cookies != null;<br>  }<br>}</pre><p><strong>Untimely verification against null</strong></p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v3027/"><strong>V3027</strong></a><strong> </strong>The variable ‘rootDoc’ was utilized in the logical expression before it was verified against null in the same logical expression. publishRootDocument.cs 34</p><pre><strong>public</strong> <strong>bool</strong> <strong>Execute</strong>(....)<br>{<br>  ....<br>  <strong>if</strong> (rootDoc.Text.Trim() == documentName.Trim() &amp;&amp;  // &lt;=<br>      rootDoc != null &amp;&amp; rootDoc.ContentType != null)<br>  ....<br>}</pre><p>The variable <em>rootDoc </em>is verified against null after the accessing via <em>rootDoc.Text</em>. The correct version of this construction is as follows:</p><pre><strong>public</strong> <strong>bool</strong> <strong>Execute</strong>(....)<br>{<br>  ....<br>  <strong>if</strong> (rootDoc != null &amp;&amp;<br>      rootDoc.Text.Trim() == documentName.Trim() &amp;&amp;<br>      rootDoc.ContentType != null)<br>  ....<br>}</pre><p><strong>A negative character index in the string</strong></p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v3057/"><strong>V3057</strong></a><strong> </strong>The ‘Substring’ function could receive the ‘-1’ value while non-negative value is expected. Inspect the second argument. ContentExtensions.cs 82</p><pre>internal <strong>static</strong> CultureInfo <strong>GetCulture</strong>(....)<br>{<br>  ....<br>  var pos = route.IndexOf(&#39;/&#39;);<br>  domain = pos == 0<br>    ? null<br>    : domainHelper.DomainForNode(<br>      <strong>int</strong>.Parse(route.Substring(0, pos)), current)  // &lt;=<br>      .UmbracoDomain;<br>  ....<br>}</pre><p>In the <em>route</em> string the program searches for the ‘/’ character, after which the the variable is assigned with the <em>pos</em> variable. The author took into account the possibility of a character in the beginning of the string (<em>pos == 0), </em>but didn’t take into account the possibility of its absence: in this case the variable <em>pos</em> will get the value -1. This will cause an exception upon the subsequent usage of the <em>pos</em> variable to extract the substring <em>route.Substring(0, pos)</em>. The correct version of this construction is as follows:</p><pre>internal <strong>static</strong> CultureInfo <strong>GetCulture</strong>(....)<br>{<br>  ....<br>  var pos = route.IndexOf(&#39;/&#39;);<br>  domain = (pos &lt;= 0)<br>    ? null<br>    : domainHelper.DomainForNode(<br>      <strong>int</strong>.Parse(route.Substring(0, pos)), current)<br>      .UmbracoDomain;<br>  ....<br>}</pre><p>Similar warnings:</p><ul><li>V3057 The ‘Substring’ function could receive the ‘-1’ value while non-negative value is expected. Inspect the first argument. DefaultUrlProvider.cs 81</li><li>V3057 The ‘Substring’ function could receive the ‘-1’ value while non-negative value is expected. Inspect the second argument. DefaultUrlProvider.cs 84</li><li>V3057 The ‘Substring’ function could receive the ‘-1’ value while non-negative value is expected. Inspect the first argument. DefaultUrlProvider.cs 126</li><li>V3057 The ‘Substring’ function could receive the ‘-1’ value while non-negative value is expected. Inspect the second argument. DefaultUrlProvider.cs 127</li><li>V3057 The ‘Substring’ function could receive the ‘-1’ value while non-negative value is expected. Inspect the first argument. PublishedContentCache.cs 147</li><li>V3057 The ‘Substring’ function could receive the ‘-1’ value while non-negative value is expected. Inspect the second argument. PublishedContentCache.cs 148</li><li>V3057 The ‘Substring’ function could receive the ‘-1’ value while non-negative value is expected. Inspect the second argument. ContentFinderByNiceUrlAndTemplate.cs 35</li><li>V3057 The ‘Substring’ function could receive the ‘-9’ value while non-negative value is expected. Inspect the second argument. requestModule.cs 187</li><li>V3057 The ‘Substring’ function could receive the ‘-1’ value while non-negative value is expected. Inspect the second argument. Action.cs 134</li><li>V3057 The ‘Substring’ function could receive the ‘-1’ value while non-negative value is expected. Inspect the first argument. LegacyShortStringHelper.cs 130</li><li>V3057 The ‘Substring’ function could receive the ‘-1’ value while non-negative value is expected. Inspect the second argument. StringExtensions.cs 573</li></ul><p><strong>Time is money</strong></p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v3057/"><strong>V3057</strong></a><strong> </strong>The ‘DateTime’ constructor receives the ‘0’ value while positive value is expected. Inspect the second argument. DateTimeExtensions.cs 24</p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v3057/"><strong>V3057</strong></a><strong> </strong>The ‘DateTime’ constructor receives the ‘0’ value while positive value is expected. Inspect the third argument. DateTimeExtensions.cs 24</p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v3057/"><strong>V3057</strong></a><strong> </strong>The ‘DateTime’ constructor receives the ‘0’ value while positive value is expected. Inspect the third argument. DateTimeExtensions.cs 26</p><pre><strong>public</strong> <strong>static</strong> DateTime <strong>TruncateTo</strong>(<strong>this</strong> DateTime dt, <br>  DateTruncate truncateTo)<br>{<br>  <strong>if</strong> (truncateTo == DateTruncate.Year)<br>    <strong>return</strong> <strong>new</strong> DateTime(dt.Year, 0, 0);  // &lt;= x2<br>  <strong>if</strong> (truncateTo == DateTruncate.Month)<br>    <strong>return</strong> <strong>new</strong> DateTime(dt.Year, dt.Month, 0);  // &lt;=<br>  ....<br>}</pre><p>This small snippet also contains error 3, immediately detected by diagnostic rule V3057. All the errors related to incorrect initialization of the object of the <em>DateTime</em> class, whose constructor is as follows: <em>public DateTime(int year, int month, int day). </em>At the same time, the parameters <em>year</em>, <em>month</em>, and <em>day </em>cannot take values <em>&lt;1. </em>Otherwise, an <em>ArgumentOutOfRangeException</em> will be thrown. The correct version of this construction is as follows:</p><pre><strong>public</strong> <strong>static</strong> DateTime <strong>TruncateTo</strong>(<strong>this</strong> DateTime dt, <br>  DateTruncate truncateTo)<br>{<br>  <strong>if</strong> (truncateTo == DateTruncate.Year)<br>    <strong>return</strong> <strong>new</strong> DateTime(dt.Year, 1, 1);<br>  <strong>if</strong> (truncateTo == DateTruncate.Month)<br>    <strong>return</strong> <strong>new</strong> DateTime(dt.Year, dt.Month, 1);<br>  ....<br>}</pre><p><strong>Erroneous condition</strong></p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v3125/"><strong>V3125</strong></a><strong> </strong>The ‘ct’ object was used after it was verified against null. Check lines: 171, 163. ContentTypeControllerBase.cs 171</p><pre><strong>protected</strong> TContentType PerformPostSave&lt;....&gt;(....)<br>{<br>  var ctId = Convert.ToInt32(....);<br>  ....<br>  <strong>if</strong> (ctId &gt; 0 &amp;&amp; ct == null) <br>    <strong>throw</strong> <strong>new</strong> HttpResponseException(HttpStatusCode.NotFound);<br>  ....<br>  <strong>if</strong> ((....) &amp;&amp; <br>      (ctId == 0 || ct.Alias != contentTypeSave.Alias))  // &lt;=<br>  ....<br>}</pre><p>There is the possibility of access by the null reference because of the condition <em>(ctId &gt; 0 &amp;&amp; ct == null) </em>in this code fragment. The exception HttpResponseException will be thrown only if both parts of the condition are true at the same time. In the case that the <em>ctld </em>variable is &lt;= 0, the work will be continued anyway regardless of the value of the <em>ct</em> variable. The error needs to fixed in the second condition, where the <em>ct </em>is used. The correct version of this construction is as follows</p><pre><strong>protected</strong> TContentType PerformPostSave&lt;....&gt;(....)<br>{<br>  var ctId = Convert.ToInt32(....);<br>  ....<br>  <strong>if</strong> (ctId &gt; 0 &amp;&amp; ct == null) <br>    <strong>throw</strong> <strong>new</strong> HttpResponseException(HttpStatusCode.NotFound);<br>  ....<br>  <strong>if</strong> ((....) &amp;&amp; <br>      (ctId == 0 || <br>      (ct != null &amp;&amp; ct.Alias != contentTypeSave.Alias)))<br>  ....<br>}</pre><p>Similar warnings:</p><ul><li>V3125 The ‘_repo’ object was used after it was verified against null. Check lines: 104, 78. Installer.aspx.cs 104</li><li>V3125 The ‘docRequest.RoutingContext.UmbracoContext’ object was used after it was verified against null. Check lines: 57, 39. ContentFinderByIdPath.cs 57</li><li>V3125 The ‘User’ object was used after it was verified against null. Check lines: 90, 80. config.cs 90</li><li>V3125 The ‘_repo’ object was used after it was verified against null. Check lines: 254, 247. installedPackage.aspx.cs 254</li><li>V3125 The ‘node.NiceUrl’ object was used after it was verified against null. Check lines: 917, 912. NodeExtensions.cs 917</li><li>V3125 The ‘dst’ object was used after it was verified against null. Check lines: 58, 55. DataEditorSetting.cs 58</li><li>V3125 The ‘result’ object was used after it was verified against null. Check lines: 199, 188. DefaultPreValueEditor.cs 199</li><li>V3125 The ‘result’ object was used after it was verified against null. Check lines: 241, 230. usercontrolPrevalueEditor.cs 241</li></ul><p><strong>An error in the format string</strong></p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v3025/">V3025</a> Incorrect format. A different number of format items is expected while calling ‘Format’ function. Format items not used: {1}. Arguments not used: 1st. HtmlHelperRenderExtensions.cs 938</p><pre><strong>public</strong> <strong>static</strong> IHtmlString <strong>EnableCanvasDesigner</strong>(....)<br>{<br>  ....<br>  string noPreviewLinks = @&quot;&lt;link href=&quot;&quot;{1}&quot;&quot; type=<br>    &quot;&quot;text/css&quot;&quot; rel=&quot;&quot;stylesheet&quot;<br>    &quot; data-title=&quot;&quot;canvasdesignerCss&quot;&quot; /&gt;&quot;;<br>  ....<br>  <strong>if</strong> (....)<br>    result = string.Format(noPreviewLinks, cssPath) +  // &lt;=<br>             Environment.NewLine;<br>  ....<br>}</pre><p>The format string <em>noPreviewLinks </em>doesn’t have a specifier ‘{0}’ for the first argument <em>cssPath </em>of the <em>string.Format </em>method. The result of this code execution will be that we’ll get an exception. The correct version of this construction is as follows:</p><pre><strong>public</strong> <strong>static</strong> IHtmlString <strong>EnableCanvasDesigner</strong>(....)<br>{<br>  ....<br>  string noPreviewLinks = @&quot;&lt;link href=&quot;&quot;{0}&quot;&quot; type=<br>    &quot;&quot;text/css&quot;&quot; rel=&quot;&quot;stylesheet&quot;<br>    &quot; data-title=&quot;&quot;canvasdesignerCss&quot;&quot; /&gt;&quot;;<br>  ....<br>  <strong>if</strong> (....)<br>    result = string.Format(noPreviewLinks, cssPath) +<br>             Environment.NewLine;<br>  ....<br>}</pre><p>Similar warnings:</p><ul><li>V3025 Incorrect format. A different number of format items is expected while calling ‘Format’ function. Format items not used: {1}. Arguments not used: 1st. HtmlHelperRenderExtensions.cs 946</li><li>V3025 Incorrect format. A different number of format items is expected while calling ‘Format’ function. Arguments not used: path. requestModule.cs 204</li><li>V3025 Incorrect format. A different number of format items is expected while calling ‘Format’ function. Arguments not used: Alias.Replace(“ “, “”). Template.cs 382</li><li>V3025 Incorrect format. A different number of format items is expected while calling ‘Format’ function. Arguments not used: Alias.Replace(“ “, “”). Template.cs 387</li><li>V3025 Incorrect format. A different number of format items is expected while calling ‘Format’ function. Arguments not used: this.Value.ClientID. SliderPrevalueEditor.cs 221</li></ul><p><strong>Untimely verification against null. Again</strong></p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v3095/"><strong>V3095</strong></a><strong> </strong>The ‘dataset’ object was used before it was verified against null. Check lines: 48, 49. ImageCropperBaseExtensions.cs 48</p><pre>internal <strong>static</strong> ImageCropData <strong>GetCrop</strong>(....)<br>{<br>  var imageCropDatas = dataset.ToArray();  // &lt;=<br>  <strong>if</strong> (dataset == null || imageCropDatas.Any() == false)<br>    <strong>return</strong> null;<br>  ....<br>}</pre><p>Unlike <a href="http://www.viva64.com/en/w/v3027/">V3027</a> diagnostic — where the untimely verification against null was found within a single condition — here we are dealing with an attempt to access the null reference in a different statement. The variable <em>dataset </em>is converted to array first, and only then is verified against <em>null. </em>The correct version of this construction is as follows:</p><pre>internal <strong>static</strong> ImageCropData <strong>GetCrop</strong>(....)<br>{<br>  var imageCropDatas = dataset?.ToArray();<br>  <strong>if</strong> (imageCropDatas == null || !imageCropDatas.Any())<br>    <strong>return</strong> null;<br>  ....<br>}</pre><p>Similar warnings:</p><ul><li>V3095 The ‘display.PropertyEditor’ object was used before it was verified against null. Check lines: 30, 43. ContentPropertyDisplayConverter.cs 30</li><li>V3095 The ‘typedSource’ object was used before it was verified against null. Check lines: 164, 198. DynamicQueryable.cs 164</li><li>V3095 The ‘attempt.Result’ object was used before it was verified against null. Check lines: 90, 113. DynamicPublishedContent.cs 90</li><li>V3095 The ‘actionExecutedContext’ object was used before it was verified against null. Check lines: 47, 76. FileUploadCleanupFilterAttribute.cs 47</li><li>V3095 The ‘type’ object was used before it was verified against null. Check lines: 92, 96. assemblyBrowser.aspx.cs 92</li><li>V3095 The ‘httpContext’ object was used before it was verified against null. Check lines: 235, 237. UmbracoContext.cs 235</li><li>V3095 The ‘dst’ object was used before it was verified against null. Check lines: 53, 55. DataEditorSetting.cs 53</li><li>V3095 The ‘_val’ object was used before it was verified against null. Check lines: 46, 55. CheckBoxList.cs 46</li><li>V3095 The ‘_val’ object was used before it was verified against null. Check lines: 47, 54. ListBoxMultiple.cs 47</li><li>V3095 The ‘databaseSettings.ConnectionString’ object was used before it was verified against null. Check lines: 737, 749. DatabaseContext.cs 737</li><li>V3095 The ‘path’ object was used before it was verified against null. Check lines: 101, 112. IOHelper.cs 101</li></ul><p><strong>A logic error</strong></p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v3022/">V3022</a> Expression ‘name != “Min” || name != “Max”’ is always true. Probably the ‘&amp;&amp;’ operator should be used here. DynamicPublishedContentList.cs 415</p><pre><strong>private</strong> object <strong>Aggregate</strong>(....)<br>{<br>  ....<br>  <strong>if</strong> (name != &quot;Min&quot; || name != &quot;Max&quot;)  // &lt;=<br>  {<br>    <strong>throw</strong> <strong>new</strong> ArgumentException(<br>      &quot;Can only use aggregate min or max methods on properties<br>       which are datetime&quot;);<br>  }<br>  ....<br>}</pre><p>As can be seen in the message of the exception, the <em>name</em> variable can only take one of the values “Min”, or “Max”. At the same time, the condition of the exception should be simultaneous unequal to the <em>name</em> variable “Min” and “Max”. But in this fragment the exception will be thrown regardless of the value of <em>name</em>. The correct version of this construction is as follows:</p><pre><strong>private</strong> object <strong>Aggregate</strong>(....)<br>{<br>  ....<br>  <strong>if</strong> (name != &quot;Min&quot; &amp;&amp; name != &quot;Max&quot;)<br>  {<br>    <strong>throw</strong> <strong>new</strong> ArgumentException(<br>      &quot;Can only use aggregate min or max methods on properties<br>       which are datetime&quot;);<br>  }<br>  ....<br>}</pre><p>In the Umbraco code, the analyzer found 32 more potentially dangerous constructions (although they may just be redundant checks). Here are some of them:</p><ul><li>V3022 Expression ‘macro == null’ is always false. MacroController.cs 91</li><li>V3022 Expression ‘p.Value == null’ is always false. ImageCropperPropertyEditor.cs 216</li><li>V3022 Expression ‘loginPageObj != null’ is always true. ProtectPage.aspx.cs 93</li><li>V3022 Expression ‘dictionaryItem != null’ is always true. TranslateTreeNames.cs 19</li><li>V3022 Expression ‘!IsPostBack’ is always true. EditUser.aspx.cs 431</li><li>V3022 Expression ‘result.View != null’ is always false. ControllerExtensions.cs 129</li><li>V3022 Expression ‘string.IsNullOrEmpty(UmbracoSettings.TEMP_FRIENDLY_XML_CHILD_CONTAINER_NODENAME) == false’ is always false. NotFoundHandlers.cs 128</li><li>V3022 Expression ‘mem != null’ is always true. ViewMembers.aspx.cs 96</li><li>V3022 Expression ‘dtd != null’ is always true. installedPackage.aspx.cs 213</li><li>V3022 Expression ‘jsonReader.TokenType == JSONToken.EndArray &amp;&amp; jsonReader.Value == null’ is always false. JSON.cs 263</li></ul><p><strong>A strange loop condition</strong></p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v3022/">V3022</a> Expression ‘!stop’ is always true. template.cs 229</p><pre><strong>public</strong> Control <strong>parseStringBuilder</strong>(....)<br>{<br>  ....<br>  <strong>bool</strong> stop = false;<br>  ....<br>  <strong>while</strong> (!stop)  // &lt;=<br>  {<br>    ....<br>  }<br>  ....<br>}</pre><p>Another suspicious construction, detected by the <a href="http://www.viva64.com/en/w/v3022/">V3022</a> diagnostic. The variable stop isn’t used inside the <em>while</em> block. The block has quite a large code fragment, about 140 lines of code, that’s why I won’t cite it here. Here is the result of searching for the <em>stop</em> variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*NOf3jJoF4lu_tWip.png" /></figure><p>Most likely, it’s not an infinite loop, as we can see a break here, as well as the exception handling blocks. Nevertheless, the loop looks very strange, and may contain a potential error.</p><p><strong>Infinite recursion</strong></p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v3110/">V3110</a> Possible infinite recursion inside ‘Render’ method. MenuSplitButton.cs 30</p><pre><strong>protected</strong> override <strong>void</strong> <strong>Render</strong>(System.Web.UI.HtmlTextWriter writer)<br>{<br>  writer.Write(&quot;&lt;/div&gt;&quot;);<br>  base.Render(writer);<br>  <strong>this</strong>.Render(writer);  // &lt;=<br>  writer.Write(&quot;&lt;div class=&#39;btn-group&gt;&quot;);<br>}</pre><p>Apparently, this code fragment has a bug caused by an infinite recursion. After the call of the Render method of the base class, there is a recursive call of the overloaded <em>Render</em> method “by the analogy”. Perhaps, the method <em>this.Render </em>should contain some condition of the exit from the recursion. However, it’s hard to make a clear conclusion as to what the correct variant of this construction should be.</p><h3>Conclusion</h3><p>So, the recheck of the Umbraco project showed significant progress in PVS-Studio, in searching for potentially dangerous and erroneous constructs in C# code. The analyzer has proven its effectiveness once again. Of course, projects should not be checked once a year, because the maximum effect of static analysis is achieved only through regular use. This allows the fixing of bugs effectively, and in good time, without letting them get to the build system, and to the end-users.</p><p>Use static analysis! We added the possibility to use our analyzer <a href="http://www.viva64.com/en/b/0457/">for free</a> so that everybody could do that. Good luck in the battle against errors and bugless code!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eabfd2a308a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linux Kernel, tested by the Linux-version of PVS-Studio]]></title>
            <link>https://medium.com/@emma_programmer/linux-kernel-tested-by-the-linux-version-of-pvs-studio-f2058e5983db?source=rss-d2ed7cc547b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2058e5983db</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Emma Brown]]></dc:creator>
            <pubDate>Mon, 12 Dec 2016 13:57:36 GMT</pubDate>
            <atom:updated>2016-12-12T13:57:36.987Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*5rSkwgzoWshK4vCQ.png" /></figure><p>Since the release of the publicly available Linux-version of PVS-Studio, it was just a matter of time until we would recheck the Linux kernel. It is quite a challenge for any static code analyzer to check a project written by professionals from all around the world, used by people in various fields, which is regularly checked and tested by different tools. So, what errors did we manage to find in such conditions?</p><h3>How we did the check</h3><p>We have <a href="http://www.viva64.com/en/b/0299/">already checked</a> the Linux kernel. A lot of things have changed since then — now it’s equally easy to check an OS, or any other project.</p><pre>pvs-studio-analyzer trace - make<br>pvs-studio-analyzer analyze -o /path/to/report.log -j8</pre><p>It took us just a few months to adapt and test the analyzer in Linux; which was previously available only for Windows. This time it was much easier to check the project.</p><p>We used PVS-Studio version 4.9-rc4 (commit bc33b0ca11e3df467777a4fa7639ba488c9d4911).</p><p>In this article we will cover only the general analysis diagnostics of levels one and two. We should note that the code really is of very high quality — the density of warnings pointing to real flaws is extremely low.</p><p>I have chosen warnings that most likely pointed to real bugs/errors. We should understand that besides useful warnings, the analyzer may issue false positives, or badly formatted code or ‘code smell’.</p><p>Unfortunately, the number of false positives in the Linux version of PVS-Studio is higher than we would like it to be. I think this is due to the fact that this version is still quite young. We have done a lot, and still continue working to minimize the number of false positives. The Linux code helped us become better, and add a good number of useful modifications to the analyzer — and now we would like to answer back.</p><h3>Typos</h3><p>The most common errors are caused by the usual typos and <a href="http://www.viva64.com/en/t/0068/">Copy-Paste</a> errors. If you have read our articles before, you’ve probably noticed that. They are everywhere: in all operating systems, and in any language. Still, they are a great example for showing the potential of a static code analyzer: it’s much harder to find them with other tools. Let’s see what we have in the Linux kernel:</p><p><strong>PVS-Studio warning</strong>: <a href="http://www.viva64.com/en/w/v581/">V581</a> The conditional expressions of the ‘if’ operators situated alongside each other are identical. Check lines: 2384, 2390. debug.c 2390</p><pre><strong>int</strong> <strong>dbg_check_nondata_nodes_order</strong>(....)<br>{<br>  ....<br>  sa = container_of(cur, <strong>struct</strong> ubifs_scan_node, list);<br>  sb = container_of(cur-&gt;next, <strong>struct</strong> ubifs_scan_node, list);</pre><pre>  <strong>if</strong> (sa-&gt;type != UBIFS_INO_NODE &amp;&amp; sa-&gt;type != UBIFS_DENT_NODE &amp;&amp;<br>      sa-&gt;type != UBIFS_XENT_NODE) {<br>    ubifs_err(c, &quot;bad node type %d&quot;, sa-&gt;type);<br>    ubifs_dump_node(c, sa-&gt;node);<br>    <strong>return</strong> -EINVAL;<br>  }<br>  <strong>if</strong> (sa-&gt;type != UBIFS_INO_NODE &amp;&amp; sa-&gt;type != UBIFS_DENT_NODE &amp;&amp;<br>      sa-&gt;type != UBIFS_XENT_NODE) {<br>    ubifs_err(c, &quot;bad node type %d&quot;, sb-&gt;type);<br>    ubifs_dump_node(c, sb-&gt;node);<br>    <strong>return</strong> -EINVAL;<br>  }<br>  ....<br>}</pre><p>The analyzer complains about two similar conditions in a row: perhaps in the second condition the programmer forgot to change <em>sa</em> to <em>sb</em>. Who says that people in cool projects don’t copy-paste?</p><p><strong>PVS-Studio warning</strong>: <a href="http://www.viva64.com/en/w/v666/">V666</a> Consider inspecting third argument of the function ‘strncmp’. It is possible that the value does not correspond with the length of a string which was passed with the first argument. spectral.c 341</p><pre><strong>static</strong> ssize_t <strong>write_file_spec_scan_ctl</strong>(<strong>struct</strong> file *file,<br>          <strong>const</strong> <strong>char</strong> __user *user_buf,<br>          <strong>size_t</strong> count, <strong>loff_t</strong> *ppos)<br>{<br>  <strong>struct</strong> ath10k *ar = file-&gt;private_data;<br>  <strong>char</strong> buf[32];<br>  <strong>ssize_t</strong> len;<br>  <strong>int</strong> res;</pre><pre>  len = min(count, <strong>sizeof</strong>(buf) - 1);<br>  <strong>if</strong> (copy_from_user(buf, user_buf, len))<br>    <strong>return</strong> -EFAULT;</pre><pre>  buf[len] = &#39;\0&#39;;</pre><pre>  mutex_lock(&amp;ar-&gt;conf_mutex);</pre><pre>  <strong>if</strong> (strncmp(&quot;trigger&quot;, buf, 7) == 0) {<br>    ....<br>  } <strong>else</strong> <strong>if</strong> (strncmp(&quot;background&quot;, buf, 9) == 0) {<br>    res = ath10k_spectral_scan_config(ar, SPECTRAL_BACKGROUND);<br>  } <strong>else</strong> <strong>if</strong> (strncmp(&quot;manual&quot;, buf, 6) == 0) {<br>    res = ath10k_spectral_scan_config(ar, SPECTRAL_MANUAL);<br>  } <strong>else</strong> <strong>if</strong> (strncmp(&quot;disable&quot;, buf, 7) == 0) {<br>    res = ath10k_spectral_scan_config(ar, SPECTRAL_DISABLED);<br>  } <strong>else</strong> {<br>    res = -EINVAL;<br>  }</pre><pre>  mutex_unlock(&amp;ar-&gt;conf_mutex);</pre><pre>  <strong>if</strong> (res &lt; 0)<br>    <strong>return</strong> res;</pre><pre>  <strong>return</strong> count;<br>}</pre><p>A classic error: two arguments should be passed to a function: a pointer to a string and its length. Quite often, when a literal serves as an argument, programmers are too lazy to evaluate the length, and just write a number. The human factor in action: people get things wrong <a href="http://www.viva64.com/en/examples/v666/">very often</a>.</p><p>See, there are several <em>strncmp </em>in a row. The literal is passed to each of them. Also, in the <em>strncmp(“background”, buf, 9) </em>the length was evaluated incorrectly: the word “background” has 10, not 9, characters.</p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v666/">V666</a> Consider inspecting third argument of the function ‘memcpy’. It is possible that the value does not correspond with the length of a string which was passed with the second argument. dpt_i2o.c 403</p><pre><strong>static</strong> <strong>void</strong> <strong>adpt_inquiry</strong>(adpt_hba* pHba)<br>{<br>  ....<br>  memset(pHba-&gt;detail, 0, <strong>sizeof</strong>(pHba-&gt;detail));<br>  memcpy(&amp;(pHba-&gt;detail), &quot;Vendor: Adaptec &quot;, 16);<br>  memcpy(&amp;(pHba-&gt;detail[16]), &quot; Model: &quot;, 8);<br>  memcpy(&amp;(pHba-&gt;detail[24]), (u8*) &amp;buf[16], 16);<br>  memcpy(&amp;(pHba-&gt;detail[40]), &quot; FW: &quot;, 4);         // &lt;=<br>  memcpy(&amp;(pHba-&gt;detail[44]), (u8*) &amp;buf[32], 4);<br>  pHba-&gt;detail[48] = &#39;\0&#39;;  /* precautionary */<br>  ....<br>}</pre><p>One more example. The length of the string “FW” is 5, not 4, characters.</p><p>How can we get rid of such an error? In C, you can use a macro like this:</p><pre>#<strong>define</strong> str_len(S) (sizeof(S) / sizeof((S)[0]))</pre><p>Using such macros is dangerous: it’s better to add compiler-specific checks, to see that the passed argument is an array.</p><p>For our readers coding in C++, I can recommend the std::string_view that finally appeared in C++17. It is better not to pass a pointer-length to the function as a pair. But if it’s necessary to evaluate the array size manually (if we need to pass it to the memcpy function), we can use std::size(array) or its equivalent: the size for literals will be evaluated in compile-time.</p><p>Avoid repeating the code, and do not be too lazy to use language tools (macros or templates) for the compile time evaluations!</p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v653/"><strong>V653</strong></a><strong> </strong>A suspicious string consisting of two parts is used for array initialization. It is possible that a comma is missing. Consider inspecting this literal: “30min” “No timeout”. lp8788-charger.c 657</p><pre><strong>static</strong> ssize_t <strong>lp8788_show_eoc_time</strong>(<strong>struct</strong> device *dev,<br>        <strong>struct</strong> device_attribute *attr, <strong>char</strong> *buf)<br>{<br>  <strong>struct</strong> lp8788_charger *pchg = dev_get_drvdata(dev);<br>  <strong>char</strong> *stime[] = { &quot;400ms&quot;, &quot;5min&quot;, &quot;10min&quot;, &quot;15min&quot;,<br>      &quot;20min&quot;, &quot;25min&quot;, &quot;30min&quot; &quot;No timeout&quot; };<br>  ....<br>}</pre><p>As is known, the two consecutive literals get linked. This allows them to be used easily in macros for instance. The danger appears when we write an array of such literals: you can miss a comma, and get an unexpected result.</p><p>In this case two last literals will “stick” to each other, and we will get “30minNo timeout”. It’s a double error. Firstly, the text is incorrect; secondly, the array will be missing one element, which can lead to access out of bounds.</p><p>I recommend using another form of formatting, so that this error will become more evident:</p><pre><strong>char</strong> *stime[] = {<br>    &quot;400ms&quot;<br>  , &quot;5min&quot;<br>  , &quot;10min&quot;<br>  , &quot;15min&quot;<br>  , &quot;20min&quot;<br>  , &quot;25min&quot;<br>  , &quot;30min&quot;<br>    &quot;No timeout&quot;<br>};</pre><p>Learn more about this method of table-style formatting in a book written by my colleague, Andrey Karpov. I suggest reading <a href="http://www.viva64.com/en/b/0391/">Chapter N13</a>.</p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v764/">V764</a> Possible incorrect order of arguments passed to ‘ahc_9005_subdevinfo_valid’ function: ‘device’ and ‘vendor’. aic7xxx_pci.c 695</p><pre><strong>const</strong> <strong>struct</strong> ahc_pci_identity *<br><strong>ahc_find_pci_device</strong>(<strong>ahc_dev_softc_t</strong> pci)<br>{<br>  ....<br>  <strong>if</strong> (ahc_get_pci_function(pci) &gt; 0<br>   &amp;&amp; ahc_9005_subdevinfo_valid(device, vendor, // &lt;=<br>                                subdevice, subvendor)<br>   &amp;&amp; SUBID_9005_MFUNCENB(subdevice) == 0)<br>    <strong>return</strong> (NULL);</pre><pre>  ....<br>}</pre><p>Sometimes it’s hard to understand what the analyzer is complaining about. By the way, it often happens that a person does not understand what the analyzer warns about, sends a report with a ‘false positive’, and it turns out that there’s actually a bug. It also seemed to me that this was a false positive: the function is defined a little earlier in the code, and all the parameters are set correctly. Here’s how it looks:</p><pre><strong>static</strong> <strong>int</strong><br><strong>ahc_9005_subdevinfo_valid</strong>(<strong>uint16_t</strong> device, <strong>uint16_t</strong> vendor,<br>        <strong>uint16_t</strong> subdevice, <strong>uint16_t</strong> subvendor)<br>{<br>  ....<br>}</pre><p>What’s the matter here? It turns out that a bit earlier this function was declared, and it is there that the arguments are confused. In fact there is nothing dangerous in the program logic, but it’s better to fix this, so as not to confuse other developers.</p><pre><strong>static</strong> <strong>int</strong> <strong>ahc_9005_subdevinfo_valid</strong>(<strong>uint16_t</strong> vendor, <strong>uint16_t</strong> device,<br>    <strong>uint16_t</strong> subvendor, <strong>uint16_t</strong> subdevice);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/0*JACeK9xMLScHzefb.png" /></figure><p>The funny thing is that this error <a href="https://kernel.googlesource.com/pub/scm/linux/kernel/git/stable/linux-stable/+/6f8f8e4d313a47e3f8aa7eeb5201d1b02ffa0951%5E!/">has already been</a> in the code: the parameters were confused, the programmer just forgot to modify the declaration. It’s good that the analyzer detected this fragment.</p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v549/"><strong>V549</strong></a><strong> </strong>The first argument of ‘memcpy’ function is equal to the second argument. wilc_wfi_cfgoperations.c 1345</p><pre><strong>static</strong> <strong>int</strong> <strong>del_pmksa</strong>(<strong>struct</strong> wiphy *wiphy,<br>                     <strong>struct</strong> net_device *netdev,<br>                     <strong>struct</strong> cfg80211_pmksa *pmksa)<br>{<br>  ....<br>  <strong>for</strong> (; i &lt; (priv-&gt;pmkid_list.numpmkid - 1); i++) {<br>    memcpy(priv-&gt;pmkid_list.pmkidlist[i].bssid,<br>           priv-&gt;pmkid_list.pmkidlist[i + 1].bssid,<br>           ETH_ALEN);<br>    memcpy(priv-&gt;pmkid_list.pmkidlist[i].pmkid,<br>           priv-&gt;pmkid_list.pmkidlist[i].pmkid,<br>           PMKID_LEN);<br>  }<br>  ....<br>}</pre><p>In the last <em>memcpy </em>the pointers are the same. Perhaps the programmer wanted to copy the previous expression:</p><pre>memcpy(priv-&gt;pmkid_list.pmkidlist[i].pmkid,<br>       priv-&gt;pmkid_list.pmkidlist[i + 1].pmkid,<br>       PMKID_LEN);</pre><h3>Unused variables</h3><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v575/"><strong>V575</strong></a><strong> </strong>The ‘strncasecmp’ function processes ‘0’ elements. Inspect the third argument. linux_wlan.c 1121</p><pre><strong>static</strong> <strong>int</strong> <strong>mac_ioctl</strong>(<strong>struct</strong> net_device *ndev,<br>                     <strong>struct</strong> ifreq *req,<br>                     <strong>int</strong> cmd)<br>{<br>  u8 *buff = NULL;<br>  s8 rssi;<br>  u32 size = 0, length = 0;<br>  <strong>struct</strong> wilc_vif *vif;<br>  s32 ret = 0;<br>  <strong>struct</strong> wilc *wilc;</pre><pre>  vif = netdev_priv(ndev);<br>  wilc = vif-&gt;wilc;</pre><pre>  <strong>if</strong> (!wilc-&gt;initialized)<br>    <strong>return</strong> 0;</pre><pre>  <strong>switch</strong> (cmd) {<br>  <strong>case</strong> SIOCSIWPRIV:<br>  {<br>    <strong>struct</strong> iwreq *wrq = (<strong>struct</strong> iwreq *)req;</pre><pre>    size = wrq-&gt;u.data.length;</pre><pre>    <strong>if</strong> (size &amp;&amp; wrq-&gt;u.data.pointer) {<br>      buff = memdup_user(wrq-&gt;u.data.pointer,<br>                         wrq-&gt;u.data.length);<br>      <strong>if</strong> (IS_ERR(buff))<br>        <strong>return</strong> PTR_ERR(buff);</pre><pre>      <strong>if</strong> (strncasecmp(buff, &quot;RSSI&quot;, length) == 0) { // &lt;=<br>        ....<br>      }<br>    }<br>  }<br>  ....<br>  }</pre><pre>done:</pre><pre>  kfree(buff);</pre><pre>  <strong>return</strong> ret;<br>}</pre><p>0 was passed as an argument to the <em>strncasecmp </em>function. There is no fragment where the <em>length</em> variable gets changed, so, it’s value remains zero. <em>size </em>should probably be used instead.</p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v751/">V751</a> Parameter ‘LCDheight’ is not used inside function body. init.c 339</p><pre><strong>static</strong><br><strong>unsigned</strong> <strong>short</strong><br><strong>SiS_GetModeID</strong>(<strong>int</strong> VGAEngine, <strong>unsigned</strong> <strong>int</strong> VBFlags,<br>              <strong>int</strong> HDisplay, <strong>int</strong> VDisplay,<br>              <strong>int</strong> Depth, <strong>bool</strong> FSTN,<br>              <strong>int</strong> LCDwidth, <strong>int</strong> LCDheight)<br>{<br>  <strong>unsigned</strong> <strong>short</strong> ModeIndex = 0;</pre><pre>  <strong>switch</strong>(HDisplay)<br>  {<br>  <strong>case</strong> 320:<br>    <strong>if</strong>(VDisplay == 200) ModeIndex = ModeIndex_320x200[Depth];<br>    <strong>else</strong> <strong>if</strong>(VDisplay == 240) {<br>      <strong>if</strong>((VBFlags &amp; CRT2_LCD) &amp;&amp; (FSTN))<br>        ModeIndex = ModeIndex_320x240_FSTN[Depth];<br>      <strong>else</strong><br>        ModeIndex = ModeIndex_320x240[Depth];<br>    }<br>    <strong>break</strong>;<br>  <strong>case</strong> 400:<br>    <strong>if</strong>((!(VBFlags &amp; CRT1_LCDA)) ||<br>       ((LCDwidth &gt;= 800) &amp;&amp; (LCDwidth &gt;= 600))) { // &lt;=<br>      <strong>if</strong>(VDisplay == 300) ModeIndex = ModeIndex_400x300[Depth];<br>    }<br>    <strong>break</strong>;<br>  <strong>case</strong> 512:<br>    <strong>if</strong>((!(VBFlags &amp; CRT1_LCDA)) ||<br>       ((LCDwidth &gt;= 1024) &amp;&amp; (LCDwidth &gt;= 768))) { // &lt;=<br>      <strong>if</strong>(VDisplay == 384) ModeIndex = ModeIndex_512x384[Depth];<br>    }<br>    <strong>break</strong>;<br>    ....<br>  }</pre><pre>  <strong>return</strong> ModeIndex;<br>}</pre><p>An unused parameter in the function isn’t always an error. In old APIs there are situations where a parameter is not needed, and it is either rewritten, or simply not used. But if you take a closer look at this fragment, you will see that the programmer forgot to compare the height. Instead, we see comparisons <em>‘(A &gt; 5) &amp;&amp; (A &gt; 3)’ </em>that are redundant by themselves.</p><h3>Confusion in the operation precedence</h3><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v502/">V502</a> Perhaps the ‘?:’ operator works in a different way than it was expected. The ‘?:’ operator has a lower priority than the ‘|’ operator. core.c 1046</p><pre><strong>static</strong> <strong>int</strong> <strong>nvme_pr_preempt</strong>(<strong>struct</strong> block_device *bdev,<br>                           u64 old, u64 <strong>new</strong>,<br>                           <strong>enum</strong> pr_type type, <strong>bool</strong> abort)<br>{<br>  u32 cdw10 = nvme_pr_type(type) &lt;&lt; 8 | abort ? 2 : 1;<br>  <strong>return</strong> nvme_pr_command(bdev, cdw10, old, <strong>new</strong>,<br>                         nvme_cmd_resv_acquire);<br>}</pre><p>A ternary operator in C is a very dangerous operator. One of the first general analysis diagnostics in PVS-Studio is about this for a reason. The thing is that it has a very low priority and it’s very easy to get confused and get a totally different evaluation order. So, when in doubt, it’s better to use parentheses.</p><h3>Suspicious checks</h3><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v517/"><strong>V517</strong></a><strong> </strong>The use of ‘if (A) {…} else if (A) {…}’ pattern was detected. There is a probability of logical error presence. Check lines: 375, 377. trx.c 375</p><pre><strong>bool</strong> <strong>rtl92ee_rx_query_desc</strong>(<strong>struct</strong> ieee80211_hw *hw,<br>         <strong>struct</strong> rtl_stats *status,<br>         <strong>struct</strong> ieee80211_rx_status *rx_status,<br>         u8 *pdesc, <strong>struct</strong> sk_buff *skb)<br>{<br>  <strong>struct</strong> rtl_priv *rtlpriv = rtl_priv(hw);<br>  <strong>struct</strong> rx_fwinfo *p_drvinfo;<br>  <strong>struct</strong> ieee80211_hdr *hdr;<br>  u32 phystatus = GET_RX_DESC_PHYST(pdesc);</pre><pre>  ....</pre><pre>  status-&gt;macid = GET_RX_DESC_MACID(pdesc);<br>  <strong>if</strong> (GET_RX_STATUS_DESC_MAGIC_MATCH(pdesc))<br>    status-&gt;wake_match = BIT(2);<br>  <strong>else</strong> <strong>if</strong> (GET_RX_STATUS_DESC_MAGIC_MATCH(pdesc))<br>    status-&gt;wake_match = BIT(1);<br>  <strong>else</strong> <strong>if</strong> (GET_RX_STATUS_DESC_UNICAST_MATCH(pdesc))<br>    status-&gt;wake_match = BIT(0);<br>  <strong>else</strong><br>    status-&gt;wake_match = 0;<br>  <br>  ....<br>}</pre><p>At first glance it’s not easy to see what’s wrong. The same check by the macro <em>GET_RX_STATUS_DESC_MAGIC_</em>MATCH is done twice. If we see its declaration, we’ll see another two macros:</p><pre>#<strong>define</strong> GET_RX_STATUS_DESC_PATTERN_MATCH(__pdesc)<br>        LE_BITS_TO_4BYTE(__pdesc+12, 29, 1)<br>#<strong>define</strong> GET_RX_STATUS_DESC_UNICAST_MATCH(__pdesc)<br>        LE_BITS_TO_4BYTE(__pdesc+12, 30, 1)<br>#<strong>define</strong> GET_RX_STATUS_DESC_MAGIC_MATCH(__pdesc)<br>        LE_BITS_TO_4BYTE(__pdesc+12, 31, 1)</pre><p>Perhaps the programmer meant to use <em>GET_RX_STATUS_DESC_PATTERN_MATCH</em>, which is missing in the original fragment. Otherwise this check simply makes no sense.</p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v547/">V547</a> Expression ‘(ptr[3] &amp; 0x1E) != 0x03’ is always true. sd.c 4115</p><pre><strong>int</strong> <strong>ext_sd_send_cmd_get_rsp</strong>(<strong>struct</strong> rtsx_chip *chip,<br>    u8 cmd_idx, u32 arg, u8 rsp_type,<br>    u8 *rsp, <strong>int</strong> rsp_len, <strong>bool</strong> special_check)<br>{<br>  <strong>int</strong> retval;<br>  <strong>int</strong> timeout = 100;<br>  u16 reg_addr;<br>  u8 *ptr;</pre><pre>  ....</pre><pre>  <strong>if</strong> (cmd_idx == SELECT_CARD) {<br>    <strong>if</strong> (rsp_type == SD_RSP_TYPE_R2) {<br>      <strong>if</strong> ((ptr[3] &amp; 0x1E) != 0x04) {<br>        rtsx_trace(chip);<br>        <strong>return</strong> STATUS_FAIL;<br>      }</pre><pre>    } <strong>else</strong> <strong>if</strong> (rsp_type == SD_RSP_TYPE_R0) {<br>      <strong>if</strong> ((ptr[3] &amp; 0x1E) != 0x03) {           // &lt;=<br>        rtsx_trace(chip);<br>        <strong>return</strong> STATUS_FAIL;<br>      }<br>    }<br>  }</pre><pre>  ....<br>}</pre><p>The error is related to the usage of bitwise operations. The result of a bitwise conjunction with <em>0x1E </em>will never be <em>0x03 </em>because of one bit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/0*cB_q_Kjm5O4Di6sH.png" /></figure><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v517/"><strong>V517</strong></a><strong> </strong>The use of ‘if (A) {…} else if (A) {…}’ pattern was detected. There is a probability of logical error presence. Check lines: 1277, 1282. ks_wlan_net.c 1277</p><pre><strong>static</strong> <strong>int</strong> <strong>ks_wlan_set_power</strong>(<strong>struct</strong> net_device *dev,<br>           <strong>struct</strong> iw_request_info *info,<br>           <strong>struct</strong> iw_param *vwrq, <strong>char</strong> *extra)<br>{<br>  <strong>struct</strong> ks_wlan_private *priv =<br>      (<strong>struct</strong> ks_wlan_private *)netdev_priv(dev);<br>  <strong>short</strong> enabled;</pre><pre>  <strong>if</strong> (priv-&gt;sleep_mode == SLP_SLEEP) {<br>    <strong>return</strong> -EPERM;<br>  }<br>  /* for SLEEP MODE */<br>  enabled = vwrq-&gt;disabled ? 0 : 1;<br>  <strong>if</strong> (enabled == 0) {  /* 0 */<br>    priv-&gt;reg.powermgt = POWMGT_ACTIVE_MODE;<br>  } <strong>else</strong> <strong>if</strong> (enabled) {  /* 1 */<br>    <strong>if</strong> (priv-&gt;reg.operation_mode == MODE_INFRASTRUCTURE)<br>      priv-&gt;reg.powermgt = POWMGT_SAVE1_MODE;<br>    <strong>else</strong><br>      <strong>return</strong> -EINVAL;<br>  } <strong>else</strong> <strong>if</strong> (enabled) {  /* 2 */<br>    <strong>if</strong> (priv-&gt;reg.operation_mode == MODE_INFRASTRUCTURE)<br>      priv-&gt;reg.powermgt = POWMGT_SAVE2_MODE;<br>    <strong>else</strong><br>      <strong>return</strong> -EINVAL;<br>  } <strong>else</strong><br>    <strong>return</strong> -EINVAL;</pre><pre>  hostif_sme_enqueue(priv, SME_POW_MNGMT_REQUEST);</pre><pre>  <strong>return</strong> 0;<br>}</pre><p>Let’s shorten the example to:</p><pre>enabled = vwrq-&gt;disabled ? 0 : 1;<br><strong>if</strong> (enabled == 0)   {  /* 0 */<br>  ....<br>} <strong>else</strong> <strong>if</strong> (enabled) {  /* 1 */<br>  ....<br>} <strong>else</strong> <strong>if</strong> (enabled) {  /* 2 */<br>  ....<br>} <strong>else</strong><br>  ....</pre><p>This code looks very strange. We see that the value range is clearly defined in the expression above: <em>enabled</em> is either <em>0</em> or <em>1</em>. However, <em>4</em> values get checked. At the same time, the comments only bring confusion: if the numbers meant to define a possible value of a variable, then it’s not what we have now: the checks for <em>1</em> and <em>2</em>are written in the same way.</p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v517/"><strong>V517</strong></a><strong> </strong>The use of ‘if (A) {…} else if (A) {…}’ pattern was detected. There is a probability of logical error presence. Check lines: 422, 424. Hal8188ERateAdaptive.c 422</p><pre><strong>static</strong> <strong>int</strong> <strong>odm_ARFBRefresh_8188E</strong>(<br>        <strong>struct</strong> odm_dm_struct *dm_odm,<br>        <strong>struct</strong> odm_ra_info *pRaInfo)<br>{  /*  Wilson 2011/10/26 */<br>  ....<br>  <strong>if</strong> (pRaInfo-&gt;HighestRate &gt; 0x13)<br>    pRaInfo-&gt;PTModeSS = 3;<br>  <strong>else</strong> <strong>if</strong> (pRaInfo-&gt;HighestRate &gt; 0x0b)<br>    pRaInfo-&gt;PTModeSS = 2;<br>  <strong>else</strong> <strong>if</strong> (pRaInfo-&gt;HighestRate &gt; 0x0b)<br>    pRaInfo-&gt;PTModeSS = 1;<br>  <strong>else</strong><br>    pRaInfo-&gt;PTModeSS = 0;<br>  ....<br>  <strong>return</strong> 0;<br>}</pre><p>Another fragment where we see two consecutive conditions. Note that at the same time, they have different bodies. It’s hard to say whether this is a real bug, or this code is just not used; this is a task for developers. The task of the analyzer is to point to a suspicious place.</p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v734/"><strong>V734</strong></a><strong> </strong>An excessive check. Examine the conditions containing search for the substrings “interleaver” and “deinterleaver”. sst-atom-controls.c 1449</p><pre><strong>static</strong> <strong>int</strong> <strong>sst_fill_widget_module_info</strong>(<br>  <strong>struct</strong> snd_soc_dapm_widget *w,<br>  <strong>struct</strong> snd_soc_platform *platform)<br>{<br>  <strong>struct</strong> snd_kcontrol *kctl;<br>  <strong>int</strong> index, ret = 0;<br>  <strong>struct</strong> snd_card *card = platform-&gt;component.card-&gt;snd_card;<br>  <strong>char</strong> *idx;</pre><pre>  down_read(&amp;card-&gt;controls_rwsem);</pre><pre>  list_for_each_entry(kctl, &amp;card-&gt;controls, list) {<br>    ....</pre><pre>    } <strong>else</strong> <strong>if</strong> (strstr(kctl-&gt;id.name, &quot;interleaver&quot;)) {<br>      <strong>struct</strong> sst_enum *e = (<strong>void</strong> *)kctl-&gt;private_value;</pre><pre>      e-&gt;w = w;</pre><pre>    } <strong>else</strong> <strong>if</strong> (strstr(kctl-&gt;id.name, &quot;deinterleaver&quot;)) {<br>      <strong>struct</strong> sst_enum *e = (<strong>void</strong> *)kctl-&gt;private_value;</pre><pre>      e-&gt;w = w;<br>    }</pre><pre>    ....<br>  }</pre><pre>  up_read(&amp;card-&gt;controls_rwsem);<br>  <strong>return</strong> 0;<br>}</pre><p>In this fragment, the programmer checks the presence of several substrings in one string. To make it more evident, I left only those substrings which are interesting to us. Let’s suppose we haven’t found <em>interleaver</em> — then there is no point in looking for <em>deinterleaver</em>, because there is definitely no <em>interleaver </em>substring. Therefore, this code fragment will never work; but since the if and else bodies are the same, it’s not dangerous. This code is simply redundant.</p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v547/">V547</a> Expression ‘block’ is always true. svclock.c 873</p><pre><strong>void</strong><br><strong>nlmsvc_grant_reply</strong>(<strong>struct</strong> nlm_cookie *cookie, __be32 status)<br>{<br>  <strong>struct</strong> nlm_block  *block;</pre><pre>  dprintk(&quot;grant_reply: looking for cookie %x, s=%d \n&quot;,<br>    *(<strong>unsigned</strong> <strong>int</strong> *)(cookie-&gt;data), status);<br>  <strong>if</strong> (!(block = nlmsvc_find_block(cookie)))<br>    <strong>return</strong>;</pre><pre>  <strong>if</strong> (block) {<br>    <strong>if</strong> (status == nlm_lck_denied_grace_period) {<br>      /* Try again in a couple of seconds */<br>      nlmsvc_insert_block(block, 10 * HZ);<br>    } <strong>else</strong> {<br>      /* Lock is now held by client, or has been rejected.<br>       * In both cases, the block should be removed. */<br>      nlmsvc_unlink_block(block);<br>    }<br>  }<br>  nlmsvc_release_block(block);<br>}</pre><p>This example demonstrates why it’s not enough for a static code analyzer to perform pattern-based, traversing <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree">AST</a>. It’s important to be able to perform control flow analysis and data flow analysis as well. At the moment when <em>block == NULL, </em>we have return, so we can say that the pointer is not null for sure. So, when we see a NULL check, we understand that there is something wrong here.</p><p>Apparently, the second check is just not necessary here. But what if the programmer wanted to check a different variable? Who knows …? This code should be reviewed by the developer.</p><p>A similar situation:</p><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v547/">V547</a> Expression ‘sym’ is always true. menu.c 498</p><pre><strong>bool</strong> <strong>menu_is_visible</strong>(<strong>struct</strong> menu *menu)<br>{<br>  <strong>struct</strong> menu *child;<br>  <strong>struct</strong> symbol *sym;</pre><pre>  ....</pre><pre>  <strong>if</strong> (!sym || sym_get_tristate_value(menu-&gt;sym) == no) // &lt;=<br>    <strong>return</strong> false;</pre><pre>  <strong>for</strong> (child = menu-&gt;list; child; child = child-&gt;next) {<br>    <strong>if</strong> (menu_is_visible(child)) {<br>      <strong>if</strong> (sym)                                         // &lt;=<br>        sym-&gt;flags |= SYMBOL_DEF_USER;<br>      <strong>return</strong> true;<br>    }<br>  }</pre><pre>  <strong>return</strong> false;<br>}</pre><h3>An erron in a macro</h3><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v733/">V733</a> It is possible that macro expansion resulted in incorrect evaluation order. Check expression: request-&gt;rq_timeout + 5 * 1000. niobuf.c 637</p><pre>#<strong>define</strong> CFS_FAIL_TIMEOUT(id, secs) \<br>cfs_fail_timeout_set(id, 0, secs * 1000, CFS_FAIL_LOC_NOSET)</pre><pre>#<strong>define</strong> OBD_FAIL_TIMEOUT(id, secs) \<br>CFS_FAIL_TIMEOUT(id, secs)</pre><pre><strong>int</strong> <strong>ptl_send_rpc</strong>(<strong>struct</strong> ptlrpc_request *request, <strong>int</strong> noreply)<br>{<br>  ....<br>  OBD_FAIL_TIMEOUT(OBD_FAIL_PTLRPC_DELAY_SEND,<br>                   request-&gt;rq_timeout + 5);<br>  ....<br>}</pre><p>These errors are very rare. I have previously seen this warning only once in a real project: interestingly enough, it was <a href="http://www.viva64.com/en/b/0377/">FreeBSD</a>. There, the error was in the macro: it’s better to enclose the parameters in brackets. If this is not done, then such a situation is possible: when using ‘x + 5’ in ‘secs * 1000’, we get ‘x + 5 * 1000’; obviously, this is not what the author expected.</p><h3>Meaningless memset</h3><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v597/"><strong>V597</strong></a><strong> </strong>The compiler could delete the ‘memset’ function call, which is used to flush ‘ps’ buffer. The memset_s() function should be used to erase the private data. atom.c 1383</p><pre><strong>int</strong> <strong>amdgpu_atom_asic_init</strong>(<strong>struct</strong> atom_context *ctx)<br>{<br>  <strong>int</strong> hwi = CU16(ctx-&gt;data_table + ATOM_DATA_FWI_PTR);<br>  <strong>uint32_t</strong> ps[16];<br>  <strong>int</strong> ret;</pre><pre>  memset(ps, 0, 64);</pre><pre>  ps[0] = cpu_to_le32(CU32(hwi + ATOM_FWI_DEFSCLK_PTR));<br>  ps[1] = cpu_to_le32(CU32(hwi + ATOM_FWI_DEFMCLK_PTR));<br>  <strong>if</strong> (!ps[0] || !ps[1])<br>    <strong>return</strong> 1;</pre><pre>  <strong>if</strong> (!CU16(ctx-&gt;cmd_table + 4 + 2 * ATOM_CMD_INIT))<br>    <strong>return</strong> 1;<br>  ret = amdgpu_atom_execute_table(ctx, ATOM_CMD_INIT, ps);<br>  <strong>if</strong> (ret)<br>    <strong>return</strong> ret;</pre><pre>  memset(ps, 0, 64); // &lt;=</pre><pre>  <strong>return</strong> ret;<br>}</pre><p>It makes no sense to add <em>memset</em> before <em>return</em>: the compiler, seeing that this operation does not change the visible state of a program (an array still beyond the scope), will remove it. If it is necessary to erase some important data, then use memset_s, or write your own equivalent.</p><p>This error by the way, is actually a vulnerability. Some data that should be erased, doesn’t get removed. More details can be found in the description of the <a href="http://www.viva64.com/en/w/v597/">V597</a>diagnostic. Actually, this is a very common vulnerability: <a href="http://www.viva64.com/en/examples/v597/">proof</a></p><h3>Dangerous use of memcmp</h3><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/w/v642/">V642</a> Saving the ‘memcmp’ function result inside the ‘unsigned char’ type variable is inappropriate. The significant bits could be lost breaking the program’s logic. host.c 1789</p><pre><strong>static</strong> <strong>void</strong> <strong>power_control_timeout</strong>(<strong>unsigned</strong> <strong>long</strong> data)<br>{<br>  ....<br>  u8 other = memcmp(requester-&gt;frame_rcvd.iaf.sas_addr,<br>                    iphy-&gt;frame_rcvd.iaf.sas_addr,<br>                    <strong>sizeof</strong>(requester-&gt;frame_rcvd.iaf.sas_addr));</pre><pre>  <strong>if</strong> (other == 0) {<br>    ....<br>  }<br>  ....<br>}</pre><p>If we read carefully what the documentation says about the return value of <em>memcmp</em>, we’ll see that there is no guarantee about the value range: the function can return any number within the scope of its type. And it’s not always -1, 0, and 1. Therefore, you cannot save the value in a variable of a smaller type: If there is a loss of higher bits, the lower ones can be zero. A similar mistake caused several vulnerabilities in <a href="http://seclists.org/oss-sec/2012/q2/493">MySQL/MariaDB</a>.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*s3pj9Y2laK1-XPuK.png" /></figure><p>As was already mentioned, Linux is a very high quality and well tested project. To find a bug, even the most insignificant one — is already good enough reason to be proud. It’s also grounds to wonder how many errors could be found before debugging and testing: the static analyzer is especially useful in this regard. You can see this by trying PVS-Studio. You may get a trial version of the Linux analyzer if you e-mail us. In case you have a non-commercial project, you can use PVS-Studio for free: just read this <a href="http://www.viva64.com/en/b/0457/">article</a>, and use our open and free utility <a href="https://github.com/viva64/how-to-use-pvs-studio-free">how-to-use-pvs-studio-free</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2058e5983db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use PVS-Studio for free]]></title>
            <link>https://medium.com/@emma_programmer/how-to-use-pvs-studio-for-free-211ab12cc490?source=rss-d2ed7cc547b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/211ab12cc490</guid>
            <category><![CDATA[pvs-studio]]></category>
            <category><![CDATA[free]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[devtools]]></category>
            <dc:creator><![CDATA[Emma Brown]]></dc:creator>
            <pubDate>Wed, 30 Nov 2016 06:24:04 GMT</pubDate>
            <atom:updated>2016-11-30T06:24:04.972Z</atom:updated>
            <content:encoded><![CDATA[<p>We want to help the software world improve the quality of their code, and get to know static analysis tools better. We are giving the opportunity to use PVS-Studio static code analyzer for free, for educational purposes, so that individual developers and enthusiastic teams could also fully use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/0*XUqCMpKzJgdi92H6.png" /></figure><h3>Introduction</h3><p>The main customers of the <a href="http://www.viva64.com/en/pvs-studio/">PVS-Studio</a> tool are the development departments of various companies. At the same time, we would also like to see individual developers as our clients. Unfortunately, our experimental product <a href="http://www.viva64.com/en/b/0320/">CppCat</a> had no success. We don’t know how we can build a successful business in the sphere of static analysis by selling individual licenses. This is why we still see PVS-Studio as a B2B solution.</p><p>I think, our failure with CppCat was predetermined. The world imposes its own laws and for example, the well-known Coverity tool is also aimed at corporate licenses. However, this does not mean that we should exclude other options of interacting with the world.</p><p>We were thinking for quite a long time about how to help small-size development teams, and how to start issuing academic licenses. At first glance, it seemed that the simplest way is to start giving away licenses to those who develop free software. Unfortunately, this solution does not seem to be the way to go.</p><p>We should clarify our point of view. However, you can skip this section and just move to the “Free PVS-Studio license” section. If you are still interested in knowing the details, then I suggest you continue reading.</p><h3>Our thoughts behind this decision</h3><p>Let’s imagine an individual developer, who writes and sells some game, for example. His code is closed, and used for commercial purposes. Nevertheless, we would be glad to help him get acquainted with the methodology of static code analysis, and provide a free license for him. This is a sort of promotional step that could get compensated later. At this point this is an individual developer, but who knows what may happen in the future.</p><p>On the other hand, let’s take a team of 50 people working in a large company, and creating a free open source project. They sit in an office, eat company cookies, have a fixed income, and position themselves as idealists in the sphere of open source development. Yes, they are making a free product, but the company gets the revenue from it by indirect means. For a number of reasons, it is beneficial for the company to keep this project open and free. It seems quite fair to us that such an organization should purchase a license in order to use the analyzer.</p><p>As you see, the criterion “a free program”, or “open source code” doesn’t suit us in making a decision. We would like to separate the projects being developed in a company, from projects of small-sized enthusiastic teams. We could do that solely by a license agreement, but in this case it’s hard to distinguish between different types of projects. In addition, this will be of little help to us in terms of promotion. Let’s be honest, big companies provide free licenses for the sake of advertisement. We are no worse and no better than others in doing the same.</p><p>The solution came quite naturally; What is the main difference between large corporate projects and the code of enthusiastic teams? Corporate projects have much less freedom, and more bureaucracy. It is unlikely that Microsoft’s management would be pleased if a Microsoft Office developer wrote in the code that it is his personal project. We thought we could use this, and suggest making comments in the code, which would make reference to PVS-Studio. In addition, the code of open source projects would promote PVS-Studio.</p><h3>Free PVS-Studio license</h3><p>You need to go through two steps to start using the PVS-Studio code analyzer for free.</p><h3>Step 1.</h3><p>If you are using PVS-Studio as a Visual Studio plugin, enter the following license key:</p><p>Name: PVS-Studio Free</p><p>Key: FREE-FREE-FREE-FREE</p><p>If you are using PVS-Studio for Linux, go to the second step, you don’t need a license file.</p><h3>Step 2.</h3><p>Make edits in all the compilable files of your project. I.e. in all the files with the extensions c, cc, cpp, cs, and so on. You don’t have to change header h-files.</p><p>You need to write two lines of comments in the beginning of each file. We offer several options. This is a kind of ‘fee’ for using PVS-Studio for free.</p><p>Comments for students (academic license):</p><p>// This is a personal academic project. Dear PVS-Studio, please check it.</p><p>// PVS-Studio Static Code Analyzer for C, C++ and C#: <a href="http://www.viva64.com/en/b/0457/">http://www.viva64.com</a></p><p>Comments for free open source projects:</p><p>// This is an open source non-commercial project. Dear PVS-Studio, please check it.</p><p>// PVS-Studio Static Code Analyzer for C, C++ and C#: <a href="http://www.viva64.com/en/b/0457/">http://www.viva64.com</a></p><p>Comments for individual developers:</p><p>// This is an independent project of an individual developer. Dear PVS-Studio, please check it.</p><p>// PVS-Studio Static Code Analyzer for C, C++ and C#: <a href="http://www.viva64.com/en/b/0457/">http://www.viva64.com</a></p><p>Of course, the options we suggest won’t be suitable for everyone. But that’s the point of such measures. If none of the variants is relevant to you of your product, we suggest you consider <a href="http://www.viva64.com/en/order/">purchasing the license</a>.</p><p>A little note. Besides the described method of using the analyzer for free, you can still download a demo version of the analyzer to see the abilities. If you wish to get rid of the restrictions imposed by a demo version, you may just <a href="http://www.viva64.com/en/about-feedback/">write to us</a>.</p><h3>Automation</h3><p>If your project has a large number of files, then you can use an additional utility. You will need to specify the directory and the code to insert. Then it will recursively traverse all the files in the folder and subfolders, adding necessary comments to the code. You can download the utility (together with the source code) here: <a href="https://github.com/viva64/how-to-use-pvs-studio-free">how-to-use-pvs-studio-free</a>.</p><h3>Conclusion</h3><p>Some developers may say that they don’t want to see two additional lines of code at the beginning of the file with the comments not related to the project itself. It is their right, and they may simply not use the tool. Or they can purchase a commercial license, and use it without any restrictions. We see these comments as a gratuity for the provided license, and also as an additional way to promote our product. I think it’s a good, fair exchange.</p><p>At the same time, it solves the problem of distinguishing between corporate projects and private initiatives. If a project is made by enthusiasts, they have the full rights to do with the code anything they want, including adding such comments. If not, then there is some organization behind the project, and we would want to get a reward from it in the form of purchasing the license.</p><p>I hope our offer and position is clear. If you still have any questions, please <a href="http://www.viva64.com/en/about-feedback/">contact us</a>.</p><p>To convince your colleagues to start using PVS-Studio code analyzer, we suggest reading the following sections of our web-site.</p><ul><li><a href="http://www.viva64.com/en/examples/">Bugs found in open source projects with PVS-Studio</a></li><li><a href="http://www.viva64.com/en/inspections/">Articles, which describe the bugs we find</a></li></ul><p>Thank you for your attention. Let’s make our software more reliable, and safer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=211ab12cc490" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analysis of bugs in Orchard CMS]]></title>
            <link>https://medium.com/@emma_programmer/analysis-of-bugs-in-orchard-cms-bc67cc6666af?source=rss-d2ed7cc547b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc67cc6666af</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[pvs-studio]]></category>
            <dc:creator><![CDATA[Emma Brown]]></dc:creator>
            <pubDate>Tue, 29 Nov 2016 12:28:55 GMT</pubDate>
            <atom:updated>2016-11-29T12:28:55.470Z</atom:updated>
            <content:encoded><![CDATA[<p>Orchard is a free, open source, community-focused Content Management System built on the ASP.NET MVC platform. Software IP management and project development governance are provided by Outercurve Foundation, a nonprofit fund.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*Izv-xEg3THKJZ76W.png" /></figure><p>For us, the developers of the PVS-Studio static analyzer, this is another chance to check an interesting project, tell people (and developers) about the errors we find and test our analyzer, of course. Today we’ll speak about the errors we found in the Orchard CMS project.</p><h3>About the Orchard CMS project</h3><p>The description of the project is taken from the site <a href="http://orchardproject.ru/about-orchard">http://www.orchardproject.net/mission</a>.</p><p>The Orchard CMS project was announced in March of 2010 with the release of the first beta-version of the project. The creators of Orchard CMS set a goal of creating a content management system on a new successful framework, ASP.NET MVC, that would meet the following demands:</p><ul><li>An open and free project that is built on community requests;</li><li>A fast engine with a modular architecture, and all necessary CMS means;</li><li>A public online gallery of modules, themes, and other components for extension from the community;</li><li>High quality typography, attention to the layout and markup of pages.</li><li>Focus on creating a comfortable and functional administration panel;</li><li>Quick desktop deployment of the system, and easy publishing on the server.</li></ul><p>Initially, the Orchard project and its source code was licensed under a free MS-PL license, but with the release of the first public version, the project changed the license to a simpler and more widespread New BSD License.</p><p>Four pre-release versions were released within a year, until Orchard CMS reached version 1.0. All this time the developers kept in touch with the community, accepting requests, considering comments, and fixing bugs. The project was launched on the codeplex.com portal in order to get user feedback — <a href="http://orchard.codeplex.com/">http://orchard.codeplex.com/</a>.</p><p>Today you can find exhaustive documentation on all aspects of Orchard CMS, participate in discussions on the project on the forums, report bugs to the bugtracker, download the latest source code and binary builds of the project.</p><p>In addition to the page for developers, an official web site, <a href="http://www.orchardproject.net/">http://www.orchardproject.net/</a> was launched that contains all the necessary documentation to work with Orchard CMS. Besides that, the official site has a gallery of modules and other components, created by the community, in order to enlarge the functionality of Orchard CMS.</p><h3>The analysis results</h3><p>We did the analysis of all source code files (3739 items) with the .cs extension. In sum total there were 214 564 lines of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/0*TUJ-_7meLZnHS5Xw.png" /></figure><p>The result of the check was 137 warnings. To be more precise, there were 39 first (high) level warnings. 28 of them clearly pointed to a problem fragment or an error. There were also 60 second (medium) level warnings. In my subjective opinion, 31 of these warnings were correct and indicated fragments that contained real bugs or typos. We aren’t going to look at the lowest level warnings, because these warnings don’t usually indicate real errors, are made up of quite a large number of false positives, and contain warnings that aren’t relevant for most of the projects.</p><p>So, let’s take a look at the most interesting of the bugs that we found. The project authors can do a more detailed review of the bugs by doing the project check themselves, or making a request for a temporary license.</p><p>Also, as far as I understand, the Orchard CMS developers are already using ReSharper in their project. I drew this conclusion based on the following:</p><p><a href="https://github.com/OrchardCMS/Orchard-Harvest-Website/blob/master/src/Orchard.4.5.resharper">https://github.com/OrchardCMS/Orchard-Harvest-Website/blob/master/src/Orchard.4.5.resharper</a></p><p>We do not like the idea of comparing PVS-Studio and ReSharper, because they are two different types of tool. But as you can see, using ReSharper did not prevent us from finding real errors in the code.</p><h3>Infinite recursion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*KXylzwX4EdQjaiJN.png" /></figure><p><a href="http://www.viva64.com/en/w/v3110/">V3110</a> Possible infinite recursion inside ‘ReturnTypeCustomAttributes’ property. ContentItemAlteration.cs 121</p><pre><strong>public</strong> override ICustomAttributeProvider <br>  ReturnTypeCustomAttributes <br>{<br>  get { <strong>return</strong> ReturnTypeCustomAttributes; }<br>}</pre><p>The first error on our list is quite a widespread typo that will lead to an infinite recursion and <em>StackOverflow </em>exception, which will also cause the program to crash once the value of the <em>ReturnTypeCustomAttributes </em>is gotten.<em> </em>Most likely, the programmer wanted to return, from the property, a field of the same name as the object <em>_dynamicMethod; </em>then, the correct variant should be like this:</p><pre><strong>public</strong> override ICustomAttributeProvider <br>  ReturnTypeCustomAttributes<br>{<br>  get { <strong>return</strong> _dynamicMethod.ReturnTypeCustomAttributes; }<br>}</pre><p>And here’s another typo which will cause an infinite recursion, and, as a consequence, throw a StackOverflow exception.</p><p>V3110 Possible infinite recursion inside ‘IsDefined’ method. ContentItemAlteration.cs 101</p><pre><strong>public</strong> override <strong>bool</strong> <strong>IsDefined</strong>(Type attributeType, <strong>bool</strong> inherit) {<br>  <strong>return</strong> IsDefined(attributeType, inherit);<br>}</pre><p>In this case the <em>IsDefined</em> method calls itself. I think the programmer wanted to call a method with the same name as the object <em>_dynamicMethod</em>. Then the correct version would look like this:</p><pre><strong>public</strong> override <strong>bool</strong> <strong>IsDefined</strong>(Type attributeType, <strong>bool</strong> inherit) {<br>  <strong>return</strong> _dynamicMethod.IsDefined(attributeType, inherit);<br>}</pre><h3>When a minute doesn’t always have 60 seconds</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/0*suSz__APr82EdIKP.png" /></figure><p><a href="http://www.viva64.com/en/w/v3118/">V3118</a> Seconds componentof TimeSpan is used, which does not represent full time interval. Possibly ‘TotalSeconds’ value was intended instead. AssetUploader.cs 182</p><pre><strong>void</strong> IBackgroundTask.Sweep() <br>{<br>  ....<br>  // Don&#39;t flood the database with progress updates; <br>  // Limit it to every 5 seconds.<br>  <strong>if</strong> ((_clock.UtcNow - lastUpdateUtc).Seconds &gt;= 5) <br>  {<br>    ....<br>  }<br>}</pre><p>Another fairly common typo, which occurs because of the <em>TimeSpan</em> type implementation. The comment shows that this method should block the database query, if there were less than 5 seconds since the previous query. But apparently, the programmer did not know that the <em>Seconds</em> property of the object of<em> TimeSpan</em>type returns not the total number of seconds in this interval, but the remaining number of seconds.</p><p>For example, if the time interval is 1 minute and 4 seconds, then the call of the <em>Seconds</em> method will return only 4 seconds. If it is necessary to return a total number of seconds, we should use the property <em>TotalSeconds. </em>For this example it will be 64 seconds.</p><p>Then the correct code could be written as such:</p><pre><strong>void</strong> IBackgroundTask.Sweep() <br>{<br>  ....<br>  // Don&#39;t flood the database with progress updates; <br>  // Limit it to every 5 seconds.<br>  <strong>if</strong> ((_clock.UtcNow - lastUpdateUtc).TotalSeconds &gt;= 5) // &lt;=<br>  {<br>    ....<br>  }<br>}</pre><h3>Missing enumeration value during the switch check</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*wV5PJrLItCVjIQe4.png" /></figure><p><a href="http://www.viva64.com/en/w/v3002/">V3002</a> The switch statement does not cover all values of the ‘TypeCode’ enum: Byte. InfosetFieldIndexingHandler.cs 65</p><pre><strong>public</strong> <strong>enum</strong> TypeCode<br>{<br>  Empty = 0,<br>  Object = 1,<br>  DBNull = 2,<br>  Boolean = 3,<br>  Char = 4,<br>  SByte = 5,<br>  Byte = 6,<br>  Int16 = 7,<br>  UInt16 = 8,<br>  Int32 = 9,<br>  UInt32 = 10,<br>  Int64 = 11,<br>  UInt64 = 12,<br>  Single = 13,<br>  Double = 14,<br>  Decimal = 15,<br>  DateTime = 16,<br>  String = 18<br>}</pre><pre><strong>public</strong> InfosetFieldIndexingHandler(....)<br>{<br>  ....<br>  var typeCode = Type.GetTypeCode(t);<br>  <strong>switch</strong> (typeCode) {<br>    <strong>case</strong> TypeCode.Empty:<br>    <strong>case</strong> TypeCode.Object:<br>    <strong>case</strong> TypeCode.DBNull:<br>    <strong>case</strong> TypeCode.String:<br>    <strong>case</strong> TypeCode.Char:<br>      ....<br>      <strong>break</strong>;<br>    <strong>case</strong> TypeCode.Boolean:<br>      ....<br>      <strong>break</strong>;<br>    <strong>case</strong> TypeCode.SByte:<br>    <strong>case</strong> TypeCode.Int16:<br>    <strong>case</strong> TypeCode.UInt16:<br>    <strong>case</strong> TypeCode.Int32:<br>    <strong>case</strong> TypeCode.UInt32:<br>    <strong>case</strong> TypeCode.Int64:<br>    <strong>case</strong> TypeCode.UInt64:<br>      ....<br>      <strong>break</strong>;<br>    <strong>case</strong> TypeCode.Single:<br>    <strong>case</strong> TypeCode.Double:<br>    <strong>case</strong> TypeCode.Decimal:<br>      ....<br>      <strong>break</strong>;<br>    <strong>case</strong> TypeCode.DateTime:<br>      ....<br>      <strong>break</strong>;<br>  }<br>}</pre><p>This code fragment is quite bulky, so it’s hard to notice the error. In this case we have the enum <em>TypeCode</em>,<em> </em>and a method <em>InfosetFieldIndexingHandler, </em>where it is checked, to which element of the enum the <em>typeCode</em> variable belongs. The programmer most likely forgot about one small <em>Byte</em> element, but added <em>SByte</em>. Because of this error, <em>Byte</em> processing will be ignored. It would be easier to avoid this error if the programmer added a <em>default</em> block, where the exception is thrown in regards to an unhandled enum items.</p><h3>No handling the return value from the Except method</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*mMCiTRVPscD4dIFr.png" /></figure><p><a href="http://www.viva64.com/en/w/v3010/">V3010</a> The return value of function ‘Except’ is required to be utilized. AdminController.cs 140</p><pre><strong>public</strong> ActionResult <strong>Preview</strong>(string themeId, string returnUrl) {<br>  ....<br>  <strong>if</strong> (_extensionManager.AvailableExtensions()<br>    ....<br>  } <strong>else</strong> {<br>    var alreadyEnabledFeatures = GetEnabledFeatures();<br>    ....<br>    alreadyEnabledFeatures.Except(<strong>new</strong>[] { themeId }); // &lt;=<br>    TempData[AlreadyEnabledFeatures] = alreadyEnabledFeatures;<br>  }<br>  ....<br>}</pre><p>As is well known, the <em>Except</em> method eliminates from the collection, for which it is called, items of another collection. Perhaps the programmer wasn’t aware of this, or did not pay attention to the fact that the result of this method returns a new collection. Then the correct variant may be as follows:</p><pre>alreadyEnabledFeatures = <br>  alreadyEnabledFeatures.Except(<strong>new</strong>[] { themeId });</pre><h3>Substring method does not take a negative value.</h3><p><a href="http://www.viva64.com/en/w/v3057/">V3057</a> The ‘Substring’ function could receive the ‘-1’ value while non-negative value is expected. Inspect the second argument. ContentIdentity.cs 139</p><pre>.... GetIdentityKeyValue(....) {<br>  ....<br>  var indexOfEquals = identityEntry.IndexOf(&quot;=&quot;);<br>  <strong>if</strong> (indexOfEquals &lt; 0) <strong>return</strong> null;</pre><pre>  var key = identityEntry.Substring(1, indexOfEquals - 1);</pre><pre>  ....<br>}</pre><p>Pay attention to the check of the <em>indexOfEquals </em>variable. The check protects from cases where the value of the variable is negative; but, there is no protection from a null value.</p><p>If the symbol ‘=’ is right at the beginning, then there will be an exception, because the second argument of the <em>Substring() </em>method will have a negative value -1.</p><p>The analyzer found other similar bugs, but I saw no point in describing each and every one of them.</p><ul><li>V3057 The ‘Substring’ function could receive the ‘-1’ value while non-negative value is expected. Inspect the second argument. CommandParametersParser.cs 18</li><li>V3057 The ‘Substring’ function could receive the ‘-1’ value while non-negative value is expected. Inspect the second argument. CommandStep.cs 73</li></ul><h3>Operation precedence in a statement</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*f0M7-jUHS1cMLpHN.png" /></figure><p><a href="http://www.viva64.com/en/w/v3022/">V3022</a> Expression ‘localPart.Name + “.” + localField.Name + “.” + storageName’ is always not null. ContentFieldProperties.cs 56</p><pre>localPart.Name + &quot;.&quot; + localField.Name + &quot;.&quot; + storageName ?? &quot;&quot;</pre><p>The programmer thought that the <em>?? </em>operator would verify only the variable <em>storageName </em>against <em>null </em>and if so, then instead of it, an empty string will added to the expression. But since the + operator has a supercedes the <em>??</em>, the whole expression will be verified against <em>null</em>. It should be noted that we’ll get the same string without any changes if we add <em>null</em> to the string. Thus, in this case we can safely remove this redundant misleading check. The correct variant can look like this:</p><pre>localPart.Name + &quot;.&quot; + localField.Name + &quot;.&quot; + storageName</pre><p>The analyzer found one more similar bug:</p><p>V3022 Expression ‘localPart.Name + “.” + localField.Name + “.” + storageName’ is always not null. ContentFieldsSortCriteria.cs 53</p><h3>A check that is always false</h3><p><a href="http://www.viva64.com/en/w/v3022/">V3022</a> Expression ‘i == 4’ is always false. WebHost.cs 162</p><pre><strong>public</strong> <strong>void</strong> <strong>Clean</strong>() {<br>  // Try to delete temporary files for up to ~1.2 seconds.<br>  <strong>for</strong> (<strong>int</strong> i = 0; i &lt; 4; i++) {<br>    Log(&quot;Waiting 300msec before trying to delete ....&quot;);<br>    Thread.Sleep(300);</pre><pre>    <strong>if</strong> (TryDeleteTempFiles(i == 4)) {<br>      Log(&quot;Successfully deleted all ....&quot;);<br>      <strong>break</strong>;<br>    }<br>  }<br>}</pre><p>We see that the iterator of the <em>i</em> loop will always range in value from 0 to 3, but despite this, the programmer checks if the iterator has value of 4 inside the body of the loop. The check will be never executed, but it’s hard for me to say how dangerous this bug is in the scope of the whole project without knowing the real goal of this code fragment.</p><p>There were other similar bugs found. All of them denote that the check will be either true or false.</p><ul><li>V3022 Expression ‘result == null’ is always false. ContentFieldDriver.cs 175</li><li>V3022 Expression ‘String.IsNullOrWhiteSpace(url)’ is always true. GalleryController.cs 93</li><li>V3022 Expression ‘_smtpSettings.Host != null’ is always true. SmtpMessageChannel.cs 143</li><li>V3022 Expression ‘loop’ is always false. IndexingTaskExecutor.cs 270</li><li>V3022 Expression ‘Convert.ToString(Shape.Value)’ is always not null. EditorShapes.cs 372</li><li>V3022 Expression ‘ModelState.IsValid’ is always true. RecycleBinController.cs 81</li><li>V3022 Expression ‘previousXml != null’ is always true. ContentDefinitionEventHandler.cs 104</li><li>V3022 Expression ‘previousXml != null’ is always true. ContentDefinitionEventHandler.cs 134</li><li>V3022 Expression ‘layoutId != null’ is always true. ProjectionElementDriver.cs 120</li></ul><h3>Using a class member before verification of the object against null</h3><p><a href="http://www.viva64.com/en/w/v3027/">V3027</a> The variable ‘x.Container’ was utilized in the logical expression before it was verified against null in the same logical expression. ContainerService.cs 130</p><pre>query.Where(x =&gt; <br>           (x.Container.Id == containerId || <br>            x.Container == null) &amp;&amp; <br>            ids.Contains(x.Id));</pre><p>As you can see from the code above (we are interested in lines 2 and 3), the programmer first checks the access to the <em>Id</em> property from the container, and then checks the container for <em>null</em>. It would be correct to verify against <em>null</em>, and then access the container elements.</p><p>Next fragment:</p><p><a href="http://www.viva64.com/en/w/v3095/">V3095</a> The ‘Delegate’ object was used before it was verified against null. Check lines: 37, 40. SerializableDelegate.cs 37</p><pre><strong>void</strong> ISerializable.GetObjectData(<br>  SerializationInfo info, <br>  StreamingContext context)<br>{<br>  info.AddValue(&quot;delegateType&quot;, Delegate.GetType());<br>  ....<br>  <strong>if</strong> (.... &amp;&amp; Delegate != null)<br>  {<br>    ....<br>  }                <br>}</pre><p>PVS-Studio found two more errors that are just the same as the one described above, so I won’t go into them here.</p><ul><li>V3095 The ‘Delegate’ object was used before it was verified against null. Check lines: 37, 40. SerializableDelegate.cs 37</li><li>V3095 The ‘widget’ object was used before it was verified against null. Check lines: 81, 93. TagsWidgetCommands.cs 81</li></ul><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/0*8f-J03cQbyx8Jt2W.png" /></figure><p>There were many more errors, typos and issues found in this project. But they didn’t seem interesting enough to describe in this article. The Orchard CMS developers can easily find all the issues, using the <a href="http://www.viva64.com/">PVS-Studio</a> tool. You may also find bugs in your projects with the help of the mentioned tool.</p><p>I would like to mention that the greatest benefit of static analysis is found in its regular use. There’s no real use in downloading the tool and doing a one-time check — that could not be considered to be serious analysis. For example, programmers regularly review the compiler warnings; not just 3 times a year before the release. If the analyzer is used on a regular basis, it will significantly save time which is usually spent on searching for typos and errors.</p><p>P.S. For those who missed the news, let me remind you that PVS-Studio can now integrate with SonarQube. An article on this topic: “<a href="http://www.viva64.com/en/b/0452/">Control source code quality using the SonarQube platform</a>”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc67cc6666af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Do Programs Run with All Those Bugs At All?]]></title>
            <link>https://medium.com/@emma_programmer/how-do-programs-run-with-all-those-bugs-at-all-9240891cb182?source=rss-d2ed7cc547b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9240891cb182</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pvs-studio]]></category>
            <category><![CDATA[magic]]></category>
            <dc:creator><![CDATA[Emma Brown]]></dc:creator>
            <pubDate>Tue, 29 Nov 2016 08:59:08 GMT</pubDate>
            <atom:updated>2016-11-29T08:59:08.563Z</atom:updated>
            <content:encoded><![CDATA[<p>Our team analyzes lots of open-source projects to demonstrate the diagnostic capabilities of the PVS-Studio analyzer. After reading our articles, people will often ask: “How does the program run with all those bugs at all?” In this article, I will try to answer this question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*x4iqVCbEACw22nUn.png" /></figure><h3>Introduction</h3><p>For a start, let me say a few words to those of our readers who are not familiar with our tool yet. We develop the PVS-Studio analyzer designed to find bugs in C/C++ source code. The best way to demonstrate its capabilities is to analyze open-source projects to find whatever bugs we can. All the found issues are gathered in a special <a href="http://www.viva64.com/en/examples/">database</a>. When we find errors that we think to be interesting, we discuss them in articles. For more articles, check our <a href="http://www.viva64.com/en/a/0084/">up-to-date articles list</a>.</p><p>So, after reading our articles, some readers wonder how programs can work with all those bugs in them at all. I don’t think programmers are really surprised by the fact, for every one of them once had to fix a bug that had happily lived in the code for a couple of years. So this article is rather meant for readers who are not closely related to the programming world or for novice programmers only starting their way into it. Nevertheless, I believe experienced programmers may find here some useful and interesting ideas too.</p><h3>The most important thing</h3><p>Different code fragments are executed with a different frequency. Some are executed at every run, others just every now and then, and there are also fragments executed on extremely rare occasions.</p><p>The rarer a certain code fragment is executed, the easier it is for a bug to hide in it. I’ll try to explain it with a number of examples.</p><p>If a bug causes a failure when drawing a large button in the program’s main window, it will be spotted right away and probably fixed by the programmer themselves before it gets to the testing department.</p><p>If a bug depends on input data, it makes it a bit easier for it to hide. Suppose a programmer is developing a graphics editor. He or she has tested the program on images with resolution of 100x100 and 300x400, and although the code is poorly written, it still runs smoothly. Fortunately, the company has testers who have discovered that the program can’t work with stretched out images with resolution of 100x10000. As you can see, this bug has survived for a bit longer.</p><p>Even more difficult to find are the bugs which require some special conditions for them to occur. Getting back to our graphics editor, suppose it is perfect at handling middle- and large-sized images, but it can’t work with 1x1 images which must be processed in a special way, while neither the programmer nor the testers have thought of checking this mode. It results in a program crash when some user accidentally creates a 1-pixel-sized image. This time, the bug has made it through to the end user.</p><p>But there are bugs which are even harder to detect. You can find them in code branches responsible for processing various non-standard situations — for example a file saving failure. A bug like that can live inside the program for years, unknown to anyone, and show up only when a user loses some important data because the hard disk has run out of space and the program, instead of warning about this and offering to save the file into a different location as intended, just crashes because of that bug.</p><h3>Answering the question</h3><p>Most bugs we detect when analyzing open-source projects with PVS-Studio don’t affect the everyday normal work of the program for thousands of users. All of these bugs are found in code fragments which execute very rarely, so nobody has to deal with them.</p><p>And it can’t be any other way. Take the Qt library, for instance. This library is debugged and tested all through and is used by a vast number of developers in their work. It simply cannot carry any bugs lying on the surface. That’s why PVS-Studio only finds bugs which rarely reveal themselves. As an example, take a look at the following function:</p><pre>QV4::ReturnedValue<br>QQuickJSContext2DPrototype::method_getImageData(....)<br>{<br>  ....<br>  qreal x = ctx-&gt;callData-&gt;args[0].toNumber();<br>  qreal y = ctx-&gt;callData-&gt;args[1].toNumber();<br>  qreal w = ctx-&gt;callData-&gt;args[2].toNumber();<br>  qreal h = ctx-&gt;callData-&gt;args[3].toNumber();<br>  <strong>if</strong> (!qIsFinite(x) || !qIsFinite(y) ||<br>      !qIsFinite(w) || !qIsFinite(w))<br>  ....<br>}</pre><p>It contains an error — the ‘h’ variable is not checked. Instead, the ‘w’ variable is checked twice. Is it a bug? Yes, it is. But it is very unlikely to show up soon.</p><p>First, not all of the applications employing the Qt library ever call the method_getImageData() function. I believe hardly anyone uses it at all, actually. Second, the error will emerge only if the last argument is incorrectly converted (there are no troubles with the other arguments). Third, this last argument must be incorrectly defined. Therefore, this bug is very unlikely to ever show up.</p><p>This is why it had survived in the Qt library’s code for a long time before it was caught by PVS-Studio. By the way, if you want to learn more about that check, here’s the article “<a href="http://www.viva64.com/en/b/0251/">Checking the Qt 5 Framework</a>”.</p><p>Now let’s sum it up.</p><p>When developing and maintaining programs, developers use a number of methods to test them (unit-tests, regression tests, manual tests, and so on). Explicit errors are quickly eliminated as both the developers themselves and product users discover them very soon.</p><p>That’s why when we run the PVS-Studio analyzer on some well-known and reliable project such as Chromium, we can only hope to find bugs that almost never reveal themselves.</p><p>I mean, bugs are still there — numbers of them (see checks <a href="http://www.viva64.com/en/a/0074/">N1</a>, <a href="http://www.viva64.com/en/b/0113/">N2</a>, <a href="http://www.viva64.com/en/b/0205/">N3</a>, <a href="http://www.viva64.com/en/b/0225/">N4</a>). But you are hardly ever to run into them when working in Chromium. It will take an effort, probably a great one, to get to the code branch where the bug is living.</p><h3>No need to use PVS-Studio then?</h3><p>Having read to this place, one may rush to draw an incorrect conclusion: “There’s no need to use PVS-Studio since it detects insignificant bugs that almost never show up”.</p><p>Usually when I feel that someone is about to draw this conclusion, I refer them to the article “<a href="http://www.viva64.com/en/b/0105/">Leo Tolstoy and static code analysis</a>”. But this time, I will try to put the answer once again into different words.</p><p>You see, our articles and single-time checks of open-source projects have very little to do with the normal use of the static code analysis methodology. Single-time checks are good for advertising the product, but no more than that. They are of very little use, really. You can only benefit from static analysis when using it regularly.</p><p>The worst thing you can do is run your code through an analyzer shortly before the release. It’s just pointless. Numbers and numbers of bugs the analyzer could have caught for you have been already found and fixed by the time at the cost of sweat and blood. It’s not an efficient way of using the tool (here’s, for example, a post about <a href="http://www.viva64.com/en/b/0221/">how you can waste 50 hours of working time</a>). After a number of sleepless nights spent working in the debugger and exchanging emails with testers, developers run the analyzer just to get a couple of useful messages. What’s the use of it when they have already spent huge amounts of time and effort to find and fix all the most horrible bugs themselves? Isn’t it an epic fail?</p><p>I’m not exaggerating, mind you. Many developers don’t really understand how to use code analyzers properly. We receive plenty of emails reading something like this: “A cool thing. Gonna use it before releasing”. That’s sad. This is why I’m continuously striving to bring light into the dark land of bugs and programmers unwilling to think.</p><p>I’m not claiming the analyzer can find all the possible bugs. It can only find some of them. But it will do it at once — as soon as the programmer has finished writing a new block of code.</p><p>The idea about static analysis is that many errors and typos can be caught at the earliest development stage. By using it regularly, you can greatly reduce the time you would otherwise spend on seeking and eliminating defects in your code.</p><h3>PVS-Studio is needed!</h3><p>To convince you once and for all, let me cite one real-life example. Recently we were analyzing and fixing bugs in the Unreal Engine game engine. Most of the bugs were non-critical, which is natural because otherwise no one would use Unreal Engine to develop their software.</p><p>At some point, we achieved a 0-message output. But the developers naturally continued to modify and edit the code. So the analyzer started to output new warnings on fresh code. We could see literally in real time how new bugs were getting into the code. They would be probably eliminated in a few days, but what for all that trouble when the analyzer can catch them right away? Here’s one of those bugs:</p><pre><strong>static</strong> <strong>void</strong> <strong>GetArrayOfSpeakers</strong>(....)<br>{<br>  Speakers.Reset();<br>  uint32 ChanCount = 0;<br>  // Build a flag field of the speaker outputs of this device<br>  <strong>for</strong> (uint32 SpeakerTypeIndex = 0;<br>       SpeakerTypeIndex &lt; ESpeaker::SPEAKER_TYPE_COUNT,    //&lt;==<br>       ChanCount &lt; NumChannels; ++SpeakerTypeIndex)<br>  {<br>    ....<br>  }<br>  check(ChanCount == NumChannels);<br>}</pre><p>Instead of the &amp;&amp; operator, the programmer accidentally wrote a comma. You can’t call this bug insignificant. It got into the version control system and, I’m sure, would have caused a lot of troubles but for PVS-Studio which had been alert and caught it.</p><p>To find out more about our experience of working with the Epic Games company, please see the article “<a href="http://www.viva64.com/en/b/0330/">How the PVS-Studio Team Improved Unreal Engine’s Code</a>”.</p><h3>Conclusion</h3><p>I suggest that you go and try our PVS-Studio code analyzer on your project right now. You can download it from <a href="http://www.viva64.com/en/pvs-studio-download/">here</a>. The tool’s interface is pretty simple, but I recommend that you check the article “<a href="http://www.viva64.com/en/b/0305/">PVS-Studio for Visual C++</a>” for useful tips on how to use the analyzer. For example, few users know how to easy and quickly exclude third-party libraries from analysis.</p><p>If you use makefile or your own build system to build your projects, you can use the <a href="http://www.viva64.com/en/d/0360/">PVS-Studio Standalone</a> application to analyze them. This tool uses a mechanism for monitoring compiler launches.</p><p>If you are scared of a huge number of diagnostic messages output at the first runs, try our new message marking mode which makes use of a special database. To put it briefly, the idea is that all the messages are considered irrelevant and are not displayed in the message output window; you will only see messages on fresh code. I’m sure you will learn very soon how convenient and useful static code analysis is when used regularly. To learn more, see the article “<a href="http://www.viva64.com/en/b/0309/">Integrating Static Analysis into a Project</a>”.</p><p>Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9240891cb182" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analysis of PHP7]]></title>
            <link>https://medium.com/@emma_programmer/analysis-of-php7-6ebe766f3aa2?source=rss-d2ed7cc547b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ebe766f3aa2</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Emma Brown]]></dc:creator>
            <pubDate>Fri, 25 Nov 2016 06:27:29 GMT</pubDate>
            <atom:updated>2016-11-25T06:27:29.728Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes checking a project one more time can be quite amusing. It helps to see which errors were fixed, and which ones got into the code since the time it was last checked. My colleague has already written an article about PHP analysis. As there was a new version released, I decided to check the source code of the interpreter once again, and I wasn’t disappointed — the project had a lot of interesting fragments to look at.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*jHQbYtLpc7O1b2EG.png" /></figure><h3>The project to be analyzed</h3><p><a href="http://php.net/">PHP</a> — is a general-purpose scripting language that is intensively used in web development. The language and its interpreter are developed within the open source project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*M6D3q0RlTHl8OAl-.png" /></figure><p>The new version release — PHP v.7.0.0. was announced on the 3rd of December, 2015. It is based on the experimental branch of PHP which was initially called phpng (PHP next generation), and was designed with a focus on increased productivity and reduced memory consumption.</p><p>The analyzed project is the PHP interpreter, the source code of which is available in the repository on <a href="https://github.com/php/php-src">GitHub</a>. We checked the <em>master</em> branch.</p><p>The analysis tool — <a href="http://www.viva64.com/en/pvs-studio/">PVS-Studio</a> static code analyzer. To do the analysis we also used the <a href="http://www.viva64.com/en/d/0323/">compiler monitoring system</a>, which allows to do the project analysis no matter what system is used to build this project. The trial version of the analyzer can be downloaded <a href="http://www.viva64.com/en/pvs-studio-download/">here</a>.</p><p>You can also read the previous article written by Sviatoslav Razmyslov <a href="http://www.viva64.com/en/b/0277/">“A Post About Analyzing PHP”</a>.</p><h3>Bugs found</h3><p>It is worth noting, that a lot of bugs found by the analyzer are located in the PHP libraries. But if we describe all of them here, the article will become too lengthy. On the other hand, the errors in the libraries will show up during the project usage. That’s why some of them are still given here.</p><p>One more thing to point out — during the analysis, there was an impression that the code was almost entirely written with the help of macros. They are just everywhere. It makes the analysis much more complicated, not to mention the debugging process. By the way, their widespread usage did more harm than good, and caused a lot of trouble — the errors in the macros were found in lots of fragments throughout the code. So here is the proof of it.</p><pre><strong>static</strong> <strong>void</strong> <strong>spl_fixedarray_object_write_dimension</strong>(zval *object, <br>                                                  zval *offset, <br>                                                  zval *value) <br>{<br>  ....<br>  <strong>if</strong> (intern-&gt;fptr_offset_set) {<br>    zval tmp;<br>    <strong>if</strong> (!offset) {<br>      ZVAL_NULL(&amp;tmp);<br>      offset = &amp;tmp;<br>    } <strong>else</strong> {<br>      SEPARATE_ARG_IF_REF(offset);<br>  }<br>  ....<br>  spl_fixedarray_object_write_dimension_helper(intern, offset, value)<br>}</pre><p><strong>PVS-Studio warning:</strong> <a href="http://www.viva64.com/en/d/0095/">V506</a> Pointer to local variable ‘tmp’ is stored outside the scope of this variable. Such a pointer will become invalid. spl_fixedarray.c 420</p><p>In case the condition of the<em> if </em>operator is true, the <em>offset </em>pointer can be assigned with the address of the <em>tmp</em> variable. The lifespan of the <em>tmp </em>variable is limited by its scope, i.e. by the body of <em>if</em> operator. Further in the code we see a call of a function that takes <em>offset</em> pointer as one of the parameters, which references to the variable that was already destroyed; this can lead to an error during the work with this pointer.</p><p>Another strange code fragment:</p><pre>#<strong>define</strong> MIN(a, b)  (((a)&lt;(b))?(a):(b))<br>#define MAX(a, b)  (((a)&gt;(b))?(a):(b))<br>SPL_METHOD(SplFileObject, fwrite)<br>{<br>  ....<br>  <strong>size_t</strong> str_len;<br>  zend_long length = 0;<br>  ....<br>  str_len = MAX(0, MIN((<strong>size_t</strong>)length, str_len));<br>  ....<br>}</pre><p><strong>PVS-Studio warning:</strong> <a href="http://www.viva64.com/en/d/0137/">V547</a> Expression is always false. Unsigned type value is never &lt; 0. spl_directory.c 2886</p><p>The code logic is simple — firstly, two values are compared, then the smallest of them is compared with zero, and then the greatest of them is written to the <em>str_len</em> variable. The problem is that <em>size_t is </em>unsigned type, and its value is always nonnegative. As a result, using the second <em>MAX </em>macro makes no sense. Only the developer can say for sure, if it is just an extra operation or some serious bug.</p><p>It’s not the only strange comparison, there were many others.</p><pre><strong>static</strong> size_t <strong>sapi_cli_ub_write</strong>(<strong>const</strong> <strong>char</strong> *str, <strong>size_t</strong> str_length)<br>{<br>  ....<br>  <strong>size_t</strong> ub_wrote;<br>  ub_wrote = cli_shell_callbacks.cli_shell_ub_write(str, str_length);<br>  <strong>if</strong> (ub_wrote &gt; -1) {<br>    <strong>return</strong> ub_wrote;<br>  }<br>}</pre><p><strong>PVS-Studio warning:</strong> <a href="http://www.viva64.com/en/d/0220/">V605</a> Consider verifying the expression: ub_wrote &gt; — 1. An unsigned value is compared to the number -1. php_cli.c 307</p><p>The variable <em>ub_wrote</em> has <em>size_t</em> type, which is unsigned. However, further in the code we see a check <em>ub_wrote &gt; -1</em>. At first glance it might seem that this expression will always be true, because <em>ub_wrote</em> can store only nonnegative values. In reality, the situation is more interesting.</p><p>The type of literal -1 (<em>int</em>) will be converted to the variable type <em>ub_wrote (size_t), </em>so<em> </em>during the comparison of <em>ub_wrote </em>with the variable we’ll have the converted value. In the 32-bit program, it will be an unsigned value <em>0xFFFFFFFF</em>, while in the 64-bit — <em>0xFFFFFFFFFFFFFFFF</em>. Thus, the variable <em>ub_wrote </em>will be compared with the maximum value of <em>unsigned long </em>type. So the result of this comparison will always be <em>false</em>, and the <em>return </em>statement will never be executed.</p><p>We came across a similar code fragment once more. The issued message: <a href="http://www.viva64.com/en/d/0220/">V605</a> Consider verifying the expression: shell_wrote &gt; — 1. An unsigned value is compared to the number -1. php_cli.c 272</p><p>The next code fragment, that got a warning from the analyzer, is also related to a macro.</p><pre>PHPAPI <strong>void</strong> <strong>php_print_info</strong>(<strong>int</strong> flag)<br>{<br>  ....<br>  <strong>if</strong> (!sapi_module.phpinfo_as_text) {<br>    php_info_print(&quot;&lt;h1&gt;Configuration&lt;/h1&gt;\n&quot;);<br>  } <strong>else</strong> {<br>    SECTION(&quot;Configuration&quot;);<br>  }<br>  ....<br>}</pre><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/d/0169/">V571</a> Recurring check. The ‘if (!sapi_module.phpinfo_as_text)’ condition was already verified in line 975. info.c 978</p><p>At first sight it might seem that everything is fine and there is no error. But let’s take a look at what the <em>SECTION </em>macro is here.</p><pre>#<strong>define</strong> SECTION(name) <strong>if</strong> (!sapi_module.phpinfo_as_text) { \<br>                        php_info_print(&quot;&lt;h2&gt;&quot; name &quot;&lt;/h2&gt;\n&quot;); \<br>                      } <strong>else</strong> { \<br>                        php_info_print_table_start(); \<br>                        php_info_print_table_header(1, name); \<br>                        php_info_print_table_end(); \<br>                      } \</pre><p>Thus, after preprocessing in the *.i-file we’ll have the following code:</p><pre>PHPAPI <strong>void</strong> <strong>php_print_info</strong>(<strong>int</strong> flag)<br>{<br>  ....<br>  <strong>if</strong> (!sapi_module.phpinfo_as_text) {<br>    php_info_print(&quot;&lt;h1&gt;Configuration&lt;/h1&gt;\n&quot;);<br>  } <strong>else</strong> {<br>    <strong>if</strong> (!sapi_module.phpinfo_as_text) { <br>      php_info_print(&quot;&lt;h2&gt;Configuration&lt;/h2&gt;\n&quot;); <br>    } <strong>else</strong> { <br>      php_info_print_table_start(); <br>      php_info_print_table_header(1, &quot;Configuration&quot;); <br>      php_info_print_table_end(); <br>    } <br>  }<br>  ....<br>}</pre><p>Now it’s much easier to spot the problem. A condition <em>(!sapi_module.phpinfo_as_text) </em>gets checked, and if it is false, it is checked again (and of course, it will never be true). You would probably agree that it looks strange, to say the least.</p><p>A similar situation involving the use of this macro occurred once more in the same function:</p><pre>PHPAPI <strong>void</strong> <strong>php_print_info</strong>(<strong>int</strong> flag)<br>{<br>  ....<br>  <strong>if</strong> (!sapi_module.phpinfo_as_text) {<br>    SECTION(&quot;PHP License&quot;);<br>    ....<br>  }<br>  ....<br>}</pre><p><strong>PVS-Studio warning:</strong> <a href="http://www.viva64.com/en/d/0169/">V571</a> Recurring check. The ‘if (!sapi_module.phpinfo_as_text)’ condition was already verified in line 1058. info.c 1059</p><p>A similar situation — the same condition, the same macro. We expand the macro and get the following:</p><pre>PHPAPI <strong>void</strong> <strong>php_print_info</strong>(<strong>int</strong> flag)<br>{<br>  ....<br>  <strong>if</strong> (!sapi_module.phpinfo_as_text) {<br>    <strong>if</strong> (!sapi_module.phpinfo_as_text) { <br>      php_info_print(&quot;&lt;h2&gt;PHP License&lt;/h2&gt;\n&quot;); <br>    } <strong>else</strong> { <br>      php_info_print_table_start(); <br>      php_info_print_table_header(1, &quot;PHP License&quot;); <br>      php_info_print_table_end(); <br>    }<br>    ....<br>  }<br>  ....<br>}</pre><p>Again, the same condition is checked twice. The second condition will be checked in case the first one is true. Then, if the first condition <em>(!sapi_module.phpinfo_as_text)</em> is true, the second one will always be true too. In such a case, the code in the <em>else</em> branch of the second <em>if</em> operator will never be executed.</p><p>Let’s move on.</p><pre><strong>static</strong> <strong>int</strong> <strong>preg_get_backref</strong>(<strong>char</strong> **str, <strong>int</strong> *backref)<br>{<br>  ....<br>  <strong>register</strong> <strong>char</strong> *walk = *str;<br>  ....<br>  <strong>if</strong> (*walk == 0 || *walk != &#39;}&#39;)<br>  ....<br>}</pre><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/d/0194/">V590</a> Consider inspecting the ‘* walk == 0 || * walk != ‘}’’ expression. The expression is excessive or contains a misprint. php_pcre.c 1033</p><p>In this code the pointer is dereferenced, and its value is compared with some literals. This code is redundant. Let’s simplify and rewrite this expression to make it more demonstrative:</p><pre><strong>if</strong> (a == 0 || a != 125)</pre><p>As you can see, the condition can be simplified to a! = 125.</p><p>This may indicate both code redundancy, and a more serious error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/0*2dB1nFIgCYM0tmZG.png" /></figure><p>The cause of some issues was Zend Engine:</p><pre><strong>static</strong> zend_mm_heap *<strong>zend_mm_init</strong>(<strong>void</strong>)<br>{<br>  ....<br>  heap-&gt;limit = (Z_L(-1) &gt;&gt; Z_L(1));<br>  ....<br>}</pre><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/d/0225/">V610</a> Unspecified behavior. Check the shift operator ‘&gt;&gt;’. The left operand ‘(- 1)’ is negative. zend_alloc.c 1865</p><p>In this code we have an operation of right shift of a negative value. This is a case of unspecified behavior. Although in terms of the language such a case is not an erroneous one, as opposed to undefined behavior, it is best to avoid such cases, because the behavior of such code may vary depending on the platform and the compiler.</p><p>Another interesting bug was found in the PCRE library:</p><pre><strong>const</strong> pcre_uint32 <strong>PRIV</strong>(ucp_gbtable[]) = {<br>  ....<br>  (1&lt;&lt;ucp_gbExtend)|(1&lt;&lt;ucp_gbSpacingMark)|(1&lt;&lt;ucp_gbL)|   /*  6 L */<br>  (1&lt;&lt;ucp_gbL)|(1&lt;&lt;ucp_gbV)|(1&lt;&lt;ucp_gbLV)|(1&lt;&lt;ucp_gbLVT),<br>  ....<br>};</pre><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/d/0090/">V501</a> There are identical sub-expressions ‘(1 &lt;&lt; ucp_gbL)’ to the left and to the right of the ‘|’ operator. pcre_tables.c 161</p><p>Errors of this kind are classic. They <a href="http://www.viva64.com/en/examples/v501/">were</a>, and still are, in C++ projects, some <a href="http://www.viva64.com/en/examples/v3001/">C# projects</a> have them and perhaps other languages too. The programmer made a typo and duplicated a subexpression <em>(1&lt;&lt;ucp_gbL)</em>in the expression. Most likely (judging by the rest of the source code), a subexpression <em>(1&lt;&lt;ucp_gbT)</em> was meant to be here. Such errors aren’t really evident in a separately taken code fragment, and in a general mass they are even harder to detect.</p><p>By the way, my colleague wrote about this error in the previous article, but nothing has changed in the code.</p><p>Another fragment from the same library:</p><pre>....<br>firstchar = mcbuffer[0] | req_caseopt;<br>firstchar = mcbuffer[0];<br>firstcharflags = req_caseopt;<br>....</pre><p><strong>PVS-Studio warning:</strong> <a href="http://www.viva64.com/en/d/0108/">V519</a> The ‘firstchar’ variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 8163, 8164. pcre_compile.c 8164</p><p>Well, the code looks strange. The programmer writes the result of the ‘|’ operation to the <em>firstchar </em>variable, and then rewrites it, ignoring the result of the previous operation. Perhaps in the second case, another variable was meant instead of <em>firstchar</em>, but it’s hard to say for sure.</p><p>There were redundant conditions as well. For example:</p><pre>PHPAPI php_stream *_php_stream_fopen_with_path(.... <strong>const</strong> <strong>char</strong> *path, <br>                                               ....)<br>{<br>  ....<br>  <strong>if</strong> (!path || (path &amp;&amp; !*path)) {<br>  ....<br>}</pre><p><strong>PVS-Studio warning: </strong><a href="http://www.viva64.com/en/d/0375/"><strong>V728</strong></a><strong> </strong>An excessive check can be simplified. The ‘||’ operator is surrounded by opposite expressions ‘!path’ and ‘path’. plain_wrapper.c 1487</p><p>This expression is redundant: in the second subexpression we can remove the verification of <em>path</em> pointer against <em>nullptr</em>. Then, the simplified expression will be like this:</p><pre><strong>if</strong> (!path || !*path)) {</pre><p>Don’t underestimate such errors. Something else was probably supposed to be there instead of the<em> path</em>variable, and then such expression would be erroneous, not redundant. By the way, this is not the only fragment. There were several more:</p><ul><li>V728 An excessive check can be simplified. The ‘||’ operator is surrounded by opposite expressions ‘!path’ and ‘path’. fopen_wrappers.c 643</li><li>V728 An excessive check can be simplified. The ‘||’ operator is surrounded by opposite expressions ‘!headers_lc’ and ‘headers_lc’. sendmail.c 728</li></ul><h3>Third-party libraries</h3><p>I have already written about this in the beginning of the article, but I would like to stress it once more. PHP uses several third-party libraries, which, alas, are not perfect and contain errors. Quite a number of warnings were issued for the code from these libraries. We could have brought them all here, but then the article would be too long.</p><p>It’s not hard to detect if the error is in the source code of the PHP interpreter or a third party library — there is a comment in the beginning of all source files that describes the license, project, and the authors. Based on these comments, it is easy to track in a project file where the error was hiding.</p><p>On the other hand some of the fragments were still worth looking at. In any case, if you use any third-party libraries, you also take the responsibility towards the users for the errors in these projects, because the error can reveal itself during the use of your project. This is why you should carefully consider those dependencies which you pull into your project.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*jtomSA_N5cjeTBNc.png" /></figure><p>The results of the analysis came out quite interesting. In fact, there were many other bugs found, in this article we had a look at a small amount of medium and high severity warnings. A considerable amount of these errors were found in the PHP libraries, and thus, implicitly, they got into its code. In the PHP code itself, we found some entertaining bugs, which we presented in this article.</p><p>To sum up, we would emphasize that it is necessary to use different tools to improve the productivity and the quality of your code. You shouldn’t confine yourself to tests and code review. A static analyzer is one of those tools that might help the programmer write better code, allowing him to use his time more productively instead of looking for bugs. Also don’t forget that a static analyzer is a tool for regular use. If you haven’t tried anything like that yet — I recommend <a href="http://www.viva64.com/en/pvs-studio-download/">downloading</a> it to see what it can find.</p><p><strong>P.S. </strong><a href="http://www.zend.com/en/community/php">Zend Engine</a> developers contacted us and said that the problems, described in the article were already fixed. Good job!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ebe766f3aa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>