Avoid performing bit manipulation bitwise and arithmetic operations on the same variable. Though data. In particular, bitwise operations are frequently performed on arithmetic values as a form of premature optimization. Bitwise operators include the unary operator ~ and the binary operators <<, >>, &, ^, and |. Although such operations are valid and will compile, they can lead to lesser reduce code readability. Specifically declaring Declaring a variable as containing a numeric value or a collection of bits bitmap makes the programmer's intentions clearer and can lead to better code maintainability.
Non-Compliant Coding Example 1
the code more maintainable.
Bitmapped types may be defined to further separate bit collections from numeric types. Doing so may make it easier to verify that bitwise operations are performed only on variables that represent bitmaps.
| Code Block |
|---|
typedef uint32_t bitmap32_t;
bitmap32_t x = 0x000007f3;
x = (x << 2) | 3; /* Shifts in two 1-bits from the right */
|
The typedef name uintN_t designates an unsigned integer type with width N. Consequently, uint32_t denotes an unsigned integer type with a width of exactly 32 bits. Bitmaps should be declared as unsigned. See INT13-C. Use bitwise operators only on unsigned operands.
Left- and right-shift operators are often employed to multiply or divide a number by a power of 2. However, using shift operators to represent multiplication or division is an optimization that renders the code less portable and less readable. Furthermore, most compilers routinely optimize multiplications and divisions by constant powers of 2 with bit-shift operations, and they are more familiar with the implementation details of the current platform.
Noncompliant Code Example (Left Shift)
In this noncompliant code In this non-compliant example, both bit manipulation and arithmetic manipulation is are performed on the integer type x. The end result is an optimized line of code that changes x to 5x + 1a (prematurely) optimized statement that assigns 5x + 1 to x for implementations where integers are represented as two's complement values.
| Code Block | |||||
|---|---|---|---|---|---|
| |||||
int compute(int x) { int y = int x =<< 502; x += (x << 2) + 1; y + 1; return x; } // ... int x = compute(50); |
Although this is a valid manipulation, the result of the Though this is a legal manipulation, the exact result of performing this shift depends on the underlying representation of the integer type . Thus the operation and is consequently implementation-defined. Additionally, it is challenging to immediately understand the effect of this code. The code is not self-documentingthe readability of the code is reduced.
Compliant Solution
...
(Left Shift)
In this compliant solution, the assignment statement is modified Changing the second line to reflect the arithmetic nature of x causes , resulting in a clearer indication of the programmer's intentions to become clearer.:
| Code Block | ||||
|---|---|---|---|---|
| ||||
int compute( int x) = 50; x ={ return 5 * x + 1; } // ... int x = compute(50); |
A reviewer might may now know recognize that the operation should also be checked for integer overflowwrapping. This might not have been apparent in the original, noncompliant code listingexample.
...
Noncompliant Code Example (Right Shift)
In this non-compliant noncompliant code example, the coder attempts to optimally divide x by 4.programmer prematurely optimizes code by replacing a division with a right shift:
| Code Block | |||||
|---|---|---|---|---|---|
| |||||
int compute(int x) { int x >>= -50; x >>= 2; 2; return x; } // ... int x = compute(-50); |
Although Though this code is likely to perform a the division by 4correctly, it is not guaranteed to. The system is free to use whatever representation of an integer it wishes. The result of this operation is dependent on whether the processor performs an arithmetic shift or a logical shiftIf x has a signed type and a negative value, the operation is implementation-defined and can be implemented as either an arithmetic shift or a logical shift. In the event of a logical shift, if the integer is represented in either one's complement or two's complement form, the most significant bit (which controls the sign for both representations) will be set to 0, causing a once negative number to become a possibly very large, positive number. For more details, see INT13-C. Use bitwise operators only on unsigned operands.
For example, if the internal representation of x is 0xFFFF FFCE (two's - complement), an arithmetic shift results in 0xFFFF FFF3 (-13 −13 in two's - complement), while whereas a logical shift results in 0x3FFF FFF3 (1,073,741,811 in two's - complement). The programmer may have not intended one of these results.
Compliant Solution
...
(Right Shift)
In this compliant solution, the right shift is replaced by division:Change the shift to a division so that the intention is clear.
| Code Block | ||||
|---|---|---|---|---|
| ||||
intint compute(int x) { return x =/ -50; x /= 44; } // ... int x = compute(-50); |
The compiler now knows exactly what the programmer intended, and it can select the correct assembly instruction.
Compliant Practice
resulting value is now more likely to be consistent with the programmer's expectations.
Exceptions
INT14-C-EX0: Routines may treat integers as bit vectors for I/O purposes. That is, they may treat an integer as a series of bits in order to write it to a file or socket. They may also read a series of bits from a file or socket and create an integer from the bits. Bitwise operations are also permitted when reading or writing the data from a tightly packed data structure of bytesIn order to further separate bit collections and numeric types, it might be prudent to define a bit-containing type. A programmer can then run automated tools over the code in question to verify that only bit manipulations are performed on variables of this type.
| Code Block | ||||
|---|---|---|---|---|
| ||||
typedef int bitcoll;
bitcoll x = 0x7f3;
x = (x << 2) | 3; /* shifts in two 1-bits from the right */
|
Risk Assessment
int value = /* Interesting value */
unsigned char bytes[sizeof(int)];
for (int i = 0; i < sizeof(int); i++) {
bytes[i] = value >> (i*8) & 0xFF;
}
/* bytes[] now has same bit representation as value */ |
NUM01-J-EX1: Bitwise operations may be used to construct constant expressions.
| Code Block | ||||
|---|---|---|---|---|
| ||||
int limit = (1 << 17) - 1; // 2^17 - 1 = 131071 |
Nevertheless, as a matter of style, it is preferable to replace such constant expressions with the equivalent hexadecimal constants.
| Code Block | ||||
|---|---|---|---|---|
| ||||
int limit = 0x1FFFF; // 2^17 - 1 = 131071 |
Risk Assessment
Performing bit manipulation and arithmetic operations on the same variable obscures the programmer's intentions and reduces readability. It also makes it more difficult for a security auditor or maintainer By complicating information regarding how a variable is used in code, it is difficult to determine which checks must be performed to eliminate security flaws and ensure data validity. Explicitly stating how a variable is used determines which checks to performintegrity.
Recommendation | Severity | Likelihood | Detectable |
|---|
Repairable | Priority | Level |
|---|
INT14- |
2 (medium)
1 (unlikely)
C | Medium | Unlikely | Yes | No |
P4 | L3 |
References
| Wiki Markup |
|---|
\[[ISO/IEC 9899-1999|cplusplus:AA. C++ References#ISO/IEC 9899-1999]\] Section 6.2.6.2, "Integer types" |
Automated Detection
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| Compass/ROSE | Can detect violations of this recommendation. However, it can detect only those violations where both bitwise and arithmetic operators are used in the same expression | ||||||||
| LDRA tool suite |
| 585 S | Fully implemented | ||||||
| Polyspace Bug Finder |
| CERT C: Rec. INT14-C | Checks for bitwise and arithmetic operation on the same data (rec. fully covered) |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
Bibliography
...
Steele, G. L. 1977. Arithmetic shifting considered harmful. SIGPLAN Not. 12, 11 (Nov. 1977), 61-69.