<?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 Love C&amp;C++ on Medium]]></title>
        <description><![CDATA[Stories by Love C&amp;C++ on Medium]]></description>
        <link>https://medium.com/@viva64articles?source=rss-67b72a9416b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*knFblRQBPBlEY5uu.jpeg</url>
            <title>Stories by Love C&amp;amp;C++ on Medium</title>
            <link>https://medium.com/@viva64articles?source=rss-67b72a9416b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:53:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@viva64articles/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[Logical Expressions in C/C++. Mistakes Made by Professionals]]></title>
            <link>https://medium.com/@viva64articles/logical-expressions-in-c-c-mistakes-made-by-professionals-66165fee63c5?source=rss-67b72a9416b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/66165fee63c5</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Love C&C++]]></dc:creator>
            <pubDate>Mon, 11 Apr 2016 06:47:44 GMT</pubDate>
            <atom:updated>2016-04-11T06:47:44.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*e2l30ND2zRRzfA95.png" /></figure><p>In programming, a logical expression is a language construct that is evaluated as true or false. Many books that teach programming “from scratch” discuss possible operations on logical expressions familiar to every beginner. In this article, I won’t be talking about the AND operator having higher precedence than OR. Instead, I will talk about common mistakes that programmers make in simple conditional expressions consisting of no more than three operators, and show how you can check your code using truth tables. Mistakes described here are the ones made by the developers of such well-known projects as FreeBSD, Microsoft ChakraCore, Mozilla Thunderbird, LibreOffice, and many others.</p><h4>Introduction</h4><p>I develop a static analyzer for C/C++/C# code, known as <a href="http://www.viva64.com/en/pvs-studio/">PVS-Studio</a>. My job involves dealing with both open-source and proprietary code of various projects, and, as the result of this activity, I write a lot of articles regarding the <a href="http://www.viva64.com/en/a/0084/">analysis of open-source projects</a>, where I talk about errors and defects found in these projects. With all that great amount of code that has been through our analyzer, we started to notice certain patterns of programming mistakes. For example, my colleague Andrey Karpov once wrote an article about <a href="http://www.viva64.com/en/b/0260/">the last-line effect</a> after he had gathered a large collection of examples of mistakes made in the last lines or blocks of similar looking code fragments.</p><p>In the beginning of this year, I used the analyzer to scan some projects by large IT companies, which, following the modern trend, make their projects’ sources publicly available under free licenses. I started to notice that almost every project has errors in conditional expressions that deal with incorrect use of conditional operators. Expressions themselves are quite simple and consist of just three operators:</p><ul><li>!= || !=</li><li>== || !=</li><li>== &amp;&amp; ==</li><li>== &amp;&amp; !=</li></ul><p>In total, you can write 6 conditional expressions using these operators, but 4 of them are incorrect: two are always true or false; in two others, the result of the whole expression does not depend on the result of one of its subexpressions.</p><p>To prove that a conditional expression is incorrect, I will construct a truth table for every example. I will also give an example from real code for each case. We will talk about the ternary operator ?: as well, whose precedence is almost the lowest, although, few programmers know about it.</p><p>Since incorrect conditional expressions are found mostly in code that checks return values of various functions, comparing them with error codes, I will be using variable err in synthetic examples below, while code1 and code2 will be used as constants, which are not equal. The value “other codes” will stand for any other constants that are not equal to code1 and code2.</p><h4>Incorrect use of the || operator</h4><h4>Expression != || !=</h4><p>The following is a synthetic example where the conditional expression will always evaluate to true:</p><pre>if ( err != code1 || err != code2)<br>{<br>  ....<br>}</pre><p>This is the truth table for this code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*v-QmPXOtryLOTipA.png" /></figure><p>And here is a real example of this error from LibreOffice project.</p><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression is always true. Probably the ‘&amp;&amp;’ operator should be used here. sbxmod.cxx 1777</p><pre>enum SbxDataType {<br>  SbxEMPTY    =  0,<br>  SbxNULL     =  1,<br>  ....<br>};</pre><pre>void SbModule::GetCodeCompleteDataFromParse(<br>  CodeCompleteDataCache&amp; aCache)<br>{<br>  ....<br>  if( (pSymDef-&gt;GetType() != SbxEMPTY) ||          // &lt;=<br>      (pSymDef-&gt;GetType() != SbxNULL) )            // &lt;=<br>    aCache.InsertGlobalVar( pSymDef-&gt;GetName(),<br>      pParser-&gt;aGblStrings.Find(pSymDef-&gt;GetTypeId()) );<br>  ....<br>}</pre><h4>Expression == || !=</h4><p>A synthetic example where the result of the whole expression does not depend on the result of its subexpression err == code1:</p><pre>if ( err == code1 || err != code2)<br>{<br>  ....<br>}</pre><p>Truth table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*lHE9OAAFYpEMrKeq.png" /></figure><p>A real example from FreeBSD project:</p><p><a href="http://www.viva64.com/en/d/0194/">V590</a> Consider inspecting the ‘error == 0 || error != — 1’ expression. The expression is excessive or contains a misprint. nd6.c 2119</p><pre>int<br>nd6_output_ifp(....)<br>{<br>  ....<br>  /* Use the SEND socket */<br>  error = send_sendso_input_hook(m, ifp, SND_OUT,<br>      ip6len);<br>  /* -1 == no app on SEND socket */<br>  if (error == 0 || error != -1)           // &lt;=<br>      return (error);<br>  ....<br>}</pre><p>It’s not much different from our synthetic example, is it?</p><h4>Incorrect use of the &amp;&amp; operator</h4><h4>Expression == &amp;&amp; ==</h4><p>A synthetic example, where the result of the conditional expression will always be false:</p><pre>if ( err == code1 &amp;&amp; err == code2)<br>{<br>  ....<br>}</pre><p>Truth table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*_jv-Nr4wve02DT9e.png" /></figure><p>A real example from SeriousEngine project.</p><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression is always false. Probably the ‘||’ operator should be used here. entity.cpp 3537</p><pre>enum RenderType {<br>  ....<br>  RT_BRUSH       = 4,<br>  RT_FIELDBRUSH  = 8,<br>  ....<br>};</pre><pre>void<br>CEntity::DumpSync_t(CTStream &amp;strm, INDEX iExtensiveSyncCheck)<br>{<br>  ....<br>  if( en_pciCollisionInfo == NULL) {<br>    strm.FPrintF_t(&quot;Collision info NULL\n&quot;);<br>  } else if (en_RenderType==RT_BRUSH &amp;&amp;       // &lt;=<br>             en_RenderType==RT_FIELDBRUSH) {  // &lt;=<br>    strm.FPrintF_t(&quot;Collision info: Brush entity\n&quot;);<br>  } else {<br>  ....<br>  }<br>  ....<br>}</pre><h4>Expression == &amp;&amp; !=</h4><p>A synthetic example where the result of the whole conditional expression does not depend on the result of its subexpression err != code2:</p><pre>if ( err == code1 &amp;&amp; err != code2)<br>{<br>  ....<br>}</pre><p>Truth table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*W9giTGgNrkHK9g25.png" /></figure><p>A real example from ChakraCore project, a JavaScript-engine for Microsoft Edge.</p><p><a href="http://www.viva64.com/en/d/0194/">V590</a> Consider inspecting the ‘sub[i] != ‘-’ &amp;&amp; sub[i] == ‘/’’ expression. The expression is excessive or contains a misprint. rl.cpp 1388</p><pre>const char *<br>stristr<br>(<br>  const char * str,<br>  const char * sub<br>)<br>{<br>  ....<br>  for (i = 0; i &lt; len; i++)<br>  {<br>    if (tolower(str[i]) != tolower(sub[i]))<br>    {<br>      if ((str[i] != &#39;/&#39; &amp;&amp; str[i] != &#39;-&#39;) ||<br>            (sub[i] != &#39;-&#39; &amp;&amp; sub[i] == &#39;/&#39;)) {              / &lt;=<br>           // if the mismatch is not between &#39;/&#39; and &#39;-&#39;<br>           break;<br>      }<br>    }<br>  }<br>  ....<br>}</pre><h4>Incorrect use of the ?: operator</h4><p><a href="http://www.viva64.com/en/d/0091/">V502</a> Perhaps the ‘?:’ operator works in a different way than it was expected. The ‘?:’ operator has a lower priority than the ‘|’ operator. ata-serverworks.c 166</p><pre>static int<br>ata_serverworks_chipinit(device_t dev)<br>{<br>  ....<br>  pci_write_config(dev, 0x5a,<br>           (pci_read_config(dev, 0x5a, 1) &amp; ~0x40) |<br>           (ctlr-&gt;chip-&gt;cfg1 == SWKS_100) ? 0x03 : 0x02, 1);<br>  }<br>  ....<br>}</pre><p>Before we finish with this article, I’d like to say a few words about the ternary operator ?:. Its precedence is almost the lowest of all operators. Only the assignment operator, the throw operator, and the comma operator have lower precedence. The error from the code sample above was found in the kernel of FreeBSD project. The authors used the ternary operator for selecting the required checkbox and for the sake of short, neat code. However, bitwise AND has higher precedence, so the conditional expression is evaluated in the wrong order. I decided to include this error in the article because it is very common for the projects I have scanned.</p><h4>Conclusion</h4><p>The patterns of errors in conditional expressions, described in this article, can be very dangerous if you are not careful enough writing the code. Despite the small number of operators, an incorrect conditional expression, as a whole, may be misinterpreted by the compiler. Such code may look quite sensible and pass code review. To secure yourself from these errors, use truth tables to check your expressions when in doubt, and also make sure you regularly scan your code with static analyzers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66165fee63c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serious Sam shooter anniversary — finding bugs in the code of the Serious Engine v.1.10]]></title>
            <link>https://medium.com/@viva64articles/serious-sam-shooter-anniversary-finding-bugs-in-the-code-of-the-serious-engine-v-1-10-ab141d6997cd?source=rss-67b72a9416b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab141d6997cd</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Love C&C++]]></dc:creator>
            <pubDate>Mon, 21 Mar 2016 13:39:27 GMT</pubDate>
            <atom:updated>2016-03-21T13:39:27.505Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*ryCcBVGU3-7nc6D6.png" /></figure><p>The first-person shooter ‘Serious Sam’ celebrated its release anniversary on March, 2016. In honor of this, the game developers form the Croatian company Croteam decided to open the source code for the game engine, Serious Engine 1 v.1.10. It provoked the interest of a large number of developers, who got an opportunity to have a look at the code and improve it. I have also decided to participate in the code improvement, and wrote an article reviewing the bugs that were found by PVS-Studio analyzer.</p><h4>Introduction</h4><p>Serious Engine is a game engine developed by a Croatian company <a href="http://www.croteam.com/">Croteam</a>. V 1.1o, and was used in the games ‘Serious Sam Classic: The First Encounter’, and ‘Serious Sam Classic: The Second Encounter’. Later on, the Croteam Company released more advanced game engines — Serious Engine 2, Serious Engine 3, and Serious Engine 4; the source code of Serious Engine version 1.10 was officially made <a href="https://github.com/Croteam-official/Serious-Engine">open</a> and available under the license <a href="https://en.wikipedia.org/wiki/GNU_General_Public_License">GNU General Public License v.2</a></p><p>The project is easily built in Visual Studio 2013, and checked by <a href="http://www.viva64.com/en/pvs-studio/">PVS-Studio</a> 6.02 static analyzer.</p><h4>Typos!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*Cxd26G3zKDtPq3Ow.png" /></figure><p><a href="http://www.viva64.com/en/d/0090/">V501</a> There are identical sub-expressions to the left and to the right of the ‘==’ operator: tp_iAnisotropy == tp_iAnisotropy gfx_wrapper.h 180</p><pre>class CTexParams {<br>public:</pre><pre>  inline BOOL IsEqual( CTexParams tp) {<br>    return tp_iFilter     == tp.tp_iFilter &amp;&amp;<br>           tp_iAnisotropy == tp_iAnisotropy &amp;&amp; // &lt;=<br>           tp_eWrapU      == tp.tp_eWrapU &amp;&amp;<br>           tp_eWrapV      == tp.tp_eWrapV; };<br>  ....<br>};</pre><p>I have changed the formatting of this code fragment to make it more visual. The defect, found by the analyzer became more evident — the variable is compared with itself. The object with the name ‘tp’ has a field ‘tp_iAnisotropy’, so, by the analogy with the neighboring part of the code, a part of the condition should be ‘tp_iAnisotropy’.</p><p><a href="http://www.viva64.com/en/d/0090/">V501</a> There are identical sub-expressions ‘GetShadingMapWidth() &lt; 32’ to the left and to the right of the ‘||’ operator. terrain.cpp 561</p><pre>void CTerrain::SetShadowMapsSize(....)<br>{<br>  ....<br>  if(GetShadowMapWidth()&lt;32 || GetShadingMapHeight()&lt;32) {<br>    ....<br>  }</pre><pre>  if(GetShadingMapWidth()&lt;32 || GetShadingMapWidth()&lt;32) { // &lt;=<br>    tr_iShadingMapSizeAspect = 0;<br>  }<br>  ....<br>  PIX pixShadingMapWidth  = GetShadingMapWidth();<br>  PIX pixShadingMapHeight = GetShadingMapHeight();<br>  ....<br>}</pre><p>The analyzer found a suspicious code fragment which checks the width and height of a map, of the width, to be more exact, because we can see two similar checks “GetShadingMapWidth()&lt;З2” in the code. Most probably, the conditions should be:</p><pre>if(GetShadingMapWidth()&lt;32 || GetShadingMapHeight()&lt;32) {<br>  tr_iShadingMapSizeAspect = 0;<br>}</pre><p><a href="http://www.viva64.com/en/d/0090/">V501</a> There are identical sub-expressions ‘(vfp_ptPrimitiveType == vfpToCompare.vfp_ptPrimitiveType)’ to the left and to the right of the ‘&amp;&amp;’ operator. worldeditor.h 580</p><pre>inline BOOL CValuesForPrimitive::operator==(....)<br>{<br>  return (<br> (....) &amp;&amp;<br> (vfp_ptPrimitiveType == vfpToCompare.vfp_ptPrimitiveType) &amp;&amp;//&lt;=<br> (vfp_plPrimitive == vfpToCompare.vfp_plPrimitive) &amp;&amp;<br> ....<br> (vfp_bDummy == vfpToCompare.vfp_bDummy) &amp;&amp;<br> (vfp_ptPrimitiveType == vfpToCompare.vfp_ptPrimitiveType) &amp;&amp;//&lt;=<br> ....<br> (vfp_fXMin == vfpToCompare.vfp_fXMin) &amp;&amp;<br> (vfp_fXMax == vfpToCompare.vfp_fXMax) &amp;&amp;<br> (vfp_fYMin == vfpToCompare.vfp_fYMin) &amp;&amp;<br> (vfp_fYMax == vfpToCompare.vfp_fYMax) &amp;&amp;<br> (vfp_fZMin == vfpToCompare.vfp_fZMin) &amp;&amp;<br> (vfp_fZMax == vfpToCompare.vfp_fZMax) &amp;&amp;<br> ....<br>);</pre><p>The condition in the overloaded comparison operator takes 35 lines. No wonder the author was copying the strings to write faster, but it’s very easy to make an error coding in such a way. Perhaps there is an extra check here, or the copied string was not renamed, and the comparison operator doesn’t always return a correct result.</p><h4>Strange comparisons</h4><p><a href="http://www.viva64.com/en/d/0152/">V559</a> Suspicious assignment inside the condition expression of ‘if’ operator: pwndView = 0. mainfrm.cpp 697</p><pre>void CMainFrame::OnCancelMode()<br>{<br>  // switches out of eventual direct screen mode<br>  CWorldEditorView *pwndView = (....)GetActiveView();<br>  if (pwndView = NULL) {                             // &lt;=<br>    // get the MDIChildFrame of active window<br>    CChildFrame *pfrChild = (....)pwndView-&gt;GetParentFrame();<br>    ASSERT(pfrChild!=NULL);<br>  }<br>  CMDIFrameWnd::OnCancelMode();<br>}</pre><p>There is quite a number of strange comparisons in the code of the engine. For example, in this code fragment we get a pointer “pwndView”, which is then assigned with NULL, making the condition always false.</p><p>Most likely the programmer meant to write the inequality operator ‘!=’ and the code should have been like this:</p><pre>if (pwndView != NULL) {<br>  // get the MDIChildFrame of active window<br>  CChildFrame *pfrChild = (....)pwndView-&gt;GetParentFrame();<br>  ASSERT(pfrChild!=NULL);<br>}</pre><p>Two more similar code fragments:</p><ul><li>V559 Suspicious assignment inside the condition expression of ‘if’ operator: pwndView = 0. mainfrm.cpp 710</li></ul><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression is always false. Probably the ‘||’ operator should be used here. entity.cpp 3537</p><pre>enum RenderType {<br>  ....<br>  RT_BRUSH       = 4,<br>  RT_FIELDBRUSH  = 8,<br>  ....<br>};</pre><pre>void<br>CEntity::DumpSync_t(CTStream &amp;strm, INDEX iExtensiveSyncCheck)<br>{<br>  ....<br>  if( en_pciCollisionInfo == NULL) {<br>    strm.FPrintF_t(&quot;Collision info NULL\n&quot;);<br>  } else if (en_RenderType==RT_BRUSH &amp;&amp;       // &lt;=<br>             en_RenderType==RT_FIELDBRUSH) {  // &lt;=<br>    strm.FPrintF_t(&quot;Collision info: Brush entity\n&quot;);<br>  } else {<br>  ....<br>  }<br>  ....<br>}</pre><p>One variable with the name “en_RenderType” is compared with two different constants. The error is in the usage of ‘&amp;&amp;’ logical and operator. A variable can never be equal to two constants at the same time, that’s why the condition is always false. The ‘||’ operator should be used in this fragment.</p><p><a href="http://www.viva64.com/en/d/0152/">V559</a> Suspicious assignment inside the condition expression of ‘if’ operator: _strModURLSelected = “”. menu.cpp 1188</p><pre>CTString _strModURLSelected;</pre><pre>void JoinNetworkGame(void)<br>{<br>  ....<br>  char strModURL[256] = {0};<br>  _pNetwork-&gt;ga_strRequiredMod.ScanF(...., &amp;strModURL);<br>  _fnmModSelected = CTString(strModName);<br>  _strModURLSelected = strModURL; // &lt;=<br>  if (_strModURLSelected=&quot;&quot;) {    // &lt;=<br>    _strModURLSelected = &quot;http://www.croteam.com/mods/Old&quot;;<br>  }<br>  ....<br>}</pre><p>An interesting bug. A request is performed in this function, and the result with the name “strModURL” is written in the buffer (url to “mod”). Later this result is saved in the object under the name “_strModURLSelected”. This is its own class implementation that works with strings. Because of a typo, in the condition “if (_strModURLSelected=””)” the url that was received earlier will be replaced with an empty string, instead of comparison. Then the operator, casting the string to the ‘const char*’ type takes action. As a result we’ll have verification against null of the pointer which contains a link to the empty string. Such a pointer can never be equal to zero. Therefore, the condition will always be true. So, the program will always use the link that is hard coded, although it was meant to be used as a default value.</p><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression is always true. Probably the ‘&amp;&amp;’ operator should be used here. propertycombobar.cpp 1853</p><pre>CEntity *CPropertyComboBar::GetSelectedEntityPtr(void) <br>{<br> // obtain selected property ID ptr<br> CPropertyID *ppidProperty = GetSelectedProperty();<br> // if there is valid property selected<br> if( (ppidProperty == NULL) || <br> (ppidProperty-&gt;pid_eptType != CEntityProperty::EPT_ENTITYPTR) ||<br> (ppidProperty-&gt;pid_eptType != CEntityProperty::EPT_PARENT) )<br> {<br>   return NULL;<br> }<br> ....<br>}</pre><p>The analyzer detected a bug that is totally different from the previous one. Two checks of the “pid_eptType” variable are always true because of the ‘||’ operator. Thus, the function always returns, regardless of the value of the “ppidProperty” pointer value and “ppidProperty-&gt;pid_eptType” variable.</p><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression ‘ulUsedShadowMemory &gt;= 0’ is always true. Unsigned type value is always &gt;= 0. gfxlibrary.cpp 1693</p><pre>void CGfxLibrary::ReduceShadows(void)<br>{<br>  ULONG ulUsedShadowMemory = ....;<br>  ....<br>  ulUsedShadowMemory -= sm.Uncache();  // &lt;=<br>  ASSERT( ulUsedShadowMemory&gt;=0);      // &lt;=<br>  ....<br>}</pre><p>An unsafe decrement of an unsigned variable is executed in this code fragment, as the variable “ulUsedShadowMemory” may overflow, at the same time there is Assert() that never issues a warning. It is a very suspicious code fragment, the developers should recheck it.</p><p><a href="http://www.viva64.com/en/d/0343/">V704</a> ‘this != 0’ expression should be avoided — this expression is always true on newer compilers, because ‘this’ pointer can never be NULL. entity.h 697</p><pre>inline void CEntity::AddReference(void) { <br>  if (this!=NULL) { // &lt;=<br>    ASSERT(en_ctReferences&gt;=0);<br>    en_ctReferences++; <br>  }<br>};</pre><p>There are 28 comparisons of ‘this’ with null in the code of the engine. The code was written a long time ago, but according to the latest standard of C++ language, ‘this’ pointer can never be null, and therefore the compiler can do the optimization and delete the check. This can lead to unexpected errors in the case of more complicated conditions. Examples can be found in the <a href="http://www.viva64.com/en/d/0343/">documentation</a> for this diagnostic.</p><p>At this point Visual C++ doesn’t work like that, but it’s just a matter of time. This code is outlawed from now on.</p><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression ‘achrLine != “”’ is always true. To compare strings you should use strcmp() function. worldeditor.cpp 2254</p><pre>void CWorldEditorApp::OnConvertWorlds()<br>{<br>  ....<br>  char achrLine[256];                // &lt;=<br>  CTFileStream fsFileList;</pre><pre>  // count lines in list file<br>  try {<br>    fsFileList.Open_t( fnFileList);<br>    while( !fsFileList.AtEOF()) {<br>      fsFileList.GetLine_t( achrLine, 256);<br>      // increase counter only for lines that are not blank<br>      if( achrLine != &quot;&quot;) ctLines++; // &lt;=<br>    }<br>    fsFileList.Close();<br>  }<br>  ....<br>}</pre><p>The analyzer detected wrong comparison of a string with an empty string. The error is that the (achrLine != “”) check is always true, and the increment of the “ctLines” is always executed, although the comments say that it should execute only for non-empty strings.</p><p>This behavior is caused by the fact that two pointers are compared in this condition: “achrLine” and a pointer to the temporary empty string. These pointers will never be equal.</p><p>Correct code, using the strcmp() function:</p><pre>if(strcmp(achrLine, &quot;&quot;) != 0) ctLines++;</pre><p>Two more wrong comparisons:</p><ul><li>V547 Expression is always true. To compare strings you should use strcmp() function. propertycombobar.cpp 965</li><li>V547 Expression ‘achrLine == “”’ is always false. To compare strings you should use strcmp() function. worldeditor.cpp 2293</li></ul><h4>Miscellaneous errors</h4><p><a href="http://www.viva64.com/en/d/0130/">V541</a> It is dangerous to print the string ‘achrDefaultScript’ into itself. dlgcreateanimatedtexture.cpp 359</p><pre>BOOL CDlgCreateAnimatedTexture::OnInitDialog() <br>{<br>  ....<br>  // allocate 16k for script<br>  char achrDefaultScript[ 16384];<br>  // default script into edit control<br>  sprintf( achrDefaultScript, ....); // &lt;=<br>  ....<br>  // add finishing part of script<br>  sprintf( achrDefaultScript,        // &lt;=<br>           &quot;%sANIM_END\r\nEND\r\n&quot;,  // &lt;=<br>           achrDefaultScript);       // &lt;=<br>  ....<br>}</pre><p>A string is formed in the buffer, then the programmer wants to get a new string, saving the previous string value and add two more words. It seems really simple.</p><p>To explain why an unexpected result can manifest here, I will quote a simple and clear example from the documentation for this diagnostic:</p><pre>char s[100] = &quot;test&quot;;<br>sprintf(s, &quot;N = %d, S = %s&quot;, 123, s);</pre><p>As a result we would want to have a string:</p><pre>N = 123, S = test</pre><p>But in practice, we will have the following string in the buffer:</p><pre>N = 123, S = N = 123, S =</pre><p>In similar situations, the same code can lead not only to incorrect text, but also to program abortion. The code can be fixed if you use a new buffer to store the result. A safe option:</p><pre>char s1[100] = &quot;test&quot;;<br>char s2[100];<br>sprintf(s2, &quot;N = %d, S = %s&quot;, 123, s1);</pre><p>The same should be done in the Serious Engine code. Due to pure luck, the code may work correctly, but it would be much safer to use an additional buffer to form the string.</p><p><a href="http://www.viva64.com/en/d/0181/">V579</a> The qsort function receives the pointer and its size as arguments. It is possibly a mistake. Inspect the third argument. mesh.cpp 224</p><pre>// optimize lod of mesh<br>void CMesh::OptimizeLod(MeshLOD &amp;mLod)<br>{<br>  ....<br>  // sort array<br>  qsort(&amp;_aiSortedIndex[0]           // &lt;=<br>        ctVertices<br>        sizeof(&amp;_aiSortedIndex[0]),  // &lt;=<br>        qsort_CompareArray);<br>  ....<br>}</pre><p>The function qsort() takes the size of the element of array to be sorted as the third argument. It is very suspicious that the pointer size is always passed there. Perhaps the programmer copied the first argument of the function to the third one, and forgot to delete the ampersand.</p><p><a href="http://www.viva64.com/en/d/0222/">V607</a> Ownerless expression ‘pdecDLLClass-&gt;dec_ctProperties’. entityproperties.cpp 107</p><pre>void CEntity::ReadProperties_t(CTStream &amp;istrm) // throw char *<br>{<br>  ....<br>  CDLLEntityClass *pdecDLLClass = en_pecClass-&gt;ec_pdecDLLClass;<br>  ....<br>  // for all saved properties<br>  for(INDEX iProperty=0; iProperty&lt;ctProperties; iProperty++) {<br>    pdecDLLClass-&gt;dec_ctProperties;  // &lt;=<br>    ....<br>  }<br>  ....<br>}</pre><p>It’s unclear, what the highlighted string does. Well, it’s clear that it does nothing. The class field is not used in any way, perhaps this error got here after refactoring or the string was left unchanged after debugging.</p><p><a href="http://www.viva64.com/en/d/0225/">V610</a> Undefined behavior. Check the shift operator ‘&lt;&lt;’. The left operand ‘(- 2)’ is negative. layermaker.cpp 363</p><pre>void CLayerMaker::SpreadShadowMaskOutwards(void)<br>{<br>  #define ADDNEIGHBOUR(du, dv)                                  \<br>  if ((pixLayerU+(du)&gt;=0)                                       \<br>    &amp;&amp;(pixLayerU+(du)&lt;pixLayerSizeU)                            \<br>    &amp;&amp;(pixLayerV+(dv)&gt;=0)                                       \<br>    &amp;&amp;(pixLayerV+(dv)&lt;pixLayerSizeV)                            \<br>    &amp;&amp;(pubPolygonMask[slOffsetMap+(du)+((dv)&lt;&lt;pixSizeULog2)])) {\<br>    ....                                                        \<br>    }</pre><pre>  ADDNEIGHBOUR(-2, -2); // &lt;=<br>  ADDNEIGHBOUR(-1, -2); // &lt;=<br>  ....                  // &lt;=<br>}</pre><p>The macro “ADDNEIGHBOUR” is declared in the body of the function, and is used 28 times in a row. Negative numbers are passed to this macro, where they are shifted. According to the latest standards of the C++ language, the shift of a negative number results in undefined behavior.</p><p><a href="http://www.viva64.com/en/d/0265/">V646</a> Consider inspecting the application’s logic. It’s possible that ‘else’ keyword is missing. sessionstate.cpp 1191</p><pre>void CSessionState::ProcessGameStream(void)<br>{<br>  ....<br>  if (res==CNetworkStream::R_OK) {<br>    ....<br>  } if (res==CNetworkStream::R_BLOCKNOTRECEIVEDYET) { // &lt;=<br>    ....<br>  } else if (res==CNetworkStream::R_BLOCKMISSING) {<br>    ....<br>  }<br>  ....<br>}</pre><p>Looking at the code formatting, we may assume that the keyword ‘else’ is missing in the cascade of conditions.</p><p>One more similar fragment:</p><ul><li>V646 Consider inspecting the application’s logic. It’s possible that ‘else’ keyword is missing. terrain.cpp 759</li></ul><p>V595 The ‘pAD’ pointer was utilized before it was verified against nullptr. Check lines: 791, 796. anim.cpp 791</p><pre>void CAnimObject::SetData(CAnimData *pAD) {<br>  // mark new data as referenced once more<br>  pAD-&gt;AddReference();                      // &lt;=<br>  // mark old data as referenced once less<br>  ao_AnimData-&gt;RemReference();<br>  // remember new data<br>  ao_AnimData = pAD;<br>  if( pAD != NULL) StartAnim( 0);           // &lt;=<br>  // mark that something has changed<br>  MarkChanged();<br>}</pre><p>In the end I would like to give an example of an error with potential dereference of a null pointer. If you read the analyzer warning, you will see how dangerous the pointer “pAD” is in this small function. Almost immediately after the call of “pAD-&gt;AddReference()”, the check “pAD != NULL”is executed, which denotes a possible passing of a pointer to this function.</p><p>Here is a full list of dangerous fragments that contain pointers:</p><ul><li>V595 The ‘_ppenPlayer’ pointer was utilized before it was verified against nullptr. Check lines: 851, 854. computer.cpp 851</li><li>V595 The ‘_meshEditOperations’ pointer was utilized before it was verified against nullptr. Check lines: 416, 418. modelermeshexporter.cpp 416</li><li>V595 The ‘_fpOutput’ pointer was utilized before it was verified against nullptr. Check lines: 654, 664. modelermeshexporter.cpp 654</li><li>V595 The ‘_appPolPnts’ pointer was utilized before it was verified against nullptr. Check lines: 647, 676. modelermeshexporter.cpp 647</li><li>V595 The ‘pModelerView’ pointer was utilized before it was verified against nullptr. Check lines: 60, 63. dlginfopgglobal.cpp 60</li><li>V595 The ‘pNewWT’ pointer was utilized before it was verified against nullptr. Check lines: 736, 744. modeler.cpp 736</li><li>V595 The ‘pvpViewPort’ pointer was utilized before it was verified against nullptr. Check lines: 1327, 1353. serioussam.cpp 1327</li><li>V595 The ‘pDC’ pointer was utilized before it was verified against nullptr. Check lines: 138, 139. tooltipwnd.cpp 138</li><li>V595 The ‘m_pDrawPort’ pointer was utilized before it was verified against nullptr. Check lines: 94, 97. wndanimationframes.cpp 94</li><li>V595 The ‘penBrush’ pointer was utilized before it was verified against nullptr. Check lines: 9033, 9035. worldeditorview.cpp 9033</li></ul><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*qF-r0CwdhAbdNAck.png" /></figure><p>The analysis of Serious Engine 1 v.1.10 showed that bugs can live in the program for a very long time, and even celebrate anniversaries! This article contains only some of the most interesting examples from the analyzer report. Several warnings were given as a list. But the whole report has quite a good number of warnings, taking into account that the project is not very large. The Croteam Company have more advanced game engines — Serious Engine 2, Serious Engine 3 and Serious Engine 4. I hate to think, how much of the unsafe code could get into the new versions of the engine. I hope that the developers will use a static code analyzer, and make the users happy, producing high-quality games. Especially knowing that the analyzer is <a href="http://www.viva64.com/en/pvs-studio-download/">easy to download</a>, <a href="http://www.viva64.com/en/d/0011/">easy to run</a> in Visual Studio, and for other systems there is a <a href="http://www.viva64.com/en/d/0360/">Standalone</a> utility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab141d6997cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A fresh eye on Oracle VM VirtualBox]]></title>
            <link>https://medium.com/@viva64articles/a-fresh-eye-on-oracle-vm-virtualbox-86fb608a19c?source=rss-67b72a9416b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/86fb608a19c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[virtualbox]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Love C&C++]]></dc:creator>
            <pubDate>Thu, 10 Mar 2016 11:16:45 GMT</pubDate>
            <atom:updated>2016-03-10T11:16:45.596Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*r3cZXgGhbjSdnrJ2.png" /></figure><p>Virtual machines are important tools in the arsenal of a software developer. Being an active user of VirtualBox, and checking various open source projects with the help of it, I was personally interested in checking its source code. We did the first check of this project in 2014, and the description of 50 errors barely fit into two articles. With the release of Windows 10 and VirtualBox 5.0.XX the stability of the program got significantly worse, in my humble opinion. So, I decided to check the project again.</p><h4>Introduction</h4><p><a href="https://www.virtualbox.org/">VirtualBox </a>(Oracle VM VirtualBox) is a general-purpose, full virtualizer for x86 hardware, targeted at server, desktop, and embedded use. It is supported by the following operating systems: Microsoft Windows, FreeBSD, Solaris/OpenSolaris, Linux, Mac OS X, DOS, ReactOS, and others.</p><p>You may find the previous articles about VirtualBox here:</p><ul><li><a href="http://www.viva64.com/en/b/0281/">Checking Oracle VM VirtualBox. Part 1.</a></li><li><a href="http://www.viva64.com/en/b/0282/">Checking Oracle VM VirtualBox. Part 2.</a></li></ul><p>These articles contain more than 50 dangerous fragments which were found using PVS-Studio 5.18. I haven’t seen such warnings in the new analyzer report. It means that the developers had a look at the articles, and fixed all the places errors were spotted by the analyzer. Those who are willing may find these places in the latest version of the source code, and can have a look at the way the fixes of PVS-Studio warnings appear in a real project. But in another check, I’ve encountered a lot of other interesting messages.</p><p>I also would like to emphasize that only regular use of static analysis (not necessarily PVS-Studio) can maintain the high quality of the code. Our all <a href="http://www.viva64.com/en/b/0330/">experience of fixing analyzer warnings in the Unreal Engine code</a>, showed that the quantity of errors constantly increases in a developing project, so after one-time checks the quality of the code will gradually get to the initial state, and new bugs will still be getting into the code. In the VirtualBox project we see a similar situation. The growth of the analyzer warnings after a one-time check looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*2FBSvYyTd3fPkRmL.png" /></figure><p>It is important to emphasize that by “regular” use of the analyzer, we mean daily checks. Many errors that are detected during the testing stage can be eliminated at the stage of writing the code.</p><p>Another advantage of the regular use of static analyzers, is the regular updates. Since the first time we checked VirtualBox, we have added more than 50 new diagnostic rules. The last section will be devoted specifically to the errors that were found using the new diagnostics.</p><p>Oracle VM VirtualBox source code was tested with the help of <a href="http://www.viva64.com/en/pvs-studio/">PVS-Studio</a> version 6.02.</p><p>Perhaps someone will need the number of the verified revision.</p><pre>Checked out external at revision 2796.<br>Checked out revision 59777.</pre><h4>Stubborn errors</h4><p>Before writing this article, I had a look at the bugs that were previously found by the analyzer, and found similar errors in the new code. I suppose the same person could be writing this code.</p><p><a href="http://www.viva64.com/en/d/0110/">V521</a> Such expressions using the ‘,’ operator are dangerous. Make sure the expression is correct. vboxmpwddm.cpp 1083</p><pre>NTSTATUS DxgkDdiStartDevice(...)<br>{<br>  ....<br>  if ( ARGUMENT_PRESENT(MiniportDeviceContext) &amp;&amp;<br>        ARGUMENT_PRESENT(DxgkInterface) &amp;&amp;<br>        ARGUMENT_PRESENT(DxgkStartInfo) &amp;&amp;<br>        ARGUMENT_PRESENT(NumberOfVideoPresentSources), // &lt;=<br>        ARGUMENT_PRESENT(NumberOfChildren)<br>        )<br>  {<br>    ....<br>  }<br>  ....<br>}</pre><p>Similar code was described in the first article. The comma operator ‘,’ evaluates the left and the right operand. The thing is, the left operand is no longer used, and the result of the operator is the value of the right operand. It is most likely that the programmer wanted to use ‘&amp;&amp;’ operator, as in other strings.</p><p><a href="http://www.viva64.com/en/d/0108/">V519</a> The ‘pThis-&gt;aCSR[103]’ variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 1230, 1231. devpcnet.cpp 1231</p><pre>static void pcnetSoftReset(PPCNETSTATE pThis)<br>{<br>  ....<br>  pThis-&gt;aCSR[94]  = 0x0000;<br>  pThis-&gt;aCSR[100] = 0x0200;<br>  pThis-&gt;aCSR[103] = 0x0105; // &lt;=<br>  pThis-&gt;aCSR[103] = 0x0105; // &lt;=<br>  ....<br>}</pre><p>The code has duplicate strings. The developers fixed a similar fragment mentioned in the first article by deleting an extra string. What we have here — an error in the array index or an extra string — we’ll see in the next versions of VirtualBox.</p><p><a href="http://www.viva64.com/en/d/0090/">V501</a> There are identical sub-expressions ‘mstrFormat.equalsIgnoreCase(“text/plain”)’ to the left and to the right of the ‘||’ operator. vboxdnddataobject.cpp 38</p><pre>STDMETHODIMP VBoxDnDDataObject::GetData(....)<br>{<br>  ....<br>  else if(<br>         mstrFormat.equalsIgnoreCase(&quot;text/plain&quot;)  // &lt;=<br>      || mstrFormat.equalsIgnoreCase(&quot;text/html&quot;)<br>      || mstrFormat.equalsIgnoreCase(&quot;text/plain;charset=utf-8&quot;)<br>      || mstrFormat.equalsIgnoreCase(&quot;text/plain;charset=utf-16&quot;)<br>      || mstrFormat.equalsIgnoreCase(&quot;text/plain&quot;)  // &lt;=<br>      || mstrFormat.equalsIgnoreCase(&quot;text/richtext&quot;)<br>      || mstrFormat.equalsIgnoreCase(&quot;UTF8_STRING&quot;)<br>      || mstrFormat.equalsIgnoreCase(&quot;TEXT&quot;)<br>      || mstrFormat.equalsIgnoreCase(&quot;STRING&quot;))<br>  {<br>  ....<br>}</pre><p>Copy-paste programming will live forever. There are already two identical “text/plain” checks, but on top of that, the whole code clock was copied to another file:</p><ul><li>V501 There are identical sub-expressions ‘!RTStrICmp(pszFormat, “text/plain”)’ to the left and to the right of the ‘||’ operator. vboxdnd.cpp 834</li></ul><h4>define true false; //happy debugging!</h4><p>No joking — such code in different variations can be found in real projects.</p><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression is always false. Unsigned type value is never &lt; 0. dt_subr.c 715</p><pre>int<br>dt_printf(dtrace_hdl_t *dtp, FILE *fp, const char *format, ...)<br>{<br>  ....<br>  if (vsnprintf(&amp;dtp-&gt;dt_buffered_buf[dtp-&gt;dt_buffered_offs], //&lt;=<br>        avail, format, ap) &lt; 0) {<br>      rval = dt_set_errno(dtp, errno);<br>      va_end(ap);<br>      return (rval);<br>    }<br>  ....<br>}</pre><p>At first glance, there is nothing to pick on here, except the analyzer. In the documentation to the “vsnprintf” function it is quite clearly stated that in case of an error, it returns a negative number. I have even given this code fragment to one of the developers of the kernel of the C++ analyzer as an example of a false positive. But it turned out that the analyzer was right.</p><p>Who could think that among thousands of header files there would be, somewhere, a string like this:</p><pre>#define vsnprintf RTStrPrintfV</pre><p>In the <a href="http://www.viva64.com/en/t/0076/">preprocessed file</a> the source fragment will be deployed as follows:</p><pre>if (RTStrPrintfV(&amp;dtp-&gt;dt_buffered_buf[dtp-&gt;dt_buffered_offs],<br>    avail, format, ap) &lt; 0) {<br>  rval = dt_set_errno(dtp, (*_errno()));<br> ( ap = (va_list)0 );<br> return (rval);<br>}</pre><p>The function RTStrPrintfV() returns the value of an unsigned type ‘size_t’, not the signed ‘int’ type, so this check will lead to a logical error, as in fact no checking is done.</p><p>Function prototypes for comparison:</p><pre>size_t  RTStrPrintfV(char *, size_t, const char *, va_list args);<br>int     vsnprintf   (char *, size_t, const char *, va_list arg );</pre><h4>Suspicious “From-To” code</h4><p><a href="http://www.viva64.com/en/d/0168/">V570</a> The ‘from-&gt;eval1D[i].u1’ variable is assigned to itself. state_evaluators.c 1006</p><pre>void<br>crStateEvaluatorDiff(CREvaluatorBits *e, CRbitvalue *bitID,<br>                     CRContext *fromCtx, CRContext *toCtx)<br>{<br>  ....<br>  from-&gt;eval1D[i].order = to-&gt;eval1D[i].order;<br>  from-&gt;eval1D[i].u1 = from-&gt;eval1D[i].u1;     // &lt;=<br>  from-&gt;eval1D[i].u2 = from-&gt;eval1D[i].u2;     // &lt;=<br>  ...<br>}</pre><p>The analyzer detected suspicious assignments of variables to themselves. Most likely on the right side of the assignment operator, the programmer should write an object with the name ‘to’ rather than ‘from’.</p><p>Five more fragments in this file:</p><ul><li>V570 The ‘from-&gt;eval1D[i].u2’ variable is assigned to itself. state_evaluators.c 1007</li><li>V570 The ‘from-&gt;eval2D[i].u1’ variable is assigned to itself. state_evaluators.c 1042</li><li>V570 The ‘from-&gt;eval2D[i].u2’ variable is assigned to itself. state_evaluators.c 1043</li><li>V570 The ‘from-&gt;eval2D[i].v1’ variable is assigned to itself. state_evaluators.c 1044</li><li>V570 The ‘from-&gt;eval2D[i].v2’ variable is assigned to itself. state_evaluators.c 1045</li></ul><p><a href="http://www.viva64.com/en/d/0242/">V625</a> Consider inspecting the ‘for’ operator. Initial and final values of the iterator are the same. state_transform.c 1365</p><pre>void<br>crStateTransformDiff(...., CRContext *fromCtx, CRContext *toCtx )<br>{<br>  ....<br>  for (i = to-&gt;colorStack.depth; i &lt;= to-&gt;colorStack.depth; i++)<br>  {<br>    LOADMATRIX(to-&gt;colorStack.stack + i);<br>    from-&gt;colorStack.stack[i] = to-&gt;colorStack.stack[i];</pre><pre>    /* Don&#39;t want to push on the current matrix */<br>    if (i != to-&gt;colorStack.depth)<br>        diff_api.PushMatrix();<br>  }<br>  ....<br>}</pre><p>I’ve decided to give a description of such errors a separate section because of one more suspicious fragment containing the ‘to’ and ‘from’ names.</p><p>The initial and the final value of the loop counter are the same in this code fragment. As a result there is just one iteration in the loop. Again, it is most likely a typo in the name of the ‘to’ object.</p><h4>About the priorities of operations</h4><p><a href="http://www.viva64.com/en/d/0159/">V564</a> The ‘&amp;’ operator is applied to bool type value. You’ve probably forgotten to include parentheses or intended to use the ‘&amp;&amp;’ operator. glsl_shader.c 4102</p><pre>static void generate_texcoord_assignment(....)<br>{<br>  DWORD map;<br>  unsigned int i;<br>  char reg_mask[6];</pre><pre>  if (!ps)<br>    return;</pre><pre>  for (i = 0, map = ps-&gt;baseShader.reg_maps.texcoord;<br>              map &amp;&amp; i &lt; min(8, MAX_REG_TEXCRD);<br>              map &gt;&gt;= 1, ++i)<br>  {<br>    if (!map &amp; 1) // &lt;=<br>      continue;<br>    ....<br>  }<br>}</pre><p>Because of the missing parentheses in the “!map &amp; 1” condition, we see that the value of the ‘map’ variable is verified against null. Apparently the programmer intended to check if the lowest bit is set. Another sign of an error, is the fact that the verification of the ‘map’ against null is already present in the loop termination condition. Thus, this condition is always false, and the ‘continue’ operator will never be executed.</p><p>The condition should most likely be written like this:</p><pre>if ( !(map &amp; 1) )<br>      continue;</pre><p><a href="http://www.viva64.com/en/d/0194/">V590</a> Consider inspecting this expression. The expression is excessive or contains a misprint. vboxdispcm.cpp 288</p><pre>HRESULT vboxDispCmSessionCmdGet(....)<br>{<br>  ....<br>  Assert(hr == S_OK || hr == S_FALSE);<br>  if (hr == S_OK || hr != S_FALSE)     // &lt;=<br>  {<br>      return hr;<br>  }<br>  ....<br>}</pre><p>The analyzer has detected a suspicious condition in which the subexpression “hr == S_OK” does not affect the result of the condition in any way.</p><p>We can make sure looking at the truth table of this conditional expression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/0*Ns58P2vf-xb1m5oo.png" /></figure><p>By the way, we can see suspicious Assert(), that has a modified conditional expression.</p><p>In general, this type of error is very common. For example, the <a href="http://www.viva64.com/en/b/0377/">FreeBSD kernel</a> was no exception.</p><p>The full list of suspicious fragments from VirtualBox:</p><ul><li>V590 Consider inspecting the ‘err == 0L || err != 1237L’ expression. The expression is excessive or contains a misprint. vboxdisplay.cpp 656</li><li>V590 Consider inspecting the ‘rc == 3209 || rc != (- 3210)’ expression. The expression is excessive or contains a misprint. vd.cpp 10876</li><li>V590 Consider inspecting the ‘rc == 3209 || rc != (- 3210)’ expression. The expression is excessive or contains a misprint. vd.cpp 10947</li><li>V590 Consider inspecting the ‘rc == 3209 || rc != (- 3210)’ expression. The expression is excessive or contains a misprint. vd.cpp 11004</li><li>V590 Consider inspecting the ‘rc == 3209 || rc != (- 3210)’ expression. The expression is excessive or contains a misprint. vd.cpp 11060</li></ul><h4>Various warnings</h4><p><a href="http://www.viva64.com/en/d/0100/">V511</a> The sizeof() operator returns size of the pointer, and not of the array, in ‘sizeof (plane)’ expression. devvga-svga3d-win.cpp 4650</p><pre>int vmsvga3dSetClipPlane(...., float plane[4]) // &lt;=<br>{<br>  ....<br>  /* Store for vm state save/restore. */<br>  pContext-&gt;state.aClipPlane[index].fValid = true;<br>  memcpy(pContext-&gt;state.aClipPlane[....], plane, sizeof(plane));<br>  ....<br>}</pre><p>The ‘plane’ variable is just a pointer to the array of ‘float’ type. The value of “sizeof(plane)” will be 4 or 8, depending on the bitness of the program. The number ‘[4]’ in the parameters of the function, gives a hint to the programmer that an array of a ‘float’ type containing 4 elements will be passed to the function. Thus, the memcpy() function copies a wrong number of bytes.</p><p><a href="http://www.viva64.com/en/d/0106/">V517</a> The use of ‘if (A) {…} else if (A) {…}’ pattern was detected. There is a probability of logical error presence. Check lines: 411, 418. mp-r0drv-nt.cpp 411</p><pre>static int rtMpCallUsingDpcs(....)<br>{<br>  ....<br>  if (enmCpuid == RT_NT_CPUID_SPECIFIC)       // &lt;=<br>  {<br>    KeInitializeDpc(&amp;paExecCpuDpcs[0], rtmpNtDPCWrapper, pArgs);<br>    KeSetImportanceDpc(&amp;paExecCpuDpcs[0], HighImportance);<br>    KeSetTargetProcessorDpc(&amp;paExecCpuDpcs[0], (int)idCpu);<br>    pArgs-&gt;idCpu = idCpu;<br>  }<br>  else if (enmCpuid == RT_NT_CPUID_SPECIFIC) // &lt;=<br>  {<br>    KeInitializeDpc(&amp;paExecCpuDpcs[0], rtmpNtDPCWrapper, pArgs);<br>    KeSetImportanceDpc(&amp;paExecCpuDpcs[0], HighImportance);<br>    KeSetTargetProcessorDpc(&amp;paExecCpuDpcs[0], (int)idCpu);<br>    pArgs-&gt;idCpu = idCpu;</pre><pre>    KeInitializeDpc(&amp;paExecCpuDpcs[1], rtmpNtDPCWrapper, pArgs);<br>    KeSetImportanceDpc(&amp;paExecCpuDpcs[1], HighImportance);<br>    KeSetTargetProcessorDpc(&amp;paExecCpuDpcs[1], (int)idCpu2);<br>    pArgs-&gt;idCpu2 = idCpu2;<br>  }<br>  ....<br>}</pre><p>A part of the code in the second condition never gets control because of two identical expressions in the cascade of conditions.</p><p><a href="http://www.viva64.com/en/d/0120/">V531</a> It is odd that a sizeof() operator is multiplied by sizeof(). tstrtfileaio.cpp 61</p><pre>void<br>tstFileAioTestReadWriteBasic(...., uint32_t cMaxReqsInFlight)<br>{<br>  /* Allocate request array. */<br>  RTFILEAIOREQ *paReqs;<br>  paReqs = (...., cMaxReqsInFlight * sizeof(RTFILEAIOREQ));<br>  RTTESTI_CHECK_RETV(paReqs);<br>  RT_BZERO(..., sizeof(cMaxReqsInFlight) * sizeof(RTFILEAIOREQ));</pre><pre>  /* Allocate array holding pointer to data buffers. */<br>  void **papvBuf = (...., cMaxReqsInFlight * sizeof(void *));<br>  ....<br>}</pre><p>The analyzer detected a suspicious product of two sizeof() operators. If we have a look at ‘RT_BZERO’ macro, we may have a question: “Why do we get a size of a variable that has the ‘uint32_t’ type and multiply it by the size of a different type?” In adjoining sections of code the size of the array is evaluated as “cMaxReqsInFlight * sizeof(RTFILEAIOREQ)”. Perhaps it is an error; the same size should be used in the string with ‘RT_BZERO’.</p><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression ‘sd &gt;= 0’ is always true. Unsigned type value is always &gt;= 0. vboxservicevminfo.cpp 1086</p><pre>static int vgsvcVMInfoWriteNetwork(void)<br>{<br>  ....<br>  SOCKET sd = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);<br>  ....<br>  if (pAdpInfo)<br>        RTMemFree(pAdpInfo);<br>  if (sd &gt;= 0)    // &lt;=<br>      closesocket(sd);<br>  ....<br>}</pre><p>The SOCKET type (in Visual C++) is unsigned, so the check “sd &gt;=0” is meaningless. The reason for such code is clear: the project is built on different operating systems, and in the UNIX systems the socket values are stored in the ‘int’ variable of signed type. In general the code for working with sockets is written correctly: to check the states, the programmer uses constants from the system header files. But cross-platform code contains a lot of conditional preprocessor directives, so in one place a check wasn’t noticed, that is always true for Windows.</p><p><a href="http://www.viva64.com/en/d/0153/">V560</a> A part of conditional expression is always true: 0x1fbe. tstiprtministring.cpp 442</p><pre>static void test2(RTTEST hTest)<br>{<br>  ....<br>  for (RTUNICP uc = 1; uc &lt;= 0x10fffd; uc++)<br>  {<br>    if (uc == 0x131 || uc == 0x130 || uc == 0x17f || 0x1fbe)// &lt;=<br>      continue;                                    //^^^^^^</pre><pre>    if (RTUniCpIsLower(uc))<br>    {<br>      RTTESTI_CHECK_MSG(....), (&quot;%#x\n&quot;, uc));<br>      strLower.appendCodePoint(uc);<br>    }<br>    if (RTUniCpIsUpper(uc))<br>    {<br>      RTTESTI_CHECK_MSG(....), (&quot;%#x\n&quot;, uc));<br>      strUpper.appendCodePoint(uc);<br>    }<br>  }<br>  ....<br>}</pre><p>Usually, we don’t write about the warnings issued for the test files in the articles. By the way, it’s very easy to exclude messages received for all the files in the specified directory. Still, I’ve decided to write about one of them here. It’s quite peculiar because of the fact that the test doesn’t actually test anything, because of a typo. The ‘continue’ operator is executed during every iteration of the for() loop. The value ‘0x1fbe’ will always be true, because an expression “uc ==” is missing in the condition. This is a good example of how <a href="http://www.viva64.com/en/a/0080/">static analysis complements unit testing</a>.</p><p>The correct version:</p><pre>if (uc == 0x131 || uc == 0x130 || uc == 0x17f || uc == 0x1fbe)<br>  continue;</pre><p><a href="http://www.viva64.com/en/d/0225/">V610</a> Undefined behavior. Check the shift operator ‘&lt;&lt;’. The left operand ‘(- 2)’ is negative. translate.c 2708</p><pre>static void gen_push_T1(DisasContext *s)<br>{<br>  ....<br>  if (s-&gt;ss32 &amp;&amp; !s-&gt;addseg)<br>    gen_op_mov_reg_A0(1, R_ESP);<br>  else<br>    gen_stack_update(s, (-2) &lt;&lt; s-&gt;dflag);<br>  ....<br>}</pre><p>According to the latest standards of the C++ language, the shift of a negative number results in undefined behavior.</p><p>Two more similar fragments:</p><ul><li>V610 Undefined behavior. Check the shift operator ‘&lt;&lt;’. The left operand is negative (‘i64’ = [-1..0]). tarvfs.cpp 234</li><li>V610 Undefined behavior. Check the shift operator ‘&lt;&lt;’. The left operand ‘-16’ is negative. translate.c 2761</li></ul><h4>TODOs</h4><p><a href="http://www.viva64.com/en/d/0112/">V523</a> The ‘then’ statement is equivalent to the ‘else’ statement. state_evaluators.c 479</p><pre>static void map2(G....)<br>{<br>  ....<br>  if (g-&gt;extensions.NV_vertex_program) {<br>/* XXX FIXME */<br>    i = target - GL_MAP2_COLOR_4;<br>  } else {<br>    i = target - GL_MAP2_COLOR_4;<br>  }<br>  ....<br>}</pre><p>“FIXME” and “TODO” can live in the code for a very long time, but the static analyzer won’t let you forget about code that was left unfinished.</p><p><a href="http://www.viva64.com/en/d/0119/">V530</a> The return value of function ‘e1kHandleRxPacket’ is required to be utilized. deve1000.cpp 3913</p><pre>static void<br>e1kTransmitFrame(PE1KSTATE pThis, bool fOnWorkerThread)<br>{<br>  ....<br>  /** @todo do we actually need to check<br>            that we&#39;re in loopback mode here? */<br>  if (GET_BITS(RCTL, LBM) == RCTL_LBM_TCVR)<br>  {<br>    E1KRXDST status;<br>    RT_ZERO(status);<br>    status.fPIF = true;<br>    e1kHandleRxPacket(pThis, pSg-&gt;aSegs[0].pvSeg, ....); // &lt;=<br>    rc = VINF_SUCCESS;                                   // &lt;=<br>  }<br>  e1kXmitFreeBuf(pThis);<br>  ....<br>}</pre><p>In other parts of the source code, the result of the function e1kHandleRxPacket () is usually saved to the ‘rc’ variable. But until the code is completed, the result of the function is not used and “VINF_SUCCESS” is always saved in the status.</p><h4>New diagnostics</h4><p>In this section I will describe the analyzer warnings that appeared in PVS-Studio, after the last check of the VirtualBox project.</p><p><a href="http://www.viva64.com/en/d/0435/">V745</a> A ‘wchar_t *’ type string is incorrectly converted to ‘BSTR’ type string. Consider using ‘SysAllocString’ function. vboxcredentialprovider.cpp 231</p><pre>static HRESULT VBoxCredentialProviderRegisterSENS(void)<br>{<br>  ....<br>  hr = pIEventSubscription-&gt;put_EventClassID(<br>                      L&quot;{d5978630-5b9f-11d1-8dd2-00aa004abd5e}&quot;);<br>  ....<br>}</pre><p>The analyzer saw that the string of “wchar_t *” type is handled as a string of BSTR type.</p><p>BSTR (basic string or binary string), is a string data type that is used in COM, Automation, and Interop functions. A string of this type is composed of a 4 byte length prefix, a data string, and a delimiter of two null characters. The length prefix is specified before the first character of the string, and does not take into account the delimiter character. In this case the length prefix will be missing before the beginning of the string.</p><p>Corrected version using the SysAllocString() function:</p><pre>static HRESULT VBoxCredentialProviderRegisterSENS(void)<br>{<br>  ....<br>  hr = pIEventSubscription-&gt;put_EventClassID(SysAllocString(<br>                     L&quot;{d5978630-5b9f-11d1-8dd2-00aa004abd5e}&quot;));<br>  ....<br>}</pre><p>More suspicious fragments:</p><ul><li>V745 A ‘wchar_t *’ type string is incorrectly converted to ‘BSTR’ type string. Consider using ‘SysAllocString’ function. vboxcredentialprovider.cpp 277</li><li>V745 A ‘wchar_t *’ type string is incorrectly converted to ‘BSTR’ type string. Consider using ‘SysAllocString’ function. vboxcredentialprovider.cpp 344</li><li>V745 A ‘wchar_t *’ type string is incorrectly converted to ‘BSTR’ type string. Consider using ‘SysAllocString’ function. string.cpp 31</li></ul><p><a href="http://www.viva64.com/en/d/0436/">V746</a> Type slicing. An exception should be caught by reference rather than by value. extpackutil.cpp 257</p><pre>RTCString *VBoxExtPackLoadDesc(....)<br>{<br>  ....<br>  xml::XmlFileParser  Parser;<br>  try<br>  {<br>    Parser.read(szFilePath, Doc);<br>  }<br>  catch (xml::XmlError Err) // &lt;=<br>  {<br>    return new RTCString(Err.what());<br>  }<br>  ....<br>}</pre><p>The analyzer detected a potential error, related to catching the exception by value. It means that a new ‘Err’ object of xml::XmlError type, will be constructed with the help of a copy constructor. At the same time some of the code will lose some data about the exception that was stored in the classes, inherited from xml::XmlError.</p><p>Another suspicious fragment:</p><ul><li>V746 Type slicing. An exception should be caught by reference rather than by value. extpackutil.cpp 330</li></ul><h4>Conclusion:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*EwClZXXBD5zlRChf.png" /></figure><p>VirtualBox project is a good example of just how important it is to do static analysis regularly on a developing project. It prevents the growth of potential bugs during the development stage, and allows fresh updates of the analysis tool.</p><p>I would also gladly check MS Word, which froze several times for 7–10 minutes fully loading the processor, when I was writing the article. But there is no such possibility. We have done some archaeological research on <a href="http://www.viva64.com/en/b/0245/">MS Word 1.1a</a>, but that is a another story.</p><p>So, feel free to <a href="http://www.viva64.com/en/pvs-studio-download/">download</a> PVS-Studio without filling in any forms, and find bugs in your project. Think about the users, and the time the programmers could save.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86fb608a19c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PVS-Studio delved into the FreeBSD kernel]]></title>
            <link>https://medium.com/@viva64articles/pvs-studio-delved-into-the-freebsd-kernel-dcfe45dfac67?source=rss-67b72a9416b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcfe45dfac67</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[freebsd]]></category>
            <dc:creator><![CDATA[Love C&C++]]></dc:creator>
            <pubDate>Wed, 17 Feb 2016 15:20:58 GMT</pubDate>
            <atom:updated>2016-02-17T15:20:58.994Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/476/0*bXwesGRuaBoeGhpC.png" /></figure><p>About a year ago we checked the Linux core. It was one of the most discussed articles at that time. We also got quite a number of requests to check FreeBSD, so finally we decided to take the time to do it.</p><h4>About the project</h4><p><a href="https://www.freebsd.org/">FreeBSD</a> is a contemporary operating system for servers, desktops and embedded computer platforms. Its code has gone through more than thirty years of continuous development, improvement and optimization. It has proven itself as a system for building intranet, Internet networks, and servers. It provides reliable network services and efficient memory management.</p><p>Despite the fact that FreeBSD is regularly <a href="https://scan.coverity.com/projects/freebsd">checked by Coverity</a>, we had a great time checking this project because a lot of suspicious fragments were found. In this article we’ll provide about 40 fragments, but the developers of this project may have a look at a full list, which contains around 1000 analyzer warnings of high severity.</p><p>To my humble opinion, a lot of those warnings issued by the analyzer are real bugs, but it’s hard for me to determine how critical they are, as I am not the developer of the system. I suppose it could be a good ground for a discussion with the authors of the project.</p><p>The source code was taken from <a href="https://github.com/freebsd/freebsd">GitHub</a> branch — ‘master’. The repository contains ~23000 files and two dozens of assembly configurations for different platforms, but I checked the kernel only, which I compiled in this way:</p><pre># make buildkernel KERNCONF=MYKERNEL</pre><h4>Methodology</h4><p>We used static code analyzer <a href="http://www.viva64.com/en/pvs-studio/">PVS-Studio</a>, version 6.01.</p><p>For convenience, I set a PC-BSD and wrote a small utility in C++, which keeps the working environment of the compilers’ runs when building the kernel. The acquired information was used to get the <a href="http://www.viva64.com/en/t/0076/">preprocessed files</a> and their analysis, done by PVS-Studio. This method allowed me to quickly check a project without having to study an unfamiliar build system to integrate the analyzer. On top of it, analysis of preprocessed files allows you to do a more in-depth analysis of the code and find more sophisticated and interesting, errors, in macros for instance. This article will provide several examples of such a kind.</p><p>Linux kernel was analyzed in the same way; this mode is also available for Windows users in the <a href="http://www.viva64.com/en/b/0243/">Standalone</a>utility, which is a part of PVS-studio distribution kit. Usually PVS-Studio seamlessly integrates into the projects. There is a number of ways to integrate the analyzer, described in the documentation. Monitoring utilities have a big advantage of trying the analyzer if the project has an unusual building system.</p><h4>Surprising luck</h4><p>The first possible error was found before I ran the analyzer on the project, and even before I built the kernel; the build was interrupted by a linking error. Having addressed the file, specified in the error, I saw the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*tU8IL3vBzD33I5Ud.png" /></figure><p>Pay attention to the highlighted fragment: a tab character is used for the formatting of the indentations; two statements are moved under the condition. But the last statement does not actually refer to a condition and will be always executed. Perhaps, curly braces were forgotten here.</p><p>Once we got a comment that we just copy the analyzer warnings, but it is not so. Before the analysis of the project we have to make sure that it gets compiled correctly; when the report is done, the warnings must be sorted/examined and commented. The same work is done by our customer support team, when they answer the incoming mails. There are also cases when the customers send examples of false positives (in their opinion) which turn out to be real bugs.</p><h4>Capy-poste and typos</h4><p>PVS-Studio analyzer is a powerful tool for static code analysis that finds bugs of various levels of severity. The first diagnostics were very simple and were created to detect most common bugs, related to typos and copy-paste programming. After the analysis review, I sort them according to the error code. So in this article we’ll start with this type of diagnostic rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*GzjZYpo5J-amPBTk.png" /></figure><p><a href="http://www.viva64.com/en/d/0090/">V501</a> There are identical sub-expressions ‘(uintptr_t) b-&gt;handler’ to the left and to the right of the ‘&gt;’ operator. ip_fw_sockopt.c 2893</p><pre>static int<br>compare_sh(const void *_a, const void *_b)<br>{<br>  const struct ipfw_sopt_handler *a, *b;</pre><pre>  a = (const struct ipfw_sopt_handler *)_a;<br>  b = (const struct ipfw_sopt_handler *)_b;<br>  ....<br>  if ((uintptr_t)a-&gt;handler &lt; (uintptr_t)b-&gt;handler)<br>    return (-1);<br>  else if ((uintptr_t)b-&gt;handler &gt; (uintptr_t)b-&gt;handler) // &lt;=<br>    return (1);<br>  <br>  return (0);<br>}</pre><p>Here is a vivid example of a bad practice — giving the variables short and uninformative names. Now because of the typo in the letter ‘b’, the a part of the condition will never be return 1. Thus, the function returns a zero status not always correctly.</p><p><a href="http://www.viva64.com/en/d/0090/">V501</a> There are identical sub-expressions to the left and to the right of the ‘!=’ operator: m-&gt;m_pkthdr.len != m-&gt;m_pkthdr.len key.c 7208</p><pre>int<br>key_parse(struct mbuf *m, struct socket *so)<br>{<br>  ....<br>  if ((m-&gt;m_flags &amp; M_PKTHDR) == 0 ||<br>      m-&gt;m_pkthdr.len != m-&gt;m_pkthdr.len) { // &lt;=<br>    ....<br>    goto senderror;<br>  }<br>  ....<br>}</pre><p>One of the fields of the structure is compared with itself; therefore, the result of the logical operation will always be False.</p><p><a href="http://www.viva64.com/en/d/0090/">V501</a> There are identical sub-expressions to the left and to the right of the ‘|’ operator: PIM_NOBUSRESET | PIM_NOBUSRESET sbp_targ.c 1327</p><pre>typedef enum {<br>  PIM_EXTLUNS      = 0x100,<br>  PIM_SCANHILO     = 0x80,<br>  PIM_NOREMOVE     = 0x40,<br>  PIM_NOINITIATOR  = 0x20,<br>  PIM_NOBUSRESET   = 0x10, // &lt;=<br>  PIM_NO_6_BYTE    = 0x08,<br>  PIM_SEQSCAN      = 0x04,<br>  PIM_UNMAPPED     = 0x02,<br>  PIM_NOSCAN       = 0x01<br>} pi_miscflag;</pre><pre>static void<br>sbp_targ_action1(struct cam_sim *sim, union ccb *ccb)<br>{<br>  ....<br>  struct ccb_pathinq *cpi = &amp;ccb-&gt;cpi;</pre><pre>    cpi-&gt;version_num = 1; /* XXX??? */<br>    cpi-&gt;hba_inquiry = PI_TAG_ABLE;<br>    cpi-&gt;target_sprt = PIT_PROCESSOR<br>         | PIT_DISCONNECT<br>         | PIT_TERM_IO;<br>    cpi-&gt;transport = XPORT_SPI;<br>    cpi-&gt;hba_misc = PIM_NOBUSRESET | PIM_NOBUSRESET; // &lt;=<br>  ....<br>}</pre><p>In this example we see that the same variable “PIM_NOBUSRESET” is used in the bitwise operation, which doesn’t affect the result in any way. Most likely a constant with a different value was meant to be used here, but the variable was left unchanged.</p><p><a href="http://www.viva64.com/en/d/0112/">V523</a> The ‘then’ statement is equivalent to the ‘else’ statement. saint.c 2023</p><pre>GLOBAL void siSMPRespRcvd(....)<br>{<br>  ....<br>  if (agNULL == frameHandle)<br>  {<br>    /* indirect mode */<br>    /* call back with success */<br>    (*(ossaSMPCompletedCB_t)(pRequest-&gt;completionCB))(agRoot,<br>       pRequest-&gt;pIORequestContext, OSSA_IO_SUCCESS, payloadSize,<br>       frameHandle);<br>  }<br>  else<br>  {<br>    /* direct mode */<br>    /* call back with success */<br>    (*(ossaSMPCompletedCB_t)(pRequest-&gt;completionCB))(agRoot,<br>       pRequest-&gt;pIORequestContext, OSSA_IO_SUCCESS, payloadSize,<br>       frameHandle);<br>  }<br>  ....<br>}</pre><p>Two condition branches are commented differently: /* indirect mode */ and /* direct mode */, but they are implemented similarly, which is very suspicious.</p><p><a href="http://www.viva64.com/en/d/0112/">V523</a> The ‘then’ statement is equivalent to the ‘else’ statement. smsat.c 2848</p><pre>osGLOBAL void<br>smsatInquiryPage89(....)<br>{<br>  ....<br>  if (oneDeviceData-&gt;satDeviceType == SATA_ATA_DEVICE)<br>  {<br>    pInquiry[40] = 0x01; /* LBA Low          */<br>    pInquiry[41] = 0x00; /* LBA Mid          */<br>    pInquiry[42] = 0x00; /* LBA High         */<br>    pInquiry[43] = 0x00; /* Device           */<br>    pInquiry[44] = 0x00; /* LBA Low Exp      */<br>    pInquiry[45] = 0x00; /* LBA Mid Exp      */<br>    pInquiry[46] = 0x00; /* LBA High Exp     */<br>    pInquiry[47] = 0x00; /* Reserved         */<br>    pInquiry[48] = 0x01; /* Sector Count     */<br>    pInquiry[49] = 0x00; /* Sector Count Exp */<br>  }<br>  else<br>  {<br>    pInquiry[40] = 0x01; /* LBA Low          */<br>    pInquiry[41] = 0x00; /* LBA Mid          */<br>    pInquiry[42] = 0x00; /* LBA High         */<br>    pInquiry[43] = 0x00; /* Device           */<br>    pInquiry[44] = 0x00; /* LBA Low Exp      */<br>    pInquiry[45] = 0x00; /* LBA Mid Exp      */<br>    pInquiry[46] = 0x00; /* LBA High Exp     */<br>    pInquiry[47] = 0x00; /* Reserved         */<br>    pInquiry[48] = 0x01; /* Sector Count     */<br>    pInquiry[49] = 0x00; /* Sector Count Exp */<br>  }<br>  ....<br>}</pre><p>This example is even more suspicious than the previous one. A big code fragment was copied, but later no changes were made.</p><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression is always true. Probably the ‘&amp;&amp;’ operator should be used here. qla_hw.c 799</p><pre>static int<br>qla_tx_tso(qla_host_t *ha, struct mbuf *mp, ....)<br>{<br>  ....<br>  if ((*tcp_opt != 0x01) || (*(tcp_opt + 1) != 0x01) ||<br>    (*(tcp_opt + 2) != 0x08) || (*(tcp_opt + 2) != 10)) { // &lt;=<br>    return -1;<br>  }<br>  ....<br>}</pre><p>Here the analyzer detected that the condition “(* (tcp_opt + 2)! = 0x08) | (* (tcp_opt + 2)! = 10) “is always true and it is really so, if you build a truth table. But most likely the ‘&amp;&amp;’ is not needed here, it is just a typo in the address offset. Perhaps the function code should be like this:</p><pre>static int<br>qla_tx_tso(qla_host_t *ha, struct mbuf *mp, ....)<br>{<br>  ....<br>  if ((*tcp_opt != 0x01) || (*(tcp_opt + 1) != 0x01) ||<br>    (*(tcp_opt + 2) != 0x08) || (*(tcp_opt + 3) != 10)) {<br>    return -1;<br>  }<br>  ....<br>}</pre><p><a href="http://www.viva64.com/en/d/0169/">V571</a> Recurring check. This condition was already verified in line 1946. sahw.c 1949</p><pre>GLOBAL<br>bit32 siHDAMode_V(....)<br>{<br>  ....<br>  if( saRoot-&gt;memoryAllocated.agMemory[i].totalLength &gt; biggest)<br>  {<br>    if(biggest &lt; saRoot-&gt;memoryAllocated.agMemory[i].totalLength)<br>    {<br>      save = i;<br>      biggest = saRoot-&gt;memoryAllocated.agMemory[i].totalLength;<br>    }<br>  }<br>  ....<br>}</pre><p>This code is really strange, if we simplify it, we’ll see the following:</p><pre>if( A &gt; B )<br>{<br>  if (B &lt; A)<br>  {<br>    ....<br>  }<br>}</pre><p>The same condition is checked twice. Most likely, something else was supposed to be written here.</p><p>A similar fragment:</p><ul><li>V571 Recurring check. This condition was already verified in line 1940. if_rl.c 1941</li></ul><h4>Dangerous macros</h4><p><a href="http://www.viva64.com/en/d/0112/">V523</a> The ‘then’ statement is equivalent to the ‘else’ statement. agtiapi.c 829</p><pre>if (osti_strncmp(buffer, &quot;0x&quot;, 2) == 0)<br>{ <br>  maxTargets = osti_strtoul (buffer, &amp;pLastUsedChar, 0);<br>  AGTIAPI_PRINTK( &quot;.... maxTargets = osti_strtoul  0 \n&quot; );<br>}<br>else<br>{<br>  maxTargets = osti_strtoul (buffer, &amp;pLastUsedChar, 10);<br>  AGTIAPI_PRINTK( &quot;.... maxTargets = osti_strtoul 10\n&quot;   );<br>}</pre><p>First, I skipped this analyzer warning, thinking that it is a false positive. But warnings of low severity should also be reviewed after the project check (to improve the analyzer). So I came across such a macro:</p><pre>#define osti_strtoul(nptr, endptr, base)    \<br>          strtoul((char *)nptr, (char **)endptr, 0)</pre><p>The ‘base’ parameter isn’t used at all, and the ‘0’ value is always passed to the “strtoul” function as the last parameter, although values ‘0’ and ‘10’ are passed to the macro. In the preprocessed files all macros got expanded and the code became similar. This macro is used in this way several dozen times. The entire list of such fragments was sent to the developers.</p><p><a href="http://www.viva64.com/en/d/0380">V733</a> It is possible that macro expansion resulted in incorrect evaluation order. Check expression: chan — 1 * 20. isp.c 2301</p><pre>static void<br>isp_fibre_init_2400(ispsoftc_t *isp)<br>....<br>  if (ISP_CAP_VP0(isp))<br>    off += ICB2400_VPINFO_PORT_OFF(chan);<br>  else<br>    off += ICB2400_VPINFO_PORT_OFF(chan - 1); // &lt;=<br>  ....<br>}</pre><p>At first glance, there is nothing strange in this code fragment. We see that sometimes the ‘chan’ value is used, sometimes less by one ‘chan — 1’, but let’s have look at the macro definition:</p><pre>#define ICB2400_VPOPT_WRITE_SIZE 20</pre><pre>#define  ICB2400_VPINFO_PORT_OFF(chan) \<br>  (ICB2400_VPINFO_OFF +                \<br>   sizeof (isp_icb_2400_vpinfo_t) +    \<br>  (chan * ICB2400_VPOPT_WRITE_SIZE))          // &lt;=</pre><p>When passing the binary expression to the macro, the calculation logic changes dramatically. The expression “(chan — 1) * 20” turns into “chan — 1 *20”, i.e. into “chan — 20”, and the incorrectly calculated size gets used further in the program.</p><h4>About the priorities of operations</h4><p>In this section, I will discuss how important it is to know the priorities of operations, use extra parentheses, if you are not sure and sometimes test yourself by building truth tables of logical expressions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*qTUPO4NNuaN-y2Z8.png" /></figure><p><a href="http://www.viva64.com/en/d/0091/">V502</a> Perhaps the ‘?:’ operator works in a different way than it was expected. The ‘?:’ operator has a lower priority than the ‘|’ operator. ata-serverworks.c 166</p><pre>ata_serverworks_chipinit(device_t dev)<br>{<br>  ....<br>  pci_write_config(dev, 0x5a,<br>           (pci_read_config(dev, 0x5a, 1) &amp; ~0x40) |<br>           (ctlr-&gt;chip-&gt;cfg1 == SWKS_100) ? 0x03 : 0x02, 1);<br>  }<br>  ....<br>}</pre><p>The priority of ‘?:’ operator is lower than of the bitwise OR ‘|’. As a result, in the bit operations, in addition to the numeric constants, the expression result “(ctlr-&gt; chip &gt; cfg1 = SWKS_100)” gets used, which suddenly changes the calculation/computation logic. Perhaps this error wasn’t noticed so far because the result seemed so close to the truth.</p><p><a href="http://www.viva64.com/en/d/0091/">V502</a> Perhaps the ‘?:’ operator works in a different way than it was expected. The ‘?:’ operator has a lower priority than the ‘|’ operator. in6.c 1318</p><pre>void<br>in6_purgeaddr(struct ifaddr *ifa)<br>{<br>  ....<br>  error = rtinit(&amp;(ia-&gt;ia_ifa), RTM_DELETE, ia-&gt;ia_flags |<br>        (ia-&gt;ia_dstaddr.sin6_family == AF_INET6) ? RTF_HOST : 0);<br>  ....<br>}</pre><p>A different file also had a fragment with a similar error with a ternary operator.</p><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression ‘cdb[0] != 0x28 || cdb[0] != 0x2A’ is always true. Probably the ‘&amp;&amp;’ operator should be used here. mfi_tbolt.c 1110</p><pre>int<br>mfi_tbolt_send_frame(struct mfi_softc *sc, struct mfi_command *cm)<br>{<br>  ....<br>  if (cdb[0] != 0x28 || cdb[0] != 0x2A) {  // &lt;=&#39;<br>    if ((req_desc = mfi_tbolt_build_mpt_cmd(sc, cm)) == NULL) {<br>      device_printf(sc-&gt;mfi_dev, &quot;Mapping from MFI &quot;<br>          &quot;to MPT Failed \n&quot;);<br>      return 1;<br>    }<br>  }<br>  else<br>    device_printf(sc-&gt;mfi_dev, &quot;DJA NA XXX SYSPDIO\n&quot;);<br>  ....<br>}</pre><p>The first conditional expression is always true, that’s why the ‘else’ branch never gets control. I will provide the truth table in case of controversial logical expressions in this and the following examples. An example for this case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/0*u6Jh1BIkvoYRe1NL.png" /></figure><p><a href="http://www.viva64.com/en/d/0194/">V590</a> Consider inspecting the ‘error == 0 || error != — 1’ expression. The expression is excessive or contains a misprint. nd6.c 2119</p><pre>int<br>nd6_output_ifp(....)<br>{<br>  ....<br>  /* Use the SEND socket */<br>  error = send_sendso_input_hook(m, ifp, SND_OUT,<br>      ip6len);<br>  /* -1 == no app on SEND socket */<br>  if (error == 0 || error != -1)           // &lt;=<br>      return (error);<br>  ....<br>}</pre><p>The problem with this fragment is that the conditional expression doesn’t depend on the result “error == 0”. Perhaps, something is wrong here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/0*ub863WqRwCzGyPjw.png" /></figure><p>Three more cases:</p><ul><li>V590 Consider inspecting the ‘error == 0 || error != 35’ expression. The expression is excessive or contains a misprint. if_ipw.c 1855</li><li>V590 Consider inspecting the ‘error == 0 || error != 27’ expression. The expression is excessive or contains a misprint. if_vmx.c 2747</li><li>V547 Expression is always true. Probably the ‘&amp;&amp;’ operator should be used here. igmp.c 1939</li></ul><p>V590 Consider inspecting this expression. The expression is excessive or contains a misprint. sig_verify.c 94</p><pre>enum uni_ieact {<br>  UNI_IEACT_CLEAR = 0x00, /* clear call */<br>  ....<br>}</pre><pre>void<br>uni_mandate_epref(struct uni *uni, struct uni_ie_epref *epref)<br>{<br>  ....<br>  maxact = -1;<br>  FOREACH_ERR(e, uni) {<br>    if (e-&gt;ie == UNI_IE_EPREF)<br>      continue;<br>    if (e-&gt;act == UNI_IEACT_CLEAR)<br>      maxact = UNI_IEACT_CLEAR;<br>    else if (e-&gt;act == UNI_IEACT_MSG_REPORT) {<br>      if (maxact == -1 &amp;&amp; maxact != UNI_IEACT_CLEAR)     // &lt;=<br>        maxact = UNI_IEACT_MSG_REPORT;<br>    } else if (e-&gt;act == UNI_IEACT_MSG_IGNORE) {<br>      if (maxact == -1)<br>        maxact = UNI_IEACT_MSG_IGNORE;<br>    }<br>  }<br>  ....<br>}</pre><p>The result of the whole conditional expression doesn’r depend on the calculation of the value “maxact != UNI_IEACT_CLEAR”. Here’s how it looks in the table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/0*9PD8EBPwNXFcF_XK.png" /></figure><p>In this section I give three ways of how to make an error in seemingly simple formulas. Just think of it…</p><p><a href="http://www.viva64.com/en/d/0197/">V593</a> Consider reviewing the expression of the ‘A = B != C’ kind. The expression is calculated as following: ‘A = (B != C)’. aacraid.c 2854</p><pre>#define EINVAL 22 /* Invalid argument */<br>#define EFAULT 14 /* Bad address */<br>#define EPERM 1 /* Operation not permitted */</pre><pre>static int<br>aac_ioctl_send_raw_srb(struct aac_softc *sc, caddr_t arg)<br>{<br>  ....<br>  int error, transfer_data = 0;<br>  ....<br>  if ((error = copyin((void *)&amp;user_srb-&gt;data_len, &amp;fibsize, <br>    sizeof (u_int32_t)) != 0)) <br>    goto out;<br>  if (fibsize &gt; (sc-&gt;aac_max_fib_size-sizeof(....))) {<br>    error = EINVAL;<br>    goto out;<br>  }<br>  if ((error = copyin((void *)user_srb, srbcmd, fibsize) != 0)) <br>    goto out;<br>  ....<br>out:<br>  ....<br>  return(error);<br>}</pre><p>In this function the error code gets corrupted, when the assignment is executed in the ‘if’ operator. I.e. in the expression “error = copyin(…) != 0” the “copyin(…) != 0” is evaluated first, and then the result (0 or 1) is written to the variable ‘error’.</p><p>The documentation for the function ‘copyin’ states that in case of an error, it returns EFAULT (value 14), and after such a check, the result of a logical operation ‘1’ gets stored in the error code. It is actually EPERM, a completely different error status.</p><p>Unfortunately, there is quite a number of such fragments.</p><ul><li>V593 Consider reviewing the expression of the ‘A = B != C’ kind. The expression is calculated as following: ‘A = (B != C)’. aacraid.c 2861</li><li>V593 Consider reviewing the expression of the ‘A = B != C’ kind. The expression is calculated as following: ‘A = (B != C)’. if_age.c 591</li><li>V593 Consider reviewing the expression of the ‘A = B != C’ kind. The expression is calculated as following: ‘A = (B != C)’. if_alc.c 1535</li><li>V593 Consider reviewing the expression of the ‘A = B != C’ kind. The expression is calculated as following: ‘A = (B != C)’. if_ale.c 606</li><li>V593 Consider reviewing the expression of the ‘A = B != C’ kind. The expression is calculated as following: ‘A = (B != C)’. if_jme.c 807</li><li>V593 Consider reviewing the expression of the ‘A = B != C’ kind. The expression is calculated as following: ‘A = (B != C)’. if_msk.c 1626</li><li>V593 Consider reviewing the expression of the ‘A = B != C’ kind. The expression is calculated as following: ‘A = (B != C)’. if_stge.c 511</li><li>V593 Consider reviewing the expression of the ‘A = B != C’ kind. The expression is calculated as following: ‘A = (B != C)’. hunt_filter.c 973</li><li>V593 Consider reviewing the expression of the ‘A = B != C’ kind. The expression is calculated as following: ‘A = (B != C)’. if_smsc.c 1365</li><li>V593 Consider reviewing the expression of the ‘A = B != C’ kind. The expression is calculated as following: ‘A = (B != C)’. if_vte.c 431</li><li>V593 Consider reviewing the expression of the ‘A = B != C’ kind. The expression is calculated as following: ‘A = (B != C)’. zfs_vfsops.c 498</li></ul><h4>Strings</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*5j784bX2PGRJHMXN.png" /></figure><p><a href="http://www.viva64.com/en/d/0130/">V541</a> It is dangerous to print the string ‘buffer’ into itself. ata-highpoint.c 102</p><pre>static int<br>ata_highpoint_probe(device_t dev)<br>{<br>  ....<br>  char buffer[64];<br>  ....<br>  strcpy(buffer, &quot;HighPoint &quot;);<br>  strcat(buffer, idx-&gt;text);<br>  if (idx-&gt;cfg1 == HPT_374) {<br>  if (pci_get_function(dev) == 0)<br>      strcat(buffer, &quot; (channel 0+1)&quot;);<br>  if (pci_get_function(dev) == 1)<br>      strcat(buffer, &quot; (channel 2+3)&quot;);<br>  }<br>  sprintf(buffer, &quot;%s %s controller&quot;,<br>    buffer, ata_mode2str(idx-&gt;max_dma));<br>  ....<br>}</pre><p>Some string is formed in the buffer. Then the programmer wants to get a new string, saving the previous string value, and add two more words. It seems really simple.</p><p>To explain why unexpected result will be recieved here, I will quote a simple and clear example from the documentation for this diagnostic:</p><pre>char s[100] = &quot;test&quot;;<br>sprintf(s, &quot;N = %d, S = %s&quot;, 123, s);</pre><p>As a result of the work we would want to get the following string:</p><pre>N = 123, S = test</pre><p>But in practice it will be like this:</p><pre>N = 123, S = N = 123, S =</pre><p>In other situations, the same code can lead not only to the incorrect text, but also to the program abortion. The code can be fixed if you use a new buffer to store the result . The correct version:</p><pre>char s1[100] = &quot;test&quot;;<br>char s2[100];<br>sprintf(s2, &quot;N = %d, S = %s&quot;, 123, s1);</pre><p><a href="http://www.viva64.com/en/d/0101/">V512</a> A call of the ‘strcpy’ function will lead to overflow of the buffer ‘p-&gt;vendor’. aacraid_cam.c 571</p><pre>#define  SID_VENDOR_SIZE   8<br>  char   vendor[SID_VENDOR_SIZE];<br>#define  SID_PRODUCT_SIZE  16<br>  char   product[SID_PRODUCT_SIZE];<br>#define  SID_REVISION_SIZE 4<br>  char   revision[SID_REVISION_SIZE];</pre><pre>static void<br>aac_container_special_command(struct cam_sim *sim, union ccb *ccb,<br>  u_int8_t *cmdp)<br>{<br>  ....<br>  /* OEM Vendor defines */<br>  strcpy(p-&gt;vendor,&quot;Adaptec &quot;);          // &lt;=<br>  strcpy(p-&gt;product,&quot;Array           &quot;); // &lt;=<br>  strcpy(p-&gt;revision,&quot;V1.0&quot;);            // &lt;=<br>  ....<br>}</pre><p>All three strings here are filled incorrectly. There is no space for <a href="http://www.viva64.com/en/t/0088/">null-terminal symbol</a> in the arrays, which may cause serious problems with such strings in the future. One space can be removed in “p-&gt;vendor” and “p-&gt;product”. Then there will be room for null terminal, that the strcpy() function adds to the end of the string. But there is no free space at all for the end of line characters for the “p-&gt;revision”; that’s why the value SID_REVISION_SIZE should be increased at least by one.</p><p>Of course, it is rather hard for me to judge about the code. It’s possible, that the terminal null is not needed at all and everything is designed for a specific buffer size. Then the strcpy() function is chosen incorrectly. In this case the code should be written like this:</p><pre>memcpy(p-&gt;vendor,   &quot;Adaptec &quot;,         SID_VENDOR_SIZE);<br>memcpy(p-&gt;product,  &quot;Array           &quot;, SID_PRODUCT_SIZE);<br>memcpy(p-&gt;revision, &quot;V1.0&quot;,             SID_REVISION_SIZE);</pre><p><a href="http://www.viva64.com/en/d/0186/">V583</a> The ‘?:’ operator, regardless of its conditional expression, always returns one and the same value: td-&gt;td_name. subr_turnstile.c 1029</p><pre>static void<br>print_thread(struct thread *td, const char *prefix)<br>{<br>  db_printf(&quot;%s%p (tid %d, pid %d, ....&quot;, prefix, td, td-&gt;td_tid,<br>      td-&gt;td_proc-&gt;p_pid, td-&gt;td_name[0] != &#39;\0&#39; ? td-&gt;td_name :<br>      td-&gt;td_name);<br>}</pre><p>Suspicious fragment. Despite the “td-&gt;td_name[0] != ‘\0’” check, this string is still printed.</p><p>Here are such fragments:</p><ul><li>V583 The ‘?:’ operator, regardless of its conditional expression, always returns one and the same value: td-&gt;td_name. subr_turnstile.c 1112</li><li>V583 The ‘?:’ operator, regardless of its conditional expression, always returns one and the same value: td-&gt;td_name. subr_turnstile.c 1196</li></ul><h4>Operations with memory</h4><p>In this section I will tell about incorrect usage of the following functions:</p><pre>void bzero(void *b, size_t len);</pre><pre>int copyout(const void *kaddr, void *uaddr, size_t len);</pre><p><a href="http://www.viva64.com/en/d/0181/">V579</a> The bzero function receives the pointer and its size as arguments. It is possibly a mistake. Inspect the second argument. osapi.c 316</p><pre>/* Autosense storage */  <br>struct scsi_sense_data sense_data;</pre><pre>void<br>ostiInitiatorIOCompleted(....)<br>{<br>  ....<br>  bzero(&amp;csio-&gt;sense_data, sizeof(&amp;csio-&gt;sense_data));<br>  ....<br>}</pre><p>To zero the structure, we should pass the structure pointer and the size of the memory to be zeroed in bytes to the bzero() function; but here the pointer size is passed to the function, not the structure size.</p><p>The correct code should be like this:</p><pre>bzero(&amp;csio-&gt;sense_data, sizeof(csio-&gt;sense_data));</pre><p><a href="http://www.viva64.com/en/d/0181/">V579</a> The bzero function receives the pointer and its size as arguments. It is possibly a mistake. Inspect the second argument. acpi_package.c 83</p><pre>int<br>acpi_PkgStr(...., void *dst, ....)<br>{<br>  ....<br>  bzero(dst, sizeof(dst));<br>  ....<br>}</pre><p>In this example we see a similar situation: the size of the pointer, not the object gets passed to the ‘bzero’ function.</p><p>Correct version:</p><pre>bzero(dst, sizeof(*dst));</pre><p><a href="http://www.viva64.com/en/d/0181/">V579</a> The copyout function receives the pointer and its size as arguments. It is possibly a mistake. Inspect the third argument. if_nxge.c 1498</p><pre>int<br>xge_ioctl_stats(xge_lldev_t *lldev, struct ifreq *ifreqp)<br>{<br>  ....<br>  *data = (*data == XGE_SET_BUFFER_MODE_1) ? &#39;Y&#39;:&#39;N&#39;;<br>  if(copyout(data, ifreqp-&gt;ifr_data, sizeof(data)) == 0)    // &lt;=<br>      retValue = 0;<br>  break;<br>  ....<br>}</pre><p>In this example the memory is copied from ‘data’ to ‘ifreqp-&gt;ifr_data’, at the same time the size of the memory to be copied is sizeof(data), i.e. 4 or 8 bytes depending on the bitness of the architecture.</p><h4>Pointers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*q8CwbF1qkkQyLdPT.png" /></figure><p><a href="http://www.viva64.com/en/d/0148/">V557</a> Array overrun is possible. The ‘2’ index is pointing beyond array bound. if_spppsubr.c 4348</p><pre>#define AUTHKEYLEN  16</pre><pre>struct sauth {<br>  u_short  proto;      /* authentication protocol to use */<br>  u_short  flags;</pre><pre>#define AUTHFLAG_NOCALLOUT  1  <br>          /* callouts */<br>#define AUTHFLAG_NORECHALLENGE  2  /* do not re-challenge CHAP */<br>  u_char  name[AUTHNAMELEN];  /* system identification name */<br>  u_char  secret[AUTHKEYLEN];  /* secret password */<br>  u_char  challenge[AUTHKEYLEN];  /* random challenge */<br>};</pre><pre>static void<br>sppp_chap_scr(struct sppp *sp)<br>{<br>  u_long *ch, seed;<br>  u_char clen;</pre><pre>  /* Compute random challenge. */<br>  ch = (u_long *)sp-&gt;myauth.challenge;<br>  read_random(&amp;seed, sizeof seed);<br>  ch[0] = seed ^ random();<br>  ch[1] = seed ^ random();<br>  ch[2] = seed ^ random(); // &lt;=<br>  ch[3] = seed ^ random(); // &lt;=<br>  clen = AUTHKEYLEN;<br>  ....<br>}</pre><p>The size of ‘u_char’ type is 1 byte in the 32 and 64 — bit applications; but the size of the ‘u_long’ type is 4 bytes in the 32-bit applications and 8 byte in the 64-bit application. So in the 32-bit application during the execution of the operation “u_long* ch = (u_long *)sp-&gt;myauth.challenge”, the array ‘ch’ will consist of 4 elements, 4 bytes each. And in the 64-bit application the array ‘ch’ will consist of 2 elements, that have 8 bytes each. Therefore, if we compile the 64-bit kernel, then when accessing ch[2] and ch[3] we’ll have array index out of bounds.</p><p><a href="http://www.viva64.com/en/d/0092/">V503</a> This is a nonsensical comparison: pointer &gt;= 0. geom_vinum_plex.c 173</p><pre>gv_plex_offset(...., int *sdno, int growing)<br>{<br>  ....<br>  *sdno = stripeno % sdcount;<br>  ....<br>  KASSERT(sdno &gt;= 0, (&quot;gv_plex_offset: sdno &lt; 0&quot;));<br>  ....<br>}</pre><p>We managed to detect a very interesting fragment with the help of diagnostic 503. There is no point in checking that the pointer is greater than or equal to 0. Most likely, the pointer “sdno” was not dereferenced in order to compare the stored value.</p><p>There are two more comparisons with null.</p><ul><li>V503 This is a nonsensical comparison: pointer &gt;= 0. geom_vinum_raid5.c 602</li><li>V503 This is a nonsensical comparison: pointer &gt;= 0. geom_vinum_raid5.c 610</li></ul><p><a href="http://www.viva64.com/en/d/0111/">V522</a> Dereferencing of the null pointer ‘sc’ might take place. mrsas.c 4027</p><pre>void<br>mrsas_aen_handler(struct mrsas_softc *sc)<br>{<br>  ....<br>  if (!sc) {<br>    device_printf(sc-&gt;mrsas_dev, &quot;invalid instance!\n&quot;);<br>    return;<br>  }<br>  if (sc-&gt;evt_detail_mem) {<br>  ....<br>}</pre><p>If the pointer “sc” is a null one, then the function will exit. However, it’s not quite clear, why the programmer tried to dereference the “sc-&gt;mrsas_dev” pointer.</p><p>A list of strange fragments:</p><ul><li>V522 Dereferencing of the null pointer ‘sc’ might take place. mrsas.c 1279</li><li>V522 Dereferencing of the null pointer ‘sc’ might take place. tws_cam.c 1066</li><li>V522 Dereferencing of the null pointer ‘sc’ might take place. blkfront.c 677</li><li>V522 Dereferencing of the null pointer ‘dev_priv’ might take place. radeon_cs.c 153</li><li>V522 Dereferencing of the null pointer ‘ha’ might take place. ql_isr.c 728</li></ul><p><a href="http://www.viva64.com/en/d/0354/">V713</a> The pointer m was utilized in the logical expression before it was verified against nullptr in the same logical expression. ip_fastfwd.c 245</p><pre>struct mbuf *<br>ip_tryforward(struct mbuf *m)<br>{<br>  ....<br>  if (pfil_run_hooks(<br>      &amp;V_inet_pfil_hook, &amp;m, m-&gt;m_pkthdr.rcvif, PFIL_IN, NULL) ||<br>      m == NULL)<br>    goto drop;<br>  ....<br>}</pre><p>The check “m == NULL” is placed incorrectly. First we need to check the pointer, and only then call the pfil_run_hooks() function.</p><h4>Loops</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*Q2iRWqzQgAidQZhJ.png" /></figure><p><a href="http://www.viva64.com/en/d/0238/">V621</a> Consider inspecting the ‘for’ operator. It’s possible that the loop will be executed incorrectly or won’t be executed at all. if_ae.c 1663</p><pre>#define  AE_IDLE_TIMEOUT    100</pre><pre>static void<br>ae_stop_rxmac(ae_softc_t *sc)<br>{<br>  int i;<br>  ....<br>  /*<br>   * Wait for IDLE state.<br>   */<br>  for (i = 0; i &lt; AE_IDLE_TIMEOUT; i--) {  // &lt;=<br>    val = AE_READ_4(sc, AE_IDLE_REG);<br>    if ((val &amp; (AE_IDLE_RXMAC | AE_IDLE_DMAWRITE)) == 0)<br>      break;<br>    DELAY(100);<br>  }<br>  ....<br>}</pre><p>In the source code of FreeBSD we found such an interesting and incorrect loop. For some reason, there is a decrement of a loop counter instead of an increment. It turns out that the loop can execute more times than the value of AE_IDLE_TIMEOUT, until the ‘break’ operator executes.</p><p>If the loop is not stopped, then we’ll have the overflow of a signed variable ‘i’. Signed variable overflow is nothing but a undefined behavior. And it’s not some abstract theoretical danger, it is very real. Recently, my colleague wrote an article on this topic: <a href="http://www.viva64.com/en/b/0374/">Undefined behavior is closer than you think</a></p><p>One more interesting moment. We <a href="http://www.viva64.com/en/b/0317/">detected</a> the same error in the code of Haiku operating system (see the section “Warnings #17, #18”) No idea, who borrowed the “if_ae.c” file, but this error appears after Copy-Paste.</p><p><a href="http://www.viva64.com/en/d/0124/">V535</a> The variable ‘i’ is being used for this loop and for the outer loop. Check lines: 182, 183. mfi_tbolt.c 183</p><pre>mfi_tbolt_adp_reset(struct mfi_softc *sc)<br>{<br>  ....<br>  for (i=0; i &lt; 10; i++) {<br>    for (i = 0; i &lt; 10000; i++);<br>  }<br>  ....<br>}</pre><p>Probably, this small piece of code is used for creating the delay, but in sum total only 10000 operations are executed, not 10*10000; why then 2 loops are needed here?</p><p>I specifically cited this example because it is the most vivid to show that the usage of the same variable in the external and nested loops leads to unexpected results.</p><p><a href="http://www.viva64.com/en/d/0124/">V535</a> The variable ‘i’ is being used for this loop and for the outer loop. Check lines: 197, 208. linux_vdso.c 208</p><pre>void<br>__elfN(linux_vdso_reloc)(struct sysentvec *sv, long vdso_adjust)<br>{<br>  ....<br>  for(i = 0; i &lt; ehdr-&gt;e_shnum; i++) {                      // &lt;=<br>    if (!(shdr[i].sh_flags &amp; SHF_ALLOC))<br>      continue;<br>    shdr[i].sh_addr += vdso_adjust;<br>    if (shdr[i].sh_type != SHT_SYMTAB &amp;&amp;<br>        shdr[i].sh_type != SHT_DYNSYM)<br>      continue;</pre><pre>    sym = (Elf_Sym *)((caddr_t)ehdr + shdr[i].sh_offset);<br>    symcnt = shdr[i].sh_size / sizeof(*sym);</pre><pre>    for(i = 0; i &lt; symcnt; i++, sym++) {                    // &lt;=<br>      if (sym-&gt;st_shndx == SHN_UNDEF ||<br>          sym-&gt;st_shndx == SHN_ABS)<br>        continue;<br>      sym-&gt;st_value += vdso_adjust;<br>    }<br>  }<br>  ....<br>}</pre><p>This is probably a too complicated example to understand if the code executes correctly. But looking at the previous example we can draw a conclusion that a wrong number of iterations is executed here as well.</p><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression ‘j &gt;= 0’ is always true. Unsigned type value is always &gt;= 0. safe.c 1596</p><pre>static void<br>safe_mcopy(struct mbuf *srcm, struct mbuf *dstm, u_int offset)<br>{<br>  u_int j, dlen, slen;                   // &lt;=<br>  caddr_t dptr, sptr;</pre><pre>  /*<br>   * Advance src and dst to offset.<br>   */<br>  j = offset;<br>  while (j &gt;= 0) {                       // &lt;=<br>    if (srcm-&gt;m_len &gt; j)<br>      break;<br>    j -= srcm-&gt;m_len;                    // &lt;=<br>    srcm = srcm-&gt;m_next;<br>    if (srcm == NULL)<br>      return;<br>  }<br>  sptr = mtod(srcm, caddr_t) + j;<br>  slen = srcm-&gt;m_len - j;</pre><pre>  j = offset;<br>  while (j &gt;= 0) {                       // &lt;=<br>    if (dstm-&gt;m_len &gt; j)<br>      break;<br>    j -= dstm-&gt;m_len;                    // &lt;=<br>    dstm = dstm-&gt;m_next;<br>    if (dstm == NULL)<br>      return;<br>  }<br>  dptr = mtod(dstm, caddr_t) + j;<br>  dlen = dstm-&gt;m_len - j;<br>  ....<br>}</pre><p>There are two dangerous loops in this function. As the ‘j’ variable (loop counters) has an unsigned type, then the “j &gt;= 0” check is always true and these loops are “infinity”. Another problem is that some value is constantly subtracted from this counter; therefore if there is an attempt to access beyond the zero value, then the ‘j’ variable will get the maximum value of its type.</p><p><a href="http://www.viva64.com/en/d/0352/">V711</a> It is dangerous to create a local variable within a loop with a same name as a variable controlling this loop. powernow.c 73</p><pre>static int<br>pn_decode_pst(device_t dev)<br>{<br>  ....<br>  struct pst_header *pst;                                   // &lt;=<br>  ....<br>  p = ((uint8_t *) psb) + sizeof(struct psb_header);<br>  pst = (struct pst_header*) p;</pre><pre>  maxpst = 200;</pre><pre>  do {<br>    struct pst_header *pst = (struct pst_header*) p;        // &lt;=</pre><pre>    ....</pre><pre>    p += sizeof(struct pst_header) + (2 * pst-&gt;numpstates);<br>  } while (cpuid_is_k7(pst-&gt;cpuid) &amp;&amp; maxpst--);            // &lt;=<br>  ....<br>}</pre><p>In the body of the loop we detected variable declaration was that matches the variable used for the loop control. I suspect that the value of the external pointer with the ‘pst’ name doesn’t change because a local pointer with the same ‘pst’ is created. Perhaps the same “pst-&gt;cupid” value is always checked in the loop condition do….while(). The developers should review this fragment and give the variables different names.</p><h4>Miscelleneous</h4><p><a href="http://www.viva64.com/en/d/0164/">V569</a> Truncation of constant value -96. The value range of unsigned char type: [0, 255]. if_rsu.c 1516</p><pre>struct ieee80211_rx_stats {<br>  ....<br>  uint8_t nf;      /* global NF */<br>  uint8_t rssi;    /* global RSSI */<br>  ....<br>};</pre><pre>static void<br>rsu_event_survey(struct rsu_softc *sc, uint8_t *buf, int len)<br>{<br>  ....<br>  rxs.rssi = le32toh(bss-&gt;rssi) / 2;<br>  rxs.nf = -96;<br>  ....<br>}</pre><p>It’s very strange that an unsigned variable “rxs.nf” is assigned with a negative value ‘-96’ As a result, the variable will have the value ‘160’.</p><p><a href="http://www.viva64.com/en/d/0376/">V729</a> Function body contains the ‘done’ label that is not used by any ‘goto’ statements. zfs_acl.c 2023</p><pre>int<br>zfs_setacl(znode_t *zp, vsecattr_t *vsecp, ....)<br>{<br>  ....<br>top:<br>  mutex_enter(&amp;zp-&gt;z_acl_lock);<br>  mutex_enter(&amp;zp-&gt;z_lock);<br>  ....<br>  if (error == ERESTART) {<br>    dmu_tx_wait(tx);<br>    dmu_tx_abort(tx);<br>    goto top;<br>  }<br>  ....<br>done:                            // &lt;=<br>  mutex_exit(&amp;zp-&gt;z_lock);<br>  mutex_exit(&amp;zp-&gt;z_acl_lock);</pre><pre>  return (error);<br>}</pre><p>In this code there are functions containing labels, but at the same time, the call of the ‘goto’ statement is missing for these labels. For example, we see that the ‘top’ label is used in this fragment, but ‘done’ isn’t used anywhere. Perhaps the programmer forgot to add a jump to the label, or it was removed over the time, while the label was left in the code.</p><p><a href="http://www.viva64.com/en/d/0265/">V646</a> Consider inspecting the application’s logic. It’s possible that ‘else’ keyword is missing. mac_process.c 352</p><pre>static void<br>mac_proc_vm_revoke_recurse(struct thread *td, struct ucred *cred,<br>    struct vm_map *map)<br>{<br>  ....<br>  if (!mac_mmap_revocation_via_cow) {<br>    vme-&gt;max_protection &amp;= ~VM_PROT_WRITE;<br>    vme-&gt;protection &amp;= ~VM_PROT_WRITE;<br>  } if ((revokeperms &amp; VM_PROT_READ) == 0)   // &lt;=<br>    vme-&gt;eflags |= MAP_ENTRY_COW |<br>        MAP_ENTRY_NEEDS_COPY;<br>  ....<br>}</pre><p>Finally, I want to tell you about suspicious formatting, which I already came across in the very beginning of the project check. Here the code is aligned in such a way that the absence of the keyword ‘else’ looks strange.</p><p><a href="http://www.viva64.com/en/d/0344/">V705</a> It is possible that ‘else’ block was forgotten or commented out, thus altering the program’s operation logics. scsi_da.c 3231</p><pre>static void<br>dadone(struct cam_periph *periph, union ccb *done_ccb)<br>{<br>  ....<br>  /*<br>   * If we tried READ CAPACITY(16) and failed,<br>   * fallback to READ CAPACITY(10).<br>   */<br>  if ((state == DA_CCB_PROBE_RC16) &amp;&amp;<br>    ....<br>  } else                                                    // &lt;=<br>  /*<br>   * Attach to anything that claims to be a<br>   * direct access or optical disk device,<br>   * as long as it doesn&#39;t return a &quot;Logical<br>   * unit not supported&quot; (0x25) error.<br>   */<br>  if ((have_sense) &amp;&amp; (asc != 0x25)                         // &lt;=<br>    ....<br>  } else { <br>    ....<br>  }<br>  ....<br>}</pre><p>This code has no error now, but it will definitely show up one day. By leaving such a big commentary before ‘else’ you may accidentally forget that this keyword was somewhere in the code and make some erroneous edits.</p><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*yfa9w3qxkz7QJ_Fn.png" /></figure><p>The FreeBSD project was tested by special version of PVS-Studio, which showed a great result! The whole material is impossible to fit in one article. Nevertheless, the development team of FreeBSD got the full list of the analyzer warnings that should be examined.</p><p>I suggest everyone to try <a href="http://www.viva64.com/en/pvs-studio/">PVS-Studio</a> on your projects. The analyzer works in Windows environment. We don’t have a public version for using the analyzer in the development of the projects for Linux/FreeBSD. We could also discuss possible variants of customization PVS-Studio for your projects and specific tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcfe45dfac67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Why is there no artificial intelligence yet?”]]></title>
            <link>https://medium.com/@viva64articles/why-is-there-no-artificial-intelligence-yet-47c684425f04?source=rss-67b72a9416b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/47c684425f04</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Love C&C++]]></dc:creator>
            <pubDate>Tue, 02 Feb 2016 11:42:11 GMT</pubDate>
            <atom:updated>2016-02-02T11:42:11.215Z</atom:updated>
            <content:encoded><![CDATA[<h3>“Why is there no artificial intelligence yet?” Or, analysis of CNTK tool kit from Microsoft Research</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*UEhR_N3RVrR20sdP.png" /></figure><p>Microsoft have given open access to the source code of a tool kit that is used in the company to speed up the development of artificial intelligence: Computational Network Toolkit is now available at Github. The developers had to create their own custom solution, because the existing tools did not work fast enough. <br>Let’s have a look at the analysis results of the source code of this project, as done by our static code analyzer.</p><h3>Introduction</h3><p><a href="https://github.com/Microsoft/CNTK">Computational Network Toolkit</a> (CNTK) is a set of tools for designing and projecting nets of different types, that can be used for image detection, speech recognition, text analysis, and much more.</p><p><a href="http://www.viva64.com/en/pvs-studio/">PVS-Studio</a> is a static analyzer for bug detection in the source code of programs, written in C, C++ and C#. The PVS-Studio tool is made for developers of contemporary applications, and integrates into the Visual Studio environments of 2010–2015.</p><p>Preparing an article on an <a href="http://www.viva64.com/en/a/0084/">open source project</a> check, we can only report , of course, on a limited number of all warnings issued by the analyzer, therefore we recommend the authors of the project run the analyzer on their code themselves, and study the complete analysis results. We also provide developers of open source projects with a temporary key.</p><p>I should say right away that there weren’t many bugs found, which was as expected. Having checked several Microsoft projects, we can say that their code really is of very high quality. But we shouldn’t <a href="http://www.viva64.com/en/b/0105/">forget</a> that the benefit of a static code analyzer is in its regular use, not random checks.</p><h3>Those misprints…</h3><p>Typos are a very unpleasant thing. They’ve penetrated social networks, books, online publications, and even TV. In simple texts they can be eliminated by means of the spell check functions in text editors; in programming it can be done with the help of static code analyzers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*mNlwo4xo0YpV19Y8.png" /></figure><p><a href="http://www.viva64.com/en/d/0090/">V501</a> There are identical sub-expressions ‘!Input(0)-&gt;HasMBLayout()’ to the left and to the right of the ‘||’ operator. trainingnodes.h 1416</p><pre>virtual void Validate(bool isFinalValidationPass) override<br>{<br>  ....<br>  if (isFinalValidationPass &amp;&amp;<br>      !(Input(0)-&gt;GetSampleMatrixNumRows() ==<br>        Input(2)-&gt;GetSampleMatrixNumRows() &amp;&amp;<br>       (Input(0)-&gt;GetMBLayout() ==<br>        Input(2)-&gt;GetMBLayout() ||<br>       !Input(0)-&gt;HasMBLayout() ||            // &lt;=<br>       !Input(0)-&gt;HasMBLayout())))            // &lt;=<br>  {<br>    LogicError(..., NodeName().c_str(),OperationName().c_str());<br>  }<br>   ....<br>}</pre><p>Formatting of this fragment is modified for clarity. Only after that it became apparent that there are two similar “! Input (0)-&gt; HasMBLayout () “checks in the condition. Most likely, it is impossible to use an element with index ‘2’ in one of the cases.</p><p><a href="http://www.viva64.com/en/d/0090/">V501</a> There are identical sub-expressions to the left and to the right of the ‘-’ operator: i0 — i0 ssematrix.h 564</p><pre>void assignpatch(const ssematrixbase &amp;patch,<br>                 const size_t i0,<br>                 const size_t i1,<br>                 const size_t j0,<br>                 const size_t j1)<br>{<br>  ....<br>  for (size_t j = j0; j &lt; j1; j++)<br>  {<br>    const float *pcol = &amp;patch(i0 - i0, j - j0);      // &lt;=<br>    float *qcol = &amp;us(i0, j);<br>    const size_t colbytes = (i1 - i0) * sizeof(*pcol);<br>    memcpy(qcol, pcol, colbytes);<br>  }<br>  ....<br>}</pre><p>Because of the misprint, the condition “i0-i0” is always equal to zero. Perhaps “i1-i0” or “j-i1” or something else was meant here. Developers should definitely recheck this place.</p><p><a href="http://www.viva64.com/en/d/0206/">V596</a> The object was created but it is not being used. The ‘throw’ keyword could be missing: throw runtime_error(FOO); simplenetworkbuilder.cpp 1578</p><pre>template &lt;class ElemType&gt;<br>ComputationNetworkPtr SimpleNetworkBuilder&lt;ElemType&gt;::<br>  BuildNetworkFromDbnFile(const std::wstring&amp; dbnModelFileName)<br>{<br>  ....<br>  if (this-&gt;m_outputLayerSize &gt;= 0)<br>    outputLayerSize = this-&gt;m_outputLayerSize;<br>  else if (m_layerSizes.size() &gt; 0)<br>    m_layerSizes[m_layerSizes.size() - 1];<br>  else<br>    std::runtime_error(&quot;Output layer size must be...&quot;);     // &lt;=<br>  ....<br>}</pre><p>The error, is that the keyword ‘throw’ was accidentally forgotten. As a result, this code does not generate an exception in case of an error. The correct code variant should be:</p><pre>....<br>else<br>  throw std::runtime_error(&quot;Output layer size must be...&quot;);<br>....</pre><h3>Working with files</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*G0g6qHP72OYb3CEj.png" /></figure><p>V739 EOF should not be compared with a value of the ‘char’ type. The ‘c’ should be of the ‘int’ type. fileutil.cpp 852</p><pre>string fgetstring(FILE* f)<br>{<br>  string res;<br>  for (;;)<br>  {<br>    char c = (char) fgetc(f);        // &lt;=<br>    if (c == EOF)                    // &lt;=<br>      RuntimeError(&quot;error reading .... 0: %s&quot;, strerror(errno));<br>    if (c == 0)<br>      break;<br>    res.push_back(c);<br>  }<br>  return res;<br>}</pre><p>The analyzer detected that the EOF constant is compared with a variable of ‘char’ type. This shows that some symbols will be processed incorrectly.</p><p>Let’s look at the way EOF is declared:</p><pre>#define EOF (-1)</pre><p>As you can see, the EOF is nothing more than ‘-1 ‘ of ‘int’ type. Fgetc() function returns a value of ‘int’ type. Specifically, it can return a number from 0 to 255 or -1 (EOF). The values read are placed into a variable of ‘char’ type. Because of this, a symbol with the 0xFF (255) value turns into -1, and then handled in the same way as the file end (EOF).</p><p>Users that use <a href="https://en.wikipedia.org/wiki/Extended_ASCII">Extended ASCII Codes</a>, may encounter an error when one of the symbols of their alphabet is handled incorrectly by the program.</p><p>For example in the <a href="https://en.wikipedia.org/wiki/Windows-1251">Windows 1251</a> code page, the last letter of Russian alphabet has the 0xFF code, and so is interpreted by the program as the end-of-file character.</p><p>Correct code fragment:</p><pre>int c = fgetc(f);<br>if (c == EOF)<br>  RuntimeError(....);</pre><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression ‘val[0] == 0xEF’ is always false. The value range of char type: [-128, 127]. file.cpp 462</p><pre>bool File::IsUnicodeBOM(bool skip)<br>{<br>  ....<br>  else if (m_options &amp; fileOptionsText)<br>  {<br>    char val[3];<br>    file.ReadString(val, 3);<br>    found = (val[0] == 0xEF &amp;&amp; val[1] == 0xBB &amp;&amp; val[2] == 0xBF);<br>  }<br>  // restore pointer if no BOM or we aren&#39;t skipping it<br>  if (!found || !skip)<br>  {<br>    SetPosition(pos);<br>  }<br>  ....<br>}</pre><p>By default the ‘char’ type has a range of values equal to [-127;127]. Using the compilation flag /J, we can specify to the compiler to use the range [0; 255]. But there is no such flag for this source file, and so this code will never determine that this file contains <a href="https://en.wikipedia.org/wiki/Byte_order_mark">BOM</a>.</p><h3>Working with memory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*9MvYPEZ4M9fAa3LT.png" /></figure><p><a href="http://www.viva64.com/en/d/0205/">V595</a> The ‘m_rowIndices’ pointer was utilized before it was verified against nullptr. Check lines: 171, 175. libsvmbinaryreader.cpp 171</p><pre>template &lt;class ElemType&gt;<br>void SparseBinaryMatrix&lt;ElemType&gt;::ResizeArrays(size_t newNNz)<br>{<br>  ....<br>  if (m_nnz &gt; 0)<br>  {<br>    memcpy(rowIndices, m_rowIndices, sizeof(int32_t)....);  // &lt;=<br>    memcpy(values, this-&gt;m_values, sizeof(ElemType)....);   // &lt;=<br>  }</pre><pre>  if (m_rowIndices != nullptr)<br>  {<br>    // free(m_rowIndices);<br>    CUDAPageLockedMemAllocator::Free(this-&gt;m_rowIndices, ....);<br>  }<br>  if (this-&gt;m_values != nullptr)<br>  {<br>    // free(this-&gt;m_values);<br>    CUDAPageLockedMemAllocator::Free(this-&gt;m_values, ....);<br>  }<br>  ....<br>}</pre><p>The analyzer detected integer dereference of a null pointer. <br>If there is a comparison with null in the code, when at an earlier time this pointer was used without a check, then this code is suspicious, and so, could be dangerous.</p><p>The memcpy() function copies the bytes located at “m_rowIndices” and “m_values”, at the same time there is dereference of this pointer and in the given code it can potentially be equal to zero.</p><p><a href="http://www.viva64.com/en/d/0099/">V510</a> The ‘sprintf_s’ function is not expected to receive class-type variable as third actual argument. binaryfile.cpp 501</p><pre>const std::wstring&amp; GetName()<br>{<br>  return m_name;<br>}</pre><pre>Section* Section::ReadSection(....)<br>{<br>  ....<br>  char message[256];<br>  sprintf_s(message,&quot;Invalid header in file %ls, in header %s\n&quot;,<br>              m_file-&gt;GetName(), section-&gt;GetName());       // &lt;=<br>  RuntimeError(message);<br>  ....<br>}</pre><p>Only POD types can serve as actual parameters of sprint_s() function. POD is an abbreviation of “Plain Old Data”, which can be interpreted as “Simple data in C style”.</p><p>“std::wstring” doesn’t belong to POD types. Instead of a pointer, the content of the object will go to the stack. This code will lead to some rubbish in the buffer or a program crash.</p><p>Correct variant:</p><pre>sprintf_s(message,&quot;Invalid header in file %ls, in header %s\n&quot;,<br>          m_file-&gt;GetName().c_str(), section-&gt;GetName().c_str());</pre><p><a href="http://www.viva64.com/en/d/0247/">V630</a> The ‘malloc’ function is used to allocate memory for an array of objects which are classes containing constructors. latticeforwardbackward.cpp 912</p><pre>void lattice::forwardbackwardalign()<br>{<br>  ....<br>  aligninfo *refinfo;<br>  unsigned short *refalign;</pre><pre>  refinfo = (aligninfo *) malloc(sizeof(aligninfo) * 1);    // &lt;=<br>  refalign = (unsigned short *) malloc(sizeof(....) * framenum);</pre><pre>  array_ref&lt;aligninfo&gt; refunits(refinfo, 1);<br>  array_ref&lt;unsigned short&gt; refedgealignmentsj(....);<br>  ....<br>}</pre><p>In this code fragment, the analyzer detected an incorrect allocation of dynamic memory for a structure of “aligninfo” type. The thing here, is that there are constructors in the structure definition, but the constructor won’t be called with this method of memory allocation. Also the destructor won’t be called during the freeing of the memory with the help of free() function.</p><p>Here you can see a code fragment with the description of “aligninfo” type.</p><pre>struct aligninfo // phonetic alignment<br>{<br>  unsigned int unit : 19;   // triphone index<br>  unsigned int frames : 11; // duration in frames<br>  unsigned int unused : 1; // (for future use)<br>  unsigned int last : 1;   // set for last entry<br>  aligninfo(size_t punit, size_t pframes)<br>      : unit((unsigned int) punit),<br>        frames((unsigned int) pframes), unused(0), last(0)<br>  {<br>    checkoverflow(unit, punit, &quot;aligninfo::unit&quot;);<br>    checkoverflow(frames, pframes, &quot;aligninfo::frames&quot;);<br>  }<br>  aligninfo() // [v-hansu] initialize to impossible values<br>  {<br>#ifdef INITIAL_STRANGE<br>    unit = unsigned int(-1);<br>    frames = unsigned int(-1);<br>    unused = unsigned int(-1);<br>    last = unsigned int(-1);<br>#endif<br>  }<br>  template &lt;class IDMAP&gt;<br>  void updateunit(const IDMAP&amp; idmap /*[unit] -&gt; new unit*/)<br>  {<br>    const size_t mappedunit = idmap[unit];<br>    unit = (unsigned int) mappedunit;<br>    checkoverflow(unit, mappedunit, &quot;aligninfo::unit&quot;);<br>  }<br>};</pre><p>Correct variant:</p><pre>aligninfo *refinfo = new aligninfo();</pre><p>And of course, you will need to call the ‘delete’ operator to free the memory.</p><p><a href="http://www.viva64.com/en/d/0210/">V599</a> The virtual destructor is not present, although the ‘IDataWriter’ class contains virtual functions. datawriter.cpp 47</p><pre>IDataWriter&lt;ElemType&gt;* m_dataWriter;<br>....<br>template &lt;class ElemType&gt;<br>void DataWriter&lt;ElemType&gt;::Destroy()<br>{<br>    delete m_dataWriter; // &lt;= V599 warning<br>    m_dataWriter = NULL;<br>}</pre><p>The analyzer warning shows that a base type of the object to be destroyed has no virtual destructor. In this case the destruction of the object of the derived class will cause undefined behavior of the program. In practice this can lead to memory leaks, and to a situation wherein other resources will not be released. Let’s try to understand what caused this warning to appear.</p><pre>template &lt;class ElemType&gt;<br>class DATAWRITER_API IDataWriter<br>{<br>public:<br>    typedef std::string LabelType;<br>    typedef unsigned int LabelIdType;</pre><pre>    virtual void Init(....) = 0;<br>    virtual void Init(....) = 0;<br>    virtual void Destroy() = 0;<br>    virtual void GetSections(....) = 0;<br>    virtual bool SaveData(....) = 0;<br>    virtual void SaveMapping(....) = 0;<br>};</pre><p>This is a definition of a base class, as we can see, it has virtual functions, but a virtual destructor is missing.</p><pre>m_dataWriter = new HTKMLFWriter&lt;ElemType&gt;();</pre><p>Thus the memory is allocated for the object of the derived class “HTKMLFWriter”. It’s description:</p><pre>template &lt;class ElemType&gt;<br>class HTKMLFWriter : public IDataWriter&lt;ElemType&gt;<br>{<br>private:<br>    std::vector&lt;size_t&gt; outputDims;<br>    std::vector&lt;std::vector&lt;std::wstring&gt;&gt; outputFiles;</pre><pre>    std::vector&lt;size_t&gt; udims;<br>    std::map&lt;std::wstring, size_t&gt; outputNameToIdMap;<br>    std::map&lt;std::wstring, size_t&gt; outputNameToDimMap;<br>    std::map&lt;std::wstring, size_t&gt; outputNameToTypeMap;<br>    unsigned int sampPeriod;<br>    size_t outputFileIndex;<br>    void Save(std::wstring&amp; outputFile, ....);<br>    ElemType* m_tempArray;<br>    size_t m_tempArraySize;<br>    ....<br>};</pre><p>Due to the missing virtual destructor in the base class, this object will not be properly destroyed. For outputDims, outputFiles objects the destructors will also not be called. However, in general it is impossible to predict all the aftereffects, this is why we use the term “undefined behavior”.</p><h3>Miscellaneous errors.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*FNlB0K97yHC9vSLt.png" /></figure><p><a href="http://www.viva64.com/en/d/0091/">V502</a> Perhaps the ‘?:’ operator works in a different way than it was expected. The ‘?:’ operator has a lower priority than the ‘|’ operator. sequenceparser.h 338</p><pre>enum SequenceFlags<br>{<br>    seqFlagNull = 0,<br>    seqFlagLineBreak = 1, // line break on the parsed line<br>    seqFlagEmptyLine = 2, // empty line<br>    seqFlagStartLabel = 4,<br>    seqFlagStopLabel = 8<br>};</pre><pre>long Parse(....)<br>{<br>  ....<br>  // sequence state machine variables<br>  bool m_beginSequence;<br>  bool m_endSequence;<br>  ....<br>  if (seqPos)<br>  {<br>    SequencePosition sequencePos(numbers-&gt;size(), labels-&gt;size(),<br>      m_beginSequence ? seqFlagStartLabel : 0 | m_endSequence ?<br>      seqFlagStopLabel : 0 | seqFlagLineBreak);<br>    // add a sequence element to the list<br>    seqPos-&gt;push_back(sequencePos);<br>    sequencePositionLast = sequencePos;<br>  }<br>  <br>  // end of sequence determines record separation<br>  if (m_endSequence)<br>      recordCount = (long) labels-&gt;size();<br>  ....<br>}</pre><p>The priority of a ternary operator ‘:?’ is lower than of a bitwise OR ‘|’ operator. Lets’ have a closer look at the fragment containing an error:</p><pre>0 | m_endSequence ? seqFlagStopLabel : 0 | seqFlagLineBreak</pre><p>It is expected that only bitwise operations with specified flags will be executed, however, because of an unexpected execution order, “0 | m_endSequence” will be executed first, instead of “m_endSequence ? seqFlagStopLabel : 0 | seqFlagLineBreak”.</p><p>In fact, this is an interesting case. In spite of the error, the code works correctly. Bitwise OR with 0 doesn’t affect anything. <br>Nevertheless, it is better to correct the error.</p><p>There are two more similar fragments:</p><ul><li>V502 Perhaps the ‘?:’ operator works in a different way than it was expected. The ‘?:’ operator has a lower priority than the ‘|’ operator. sequenceparser.h 433</li><li>V502 Perhaps the ‘?:’ operator works in a different way than it was expected. The ‘?:’ operator has a lower priority than the ‘|’ operator. sequenceparser.h 598</li></ul><p><a href="http://www.viva64.com/en/d/0119/">V530</a> The return value of function ‘size’ is required to be utilized. basics.h 428</p><pre>// TODO: merge this with todouble(const char*) above<br>static inline double todouble(const std::string&amp; s)<br>{<br>  s.size(); // just used to remove the unreferenced warning</pre><pre>  double value = 0.0;<br>  ....<br>}</pre><p>There is no error here, which we can see in the comment, but this example is given here for two reasons:</p><p>Firstly, to disable a compiler warning, there is an UNREFERENCED_PARAMETER macro, whose name makes it clear that the parameter of the function is not used deliberately:</p><pre>#define UNREFERENCED_PARAMETER(P) (P)</pre><pre>static inline double todouble(const std::string&amp; s)<br>{<br>  UNREFERENCED_PARAMETER(s);<br>  ....<br>}</pre><p>Secondly, we would like to show another compiler warning that most likely indicates an error.</p><p><a href="http://www.viva64.com/en/d/0119/">V530</a> The return value of function ‘empty’ is required to be utilized. utterancesourcemulti.h 340</p><pre>template &lt;class UTTREF&gt;<br>std::vector&lt;shiftedvector&lt;....&gt;&gt;getclassids(const UTTREF &amp;uttref)<br>{<br>  std::vector&lt;shiftedvector&lt;....&gt;&gt; allclassids;<br>  allclassids.empty();  // &lt;=<br>  ....<br>}</pre><p>There is no point in non-use of the result of the empty() function.</p><p>Perhaps the vector was to be cleared with the clear() function.</p><p>A similar fragment:</p><ul><li>V530 The return value of function ‘empty’ is required to be utilized. utterancesourcemulti.h 364</li></ul><p><a href="http://www.viva64.com/en/d/0322/">V688</a> The ‘m_file’ local variable possesses the same name as one of the class members, which can result in confusion. sequencereader.cpp 552</p><pre>template &lt;class ElemType&gt;<br>class SequenceReader : public IDataReader&lt;ElemType&gt;<br>{<br>protected:<br>  bool m_idx2clsRead;<br>  bool m_clsinfoRead;</pre><pre>  bool m_idx2probRead;<br>  std::wstring m_file;                               // &lt;=<br>  ....<br>}</pre><pre>template &lt;class ElemType&gt;<br>template &lt;class ConfigRecordType&gt;<br>void SequenceReader&lt;ElemType&gt;::InitFromConfig(....)<br>{<br>  ....<br>  std::wstring m_file = readerConfig(L&quot;file&quot;);       // &lt;=<br>  if (m_traceLevel &gt; 0)<br>  {<br>    fprintf(stderr, &quot;....&quot;, m_file.c_str());</pre><pre>  }<br>  ....<br>}</pre><p>Using variables of the same name in the class, class functions, and class parameters, is a very bad programming style. For instance: was the variable declaration “std::wstring m_file = readerConfig(L”file”);” supposed to be here, or was it added temporarily for debugging and then, was left forgotten?</p><p>Developers should also review the following fragments:</p><ul><li>V688 The ‘m_file’ local variable possesses the same name as one of the class members, which can result in a confusion. sequencereader.cpp 1554</li><li>V688 The ‘m_mbStartSample’ function argument possesses the same name as one of the class members, which can result in a confusion. sequencereader.cpp 2062</li><li>V688 The ‘m_file’ local variable possesses the same name as one of the class members, which can result in a confusion. lusequencereader.cpp 417</li></ul><h3>Conclusion:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*Z8qvgErIy3gMAw5l.png" /></figure><p>Computational Network Toolkit (CNTK), being a relatively small project, turned out to be a pretty interesting piece of software. As the CNTK project has just recently been made open, we are looking forward to seeing new ideas for its usage, and of course, other open source projects by Microsoft.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47c684425f04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ChakraCore: analysis of JavaScript-engine for Microsoft Edge]]></title>
            <link>https://medium.com/@viva64articles/chakracore-analysis-of-javascript-engine-for-microsoft-edge-d774e2563b8e?source=rss-67b72a9416b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d774e2563b8e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Love C&C++]]></dc:creator>
            <pubDate>Fri, 22 Jan 2016 11:36:48 GMT</pubDate>
            <atom:updated>2016-01-22T11:36:48.756Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*0hmryFTBU5BCcF98.png" /></figure><p>On the JSConf US conference in December 2015 the developers announced that they were planning to make open the source code of Chakra key components, a JavaScript-engine, operating in Microsoft Edge. Recently the ChackraCore source code became available under the MIT license in the corresponding repository on GitHub. In this article you will find interesting code fragments that were detected with the help of PVS-Studio code analyzer.</p><h4>Introduction</h4><p><a href="https://github.com/Microsoft/ChakraCore">ChakraCore</a> is the core part of Chakra, the high-performance JavaScript engine that powers Microsoft Edge and Windows applications written in HTML/CSS/JS. ChakraCore supports Just-in-time (JIT) compilation of JavaScript for x86/x64/ARM, garbage collection, and a wide range of the latest JavaScript features.</p><p><a href="http://www.viva64.com/en/pvs-studio/">PVS-Studio</a> is a static analyzer for bug detection in the source code of programs, written in C, C++ and C#. PVS-Studio tool is designed for developers of contemporary applications and integrates into the Visual Studio environments of 2010–2015.</p><p>In an article on an <a href="http://www.viva64.com/en/a/0084/">open source project</a> check, we report only about a limited number of all of the warnings issued by the analyzer, therefore we recommend the authors of the project to run the analyzer on their code themselves and study complete analysis results. We also provide developers of open source projects with a temporary key.</p><h4>Various errors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*B4QemjVf-bjQKQzq.png" /></figure><p><a href="http://www.viva64.com/en/d/0090/">V501</a> There are identical sub-expressions ‘this-&gt;propId == Js::PropertyIds::_superReferenceSymbol’ to the left and to the right of the ‘||’ operator. diagobjectmodel.cpp 123</p><pre>IDiagObjectModelDisplay * ResolvedObject::CreateDisplay()<br>{<br> ....<br>  if (this-&gt;isConst ||<br>    this-&gt;propId == Js::PropertyIds::_superReferenceSymbol ||<br>    this-&gt;propId == Js::PropertyIds::_superReferenceSymbol)<br>  {<br>      pOMDisplay-&gt;SetDefaultTypeAttribute(....);<br>  }<br>  ....<br>}</pre><p>There two similar checks in the condition. Probably, while writing the code, a programmer accidentally chose the same constant in the IntelliSense menu, for instance, instead of “Js::PropertyIds:: _superCtorReferenceSymbol”.</p><p><a href="http://www.viva64.com/en/d/0090/">V501</a> There are identical sub-expressions ‘GetVarSymID(srcIndexOpnd-&gt;GetStackSym())’ to the left and to the right of the ‘==’ operator. globopt.cpp 20795</p><pre>void GlobOpt::EmitMemop(....)<br>{<br>  ....<br>  IR::RegOpnd *srcBaseOpnd = nullptr;<br>  IR::RegOpnd *srcIndexOpnd = nullptr;<br>  IRType srcType;<br>  GetMemOpSrcInfo(...., srcBaseOpnd, srcIndexOpnd, srcType);<br>  Assert(GetVarSymID(srcIndexOpnd-&gt;GetStackSym()) ==        // &lt;=<br>         GetVarSymID(srcIndexOpnd-&gt;GetStackSym()));         // &lt;=<br>  ....<br>}</pre><p>Two more identical comparisons. Most likely “srcIndexOpnd-&gt;GetStackSym()” was meant to be compared with “srcBaseOpnd -&gt;GetStackSym()” .</p><p><a href="http://www.viva64.com/en/d/0090/">V517</a> The use of ‘if (A) {…} else if (A) {…}’ pattern was detected. There is a probability of logical error presence. Check lines: 3220, 3231. lower.cpp 3220</p><pre>bool Lowerer::GenerateFastBrSrEq(....,<br>                                 IR::RegOpnd * srcReg1,<br>                                 IR::RegOpnd * srcReg2,<br>                                 ....)<br>{<br>  if (srcReg2 &amp;&amp; IsConstRegOpnd(srcReg2))<br>  {<br>    ....<br>  }<br>  else if (srcReg1 &amp;&amp; IsConstRegOpnd(srcReg1))<br>  {<br>    ....<br>  }<br>  else if (srcReg2 &amp;&amp; (srcReg2-&gt;m_sym-&gt;m_isStrConst))<br>  {<br>    ....<br>  }<br>  else if (srcReg1 &amp;&amp; (srcReg1-&gt;m_sym-&gt;m_isStrConst))       // &lt;=<br>  {<br>    ....<br>  }<br>  else if (srcReg2 &amp;&amp; (srcReg2-&gt;m_sym-&gt;m_isStrEmpty))<br>  {<br>    ....<br>  }<br>  else if (srcReg1 &amp;&amp; (srcReg1-&gt;m_sym-&gt;m_isStrConst))       // &lt;=<br>  {<br>    ....<br>  }</pre><pre>  return false;<br>}</pre><p>The analyzer detected two similar checks in the cascade of conditional operators; as a result a code block in the last condition never gets control. Full code of the given example is very long and it’s hard to notice a misprint. It is a good example, showing benefits from using a static code analyzer during the work with similar code, when the programmer gets quickly tired and lets his guard down.</p><p>Most likely, last two conditions were meant to be like this:</p><pre>....<br>else if (srcReg2 &amp;&amp; (srcReg2-&gt;m_sym-&gt;m_isStrEmpty))<br>{<br>  ....<br>}<br>else if (srcReg1 &amp;&amp; (srcReg1-&gt;m_sym-&gt; m_isStrEmpty))       // &lt;=<br>{<br>  ....<br>}</pre><p><a href="http://www.viva64.com/en/d/0354/">V713</a> The pointer scriptContext was utilized in the logical expression before it was verified against nullptr in the same logical expression. diaghelpermethodwrapper.cpp 214</p><pre>template &lt;bool doCheckParentInterpreterFrame&gt;<br>void HandleHelperOrLibraryMethodWrapperException(....)<br>{<br>  ....<br>  if (!exceptionObject-&gt;IsDebuggerSkip() ||<br>    exceptionObject == scriptContext-&gt;GetThreadContext()-&gt;.... ||<br>    exceptionObject == scriptContext-&gt;GetThreadContext()-&gt;.... ||<br>    !scriptContext)    // &lt;=<br>  {<br>    throw exceptionObject-&gt;CloneIfStaticExceptionObject(....);<br>  }<br>  ....<br>}</pre><p>Dereference of “scriptContext” pointer is done before its validity is checked. It was luck that such a bug wasn’t noticed and didn’t affect the program. Such bugs can live in the code for a very long time and show up in rare atypical situations.</p><p><a href="http://www.viva64.com/en/d/0168/">V570</a> The ‘this-&gt;isInlined’ variable is assigned to itself. functioncodegenjittimedata.h 625</p><pre>void SetupRecursiveInlineeChain(<br>    Recycler *const recycler,<br>    const ProfileId profiledCallSiteId)<br>{<br>  if (!inlinees)<br>  {<br>    inlinees = RecyclerNewArrayZ(....);<br>  }<br>  inlinees[profiledCallSiteId] = this;<br>  inlineeCount++;<br>  this-&gt;isInlined = isInlined;   // &lt;=<br>}</pre><p>It’s very suspicious that the same value is stored in the ‘isInlined’ boolean variable. Most likely the programmer intended to write something else.</p><p>Here is one more fragment, where the variable is assigned to itself:</p><ul><li>V570 The ‘sym-&gt;m_isTaggableIntConst’ variable is assigned to itself. linearscan.cpp 3170</li></ul><p><a href="http://www.viva64.com/en/d/0194/">V590</a> Consider inspecting the ‘sub[i] != ‘-’ &amp;&amp; sub[i] == ‘/’’ expression. The expression is excessive or contains a misprint. rl.cpp 1388</p><pre>const char *<br>stristr<br>(<br>  const char * str,<br>  const char * sub<br>)<br>{<br>  ....<br>  for (i = 0; i &lt; len; i++)<br>  {<br>    if (tolower(str[i]) != tolower(sub[i]))<br>    {<br>      if ((str[i] != &#39;/&#39; &amp;&amp; str[i] != &#39;-&#39;) ||<br>            (sub[i] != &#39;-&#39; &amp;&amp; sub[i] == &#39;/&#39;)) {              / &lt;=<br>           // if the mismatch is not between &#39;/&#39; and &#39;-&#39;<br>           break;<br>      }<br>    }<br>  }<br>  ....<br>}</pre><p>The analyzer detected, that a part of the (sub[i] != ‘-’) conditional expression doesn’t influence the check result. To make sure, let’s have a look at the truth table. Most likely there is a misprint here; it’s hard to say how to write this code correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/0*kzAHnf6MoGGRRNc5.png" /></figure><p><a href="http://www.viva64.com/en/d/0215/">V603</a> The object was created but it is not being used. If you wish to call constructor, ‘this-&gt;StringCopyInfo::StringCopyInfo(….)’ should be used. stringcopyinfo.cpp 64</p><pre>void StringCopyInfo::InstantiateForceInlinedMembers()<br>{<br>    AnalysisAssert(false);</pre><pre>    StringCopyInfo copyInfo;<br>    JavascriptString *const string = nullptr;<br>    wchar_t *const buffer = nullptr;</pre><pre>    (StringCopyInfo());                     // &lt;=<br>    (StringCopyInfo(string, buffer));       // &lt;=<br>    copyInfo.SourceString();<br>    copyInfo.DestinationBuffer();<br>}</pre><p>Programmers often make <a href="http://www.viva64.com/en/b/0127/">mistakes</a>, trying to explicitly call the constructor to initialize the object. In this example we see new unnamed objects of “StringCopyInfo” type that get created and then immediately destroyed. As a result, the class fields are left uninitialized.</p><p>The correct solution would be to create an initialization function and call it from the constructors in this fragment as well.</p><p><a href="http://www.viva64.com/en/d/0225/">V610</a> Undefined behavior. Check the shift operator ‘&lt;&lt;’. The left operand ‘-1’ is negative. constants.h 39</p><pre>class Constants<br>{<br>public:<br>  ....<br>  static const int Int31MinValue = -1 &lt;&lt; 30;<br>  ....<br>};</pre><p>According to the latest standard of the C++ language, a shift of a negative number results in undefined behavior.</p><p><a href="http://www.viva64.com/en/d/0148/">V557</a> Array overrun is possible. The value of ‘i’ index could reach 8. rl.cpp 2375</p><pre>enum TestInfoKind::_TIK_COUNT = 9</pre><pre>const char * const TestInfoEnvLstFmt[] =<br>{<br>   &quot; TESTFILE=\&quot;%s\&quot;&quot;,<br>   &quot; BASELINE=\&quot;%s\&quot;&quot;,<br>   &quot; CFLAGS=\&quot;%s\&quot;&quot;,<br>   &quot; LFLAGS=\&quot;%s\&quot;&quot;,<br>   NULL,<br>   NULL,<br>   NULL,<br>   NULL    // &lt;= TestInfoEnvLstFmt[7]<br>};</pre><pre>void<br>WriteEnvLst<br>(<br>   Test * pDir, TestList * pTestList<br>)<br>{<br>  ....<br>  // print the other TIK_*<br>  for(int i=0;i &lt; _TIK_COUNT; i++) {<br>    if (variants-&gt;testInfo.data[i] &amp;&amp; TestInfoEnvLstFmt[i]){// &lt;=<br>       LstFilesOut-&gt;Add(TestInfoEnvLstFmt[i],               // &lt;=<br>                        variants-&gt;testInfo.data[i]);<br>    }<br>    ....<br>  }<br>  ....<br>}</pre><p>The analyzer detected that array index is out of bounds. The things is that the for() loop performs 9 iterations, but there are only 8 elements in the “TestInfoEnvLstFmt[]” array.</p><p>Perhaps, one more NULL was forgotten in the end:</p><pre>const char * const TestInfoEnvLstFmt[] =<br>{<br>   &quot; TESTFILE=\&quot;%s\&quot;&quot;,<br>   &quot; BASELINE=\&quot;%s\&quot;&quot;,<br>   &quot; CFLAGS=\&quot;%s\&quot;&quot;,<br>   &quot; LFLAGS=\&quot;%s\&quot;&quot;,<br>   NULL,<br>   NULL,<br>   NULL,<br>   NULL    // &lt;= TestInfoEnvLstFmt[7]<br>   NULL    // &lt;= TestInfoEnvLstFmt[8]<br>};</pre><p>But there is a chance that some string is missing in the middle of the array!</p><h4>Dangerous pointers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*WNINh1l6enxwAWxT.png" /></figure><p>V595 diagnostic looks for such code fragments where the pointer is dereferenced before it is compared with null. Usually in the projects there are several of such warnings. Such an error holds the record in out error base according to the number of issues found (see <a href="http://www.viva64.com/en/examples/V595/">examples</a>). But in general V595 diagnostics are too boring to give a lot of examples from a project. Also the check and dereference of a pointer can be located quite far away from each other in the function, having dozens or even hundreds of strings between them; that makes the explanation of this bug more complicated in the scope of an article.</p><p>That’s why I’ll provide several short examples of the code that most probably contain an error related to the pointer handling.</p><p><a href="http://www.viva64.com/en/d/0205/">V595</a> The ‘instrLd’ pointer was utilized before it was verified against nullptr. Check lines: 1823, 1831. flowgraph.cpp 1823</p><pre>IR::Instr *<br>FlowGraph::PeepTypedCm(IR::Instr *instr)<br>{<br> ....<br> if (instrLd &amp;&amp; !instrLd-&gt;GetSrc1()-&gt;IsEqual(instr-&gt;GetDst()))<br> {<br>   return nullptr;<br> }<br> <br> if(instrLd2 &amp;&amp; !instrLd2-&gt;GetSrc1()-&gt;IsEqual(instrLd-&gt;GetDst()))<br> {<br>   return nullptr;<br> }<br> ....<br>}</pre><p>Have a look at the pointer with the name “instrLd”. In the first case we see that it is dereferenced and compared with null, in the second case a programmer forgot to do so, that’s why it can cause null pointer dereference.</p><p><a href="http://www.viva64.com/en/d/0205/">V595</a> The ‘src2Val’ pointer was utilized before it was verified against nullptr. Check lines: 9717, 9725. globopt.cpp 9717</p><pre>bool GlobOpt::TypeSpecializeIntBinary(....)<br>{<br>  ....<br>  bool isIntConstMissingItem = src2Val-&gt;GetValueInfo()-&gt;....</pre><pre>  if(isIntConstMissingItem)<br>  {<br>      isIntConstMissingItem = Js::SparseArraySegment&lt;int&gt;::....<br>  }</pre><pre>  if (!src2Val || !(src2Val-&gt;GetValueInfo()-&gt;IsLikelyInt()) ||<br>      isIntConstMissingItem)<br>  {<br>      return false;<br>  }<br>  ....<br>}</pre><p>Pointer “Src2Val” is used at the beginning of the function, but then the developers actively began checking whether this pointer is equal to zero.</p><p><a href="http://www.viva64.com/en/d/0205/">V595</a> The ‘m_lastInstr’ pointer was utilized before it was verified against nullptr. Check lines: 214, 228. irbuilderasmjs.cpp 214</p><pre>void<br>IRBuilderAsmJs::AddInstr(IR::Instr * instr, uint32 offset)<br>{<br>  m_lastInstr-&gt;InsertAfter(instr);                  // &lt;=<br>  if (offset != Js::Constants::NoByteCodeOffset)<br>  {<br>    ....<br>  }<br>  else if (m_lastInstr)                             // &lt;=<br>  {<br>      instr-&gt;SetByteCodeOffset(m_lastInstr-&gt;GetByteCodeOffset());<br>  }<br>  m_lastInstr = instr;<br>  ....<br>}</pre><p>One more example of careless use of a pointer that can potentially be a null pointer.</p><p>A list of similar fragments:</p><ul><li>V595 The ‘arrayData’ pointer was utilized before it was verified against nullptr. Check lines: 868, 870. immutablelist.h 868</li><li>V595 The ‘pMembersList’ pointer was utilized before it was verified against nullptr. Check lines: 2012, 2015. diagobjectmodel.cpp 2012</li><li>V595 The ‘walkerRef’ pointer was utilized before it was verified against nullptr. Check lines: 3191, 3193. diagobjectmodel.cpp 3191</li><li>V595 The ‘block-&gt;loop’ pointer was utilized before it was verified against nullptr. Check lines: 981, 1002. globopt.cpp 981</li><li>V595 The ‘src2Val’ pointer was utilized before it was verified against nullptr. Check lines: 12528, 12536. globopt.cpp 12528</li><li>V595 The ‘symDst’ pointer was utilized before it was verified against nullptr. Check lines: 1966, 1967. irbuilderasmjs.cpp 1966</li><li>V595 The ‘symDst’ pointer was utilized before it was verified against nullptr. Check lines: 2010, 2011. irbuilderasmjs.cpp 2010</li><li>V595 The ‘symDst’ pointer was utilized before it was verified against nullptr. Check lines: 2076, 2077. irbuilderasmjs.cpp 2076</li><li>V595 The ‘symDst’ pointer was utilized before it was verified against nullptr. Check lines: 3591, 3592. irbuilderasmjs.cpp 3591</li><li>V595 The ‘symDst’ pointer was utilized before it was verified against nullptr. Check lines: 4113, 4114. irbuilderasmjs.cpp 4113</li><li>V595 The ‘symDst’ pointer was utilized before it was verified against nullptr. Check lines: 4510, 4511. irbuilderasmjs.cpp 4510</li><li>V595 The ‘m_lastInstr’ pointer was utilized before it was verified against nullptr. Check lines: 1102, 1116. irbuilder.cpp 1102</li></ul><p>This list shows some simplest and clearest examples. To examine all fragments like that, developers should have a look at the analysis result themselves.</p><p><a href="http://www.viva64.com/en/d/0111/">V522</a> Dereferencing of the null pointer ‘tempNumberTracker’ might take place. backwardpass.cpp 578</p><pre>void<br>BackwardPass::MergeSuccBlocksInfo(BasicBlock * block)<br>{<br>  TempNumberTracker * tempNumberTracker = nullptr; // &lt;= line 346<br>  ....<br>  if (!block-&gt;isDead)<br>  {<br>      ....<br>      if(!IsCollectionPass())<br>      {<br>          ....<br>          if (this-&gt;DoMarkTempNumbers())<br>          {<br>              tempNumberTracker = JitAnew(....);   // &lt;= line 413<br>          }<br>      ....<br>  ....<br>  if (blockSucc-&gt;tempNumberTracker != nullptr)<br>  {<br>      ....<br>      tempNumberTracker-&gt;MergeData(....);          // &lt;= line 578<br>      if (deleteData)<br>      {<br>          blockSucc-&gt;tempNumberTracker = nullptr;<br>      }<br>  }<br>  ....<br>}</pre><p>Example of another diagnostic which is also connected with the pointers. Here is a code fragment of the MergeSuccBlocksInfo() function, which is quite long — 707 strings. But with the help of static analysis we managed to find “tempNumberTracker” pointer, whose initialization can potentially fail due to several conditions. As a result, if the odds are against the programmer, there will be dereference of a null pointer.</p><h4>Stop! Check Assert!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*toULn13wI0UzITFn.png" /></figure><p>Assert, located in the program indicates that a programmer assumes that some expression is true for a correctly running program. But can these “successful checks be trusted”?</p><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression ‘srcIndex — src-&gt;left &gt;= 0’ is always true. Unsigned type value is always &gt;= 0. sparsearraysegment.inl 355</p><pre>class SparseArraySegmentBase<br>{<br>public:<br>    static const uint32 MaxLength;<br>    ....<br>    uint32 size;<br>    ....<br>}</pre><pre>template&lt;typename T&gt;<br>SparseArraySegment&lt;T&gt;* SparseArraySegment&lt;T&gt;::CopySegment(....,<br>  uint32 srcIndex, ....)<br>{<br>  ....<br>  AssertMsg(srcIndex - src-&gt;left &gt;= 0,                    // &lt;=<br>    &quot;src-&gt;left &gt; srcIndex resulting in \<br>     negative indexing of src-&gt;elements&quot;);<br>  js_memcpy_s(dst-&gt;elements + dstIndex - dst-&gt;left,<br>              sizeof(T) * inputLen,<br>              src-&gt;elements + srcIndex - src-&gt;left,<br>              sizeof(T) * inputLen);<br>  return dst;<br>}</pre><p>Note the comparison “srcIndex-src-&gt; left &gt; = 0”. Difference of two unsigned numbers will always be greater than or equal to zero. Further on this function is used for working with the memory. The result can be different from the one that the programmer expected.</p><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression is always true. Probably the ‘&amp;&amp;’ operator should be used here. bytecodegenerator.cpp 805</p><pre>void ByteCodeGenerator::AssignRegister(Symbol *sym)<br>{<br>  AssertMsg(sym-&gt;GetDecl() == nullptr ||<br>            sym-&gt;GetDecl()-&gt;nop != knopConstDecl ||      // &lt;=<br>            sym-&gt;GetDecl()-&gt;nop != knopLetDecl, &quot;....&quot;); // &lt;=<br>            <br>  if (sym-&gt;GetLocation() == Js::Constants::NoRegister)<br>  {<br>    sym-&gt;SetLocation(NextVarRegister());<br>  }<br>}</pre><p>In this Assert testing of some values is done only partially. If the expression “sym-&gt;GetDecl() == nullptr” is false, then the following conditions are always true. You can check it by building a truth table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/0*CP-ejEpZJYoGtyeZ.png" /></figure><p><a href="http://www.viva64.com/en/d/0137/">V547</a> Expression ‘callSiteId &gt;= 0’ is always true. Unsigned type value is always &gt;= 0. inline.cpp 1181</p><pre>typedef uint16 ProfileId;</pre><pre>Func * Inline::BuildInlinee(Js::FunctionBody* funcBody, ....)<br>{<br>  ....<br>  Js::ProfileId callSiteId = static_cast&lt;Js::ProfileId&gt;(....);<br>  Assert(callSiteId &gt;= 0);<br>  ....<br>}</pre><p>In this and couple of other fragments the analyzer detected incorrect comparison of an unsigned number with null:</p><ul><li>V547 Expression ‘callSiteId &gt;= 0’ is always true. Unsigned type value is always &gt;= 0. inline.cpp 2627</li><li>V547 Expression ‘callSiteId &gt;= 0’ is always true. Unsigned type value is always &gt;= 0. inline.cpp 3657</li></ul><h4>Conclusion</h4><p>Microsoft has a positive tendency to release their projects under free licenses. For us it is an additional opportunity to test the analyzer on new projects and also a way to demonstrate usefulness and effectiveness of static code analysis on the projects of such a large and well known software vendor.</p><p>You may be interested to see the full list of all <a href="http://www.viva64.com/en/a/0084/">scanned projects</a> that includes other projects from Microsoft, such as .NET CoreCLR, CoreFX .NET and Microsoft Code Contracts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d774e2563b8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Tribute to Opening Up Dolphin Smalltalk 7’s Source Code]]></title>
            <link>https://medium.com/@viva64articles/a-tribute-to-opening-up-dolphin-smalltalk-7-s-source-code-6ce61d8c1b82?source=rss-67b72a9416b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ce61d8c1b82</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[smalltalk]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Love C&C++]]></dc:creator>
            <pubDate>Tue, 12 Jan 2016 11:45:34 GMT</pubDate>
            <atom:updated>2016-01-12T11:45:34.081Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*sjDqBTtm0xM4YK2i.png" /></figure><p>A few days ago, the ObjectArts company made their source code and the Dolphin Smalltalk IDE open, making it available under the MIT license! Of course, I couldn’t miss the chance to try our PVS-Studio code analyzer on the project. Right off, my congratulations go to the developers: they really managed to create high-quality code which has no critical bugs. However, some bugs and smelling code are always to be found in any project, and I hope this article will help make the code a bit better.</p><h4>About the project</h4><p><a href="http://object-arts.com/dolphin7.html">Dolphin Smalltalk</a> is an IDE for the implementation of the Smalltalk language by Object Arts, targeted at the Microsoft Windows platform. Its key features are tight integration with the operating system’s native widgets and subsystems, including COM and ActiveX, and user-friendly GUI.</p><p>For a long time, Dolphin Smalltalk was available as two separate products: a shareware limited Community Edition and the commercial Professional Edition. The latter provided all the functions, including advanced editors and compilation of applications in standalone mode, but its price was about four hundred dollars.</p><p>I analyzed <a href="https://github.com/objectarts/DolphinVM">Dolphin Smalltalk Virtual Machine</a> source code with <a href="http://www.viva64.com/en/pvs-studio/">PVS-Studio</a> 6.00, and here are the analysis results. Although DolphinVM is a tiny project, there are still a few suspicious spots in it.</p><h4>Analysis results</h4><p>Warning No. 1: <a href="http://www.viva64.com/en/d/0226/">V611</a> The memory was allocated using ‘new T[]’ operator but was released using the ‘delete’ operator. Consider inspecting this code. It’s probably better to use ‘delete [] msg;’. compiler.cpp 379</p><pre>Compiler::StaticType Compiler::FindNameAsStatic(....)<br>{<br>  ....<br>  char* msg = new char[strlen(szPrompt)+name.size()+32];<br>  ::wsprintf(msg, szPrompt, name.c_str());<br>  char szCaption[256];<br>  ::LoadString(GetResLibHandle(), IDR_COMPILER, szCaption, ....);<br>  int answer = ::MessageBox(NULL, msg, szCaption, ....);<br>  delete msg;  //&lt;==??<br>  ....<br>}</pre><p>The analyzer detected an error that has to do with allocating and freeing memory using inconsistent techniques.</p><p>When calling operator “new []” to allocate memory, it must be freed with operator “delete []”.</p><p>Warning No. 2: <a href="http://www.viva64.com/en/d/0357/">V716</a> Suspicious type conversion in return statement: returned BOOL, but function actually returns HRESULT. idolphinstart.cpp 78</p><pre>#define STDMETHODIMP    HRESULT STDMETHODCALLTYPE</pre><pre>STDMETHODIMP CDolphinSmalltalk::GetVersionInfo(LPVOID pvi)<br>{<br>  extern BOOL __stdcall GetVersionInfo(VS_FIXEDFILEINFO* ....);<br>  return ::GetVersionInfo(static_cast&lt;VS_FIXEDFILEINFO*&gt;(pvi));<br>}</pre><p>In this code, type “BOOL” is implicitly cast to “HRESULT”. Although this operation is quite valid in C++, in practice it doesn’t make sense in practice. Type <a href="https://en.wikipedia.org/wiki/HRESULT">HRESULT</a> is designed to store a status value, and it has a fairly complex format and has nothing in common with type BOOL.</p><p>Warning No. 3: <a href="http://www.viva64.com/en/d/0340/">V701</a> realloc() possible leak: when realloc() fails in allocating memory, original pointer ‘elems’ is lost. Consider assigning realloc() to a temporary pointer. compiler.cpp 2922</p><pre>POTE Compiler::ParseByteArray()<br>{<br>  NextToken();<br>  while (m_ok &amp;&amp; !ThisTokenIsClosing())<br>  {<br>    if (elemcount&gt;=maxelemcount)<br>    {<br>      _ASSERTE(maxelemcount &gt; 0);<br>      maxelemcount *= 2;<br>      elems = (BYTE*)realloc(elems, maxelemcount*sizeof(BYTE));<br>    }<br>    ....<br>  }<br>  ....<br>}</pre><p>This code is potentially dangerous: we recommend using a separate variable to store the return result of function realloc(). The realloc() function is used to change the size of a memory block. If such change is impossible for the moment, it will return a null pointer. The problem is that pointer ptr, referring to this memory block, may get lost when using constructs like “ptr = realloc(ptr, …)”.</p><p>Two more issues of this kind:</p><ul><li>V701 realloc() possible leak: when realloc() fails in allocating memory, original pointer ‘m_pAllocations’ is lost. Consider assigning realloc() to a temporary pointer. alloc.cpp 436</li><li>V701 realloc() possible leak: when realloc() fails in allocating memory, original pointer ‘pUnmarked’ is lost. Consider assigning realloc() to a temporary pointer. gc.cpp 217</li></ul><p>Warning No. 4: <a href="http://www.viva64.com/en/d/0137/">V547</a> Expression ‘i &gt;= 0’ is always true. Unsigned type value is always &gt;= 0. compact.cpp 35</p><pre>// Answer the index of the last occuppied OT entry<br>unsigned __stdcall ObjectMemory::lastOTEntry()<br>{<br>  HARDASSERT(m_pOT);<br>//  HARDASSERT(m_nInCritSection &gt; 0);</pre><pre>  unsigned i = m_nOTSize-1;<br>  const OTE* pOT = m_pOT;<br>  while (pOT[i].isFree())<br>  {<br>    ASSERT(i &gt;= 0);<br>    i--;<br>  }</pre><pre>  return i;<br>}</pre><p>There is hardly any bug here, but the code doesn’t look right anyway. Thearray items are checked in turn until the isFree() function returns false. ASSERT is incorrect here because it doesn’t check anything. The ‘i’ variable is unsigned, so it will always be greater than or equal to 0.</p><p>One more ‘&gt;=0’ check over an unsigned type:</p><ul><li>V547 Expression is always true. Unsigned type value is always &gt;= 0. loadimage.cpp 343</li></ul><p>Warning No. 5: <a href="http://www.viva64.com/en/d/0377/">V730</a> Not all members of a class are initialized inside the constructor. Consider inspecting: m_dwSize. imagefilemapping.h 13</p><pre>class ImageFileMapping<br>{<br>  HANDLE m_hFile;<br>  HANDLE m_hMapping;<br>  LPVOID m_pData;<br>  DWORD  m_dwSize;</pre><pre>public:<br>  ImageFileMapping() : m_hFile(0), m_hMapping(0), m_pData(NULL){}<br>  ~ImageFileMapping() { Close(); }<br>  ....<br>};</pre><p>This is just another example of potentially dangerous code. Class “ImageFileMapping” contains four fields, but only three of them are initialized in the constructor; member ‘m_dwSize’ remains uninitialized.</p><p>It’s quite a common practice to ignore the “size” field in a class if the pointer to the array is still null. But it’s easy to make a mistake in such code, so it’s better to initialize all the class members.</p><p>Other similar classes:</p><ul><li>V730 Not all members of a class are initialized inside the constructor. Consider inspecting: m_flags, m_oopWorkspacePools, m_context, m_compiledMethodClass. compiler.cpp 84</li><li>V730 Not all members of a class are initialized inside the constructor. Consider inspecting: m_tokenType, m_integer, tp, m_cc, m_base. lexer.cpp 40</li></ul><p>Warning No. 6: <a href="http://www.viva64.com/en/d/0290/">V665</a> Possibly, the usage of ‘#pragma warning(default: X)’ is incorrect in this context. The ‘#pragma warning(push/pop)’ should be used instead. Check lines: 99, 101. compact.cpp 101</p><pre>// Perform a compacting GC<br>size_t ObjectMemory::compact()<br>{<br>  ....<br>  #pragma warning (disable : 4127)<br>  while(true)<br>  #pragma warning (default : 4127)<br>  ....<br>}</pre><p>Programmers often assume that all the warnings disabled by “pragma warning(disable: X)” will start working again after the “pragma warning(default : X)” directive. This is a wrong assumption. The ‘pragma warning(default : X)’ directive restores the DEFAULT state of warning ‘X’. And it’s obviously a different thing.</p><p>Fixed version of the code:</p><pre>size_t ObjectMemory::compact()<br>{<br>  ....<br>  #pragma warning(push)<br>  #pragma warning (disable : 4127)<br>  while(true)<br>  #pragma warning(pop)<br>  ....<br>}</pre><p>Here’s an interesting article on the subject: “<a href="http://www.viva64.com/en/k/0048/">So you want to suppress this message in Visual C++</a>”.</p><p>And here is a list of other issues of this kind:</p><ul><li>V665 Possibly, the usage of ‘#pragma warning(default: X)’ is incorrect in this context. The ‘#pragma warning(push/pop)’ should be used instead. Check lines: 244, 246. expire.cpp 246</li><li>V665 Possibly, the usage of ‘#pragma warning(default: X)’ is incorrect in this context. The ‘#pragma warning(push/pop)’ should be used instead. Check lines: 226, 241. expire.cpp 241</li><li>V665 Possibly, the usage of ‘#pragma warning(default: X)’ is incorrect in this context. The ‘#pragma warning(push/pop)’ should be used instead. Check lines: 126, 128. interfac.cpp 128</li><li>V665 Possibly, the usage of ‘#pragma warning(default: X)’ is incorrect in this context. The ‘#pragma warning(push/pop)’ should be used instead. Check lines: 385, 387. interprt.cpp 387</li></ul><p>Warning No. 7: <a href="http://www.viva64.com/en/d/0176/">V576</a> Incorrect format. Consider checking the fourth actual argument of the ‘wsprintfA’ function. To print the value of pointer the ‘%p’ should be used. interfac.cpp 679</p><pre>inline DWORD __stdcall<br>Interpreter::GenericCallbackMain(SMALLINTEGER id, BYTE* lpArgs)<br>{<br>  ....<br>#ifdef _DEBUG<br>  {<br>    char buf[128];<br>    wsprintf(buf, &quot;WARNING: .... (%d, %x)\n&quot;, id, lpArgs);<br>    WarningWithStackTrace(buf);<br>  }<br>  #endif<br>  ....<br>}</pre><p>Programmers often use specifier ‘%x’ to print a pointer’s value.</p><p>However, it’s a mistake because this code will work only on the systems where the pointer size coincides with the size of type ‘int’. On Win64, for example, this code will print only the least significant part of pointer ‘ptr’. To avoid this bug, one should use specifier ‘%p’.</p><p>Warning No. 8: <a href="http://www.viva64.com/en/d/0137/">V547</a> Expression ‘ch &gt; 127’ is always false. The value range of char type: [-128, 127]. decode.cpp 55</p><pre>ostream&amp; operator&lt;&lt;(ostream&amp; stream, const VariantCharOTE* oteChars)<br>{<br>  ....<br>  char ch = string-&gt;m_characters[i];<br>  //if (ch = &#39;\0&#39;) break;<br>  if (ch &lt; 32 || ch &gt; 127)  //&lt;==<br>  {<br>    static char hexChars[16+1] = &quot;0123456789ABCDEF&quot;;<br>    ....<br>  }<br>  ....<br>}</pre><p>The ‘char’ type’s default range is [-127;127]. We can use the /J compilation switch to make the compiler use the range [0;255] instead. However, there is no such switch specified when compiling this source file, so the check “ch &gt; 127” doesn’t make sense.</p><p>Warning No. 9: <a href="http://www.viva64.com/en/d/0322/">V688</a> The ‘prev’ function argument possesses the same name as one of the class members, which can result in a confusion. thrdcall.h 126</p><pre>void LinkAfter(T* prev)<br>{<br>  T* pThis = static_cast&lt;T*&gt;(this);<br>  this-&gt;next = prev-&gt;next;<br>  if (this-&gt;next)<br>    this-&gt;next-&gt;prev = pThis;<br>  this-&gt;prev = prev;<br>  prev-&gt;next = pThis;<br>}</pre><p>I don’t think there is any bug in this function, but it’s not a good style to give the same name to class function parameters and class members as it may lead to typos that will result in handling a wrong variable.</p><p>Warning No. 10: <a href="http://www.viva64.com/en/d/0212/">V601</a> The ‘false’ value is implicitly cast to the integer type. compiler.cpp 1940</p><pre>int Compiler::ParseUnaryContinuation(...., int textPosition)<br>{<br>  int continuationPointer = m_codePointer;<br>  MaybePatchLiteralMessage();<br>  while (m_ok &amp;&amp; (ThisToken()==NameConst)) <br>  {<br>    int specialCase=false;  //&lt;==<br>    ....<br>    if (!specialCase)       //&lt;==<br>    {<br>      int sendIP = GenMessage(ThisTokenText(), 0, textPosition);<br>      AddTextMap(sendIP, textPosition, ThisTokenRange().m_stop);<br>    }<br>    ....<br>  }<br>  ....<br>}</pre><p>The warning for this code should rather be treated as a recommendation. If ‘specialCase’ is handled as a logical variable throughout the code, it is better to use the standard type ‘bool’ as its type.</p><h4>Conclusion</h4><p>So, one more project has been added to the list of <a href="http://www.viva64.com/en/a/0084/">open-source projects</a> scanned by our analyzer.</p><p>Preparing articles with project analysis results, we skip a lot of warnings issued by the analyzer. That’s why we recommend the project authors to scan their code and examine all the warnings themselves.</p><p>As a usual reminder, remember that it is regular, not occasional, use that makes the analyzer valuable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ce61d8c1b82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyzing IronPython and IronRuby with PVS-Studio]]></title>
            <link>https://medium.com/@viva64articles/analyzing-ironpython-and-ironruby-with-pvs-studio-8cd6fc26642c?source=rss-67b72a9416b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cd6fc26642c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pvs-studio]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Love C&C++]]></dc:creator>
            <pubDate>Mon, 11 Jan 2016 11:59:44 GMT</pubDate>
            <atom:updated>2016-01-11T11:59:44.281Z</atom:updated>
            <content:encoded><![CDATA[<p>Just a while ago, we released a new version of our analyzer PVS-Studio with support of C#-code analysis. With the development paused for the time of the release, I took this opportunity to test the analyzer. For my experiments, I picked projects IronPython and IronRuby. After I scanned them, I thought I could tell you about the analysis results in this small article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*0vHceqevPvbE2c7Q.png" /></figure><h4>IronPython and IronRuby</h4><p>IronPython and IronRuby are implementations of programming languages Python and Ruby on the .NET platform. The projects’ source codes can be downloaded from GitHub <a href="https://github.com/IronLanguages/main">here</a>. The pack also includes the source code of <a href="https://en.wikipedia.org/wiki/Dynamic_Language_Runtime">DLR</a>. Starting with .NET Framework 4.0, DLR ships as its integral part, and IronPython and IronRuby use it. But since the old version of DLR happened to be in the pack, I analyzed it too.</p><h4>Analysis details</h4><p>So, the whole code is made up of three large parts: DLR, IronPython, and IronRuby, and contains 1630 *.cs files. The analysis was done with PVS-Studio 6.00, which can be downloaded from <a href="http://www.viva64.com/en/pvs-studio/">our website</a>. It took me a bit more than a minute to analyze the solution. The analyzer output 34 warnings of the first level, 15 warnings of the second level, and 280 warnings of the third level.</p><p>Out of 34 first-level warnings, 19 turned out to be genuine bugs (which is a good result), and 6 warnings refer to suspicious fragments that should be reviewed. The remaining 9 warnings are false positives, half of which can be eliminated through some improvements to the analyzer itself, which we will make soon.</p><p>Among second- and third-level warnings, there were way fewer bugs and suspicious fragments.</p><h4>Errors found</h4><p>Now let’s discuss examples of real bugs found by PVS-Studio in the projects:</p><p>Samples 1 and 2. Carelessness.</p><pre>private bool Enter(RangeExpression/*!*/ node, bool isCondition) {<br>    ....<br>    if (!isCondition &amp;&amp; litBegin != null &amp;&amp; litEnd != null<br>        &amp;&amp; litBegin.Value is int &amp;&amp; litBegin.Value is int) {<br>        _result = MakeNode(NodeKind.lit, new Range(<br>            (int)litBegin.Value, (int)litEnd.Value,<br>            node.IsExclusive));<br>    } else {<br>    ....<br>    }<br>....<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0381/">V3001</a> There are identical sub-expressions ‘litBegin.Value is int’ to the left and to the right of the ‘&amp;&amp;’ operator. IronRubyParseTreeOps.cs 277</p><p>In the condition, litBegin.Value is checked twice for being of type ‘int’ instead of checking litEnd.Value as well.</p><p>Similar duplicate checks can be found in two more places, for example:</p><pre>private static PythonTuple ReduceProtocol2(<br>    CodeContext/*!*/ context, object self) {<br>    ....<br>    if (self is PythonDictionary || self is PythonDictionary) {<br>        dictIterator = PythonOps.Invoke(context, self,<br>            &quot;iteritems&quot;, ArrayUtils.EmptyObjects);<br>    }<br>    ....<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0381/">V3001</a> There are identical sub-expressions ‘self is PythonDictionary’ to the left and to the right of the ‘||’ operator. IronPython ObjectOps.cs 452</p><p>Sample 3. Identical expressions.</p><pre>protected override MSAst.Expression VisitTry(<br>    MSAst.TryExpression node) {<br>    ....<br>    if (newHandlers != null || newFinally != null) {<br>        node = Ast.MakeTry(node.Type, node.Body,<br>            newFinally != null ? newFinally : node.Finally,<br>            node.Fault,<br>            newHandlers != null ? newHandlers : newHandlers<br>        );<br>    }<br>    return node;<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0383/">V3012</a> The ‘?:’ operator, regardless of its conditional expression, always returns one and the same value: newHandlers. DebugInfoRewriter.cs 252</p><p>In this example, newHandlers is used in both parts of the conditional statement. Actually, it is node.Handlers that was meant to be used when newHandlers is null.</p><p>Samples 4 and 5. Carelessness.</p><pre>public static bool HasValue(RubyContext/*!*/ context,<br>    object/*!*/ self, object value) {<br>    var strValue = value as MutableString;<br>    if (value == null) {<br>        return false;<br>    }<br>    var clrStrValue = strValue.ConvertToString();<br>    ....<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0388/">V3019</a> Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘value’, ‘strValue’. EnvironmentSingletonOps.cs 189</p><p>When casting a variable’s type with the ‘as’ operator, programmers’ common mistake is to check the source object, instead of the resulting one, for null and then go on to use an unchecked reference.</p><p>Another similar case:</p><pre>private static RubyRegex/*!*/ ConstructRubyRegexp(<br>    RubyConstructor/*!*/ ctor, Node/*!*/ node) {<br>    ScalarNode scalar = node as ScalarNode;<br>    if (node == null) {<br>        throw RubyExceptions.CreateTypeError(<br>            &quot;Can only create regex from scalar node&quot;);<br>    }<br>    Match match = _regexPattern.Match(scalar.Value);<br>    ....<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0388/">V3019</a> Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘node’, ‘scalar’. RubyConstructor.cs 230</p><p>Sample 6. Copy-Paste.</p><pre>private void LoadNewObj(CodeContext/*!*/ context) {<br>    PythonTuple args = PopStack() as PythonTuple;<br>    if (args == null) {<br>        throw PythonOps.TypeError(&quot;expected second argument, got {0}&quot;,<br>            DynamicHelpers.GetPythonType(args));<br>    }<br>    PythonType cls = PopStack() as PythonType;<br>    if (args == null) {<br>        throw PythonOps.TypeError(&quot;expected first argument, got {0}&quot;,<br>            DynamicHelpers.GetPythonType(args));<br>    }<br>    ....<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0390/">V3021</a> There are two ‘if’ statements with identical conditional expressions. The first ‘if’ statement contains method return. This means that the second ‘if’ statement is senseless. cPickle.cs 2194</p><p>In this code fragment, two conditions and calls on function GetPythonType() are totally the same. The second condition was obviously written by copying the first one, but the programmer forgot to change the name of the variable in the copied fragment. There were two more errors of this kind in the project.</p><p>Sample 7. Identical conditions.</p><pre>public static int Compare(SourceLocation left, SourceLocation right) {<br>    if (left &lt; right) return -1;<br>    if (right &gt; left) return 1;<br>    return 0;<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0390/">V3021</a> There are two ‘if’ statements with identical conditional expressions. The first ‘if’ statement contains method return. This means that the second ‘if’ statement is senseless. SourceLocation.cs 156</p><p>This method seems too simple to make a mistake in it, doesn’t it? Nevertheless, the programmer swapped parameters left and right in the second condition for some reason. As a result, both conditions check one and the same thing — and this is what the analyzer didn’t like.</p><p>The fixed version of the code:</p><pre>public static int Compare(SourceLocation left, SourceLocation right) {<br>    if (left &lt; right) return -1;<br>    if (left &gt; right) return 1;<br>    return 0;<br>}</pre><p>Sample 8. Extra condition.</p><pre>private void WriteSingleQuoted(string text, bool split) {<br>    ....<br>    while (ending &lt;= text.Length) {<br>        c = &#39;\0&#39;;<br>        if (ending &lt; text.Length) {<br>            c = text[ending];<br>        }<br>        if (spaces) {<br>            if (c == 0 || c != 32) {<br>            ....<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0411/">V3023</a> Consider inspecting the ‘c == 0 || c != 32’ expression. The expression is excessive or contains a misprint. Emitter.cs 308</p><p>The ‘c’ variable is first assigned a default value, ‘\0’. Then, in case the whole string hasn’t been processed yet, ‘c’ is assigned the next character of the string. At the end, it is checked if ‘c’ still contains the default value or any other character except space. The zero check is not necessary here, actually, since zero can’t be equal to 32 (the space code) anyway. This defect doesn’t cause any bugs but makes the code less clear, so the null check should be left out. The analyzer found a few more similar extra checks in this project.</p><p>Samples 9 and 10. Incorrect format string.</p><p>The general problem about using function String.Format is that the compiler doesn’t check if the amount and numbers of a format string’s parameters correspond with the numbers of parameters passed to String.Format. It may result in forming an incorrect string or raising a FormatException. See the following examples.</p><pre>public T Current {<br>    get {<br>        try {<br>            return (T)enumerable.Current;<br>        }<br>        catch (InvalidCastException iex) {<br>            throw new InvalidCastException(string.Format(<br>&quot;Error in IEnumeratorOfTWrapper.Current. Could not cast: {0} in {0}&quot;,<br>typeof(T).ToString(), enumerable.Current.GetType().ToString()), iex);<br>        }<br>    }<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0392/">V3025</a> Incorrect format. A different number of format items is expected while calling ‘Format’ function. Expected: 1. Present: 2. ConversionWrappers.cs 235</p><p>In this example, the last parameter is not used. Instead, value typeof(T).ToString() will be printed twice.</p><pre>private static void DumpGenericParameters(<br>    MetadataTableView genericParams,<br>    MetadataRecord owner) {<br>    foreach (GenericParamDef gp in genericParams) {<br>        _output.WriteLine(&quot;  generic parameter #{0}: {1}&quot;,<br>        gp.Index, gp.Name, gp.Attributes);<br>    ....<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0392/">V3025</a> Incorrect format. A different number of format items is expected while calling ‘WriteLine’ function. Expected: 2. Present: 3. Program.cs 268</p><p>And here, function WriteLine receives one parameter more than suggested by the format string.</p><p>Sample 11. Null check after addressing.</p><pre>public static MutableString ChompInPlace(....) {<br>    MutableString result = InternalChomp(self, separator);<br>    if (result.Equals(self) || result == null) {<br>        self.RequireNotFrozen();<br>        return null;<br>    }<br>    ....<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0414/">V3027</a> The variable ‘result’ was utilized in the logical expression before it was verified against null in the same logical expression. MutableStringOps.cs 1097</p><p>In this condition, the null check and the call on method Equals should be swapped. The way it is written originally, the application may crash, raising a NullReferenceException.</p><p>Sample 12. Troubles with syncing.</p><pre>class DictThreadGlobalState {<br>    public int DoneCount;<br>    ....<br>}</pre><pre>private static void RunThreadTest(DictThreadGlobalState globalState) {<br>    ....<br>    globalState.DoneEvent.Reset();<br>    globalState.Event.Set();<br>    while (globalState.DoneCount != 0) {<br>        // wait for threads to get back to finish<br>    }<br>    ....<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0419/">V3032</a> Waiting on this expression is unreliable, as compiler may optimize some of the variables. Use volatile variable(s) or synchronization primitives to avoid this. EngineTest.cs 2558</p><p>This code contains an error that will only show up on some occasions, depending on the execution environment, .NET Framework’s version, the number of processors on the computer, and other implementation specifics. Such bugs are very difficult to catch. In this case, the DoneCount variable is not declared as volatile; therefore, the compiler assumes it is used by one thread only and its value can be cached and then restored from the cache all the time as this variable doesn’t change inside the loop. In our case, however, it does change in another thread. That’s why variables should be declared as volatile when used to sync threads. See <a href="https://msdn.microsoft.com/en-us/library/x13ttww7.aspx">MSDN</a> for details.</p><p>Sample 13. Double assignment</p><pre>private static Dictionary&lt;string, EncodingInfoWrapper&gt;<br>    MakeCodecsDict() {<br>    ....<br>    switch (normalizedName) {<br>        case &quot;iso_8859_1&quot;:<br>            d[&quot;8859&quot;] = d[&quot;latin_1&quot;] = d[&quot;latin1&quot;] =<br>            d[&quot;iso 8859_1&quot;] = d[&quot;iso8859_1&quot;] = d[&quot;cp819&quot;] = d[&quot;819&quot;] =<br>            d[&quot;latin&quot;] = d[&quot;latin1&quot;] = d[&quot;l1&quot;] = encs[i];<br>            break;<br>    ....<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0403/">V3005</a> The ‘d[“latin1”]’ variable is assigned to itself. StringOps.cs 1905</p><p>In this code, the d[“latin1”] variable is assigned values twice. The second assignment seems to be just superfluous code, not a bug. But it is also possible that this code was meant to handle some code page. Anyway, it should be checked.</p><p>Sample 14. Checking an unsigned variable for null</p><pre>public static int __hash__(UInt64 x) {<br>    int total = unchecked((int) (((uint)x) + (uint)(x &gt;&gt; 32)));<br>    if (x &lt; 0) {<br>        return unchecked(-total);<br>    }<br>    return total;<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0391/">V3022</a> Expression ‘x &lt; 0’ is always false. Unsigned type value is always &gt;= 0. IntOps.Generated.cs 1967</p><p>I’m almost sure it is ‘total’, not ‘x’, that should be compared with null because it doesn’t look right doing something to ‘x’ all the time and then check a special case. Besides, ‘total’ is signed, so the check “total &lt; 0” seems to make more sense.</p><p>Sample 15. Identical checks.</p><pre>public void ReflectTypes(Type[]/*!*/ allTypes) {<br>    ....<br>    def.Super = null;<br>    if (cls != null &amp;&amp; def.Extends != typeof(BasicObject)<br>        &amp;&amp; !def.Extends.IsInterface) {<br>        if (cls != null &amp;&amp; cls.Inherits != null) {<br>            def.Super = new TypeRef(cls.Inherits);<br>    ....<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0415/">V3030</a> Recurring check. The ‘cls != null’ condition was already verified in line 373. LibraryDef.cs 374</p><p>In both conditions, the ‘cls’ variable is checked for null. The programmer probably wanted to check ‘def’ for null in the first condition since they address its property Extends right after the check. But it’s not really necessary, either, because ‘def.Super’ is assigned null right before the condition, which means that ‘def’ is not null anymore. So, it’s just an extra check.</p><p>Sample 16. Copy-paste.</p><p>Now we’ve got to the third-level warnings, which make a total of 280. Most of them deal with pairs of functions with identical bodies and comparison of floating-point numbers. I didn’t expect to find anything serious here, so I just started skimming the warnings but eventually stumbled upon one interesting thing.</p><pre>public static bool IsPositiveOne(BigDecimal x) {<br>    return IsOne(x) &amp;&amp; IsPositive(x);<br>}<br>public static bool IsNegativeOne(BigDecimal x) {<br>    return IsOne(x) &amp;&amp; IsPositive(x);<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0389/">V3013</a> It is odd that the body of ‘IsPositiveOne’ function is fully equivalent to the body of ‘IsNegativeOne’ function (351, line 355). BigDecimal.cs 351</p><p>This is a real bug that results from copying code from one function to another. The fixed version of the code should look like this:</p><pre>public static bool IsNegativeOne(BigDecimal x) {<br>    return IsOne(x) &amp;&amp; IsNegative(x);<br>}</pre><p>Sample 17. Strange check for NaN.</p><pre>public static bool Equals(float x, float y) {<br>    if (x == y) {<br>        return !Single.IsNaN(x);<br>    }<br>    return x == y;<br>}</pre><p>PVS-Studio diagnostic message: <a href="http://www.viva64.com/en/d/0412/">V3024</a> An odd precise comparison: x == y. Consider using a comparison with defined precision: Math.Abs(A — B) &lt; Epsilon. FloatOps.cs 1048</p><p>I’m not sure why one would need a special check for NaN here. If the (x == y) condition is true, then neither ‘x’ nor ‘y’ is NaN because NaN doesn’t equal any other value, including itself. That is, the first return statement will always return true. It seems this check for NaN is just superfluous.</p><h4>Conclusion</h4><p>I think the analyzer had done well with the analysis of these projects. Firstly, it caught a couple of dozens of interesting bugs, the fixing of which will make the project’s code better; secondly, I found a few false positives that can be eliminated by making some improvements to our product. So, I encourage everyone to go download the PVS-Studio demo version and run it on their code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cd6fc26642c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Christmas Analysis of .NET Core Libraries (CoreFX)]]></title>
            <link>https://medium.com/@viva64articles/christmas-analysis-of-net-core-libraries-corefx-50d76814a4?source=rss-67b72a9416b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/50d76814a4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Love C&C++]]></dc:creator>
            <pubDate>Mon, 28 Dec 2015 12:39:17 GMT</pubDate>
            <atom:updated>2015-12-28T12:40:09.375Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/293/0*GzdJOGDOgRiwHGeM.png" /></figure><p>About a year ago Microsoft made the CoreCLR and CoreFX source code open. The latter project wasn’t of a big interest to us until recently, as it was written in C#, not in C++. But with the release of a new version of PVS-Studio 6.00 that now supports C# I decided to go back to the CoreFX and write an article about its analysis.</p><h4>Introduction</h4><p>.NET Core is a modular runtime and library implementation that includes a subset of the .NET Framework.NET Core consists of a set of libraries, called “CoreFX”, and a small, optimized runtime, called “CoreCLR”.</p><p>.NET Core is open source software that is available at GitHub:</p><ul><li><a href="https://github.com/dotnet/corefx">.NET Core Libraries (CoreFX)</a></li><li><a href="https://github.com/dotnet/coreCLR">.NET Core Common Language Runtime (CoreCLR)</a></li></ul><p>These are large-scale Microsoft products that are very well written, but still we managed to find some suspicious code fragments.</p><p>The article about CoreCLR analysis can be found here: <a href="http://www.viva64.com/en/b/0310/">PVS-Studio: 25 Suspicious Code Fragments in CoreCLR</a>.</p><p>CoreFX project that we are going to discuss in this article was checked with the help of a static code analyzer PVS-Studio 6.00 that now has C# support.</p><h4>Analysis results</h4><p>Preparing an article about the check of an <a href="http://www.viva64.com/en/a/0084/">open source project</a>, we report only about a certain number of all of the warnings issued by the analyzer. Therefore we recommend the authors of the project to run the analyzer on their code themselves and study the complete analysis results.</p><h4>The most dangerous code fragments</h4><p><a href="http://www.viva64.com/en/d/0414/">V3027</a> The variable ‘start.BaseMapping’ was utilized in the logical expression before it was verified against null in the same logical expression. Mappings.cs 598</p><pre>internal void SetSequence()<br>{<br>  if (TypeDesc.IsRoot)<br>      return;</pre><pre>  StructMapping start = this;</pre><pre>  // find first mapping that does not have the sequence set<br>  while (!start.BaseMapping.IsSequence &amp;&amp;          //&lt;==<br>          start.BaseMapping != null    &amp;&amp;          //&lt;==???<br>         !start.BaseMapping.TypeDesc.IsRoot)<br>      start = start.BaseMapping;<br>  ....<br>}</pre><p>We see a serious logical error here! An object with the ‘start’ name in the body of the loop gets changed during every iteration and the loop executes while the object is in a particular state. BUT the check of the “start.BaseMapping != null” condition is done only after the access to “start.BaseMapping.IsSequence”, which can lead to the dereference of the null reference.</p><p><a href="http://www.viva64.com/en/d/0388/">V3019</a> Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘comparand’, ‘comparedCredentialKey’. CredentialCache.cs 4007</p><pre>public override bool Equals(object comparand)<br>{<br>  CredentialHostKey comparedCredentialKey =<br>                                  comparand as CredentialHostKey;</pre><pre>  if (comparand == null)<br>  {<br>    // This covers also the compared == null case<br>    return false;<br>  }</pre><pre>  bool equals = string.Equals(AuthenticationType,<br>        comparedCredentialKey.AuthenticationType, ....<br>  ....<br>}</pre><p>Object of any type or null can be passed to the function. If the null gets passed, this case will be handled incorrectly. If it is an object of a type that cannot be converted to “CredentialHostKey” type, then there will be an error accessing the “comparedCredentialKey.AuthenticationType”, because the variable “comparedCredentialKey” can be null.</p><p>Most likely the code meant to look like this:</p><pre>CredentialHostKey comparedCredentialKey =<br>                                  comparand as CredentialHostKey;<br>if (comparedCredentialKey == null)<br>{<br>  return false;<br>}</pre><p>A similar fragment in the code:</p><ul><li>V3019 Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘comparand’, ‘comparedCredentialKey’. CredentialCache.cs 497</li></ul><p><a href="http://www.viva64.com/en/d/0395/">V3008</a> The ‘HResult’ variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 169, 166. WebSocketException.cs 169</p><pre>private void SetErrorCodeOnError(int nativeError)<br>{<br>    if (!Succeeded(nativeError))<br>    {<br>        HResult = nativeError;<br>    }</pre><pre>    HResult = nativeError;  //&lt;==???<br>}</pre><p>Somehow, regardless of the conditions, the variable “HResult” always gets the same value. Most likely the function should be implemented in a different way.</p><p><a href="http://www.viva64.com/en/d/0395/">V3008</a> The ‘ResPrec’ variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 1735, 1731. SQLDecimal.cs 1735</p><pre>public static SqlDecimal operator /(SqlDecimal x, SqlDecimal y)<br>{<br>  int ResPrec;<br>  ....<br>  ResPrec = ResScale + x.m_bPrec + y.m_bPrec + 1;     //&lt;==<br>  MinScale = Math.Min(ResScale, s_cNumeDivScaleMin);</pre><pre>  ResInteger = Math.Min(ResInteger, s_NUMERIC_MAX_PRECISION);<br>  ResPrec = ResInteger + ResScale;                    //&lt;==</pre><pre>  if (ResPrec &gt; s_NUMERIC_MAX_PRECISION)<br>      ResPrec = s_NUMERIC_MAX_PRECISION;<br>  ....<br>}</pre><p>It is very suspicious, that the value of the “ResPrec” variable is evaluated according to some formula and then it is just replaced with another value.</p><p><a href="http://www.viva64.com/en/d/0410/">V3020</a> An unconditional ‘return’ within a loop. Enumerable.cs 517</p><pre>public override bool MoveNext()<br>{<br>  switch (state)<br>  {<br>    case 1:<br>      _enumerator = _source.GetEnumerator();<br>      state = 2;<br>      goto case 2;<br>    case 2:<br>      while (_enumerator.MoveNext())<br>      {<br>        current = _selector(_enumerator.Current);<br>        return true;<br>      }<br>      Dispose();<br>      break;<br>  }<br>  return false;<br>}</pre><p>It’s strange, that in the body of the “while” loop, the function exists without any condition. Perhaps there is an issue in the code.</p><p>Another similar loop:</p><ul><li>V3020 An unconditional ‘return’ within a loop. JsonDataContract.cs 128</li></ul><p><a href="http://www.viva64.com/en/d/0395/">V3008</a> The ‘prefix’ variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 953, 952. XmlSerializationWriter.cs 953</p><pre>protected void WriteAttribute(string localName, string ns, ....)<br>{<br>  ....<br>  string prefix = localName.Substring(0, colon);<br>  prefix = _w.LookupPrefix(ns);<br>  _w.WriteStartAttribute(prefix,<br>                         localName.Substring(colon + 1), ns);<br>  ....<br>}</pre><p>A substring from the ‘localName’, that has a “colon” length, is saved into the ‘prefix’ variable and then the value is replaced with a different one. Further on we see that the remaining substring from the ‘localName’ is still used while the first part is lost. A very questionable code fragment.</p><p><a href="http://www.viva64.com/en/d/0415/">V3030</a> Recurring check. The ‘baseTableRowCounts == null’ condition was already verified in line 68. MetadataAggregator.cs 70</p><pre>private MetadataAggregator(....)<br>{<br>  ....<br>  if (baseTableRowCounts == null)                           //&lt;==<br>  {<br>    if (baseReader == null)<br>    {<br>      throw new ArgumentNullException(&quot;deltaReaders&quot;);<br>    }</pre><pre>    if (baseReader.GetTableRowCount(TableIndex.EncMap) != 0)<br>    {<br>      throw new ArgumentException(&quot;....&quot;, &quot;baseReader&quot;);<br>    }</pre><pre>    CalculateBaseCounts(baseReader, out baseTableRowCounts, //&lt;==<br>                                    out baseHeapSizes);<br>  }<br>  else<br>  {<br>    if (baseTableRowCounts == null)                         //&lt;==???<br>    {<br>      throw new ArgumentNullException(&quot;baseTableRowCounts&quot;);<br>    }</pre><pre>    ....<br>  }<br>  ....<br>}</pre><p>The analyzer detected a condition that has already been checked. If you look at the code fragment, the last check in the ‘else’ — “baseTableRowCounts == null” makes no sense. You may also see that if the “baseTableRowCounts” variable is null, the programmer tries to change its value by calling the CalculateBaseCounts() function. Most likely an extra “baseTableRowCounts == null” check is missing after this function. I.e. the code was probably meant to look like this:</p><pre>private MetadataAggregator(....)<br>{<br>  ....<br>  if (baseTableRowCounts == null)<br>  {<br>    if (baseReader == null)<br>    {<br>      throw new ArgumentNullException(&quot;deltaReaders&quot;);<br>    }</pre><pre>    if (baseReader.GetTableRowCount(TableIndex.EncMap) != 0)<br>    {<br>      throw new ArgumentException(&quot;....&quot;, &quot;baseReader&quot;);<br>    }</pre><pre>    CalculateBaseCounts(baseReader, out baseTableRowCounts,<br>                                    out baseHeapSizes);<br>    if (baseTableRowCounts == null)<br>    {<br>      throw new ArgumentNullException(&quot;baseTableRowCounts&quot;);<br>    }</pre><pre>  }<br>  else<br>  {<br>    ....<br>  }<br>  ....<br>}</pre><h3>Other warnings:</h3><p><a href="http://www.viva64.com/en/d/0391/">V3022</a> Expression ‘readercount &gt;= 0’ is always true. Unsigned type value is always &gt;= 0. ReaderWriterLockSlim.cs 977</p><pre>private void ExitAndWakeUpAppropriateWaitersPreferringWriters()<br>{<br>  ....<br>  uint readercount = GetNumReaders();<br>  ....<br>  <br>  if (readercount == 1 &amp;&amp; _numWriteUpgradeWaiters &gt; 0)<br>  {<br>    ....<br>  }<br>  else if (readercount == 0 &amp;&amp; _numWriteWaiters &gt; 0)<br>  {<br>    ExitMyLock();<br>    _writeEvent.Set();<br>  }<br>  else if (readercount &gt;= 0)<br>  {<br>    ....<br>  }<br>  else<br>    ExitMyLock();<br>  ....<br>}</pre><p>The variable “readercount” has an unsigned type, so the condition “readercount &gt;= 0” is meaningless. Perhaps it is used to be a signed type variable, so there was some chance for the ExitMyLOck() function to execute in the last ‘else’. Now this code never gets control. This fragment has to be rewritten.</p><p><a href="http://www.viva64.com/en/d/0384/">V3014</a> It is likely that a wrong variable is being incremented inside the ‘for’ operator. Consider reviewing ‘i’. RegexCharClass.cs 1094</p><pre>private void Canonicalize()<br>{<br>  ....<br>  for (i = 1, j = 0; ; i++)<br>  {<br>    for (last = _rangelist[j]._last; ; i++)<br>    {<br>      if (i == _rangelist.Count || last == LastChar)<br>      {<br>        done = true;<br>        break;<br>      }</pre><pre>      if ((CurrentRange = _rangelist[i])._first &gt; last + 1)<br>        break;</pre><pre>      if (last &lt; CurrentRange._last)<br>        last = CurrentRange._last;<br>    }</pre><pre>    _rangelist[j] = new SingleRange(_rangelist[j]._first, last);</pre><pre>    j++;</pre><pre>    if (done)<br>      break;</pre><pre>    if (j &lt; i)<br>      _rangelist[j] = _rangelist[i];<br>  }<br>  _rangelist.RemoveRange(j, _rangelist.Count - j);<br>  ....<br>}</pre><p>The analyzer detected a change of one loop counter in a different loop. It is difficult to say whether there is an error in this function, but the code is written not very clearly. It is quite possible to make a mistake somewhere in the index when accessing the array, because it’s difficult to monitor the changes of one counter in several loops.</p><p><a href="http://www.viva64.com/en/d/0402/">V3004</a> The ‘then’ statement is equivalent to the ‘else’ statement. XmlSerializationWriterILGen.cs 1213</p><pre>private void WriteMember(...., TypeDesc memberTypeDesc, ....)<br>{<br>  ....<br>  if (memberTypeDesc.IsArray)<br>  {<br>    LocalBuilder localI = ilg.DeclareOrGetLocal(typeof(Int32), iVar);<br>    ilg.For(localI, 0, ilg.GetLocal(aVar));<br>  }<br>  else<br>  {<br>    LocalBuilder localI = ilg.DeclareOrGetLocal(typeof(Int32), iVar);<br>    ilg.For(localI, 0, ilg.GetLocal(aVar));<br>  }<br>  ....<br>}</pre><p>The condition that doesn’t affect anything as only one code type will be executed. It’ classic Copy-Paste.</p><p><a href="http://www.viva64.com/en/d/0402/">V3004</a> The ‘then’ statement is equivalent to the ‘else’ statement. SqlUtil.cs 93</p><pre>internal static void ContinueTask(....)<br>{<br>  ....<br>  if (connectionToDoom != null || connectionToAbort != null)<br>  {<br>    try<br>    {<br>      onSuccess();<br>    }<br>    catch (Exception e)<br>    {<br>      completion.SetException(e);<br>    }<br>  }<br>  else<br>  { // no connection to doom - reliability section not required<br>    try<br>    {<br>      onSuccess();<br>    }<br>    catch (Exception e)<br>    {<br>      completion.SetException(e);<br>    }<br>  }<br>  ....<br>}</pre><p>There are also too many similar code fragments, although in the commentary it is written that the situations are different.</p><h4>Conclusion</h4><p>Here it is — another Microsoft project analysis. The code is rather qualitative, taking into account the considerable size of the project. But the programmers can still make errors. This article gives only an overview of the bugs found and the list of the warnings provided here is far from being complete.</p><p>Two main factors that facilitate safe and high-quality code:</p><ul><li>Regular, not casual static analysis;</li><li>Review of the analyzer warnings should be done by the authors of the corresponding fragments.</li></ul><p>We hope you enjoyed this article. In the future there will be more articles about the checks of the projects written in C/C++ and C#.</p><p>Thank you for your attention. We wish you bug free code in the coming new year!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50d76814a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analysis of Microsoft Code Contracts]]></title>
            <link>https://medium.com/@viva64articles/analysis-of-microsoft-code-contracts-521f1a2aaf69?source=rss-67b72a9416b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/521f1a2aaf69</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Love C&C++]]></dc:creator>
            <pubDate>Tue, 15 Dec 2015 07:31:22 GMT</pubDate>
            <atom:updated>2015-12-15T07:32:54.436Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/389/0*qDLATWug7AlRZEYt.jpg" /></figure><p>We have successfully created and continue developing PVS-Studio analyzer for C/C++ languages. Over the time, it became clear that many of the diagnostics that we have implemented are not related to a specific programming language, so we decided to apply our experience to another programming language, namely C#. In this article, we are talking about the analysis of Code Contracts project by Microsoft done by our C# analyzer</p><h4>About MS Code Contracts</h4><p><a href="http://research.microsoft.com/en-us/projects/contracts/">Code Contracts</a> provide a language-agnostic way to express coding assumptions in .NET programs. The contracts take the form of preconditions, postconditions, and object invariants. Contracts act as checked documentation of your external and internal APIs. The contracts are used to improve testing via runtime checking, enable static contract verification, and documentation generation.</p><p>It is a medium-sized project (~ 4000 source files), which is actively developing: it contains quite a number of code fragments that are not finished and sometimes incorrectly written. This stage is perfect for implementing a static code analyzer.</p><h4>About new C# analyzer.</h4><p>The Code Contracts project was checked by the experimental version of PVS-Studio which is available at this link: <a href="http://www.viva64.com/ru/pvs-studio/">http://files.viva64.com/beta/PVS-Studio_setup.exe</a>.</p><p>But it won’t be experimental forever. We are planning to release the first version of PVS-Studio with C# support on the 22.12.2015. The release number is going to change to 6.0.</p><p>The pricing policy will remain unchanged. Previously, PVS-Studio allowed to run the analysis of programs written in C, C++, C++/CLI, C++/CX. Now we have added C# to this list.</p><h4>Analysis results.</h4><p>Preparing an article on an <a href="http://www.viva64.com/en/a/0084/">open source project</a> check, we report only about a certain number of all of the warnings issued by the analyzer, therefore we recommend the authors of the project to run the analyzer on their code themselves and study the complete analysis results.</p><h4>The most dangerous code fragments.</h4><p><a href="http://www.viva64.com/en/d/0392/print/">V3025</a> Incorrect format. A different number of actual arguments is expected while calling ‘Format’ function. Expected: 3. Present: 2. VSServiceProvider.cs 515</p><pre>void AskToReportError(Exception exn) {<br>  ....<br>  var emailBody = new StringBuilder();<br>  emailBody.AppendLine(&quot;Hi Code Contracts user,&quot;);<br>  emailBody.AppendLine();<br>  ....<br>  emailBody.AppendLine(<br>    String.Format(&quot;.... {0} {1} Visual Studio {2} Bug Report&quot;,<br>      typeof(VSServiceProvider).Assembly.GetName().Version,<br>#if DEBUG<br>                                                 &quot;Debug&quot;<br>#else<br>                                                 &quot;Release&quot;<br>#endif<br>                                           ));<br>  ....<br>}</pre><p>String.Format() function expects 3 arguments, but only 2 arguments were passed. In this case we have <a href="https://msdn.microsoft.com/en-us/library/system.formatexception%28v=vs.110%29.aspx">FormatException</a>.</p><p><a href="http://www.viva64.com/en/d/0384/print/">V3014</a> It is likely that a wrong variable is being incremented inside the ‘for’ operator. Consider reviewing ‘i’. SparseArray.cs 1956</p><pre>override public string ToString()<br>{<br>  StringBuilder str = new StringBuilder();</pre><pre>  for (int i = 0; i &lt; data.Length; i++)<br>  {<br>    if (data[i] != null)<br>    {<br>      for (int j = 0; j &lt; lastElement[i]; i++)  //&lt;==<br>      {<br>        str.AppendFormat(&quot;({0},{1})&quot;, data[i][j].Index,<br>                                      data[i][j].Value);<br>      }<br>    }<br>  }</pre><pre>  return str.ToString();<br>}</pre><p>In a nested loop the counter variable ‘j’ is not changed, because we have modification of outer loop counter ‘i++’ instead of ‘j++’</p><p>Couple more similar fragments:</p><ul><li>V3014 It is likely that a wrong variable is being incremented inside the ‘for’ operator. Consider reviewing ‘k’. Writer.cs 3984</li><li>V3014 It is likely that a wrong variable is being incremented inside the ‘for’ operator. Consider reviewing ‘count_d’. Octagons.cs 509</li></ul><p><a href="http://www.viva64.com/en/d/0382/print/">V3003</a> The use of ‘if (A) {…} else if (A) {…}’ pattern was detected. There is a probability of logical error presence. Check lines: 203, 207. WeakestPreconditionProver.csToSMT2.cs 203</p><pre>private BoxedExpression DeclareVariable(....)<br>{<br>  var tmp = original.ToString().Replace(&#39; &#39;, &#39;_&#39;);<br>  this.Info.AddDeclaration(string.Format(&quot;....&quot;, tmp, type));<br>  this.ResultValue = tmp;</pre><pre>  if (type == FLOAT32)       //&lt;==<br>  {<br>    types[original] = FloatType.Float32;<br>  }<br>  else if (type == FLOAT64)  //&lt;==<br>  {<br>    types[original] = FloatType.Float64;<br>  }</pre><pre>  return original;<br>}</pre><p>The analyzer detected two similar conditional expressions, because of which the operators in the second condition will never get control. Although, at first glance, it is not so, we’ll move on to the definition of constants FLOAT32 and FLOAT64, and see the following code:</p><pre>private const string FLOAT32 = &quot;(_ FP 11 53)&quot;; // To change!!!<br>private const string FLOAT64 = &quot;(_ FP 11 53)&quot;;</pre><p>The constants really are equal! Although we have a commentary here that the FLOAT32 constant value should be replaced, this spot is easy to skip in the future. In developing projects, it is important to tag places as TODO and to regularly review the results of static code analysis.</p><p><a href="http://www.viva64.com/en/d/0382/print/">V3003</a> The use of ‘if (A) {…} else if (A) {…}’ pattern was detected. There is a probability of logical error presence. Check lines: 1200, 1210. OutputPrettyCS.cs 1200</p><pre>public enum TypeConstraint<br>{<br>  NONE,<br>  CLASS,     //&lt;==<br>  STRUCT,    //&lt;==<br>  BASECLASS,<br>}</pre><pre>public void Output(OutputHelper oh)<br>{<br>  Contract.Requires(oh != null);</pre><pre>  oh.Output(&quot;where &quot;, false);<br>  mParent.OutputName(oh);<br>  oh.Output(&quot; : &quot;, false);<br>  //** base class<br>  bool comma = false;<br>  if (mTypeConstraint == TypeConstraint.CLASS)       //&lt;==???<br>  {<br>    oh.Output(&quot;class&quot;, false);<br>    comma = true;<br>  }<br>  else if (mTypeConstraint == TypeConstraint.STRUCT)<br>  {<br>    oh.Output(&quot;struct&quot;, false);<br>    comma = true;<br>  }<br>  else if (mTypeConstraint == TypeConstraint.CLASS)  //&lt;==???<br>  {<br>    oh.Output(mClassConstraint, false);<br>    comma = true;<br>  }<br>}</pre><p>In this code fragment the same conditions are more obvious. Most likely in one of the conditions the programmer wanted to compare the ‘mTypeConstraint’ variable with a constant TypeConstraint.BASECLASS instead of TypeConstraint.CLASS.</p><p><a href="http://www.viva64.com/en/d/0391/print/">V3022</a> Expression ‘c &gt; ‘\xFFFF’’ is always false. Output.cs 685</p><pre>private static string Encode(string s)<br>{<br>  ....<br>  foreach( char c in s ) {<br>    if (c == splitC || c == &#39;\n&#39; || c == &#39;\\&#39;) {<br>      specialCount++;<br>    }<br>    else if (c &gt; &#39;\x7F&#39;) {<br>      if (c &gt; &#39;\xFFFF&#39;) specialCount += 9;<br>      else specialCount += 5;<br>    }<br>  }<br>  ....<br>}</pre><p>The expression “c &gt; ‘\xFFFF’” will never be true and the “specialCount += 9” operator will never be executed. The ‘c’ variable has a Char type, the maximum value of which is “\xFFFF ‘. It’s not really clear how this code should work and how it should be fixed. Perhaps we have a typo here or it is a code fragment, taken from an application written in a different language. For example, in C/C++ sometimes developers use 32-bit symbols. And “play around” with the 0xFFFF value. Example of such code:</p><pre>/* putUTF8 -- write a character to stdout in UTF8 encoding */<br>static void putUTF8(long c)<br>{<br>  if (c &lt;= 0x7F) {         /* Leave ASCII encoded */<br>    printf(&quot;&amp;#%ld;&quot;, c);<br>  } else if (c &lt;= 0x07FF) {     /* 110xxxxx 10xxxxxx */<br>    putchar(0xC0 | (c &gt;&gt; 6));<br>    putchar(0x80 | (c &amp; 0x3F));<br>  } else if (c &lt;= 0xFFFF) {     /* 1110xxxx + 2 */<br>    putchar(0xE0 | (c &gt;&gt; 12));<br>    putchar(0x80 | ((c &gt;&gt; 6) &amp; 0x3F));<br>    putchar(0x80 | (c &amp; 0x3F));<br>  } else if (c &lt;= 0x1FFFFF) {    /* 11110xxx + 3 */<br>    putchar(0xF0 | (c &gt;&gt; 18));<br>    putchar(0x80 | ((c &gt;&gt; 12) &amp; 0x3F));<br>    putchar(0x80 | ((c &gt;&gt; 6) &amp; 0x3F));<br>    putchar(0x80 | (c &amp; 0x3F));<br>  } else if (c &lt;= 0x3FFFFFF) {    /* 111110xx + 4 */<br>    putchar(0xF8 | (c &gt;&gt; 24));<br>    putchar(0x80 | ((c &gt;&gt; 18) &amp; 0x3F));<br>    putchar(0x80 | ((c &gt;&gt; 12) &amp; 0x3F));<br>    putchar(0x80 | ((c &gt;&gt; 6) &amp; 0x3F));<br>    putchar(0x80 | (c &amp; 0x3F));<br>  } else if (c &lt;= 0x7FFFFFFF) {    /* 1111110x + 5 */<br>    putchar(0xFC | (c &gt;&gt; 30));<br>    putchar(0x80 | ((c &gt;&gt; 24) &amp; 0x3F));<br>    putchar(0x80 | ((c &gt;&gt; 18) &amp; 0x3F));<br>    putchar(0x80 | ((c &gt;&gt; 12) &amp; 0x3F));<br>    putchar(0x80 | ((c &gt;&gt; 6) &amp; 0x3F));<br>    putchar(0x80 | (c &amp; 0x3F));<br>  } else {          /* Not a valid character... */<br>    printf(&quot;&amp;#%ld;&quot;, c);<br>  } <br>}</pre><p><a href="http://www.viva64.com/en/d/0395/print/">V3008</a> The ‘this.InsideMonitor’ variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 751, 749. AssertionCrawlerAnalysis.cs 751</p><pre>private Data(Data state, Variable v)<br>{<br>  this.IsReached = state.IsReached;<br>  this.InsideMonitor = state.InsideMonitor;  //&lt;==<br>  this.symbols = new List&lt;Variable&gt;(state.symbols) { v };<br>  this.InsideMonitor = false;                //&lt;==???<br>}</pre><p>It’s very suspicious that some function changes the state of an object using the values passed through the function parameters and at the last moment replaces “this.InsideMonitor” field value with a ‘false’ constant. Previously the assignment “this.InsideMonitor = state.InsideMonitor” has already been executed.</p><p><a href="http://www.viva64.com/en/d/0387/print/">V3009</a> It’s odd that this method always returns one and the same value of ‘true’. LinearEqualities.cs 5262</p><pre>public bool TryGetFirstAvailableDimension(out int dim)<br>{<br>  for (var i = 0; i &lt; map.Length; i++)<br>  {<br>    if (!map[i])<br>    {<br>      dim = i;<br>      return true;<br>    }<br>  }</pre><pre>  map.Length++;</pre><pre>  dim = map.Length;</pre><pre>  return true;<br>}</pre><p>The analyzer detected a function that always returns the same “true” value. We can assume that when the “!map[i]” condition is executed the function should return a certain kind of value, but if this condition has never been true, then it should return a different value. Perhaps, there is an error.</p><h4>Other warnings:</h4><p><a href="http://www.viva64.com/en/d/0392/print/">V3025</a> Incorrect format. A different number of actual arguments is expected while calling ‘Format’ function. Expected: 1. Present: 2. Output.cs 68</p><pre>public override void WriteLine(string value)<br>{<br>  output.WriteLine(string.Format(&quot;{1}&quot;, DateTime.Now,<br>    value.Replace(&quot;{&quot;, &quot;{{&quot;).Replace(&quot;}&quot;,&quot;}}&quot;)));<br>  //output.WriteLine(string.Format(&quot;[{0}] {1}&quot;,<br>    //DateTime.Now., value));<br>}</pre><p>Earlier the String.Format() function received and printed 2 values: date and some value. Then this code was commented out and another variant was written, where the argument with the 0 index is not used, so the date is not printed.</p><p>Other examples of formatting functions calls with unused arguments:</p><ul><li>V3025 Incorrect format. A different number of actual arguments is expected while calling ‘Format’ function. Expected: 6. Present: 7. CacheModelExtensions.cs 46</li><li>V3025 Incorrect format. A different number of actual arguments is expected while calling ‘Format’ function. Expected: 1. Present: 2. CodeFixesInference.cs 1608</li><li>V3025 Incorrect format. A different number of actual arguments is expected while calling ‘Format’ function. Expected: 2. Present: 3. ExpressionManipulation.cs 442</li></ul><p><a href="http://www.viva64.com/en/d/0402/print/">V3004</a> The ‘then’ statement is equivalent to the ‘else’ statement. Metadata.cs 2602</p><pre>private void SerializeFieldRvaTable(....)<br>{<br>  ....<br>  switch (row.TargetSection){<br>    case PESection.SData:<br>    case PESection.TLS:<br>      Fixup fixup = new Fixup();<br>      fixup.fixupLocation = writer.BaseStream.Position;<br>      fixup.addressOfNextInstruction = row.RVA;<br>      if (row.TargetSection == PESection.SData){<br>        sdataFixup.nextFixUp = fixup;   //&lt;==<br>        sdataFixup = fixup;             //&lt;==<br>      }else{<br>        sdataFixup.nextFixUp = fixup;   //&lt;==<br>        sdataFixup = fixup;             //&lt;==<br>      }<br>      writer.Write((int)0);<br>      break;<br>  ....<br>}</pre><p>The analyzer detected identical blocks of code in a conditional operator. This may be an unnecessary code fragment or code block was not changed after copying. <a href="http://www.viva64.com/en/t/0068/">Copy-Paste</a> does not have mercy on C# programmers.</p><p>A full list of similar fragments:</p><ul><li>V3004 The ‘then’ statement is equivalent to the ‘else’ statement. Nodes.cs 6698</li><li>V3004 The ‘then’ statement is equivalent to the ‘else’ statement. Nodes.cs 6713</li><li>V3004 The ‘then’ statement is equivalent to the ‘else’ statement. WarningSuggestionLinkOutput.cs 108</li><li>V3004 The ‘then’ statement is equivalent to the ‘else’ statement. NonNullAnalyzer.cs 1753</li></ul><p><a href="http://www.viva64.com/en/d/0381/print/">V3001</a> There are identical sub-expressions ‘semanticType.Name == null’ to the left and to the right of the ‘||’ operator. ContractsProvider.cs 694</p><pre>public bool TryGetTypeReference(....)<br>{<br>  ....<br>  if (semanticType.Name == null || semanticType.Name == null)<br>    goto ReturnFalse;<br>  cciType = new Microsoft.Cci.MutableCodeModel.NamespaceTypeR....<br>  {<br>    ContainingUnitNamespace = cciNamespace,<br>    GenericParameterCount = (ushort) (....),<br>    InternFactory = Host.InternFactory,<br>    IsValueType = semanticType.IsValueType,<br>    IsEnum = semanticType.TypeKind == TypeKind.Enum,<br>    Name = Host.NameTable.GetNameFor(semanticType.Name),<br>    TypeCode=CSharpToCCIHelper.GetPrimitiveTypeCode(semanticType)<br>  };<br>  goto ReturnTrue;&#39;<br>  ....<br>}</pre><p>The condition “semanticType.Name == null” is checked 2 times. There two options here — this check is either redundant and can be simplified; or another object field was not checked.</p><p>Another warning on this kind:</p><ul><li>V3001 There are identical sub-expressions ‘semanticType.Name == null’ to the left and to the right of the ‘||’ operator. ContractsProvider.cs 714</li></ul><p><a href="http://www.viva64.com/en/d/0388/print/">V3019</a> Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘other’, ‘right’. CallerInvariant.cs 189</p><pre>public override Predicate JoinWith(Predicate other)<br>{<br>  var right = other as PredicateNullness;<br>  if (other != null)<br>  {<br>    if (this.value == right.value)<br>    {<br>      return this;<br>    }<br>  }</pre><pre>  return PredicateTop.Value;<br>}</pre><p>The analyzer detected a potential error, which can lead to access by null reference. It is necessary to compare the result of the ‘as’ operator execution with ‘null’</p><p>If you encounter a situation, when the ‘other’ object is not null, but it’s impossible to cast it to the ‘PredicateNullness’ type, then we have an access by null reference when getting the “right.value”.</p><p>There is quite a number of such comparisons in the project. Here is the full list:</p><ul><li>V3019 Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘facts’, ‘moreRefinedFacts’. SimplePostconditionDispatcher.cs 319</li><li>V3019 Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘objProvenance’, ‘provenance’. AssertionCrawlerAnalysis.cs 816</li><li>V3019 Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘prev’, ‘other’. NonRelationalValueAbstraction.cs 1063</li><li>V3019 Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘prev’, ‘castedPrev’. GenericDomains.cs 1657</li><li>V3019 Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘a’, ‘right’. LinearEqualitiesForSubpolyhedra.cs 859</li><li>V3019 Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘a’, ‘other’. NonRelationalValueAbstraction.cs 1047</li><li>V3019 Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘a’, ‘other’. NonRelationalValueAbstraction.cs 1055</li><li>V3019 Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘a’, ‘right’. LinearEqualities.cs 849</li><li>V3019 Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘a’, ‘right’. LinearEqualities.cs 973</li><li>V3019 Possibly an incorrect variable is compared to null after type conversion using ‘as’ keyword. Check variables ‘a’, ‘right’. LinearEqualities.cs 1119</li></ul><p><a href="http://www.viva64.com/en/d/0415/print/">V3030</a> Recurring check. The ‘this.lineOffsets == null’ condition was already verified in line 612. Nodes.cs 613</p><pre>public virtual void InsertOrDeleteLines(....)<br>{<br>  ....<br>  if (this.lineOffsets == null)<br>    if (this.lineOffsets == null) this.ComputeLineOffsets();<br>  if (lineCount &lt; 0)<br>    this.DeleteLines(offset, -lineCount);<br>  else<br>    this.InsertLines(offset, lineCount);<br>  ....<br>}</pre><p>Two identical “this.lineOffsets == null” checks, written one after another. This code has no sense. Probably the programmer intended to check something else.</p><p><a href="http://www.viva64.com/en/d/0401/print/">V3002</a> The switch statement does not cover all values of the ‘UnaryOperator’ enum: Conv_dec. WeakestPreconditionProver.csToSMT2.cs 453</p><pre>private string Combine(UnaryOperator unaryOperator, string arg)<br>{<br>  Contract.Requires(arg != null);</pre><pre>  var format = &quot;({0} {1})&quot;;<br>  string op = null;</pre><pre>  switch (unaryOperator)<br>  {<br>    case UnaryOperator.Neg:<br>    case UnaryOperator.Not:<br>    case UnaryOperator.Not:<br>      {<br>        op = &quot;not&quot;;<br>      }<br>      break;</pre><pre>    case UnaryOperator.WritableBytes:<br>    case UnaryOperator.Conv_i:<br>    case UnaryOperator.Conv_i1:<br>    case UnaryOperator.Conv_i2:<br>    case UnaryOperator.Conv_i4:<br>    case UnaryOperator.Conv_i8:<br>    case UnaryOperator.Conv_r_un:<br>    case UnaryOperator.Conv_r4:<br>    case UnaryOperator.Conv_r8:<br>    case UnaryOperator.Conv_u:<br>    case UnaryOperator.Conv_u1:<br>    case UnaryOperator.Conv_u2:<br>    case UnaryOperator.Conv_u4:<br>    case UnaryOperator.Conv_u8:<br>      {<br>        return null;<br>     }<br>  }</pre><pre>  return string.Format(format, op, arg);<br>}</pre><p>The analyzer detected a ‘switch’ operator, where the choice of the variant is made via the enum type variable. At the same time one element “UnaryOperator Conv_dec” was omitted in the ‘switch’ operator. It is very suspicious.</p><p>Below is the definition of “UnaryOperator” enumeration:</p><pre>public enum UnaryOperator<br>{<br>  ....<br>  Conv_u8,<br>  Conv_r_un,<br>  Neg,<br>  Not,<br>  WritableBytes,<br>  Conv_dec,      //&lt;==<br>}</pre><p>A possible error is that this function is implemented in such a way that it returns a formatted string for the “UnaryOperator.Not” value and in all other cases it returns ‘null’ value. But as the “UnaryOperator. Conv_dec” is missing, then the ‘op’ variable value is ‘null’ and it will get to the formatted string that the function will return.</p><h4>Conclusion</h4><p>We hope you enjoyed this article. In the future there will be more articles about the checks of the projects.</p><p>As it was mentioned before, PVS-Studio C# release is on the 22.12.2015. Usually at the end of the year, people make decisions about the future purchases. That’s why to all who are interested we offer to contact us without hesitations about the <a href="http://www.viva64.com/en/order/">purchase</a> of PVS-Studio. We’ll be very glad to see you among our <a href="http://www.viva64.com/en/customers">customers</a>.</p><p>Thank you for your attention. We wish you bugless code!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=521f1a2aaf69" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>