Merge pull request #1605 from geoffw0/bitwiseneg

CPP: Make BitwiseSignCheck.ql more accurate
This commit is contained in:
Robert Marsh
2019-07-24 12:33:40 -07:00
committed by GitHub
4 changed files with 25 additions and 6 deletions

View File

@@ -12,9 +12,9 @@
import cpp
from RelationalOperation e, BinaryBitwiseOperation lhs
where lhs = e.getLeftOperand() and
where lhs = e.getGreaterOperand() and
lhs.getActualType().(IntegralType).isSigned() and
forall(int op | op = lhs.(BitwiseAndExpr).getAnOperand().getValue().toInt() | op < 0) and
e.getRightOperand().getValue() = "0" and
e.getLesserOperand().getValue() = "0" and
not e.isAffectedByMacro()
select e, "Potential unsafe sign check of a bitwise operation."

View File

@@ -1,3 +1,5 @@
| bsc.cpp:2:10:2:32 | ... > ... | Potential unsafe sign check of a bitwise operation. |
| bsc.cpp:6:10:6:32 | ... > ... | Potential unsafe sign check of a bitwise operation. |
| bsc.cpp:10:10:10:33 | ... >= ... | Potential unsafe sign check of a bitwise operation. |
| bsc.cpp:18:10:18:28 | ... > ... | Potential unsafe sign check of a bitwise operation. |
| bsc.cpp:22:10:22:28 | ... < ... | Potential unsafe sign check of a bitwise operation. |

View File

@@ -1,15 +1,31 @@
bool is_bit_set_v1(int x, int bitnum) {
return (x & (1 << bitnum)) > 0;
return (x & (1 << bitnum)) > 0; // BAD
}
bool is_bit_set_v2(int x, int bitnum) {
return ((1 << bitnum) & x) > 0;
return ((1 << bitnum) & x) > 0; // BAD
}
bool plain_wrong(int x, int bitnum) {
return (x & (1 << bitnum)) >= 0;
return (x & (1 << bitnum)) >= 0; // ???
}
bool is_bit24_set(int x) {
return (x & (1 << 24)) > 0;
return (x & (1 << 24)) > 0; // GOOD (result will always be positive)
}
bool is_bit31_set_bad_v1(int x) {
return (x & (1 << 31)) > 0; // BAD
}
bool is_bit31_set_bad_v2(int x) {
return 0 < (x & (1 << 31)); // BAD
}
bool is_bit31_set_good(int x) {
return (x & (1 << 31)) != 0; // GOOD (uses `!=`)
}
bool deliberately_checking_sign(int x, int y) {
return (x & y) < 0; // GOOD (use of `<` implies the sign check is intended)
}