...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <limits.h> #include <stddef.h> #include <inttypes.h> extern size_t popcount(uintmax_t); #define PRECISION(x) popcount(x) void func(signed long si_a, signed long si_b) { signed long result; if ((si_a < 0) || (si_b < 0) || (si_b >= PRECISION(ULONG_MAX)) || (si_a > (LONG_MAX >> si_b))) { /* Handle error */ } else { result = si_a << si_b; } /* ... */ } |
Noncompliant Code Example (Right Shift)
...
Although shifting a negative number of bits or shifting a number of bits greater than or equal to the width of the promoted left operand is undefined behavior in C, the risk is generally low because processors frequently reduce the shift amount modulo the width of the type.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
INT34-C | Low | Unlikely | Medium | P2 | L3 |
Automated Detection
Tool | Version | Checker | Description | ||||
---|---|---|---|---|---|---|---|
Astrée |
|
Supported, but no explicit checker | |||||||||
CodeSonar |
| LANG.ARITH.BIGSHIFT | Shift amount exceeds bit width | ||||||
Compass/ROSE |
Can detect violations of this rule. Unsigned operands are detected when checking for INT13-C. Use bitwise operators only on unsigned operands | |||||||||
Coverity |
| BAD_SHIFT | Implemented | ||||||
ECLAIR |
| CC2.INT34 | Partially implemented | ||||||
LDRA tool suite |
| 51 S, 403 S, 479 S | Partially implemented | ||||||
Parasoft C/C++test |
|
|
| MISRA-038 |
Polyspace Bug Finder | R2016a | Shift operator on negative value Overflow from shifting operation | |||||||
PRQA QA-C |
| 0499 | Partially implemented | ||||||
Cppcheck |
| shiftNegative, shiftTooManyBits | Context sensitive analysis | ||||||
PVS-Studio | 6.22 | V610 | General analysis rule |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
Key here (explains table format and definitions)
Taxonomy | Taxonomy item | Relationship |
---|---|---|
CERT C | INT13-C. Use bitwise operators only on unsigned operands | Prior to 2018-01-12: CERT: Unspecified Relationship |
CERT C | INT35-C. Use correct integer precisions | Prior to 2018-01-12: CERT: Unspecified Relationship |
CERT C | INT32-C. Ensure that operations on signed integers do not result in overflow | Prior to 2018-01-12: CERT: Unspecified Relationship |
ISO/IEC TR 24772:2013 | Arithmetic Wrap-Around Error [FIF] | Prior to 2018-01-12: CERT: Unspecified Relationship |
CWE 2.11 | CWE-682 | 2017-07-07: CERT: Rule subset of CWE |
CWE 2.11 | CWE-758 | 2017-07-07: CERT: Rule subset of CWE |
CERT-CWE Mapping Notes
Key here for mapping notes
...
- Incorrect calculations that do not involve out-of-range bit shifts
Bibliography
[C99 Rationale 2003] | 6.5.7, "Bitwise Shift Operators" |
[Dowd 2006] | Chapter 6, "C Language Issues" |
[Seacord 2013b] | Chapter 5, "Integer Security" |
[Viega 2005] | Section 5.2.7, "Integer Overflow" |
...
...