Skip to content

Commit ff8e04a

Browse files
committed
CPP: Fix bug.
1 parent 62625cc commit ff8e04a

File tree

3 files changed

+11
-6
lines changed

3 files changed

+11
-6
lines changed

cpp/ql/src/Likely Bugs/Arithmetic/BitwiseSignCheck.ql

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,16 @@ import cpp
1414

1515
from RelationalOperation e, BinaryBitwiseOperation lhs
1616
where
17-
lhs = e.getGreaterOperand() and
17+
// `lhs > 0` (or `0 < lhs`)
18+
// (note that `lhs < 0`, `lhs >= 0` or `lhs <= 0` all imply that the signedness of
19+
// `lhs` is understood, so should not be flagged).
20+
(e instanceof GTExpr or e instanceof LTExpr) and
21+
e.getGreaterOperand() = lhs and
22+
e.getLesserOperand().getValue() = "0" and
23+
// lhs is signed
1824
lhs.getActualType().(IntegralType).isSigned() and
25+
// if `lhs` has the form `x & c`, with constant `c`, `c` is negative
1926
forall(int op | op = lhs.(BitwiseAndExpr).getAnOperand().getValue().toInt() | op < 0) and
20-
e.getLesserOperand().getValue() = "0" and
27+
// exception for cases involving macros
2128
not e.isAffectedByMacro()
2229
select e, "Potential unsafe sign check of a bitwise operation."
Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
| bsc.cpp:2:10:2:32 | ... > ... | Potential unsafe sign check of a bitwise operation. |
22
| bsc.cpp:6:10:6:32 | ... > ... | Potential unsafe sign check of a bitwise operation. |
3-
| bsc.cpp:10:10:10:33 | ... >= ... | Potential unsafe sign check of a bitwise operation. |
43
| bsc.cpp:18:10:18:28 | ... > ... | Potential unsafe sign check of a bitwise operation. |
54
| bsc.cpp:22:10:22:28 | ... < ... | Potential unsafe sign check of a bitwise operation. |
6-
| bsc.cpp:34:10:34:21 | ... >= ... | Potential unsafe sign check of a bitwise operation. |

cpp/ql/test/query-tests/Likely Bugs/Arithmetic/BitwiseSignCheck/bsc.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ bool is_bit_set_v2(int x, int bitnum) {
77
}
88

99
bool plain_wrong(int x, int bitnum) {
10-
return (x & (1 << bitnum)) >= 0; // GOOD (testing for `>= 0` is the logical negation of `< 0`, a negativity test) [FALSE POSITIVE]
10+
return (x & (1 << bitnum)) >= 0; // GOOD (testing for `>= 0` is the logical negation of `< 0`, a negativity test)
1111
}
1212

1313
bool is_bit24_set(int x) {
@@ -31,7 +31,7 @@ bool deliberately_checking_sign(int x, int y) {
3131
}
3232

3333
bool deliberately_checking_sign2(int x, int y) {
34-
return (x & y) >= 0; // GOOD (testing for `>= 0` is the logical negation of `< 0`, a negativity test) [FALSE POSITIVE]
34+
return (x & y) >= 0; // GOOD (testing for `>= 0` is the logical negation of `< 0`, a negativity test)
3535
}
3636

3737
bool is_bit_set_v3(int x, int bitnum) {

0 commit comments

Comments
 (0)