Files
codeql/javascript/ql/src/Expressions/BitwiseSignCheck.qhelp
2018-08-02 17:53:23 +01:00

50 lines
1.3 KiB
XML

<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>
Checking whether the result of a bitwise operation is greater than zero may yield unexpected results
due to arithmetic overflow.
</p>
</overview>
<recommendation>
<p>
It is more robust to check whether the result of the bitwise operation is <i>non-zero</i>.
</p>
</recommendation>
<example>
<p>
In the following example, function <code>bitIsSet</code> is meant to implement a check
whether the <code>n</code>th bit of value <code>x</code> is set.
</p>
<sample src="examples/BitwiseSignCheck.js" />
<p>
However, this check fails to produce the correct value when <code>x</code> is set to
<code>-1</code> (that is, all its bits are ones), and <code>n</code> is set to
<code>31</code>: in this case, the expression <code>x &amp; (1&lt;&lt;n)</code>
evaluates to <code>-2147483648</code>. So the function returns <code>false</code>,
even though the 31st bit of <code>x</code> is, in fact, set.
</p><p>
To account for this edge case, <code>bitIsSet</code> should be rewritten like this:
</p>
<sample src="examples/BitwiseSignCheckGood.js" />
</example>
<references>
<li>Mozilla Developer Network: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">Bitwise operators</a>.</li>
</references>
</qhelp>