Files
codeql/cpp/ql/test/query-tests/Likely Bugs/Arithmetic/PointlessComparison/RegressionTests.cpp
Dave Bartolomeo 669ac2f4b4 C++: Fix FP in PointlessComparison due to preprocessor
Reported by an LGTM customer here: https://discuss.lgtm.com/t/2-false-positives-in-c-for-comparison-is-always-same/1943.

Even though the comparison is pointless in the preprocessor configuration in effect during extraction, it is not pointless in other preprocessor configurations. Similar to ExprHasNoEffect, we'll now exclude results in functions that contain preprocessor-excluded code. I factored the similar code already used in ExprHasNoEffect in a non-recursive version into Preprocessor.qll, leaving the recursive version in ExprHasNoEffect.ql. I believe the recursive version is too aggressive for PointerlessComparison, which does no interprocedural analysis.
2019-03-25 16:19:18 -07:00

82 lines
1.3 KiB
C++

// Regression test. The AsmStmt might modify the arguments, which are passed by
// reference.
// Helper function for regression_test_00, below.
static void modify_args(unsigned int& a, unsigned int& b, unsigned int& c, unsigned int& d)
{
#if defined(__GNUC__)
__asm__ __volatile__
(
"cpuid\n\t"
: "+a" (a), "+b" (b), "+c" (c), "+d" (d)
);
#else
a++;
b++;
c++;
d++;
#endif
}
int regression_test_00() {
unsigned int a = 0, b = 0, c = 0, d = 0;
modify_args(a, b, c, d);
const unsigned int x = a;
// 'a' might have been modified by the call to 'modify_args',
// so we do not know if this condition is true or false.
if (x >= 1)
{
return true;
}
return false;
}
static const unsigned int e = -1;
void test_e(int f) {
if (f == e) { // GOOD
// ...
}
}
#define MAX_VAL ((size_t) -1)
typedef unsigned int size_t;
static int foo(size_t *size)
{
int bar;
if (*size <= MAX_VAL) // BAD (pointless comparison) [NO LONGER REPORTED]
*size = MAX_VAL;
}
// ODASA-7205
int regression_test_01(unsigned long bb) {
if (bb + 1 == 0) { // GOOD [NO LONGER REPORTED]
return 0;
} else {
return 1;
}
}
int containsIfDef(int x) {
int result = 0;
if (x > 0) {
result = 1;
}
#if _CONDITION
if (x < 0) {
result = -1;
}
#endif
return result >= 0;
}