...
| Code Block | ||||
|---|---|---|---|---|
| ||||
uint8_t port = 0x5a;
uint8_t result_8 = ( ~port ) >> 4;
|
In this example, a bitwise complement of port is first computed and then shifted 4 bits to the right. If both of these operations are performed on an 8-bit unsigned integer, then result_8 will have the value 0x0a. However, port is first promoted to a signed int, with the following results (on a typical architecture where type int is 32 bits wide):
Expression | Type | Value | Notes |
|---|---|---|---|
|
|
|
|
|
|
|
|
| Whether or not value is negative is implementation-defined. |
|
|
|
Compliant Solution
In this compliant solution, the bitwise complement of port is converted back to 8 bits. Consequently, result_8 is assigned the expected value of 0x0aU.
| Code Block | ||||
|---|---|---|---|---|
| ||||
uint8_t port = 0x5a;
uint8_t result_8 = (uint8_t) (~port) >> 4;
|
...
Bitwise operations on shorts and chars can produce incorrect data.
Recommendation | Severity | Likelihood | Detectable |
|---|
Repairable | Priority | Level | |
|---|---|---|---|
EXP14-C | low | likely | No |
No | P3 | L3 |
Automated Detection
Tool | Version | Checker | Description |
|---|
| Section |
|---|
Compass/ROSE |
| Astrée |
| Supported | |||||||
| Axivion Bauhaus Suite |
| CertC-EXP14 | Fully implemented | ||||||
| CodeSonar |
| LANG.CAST.RIP | Risky integer promotion | ||||||
| Compass/ROSE | |||||||||
| CC2.EXP14 | Fully implemented | |||||||
| Parasoft C/C++test |
| CERT_C-EXP14-a | Avoid mixing arithmetic of different precisions in the same expression | ||||||
| Security Reviewer - Static Reviewer |
| C50 | Fully implemented |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...
...
| VOID EXP15-CPP. Beware of integer promotion when performing bitwise operations on chars or shorts | |
| MISRA-C | Rule 10.5 |
Bibliography
...