Repository navigation
Conversation
a1c4a25 to
8dc01be
Compare
8dc01be to
d37f6b1
Compare
|
I have created this ticket: https://trac.cppcheck.net/ticket/15000 |
|
I will update the commit message with Fix #15000 ... |
d37f6b1 to
3e3fa63
Compare
3e3fa63 to
2d5f3a7
Compare
|
The PR title should be updated. The commit message will not be shown in the git log but the PR title will. |
Done. PR title updated to "Fix #15000 CheckCondition: detect compareValueOutOfTypeRange for bounded cast/arithmetic expressions" ; let me know if better convention would apply here. |
Thanks! I don't have a strict pattern that must be followed but I typically put parentheses around the ticket title. Most important is that you indicated which ticket it solves.. |
|
I have a feeling that some of the logic should be performed in ValueFlow and not in the check. Currently, ValueFlow only seems to handle |
I agree that checkers should have some nice way to determine min/max values for an expression. If that is put in |
I meant that ValueFlow should determine that the condition is always true/false, instead of having complex parsing logic (in this case, for casts and arithmetic) in the checker. |
2d5f3a7 to
a8d48d3
Compare
1f38959 to
1ebcbe5
Compare
1ebcbe5 to
1de33f6
Compare
|
I rebased against main (no conflicts). |
1de33f6 to
8502e53
Compare
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems in this version.
- Still open: the false positive first reported in C116 is still there. In
void m2(int x) { if (x < 1u || x >= 4294967295u) return; if (~x != 1) use(3); }the PR reportsCondition '~x!=1' is always true. That is wrong: forx == -2,~x == 1. Base gives a different wrong result on this function (x>=4294967295ualways true). - Fixed: the C122
negativeIndexfalse negative (for (int i = n - 1; ...)with an unsignedn). The "tight exclusion" witness invalueFlowForLoopbrings back all of base's warnings. - Reproducer: the #15000 case is reported as
knownConditionTrueFalse. - No new false positives: none of the extra cast, arithmetic, mixed-sign and for-loop cases I tried gave a new false positive. In several of them the PR removes a wrong result that base gives.
Earlier comments
75 earlier comments, 1 open
@jfdeverge, please fix, resolve or reply to the open comments: #69.
Testing
Build: make -j8 cppcheck testrunner in pr/ and make cppcheck in base/ both built without errors.
Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestStl, TestType, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0. I did not run the Python CLI tests this time.
How I compared: every result below compares base and PR using cppcheck -q --enable=style,warning,portability --platform=unix64 --template='{line}:{id}:{message}' <file>.
Re-checked earlier findings
C122 is fixed. Test file l8.c, with these extra lines:
u * 2 - 3u - 1 - 1-(int)uint s = u - 1;used as the start valueif (x < -5) return;
The PR reports every negativeIndex that base reports. It also adds one for for (int i = -(int)u; ...), where base gives none. The reported index there is -2147483647, though the real minimum is -255.
C116 m2 is still open:
void use(int);
void m2(int x) { if (x < 1u || x >= 4294967295u) return; if (~x != 1) use(3); }- Base:
2:knownConditionTrueFalse:Condition 'x>=4294967295u' is always true. This is wrong too. - PR:
2:knownConditionTrueFalse:Condition '~x!=1' is always true. This is wrong, becausex == -2passes the guard and gives~x == 1.
The #15000 reproducer, written with stdint.h types, gives Condition '(((int64_t)((uint32_t)tmp))-1LL)>4294967295LL' is always false.
New probes (p1.c, p2.c, p3.c)
p1.c, about 25 cases: casts combined with + - * / % << >> &, and == against unsigned constants. There are no new false positives. There is one new correct result: uint8_t c = (uint8_t)x; c + 1 > 256 is always false.
p2.c: mixed-sign ==/< against unsigned constants, oppositeInnerCondition, and for-loop start values. Results:
- The results match base except for three improvements:
x <= 0xFFFFFFFFuis now correctly reported as always true.- Base's wrong result for
signed char c == 0xFFFFFFFFuis gone. - Base's false
negativeIndexforfor (int i = n - 1; i < 10 && n; i++)is gone.
- Two wrong results are the same in base and the PR, so the PR did not cause them:
if (x >= 0x80000000u) { if (x == 0x80000000u) }givesoppositeInnerCondition.x >= 0xFFFFFFF0u && x < 5givesincorrectLogicOperator.
p3.c: the at-minimum and at-maximum paths of the rewritten checkCompareValueOutOfTypeRange (INT_MIN <= x, s < 0xFFFFFFFFu, 0xFFFFFFFFu > s, s < 0x80000000u, bool, unsigned char and short). The PR removes four wrong "always true" results from base: lines 7, 11 and 22, all short against an unsigned constant. It gives no new false positives.
Real code: I ran both versions on lib/checkcondition.cpp, lib/mathlib.cpp and cli/cmdlineparser.cpp. The warnings were identical. The PR took 394 s and base 346 s, a single run each, so I could not tell whether the difference is noise.
Automated review of bcd8c72 by Claude. The pull request was built and tested locally.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems in this version.
- Still open (already in comments.md, C116):
void m2(int x) { if (x < 1u || x >= 4294967295u) return; if (~x != 1) use(3); }is still reported asCondition '~x!=1' is always true. That is wrong, becausex == -2passes the guard and gives~x == 1. I did not report it again. - Earlier findings: every other finding from the earlier reviews (C37–C122) that I re-ran now gives the correct result.
- New probes: I tried casts, arithmetic, out-of-range comparisons, mixed-sign comparisons, for loops, per-call-path inference, float bounds and C++ casts. They gave no new false positives, false negatives or crashes. In several cases the PR removes a wrong base result, for example:
short s; s > 0xFFFFuwas reported as always false;signed char c; c > 200uwas reported as always false;uint64_t x; x == -1was reported as always false.
- Real code: base and PR gave identical warnings, and the run time was the same.
Earlier comments
75 earlier comments, 1 open
@jfdeverge, please fix, resolve or reply to the open comments: #69.
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.
Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestStl, TestType, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0.
CLI tests: pytest other_test.py -k "15000 or floating or unsigned_loop or bounded or cast or missing_include" gives 8 passed.
Earlier reproducers (old.c, w.c, s.cpp, bf.c)
- I re-ran about 30 reproducers from C37–C122 on unix64, plus the
wchar_tcase on win64. - All of them now give correct results, with one exception: C116's
m2still gives5:knownConditionTrueFalse:Condition '~x!=1' is always true. - The bitfield dump check gives
bits="0"for~and++. - The #11592 expectation is restored.
New probes: each one compares base and PR with cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{id}:{message}'.
a.c, about 30 cast and arithmetic cases:- Covered: shifts,
/ -1,<<=,*=,+=with wrap, unary minus on casts,_Boolcasts, bitfields and 64-bit wrap. - No new false positives.
- The PR removes base's wrong results for
uint64_t u = x; u + 1 == 0,unsigned u = -(uint8_t)x; u > 255,uint8_t y += 200; y < 100andy += 0xFFFFFF00u; y < 10.
- Covered: shifts,
b.c, plaincharwith--funsigned-char,--fsigned-charand--platform=unspecified: the new results are correct for an unsigned char ((char)x == -1is always false), and there is no output with the unspecified platform.c.c, per-call-path inference: functions called with several argument pairs, and values from conditions. There are two correct new warnings:- negativeIndex in
a[x - y]for the callf1(1,2); - zerodiv in
100 / (x - y)for the callf4(5,5). - I found no false "always" conditions.
- negativeIndex in
d.c, float>=/<=guards followed by other comparisons,sqrtand int casts: same results as base.e.c, about 32compareValueOutOfTypeRangecases on unix64, win64 and unix32: every result the PR gives is correct. The PR removes four wrong base results (short/signed charagainst unsigned constants) and two wrong base results foruint64_t/unsigned longagainst -1.f.c, for loops with cast start values or limits: same results as base.g.c, mixed-sign comparisons, includinglong longagainst0xFFFFFFFFu,shortagainst0xFFFFFFFFuandintagainst0xFFFF…ull:short s; if (s == 0xFFFFFFFFu) { if (s == -1) }is now correctly reported as always true; base gave a wrongoppositeInnerCondition.int x; if (0xFFFFFFFFu == x) { if (x == -1) }is now correctly reported as always true; base said always false.
h.cpp, C++ casts:static_castto anenum class, templates, functional casts,constexprand'\xff'. The only new result isunsigned char c; c == '\xff'always false, which is correct.
Real code: I ran both builds with -j3 --enable=style,warning,portability --platform=unix64 --library=posix on lib/checkother.cpp, lib/checkstl.cpp, cli/cmdlineparser.cpp, test/cfg/windows.cpp and test/cfg/gnu.c. The output is identical. The PR took 452 s and base 450 s.
Seen but not caused by the PR: size_t n; std::vector<int> v; if (v.size() < n + 1) is reported as always true by both base and the PR. The PR removes the plain-variable versions of this wrong result (0 < n + 1, n + 1u != 0u).
Automated review of 98a4f1b by Claude. The pull request was built and tested locally.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems. The PR now handles correctly the last open item from earlier reviews (C116, ~x != 1 after if (x < 1u || x >= 4294967295u) return;). It no longer reports that condition. Base reported x>=4294967295u as always true there, which was also wrong.
On my probes every result that differs from base is either a correct new warning or a removed wrong base warning. The probes covered casts with arithmetic and compound assignment, loops with cast start values, clamp-and-narrow, mixed-sign comparisons (including constants of promoted rank such as (unsigned short)0xFFFF against short), enums, bitfields, char16_t/char32_t and C++ casts. Examples:
(uint16_t)wrap ony + 1: no longer wrongly always false.(unsigned)x/(uint64_t)xof a value that may be negative: no longer wrongly always false.x < 0x80000000ufollowed byx < 0: base said always true (wrong); the PR says always false (correct).
One wrong result is not caused by the PR: if (x > 5u) { if (x < 0) ... } with int x gives a wrong oppositeInnerCondition in both base and the PR, even though the PR changed isOppositeCond for mixed-sign constants.
Earlier comments
71 earlier comments, 0 open
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.
Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestStl, TestType, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0.
CLI tests: pytest other_test.py -k "15000 or floating or unsigned or bounded or cast" gives 4 passed. These include the two new tests.
Probes: each one compares the PR and base with cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{column}:{id}:{message}'.
m2.c, the PR reproducer and C116'sm2:- The PR reports the reproducer's condition as always false.
m2is no longer reported.- Base gives a wrong
x>=4294967295ualways true.
p.c,short/signed charagainstunsigned short/unsigned charconstants (variables, casts,||, nestedif): the newcompareValueOutOfTypeRangeErrorresults are all correct, because both operands are promoted toint. TheknownConditionTrueFalseresults are the same as base.q.c, 22 cases of a value from(uint8_t)/(int8_t)/(uint16_t)followed by*=,+=,<<=,|=,~,%,/,>>, unary minus and modification through a pointer or function:- The only new result is
y = ~y; y > 255always true, which is correct. - Base's wrong
uint16_t y = y + 1; y == 0always false is gone. - Base's wrong
integerOverflowCondonint8y * yis gone.
- The only new result is
r.c, for loops with cast start values and limits, andINT_MIN/LLONG_MINlimits:- Results are the same as base, except that base's wrong
compareValueOutOfTypeRangeErrorfori < -2147483647-1is replaced by a correctknownConditionTrueFalse. - No crash.
- Results are the same as base, except that base's wrong
s.cpp, enum class, bitfields,char16_t/char32_t,static_cast, functional casts, multiplication of casts,/ -1,<<: the only new result is(uint32_t)x + 0ULL > 4294967295ULLalways false, which is correct.t.c, condition-bounded values followed by casts or wrapping arithmetic: the PR removes 7 wrong base results, for exampleif (x < -5 || x > 5) return; unsigned y = (unsigned)x; y > 5always false, andif (x > 300) { uint8_t y = (uint8_t)x; y == 0 }always false. It adds none.u.c, mixed-sign nested and else-if conditions:x < 0x80000000u→x < 0: correctly always false; base said always true.x <= 5u→x < 0: correctly always false.x > 5u→x < 0: a wrongoppositeInnerConditionin both base and the PR, so not caused by the PR.
Real code: I ran lib/token.cpp with --enable=style,warning. The output is identical and both take 79 s.
Automated review of a66da09 by Claude. The pull request was built and tested locally.
|
Test results for commit a66da09 (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-51-20-36-10.eu-north-1.compute.amazonaws.com/pr-8819/ Posted automatically by the cppcheck PR test runner. +N: warnings only with this PR, -N: warnings only with main. The AI review is written by Claude and can be wrong. |
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
One new false negative. The new for-loop start-value logic in valueFlowForLoop (lib/valueflow.cpp:5798) ignores a start value whose only lower limit is the minimum of its unsigned type. When the loop variable starts from an unsigned variable (for (int i = n; …) with an unsigned char, unsigned short or unsigned n, or a (uint8_t) cast), the PR no longer gives the loop variable a possible value at that minimum. As a result, real negativeIndex errors (a[i - 1]) and zerodiv errors (100 / i) that the merge base reports are lost: n == 0 is a valid input. The code comment treats this lower limit as vacuous, but the start value really can be 0. Earlier reviews did not raise this; C122 only covered i = n - 1.
Apart from this I found no new problems. The unit tests and the PR's CLI tests pass. I re-ran the reproducers of the main earlier findings, and the results are correct now or the same as base.
Comments
72 comments, 0 open, 1 new
@jfdeverge, please fix, resolve or reply to the open and new comments: #72.
For #72 (false negative), it is enough to create a Trac ticket and link it here. It does not need to be fixed in this PR.
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.
Unit tests: ./testrunner with TestCondition, TestValueFlow, TestBufferOverrun, TestStl, TestType, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all exit with 0.
CLI tests: pytest other_test.py -k "15000 or floating or unsigned or bounded or cast or missing_include" gives 8 passed. That includes the two new tests.
New false negative: for-loop start value from an unsigned variable
lp2.c:
#include <stdint.h>
int a[10];
void p1(unsigned char n) { for (int i = n; i < 10; i++) a[i - 1] = 0; }
void p2(unsigned n) { for (unsigned i = n; i < 10; i++) a[i - 1] = 0; }
void p3(int n) { if (n < 0) return; for (int i = n; i < 10; i++) a[i - 1] = 0; }
void p4(void) { for (int i = 0; i < 10; i++) a[i - 1] = 0; }
void p5(int x) { for (int i = (uint8_t)x; i < 10; i++) a[i - 1] = 0; }
void p6(unsigned char n) { for (int i = n; i < 10; i++) a[i - 2] = 0; }
void p7(unsigned short n) { for (int i = n; i < 10; i++) a[i - 1] = 0; }
void p8(unsigned char n) { for (int i = n; i < 10; i++) { int j = i - 1; a[j] = 0; } }Command: cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{id}:{message}' lp2.c
Base:
3:negativeIndex:Array 'a[10]' accessed at index -1, which is out of bounds.
5:negativeIndex:Array 'a[10]' accessed at index -1, which is out of bounds.
6:negativeIndex:Array 'a[10]' accessed at index -1, which is out of bounds.
7:negativeIndex:Array 'a[10]' accessed at index -1, which is out of bounds.
8:negativeIndex:Array 'a[10]' accessed at index -2, which is out of bounds.
9:negativeIndex:Array 'a[10]' accessed at index -1, which is out of bounds.
10:negativeIndex:Array 'a[10]' accessed at index -1, which is out of bounds.
PR (the same with --check-level=exhaustive):
5:negativeIndex:Either the condition 'n<0' is redundant or the array 'a[10]' is accessed at index -1, which is out of bounds.
6:negativeIndex:Array 'a[10]' accessed at index -1, which is out of bounds.
The warnings for p1, p5, p6, p7 and p8 are lost. Each of them really happens when n == 0 or x == 0.
zerodiv is lost in the same way (lp4.c):
int z1(unsigned char n) { int s = 0; for (int i = n; i < 10; i++) s += 100 / i; return s; }
int z2(unsigned n) { int s = 0; for (unsigned i = n; i < 10; i++) s += 100 / i; return s; }- Base:
1:zerodiv:Division by zero.and2:zerodiv:Division by zero. - PR: no output.
With --debug on p1, base gives i {<=9,!>=10,>=0,!<=-1} and the PR gives i {<=9,!>=10,!<=-1}. The possible >=0 start value is gone.
Other probes (same as base, or better):
- Casts with arithmetic: about 20 cases with
*,<<,/,%, unary minus,++,*=and widening to 64 bits. No new false positives. Two wrong base results are gone:uint8_t d = c + 1; d == 0andc++; c == 0. - Mixed-sign comparisons: 19 cases of
isOppositeCond,||/&&andelse ifwith0xFFFFFFFFu/0x80000000u. Every new result is correct, for examplex > 0x7FFFFFFFu→x >= 0is now always false; base said always true. The remaining wrong results are the same in base. - Shift counts, float
>=/<=guards withlog/sqrt/acos/int casts, enums with an underlying type,boolandcharcasts: same as base. One new correct result:invalidFunctionArgforlog(x)underx <= 0.0 && x >= 0.0. - Earlier reproducers re-checked: resize guard,
a[i + 1]with an unsigned index,char == 0xFF, flag enum,~(uint32_t)x,y -= 1after a cast, negative value cast to unsigned,short == 0xFFFFu,(char)xzerodivcond, andwchar_ton win64. All give correct results. - Timing: two generated files (900 cast/condition statements, and 200 loops with conditions) take the same time with base and the PR.
Automated review of 7e09034 by Claude. The pull request was built and tested locally.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new false positives, false negatives or crashes. The last open finding, C129 (for loop starting from an unsigned value, a[i - 1] and 100 / i), is fixed: the PR reports the negativeIndex and zerodiv warnings again, as base does.
New finding: one real file is about 25% slower to check. On lib/vf_settokenvalue.cpp the check takes about 50 s with the PR and about 40 s with base. The warnings are the same. --showtime=summary shows that base reaches a fixpoint after 3 valueflow passes, and the PR needs 4 (the default maxIterations). Each pass takes about the same time in both versions, so the extra pass is the whole slowdown. The cast and range facts keep changing in pass 3. On test/cfg/std.c the times are the same, and the 1000-package run in C127 shows only +0.6%. So this is probably limited to some files, but it is worth a look.
All earlier findings that I re-ran are fixed.
Comments
52 comments, 0 open, 0 new
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.
Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestType, TestStl, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0.
CLI tests: pytest other_test.py -k "15000 or bounded or cast or unsigned or float" gives 4 passed.
Reproducer: the #15000 case gives knownConditionTrueFalse: Condition '(((int64_t)((uint32_t)tmp))-1LL)>4294967295LL' is always false. Base gives nothing.
C129: this input now gives the same four warnings as base (three negativeIndex, one zerodiv):
int a[10];
void p1(unsigned char n) { for (int i = n; i < 10; i++) a[i - 1] = 0; }
void p7(unsigned short n) { for (int i = n; i < 10; i++) a[i - 1] = 0; }
void p5(int x) { for (int i = (uint8_t)x; i < 10; i++) a[i - 1] = 0; }
int z2(unsigned n) { int s = 0; for (unsigned i = n; i < 10; i++) s += 100 / i; return s; }Differential fuzzing: I generated 30 files with 60 functions each, all checked with --platform=unix64. Each function:
- takes an 8- or 16-bit parameter;
- applies random casts, arithmetic,
~and clamps to it; - ends with a comparison against a boundary constant.
I compiled every file with gcc -fwrapv and ran it on all input values. Then I checked each "always true" or "always false" claim (knownConditionTrueFalse or compareValueOutOfTypeRangeError) on the final condition against the real results. The PR made no wrong claim. Base made several, for example ((int8_t)((int)z)) != -1 reported as always true.
Other probes, PR compared with base:
- Cast and arithmetic cases: about 40 of them, including bitfields,
bool,char16_t/wchar_t, enums,size_t→int, pointer→uintptr_t, andswitchon a cast. Every difference is a correct new warning or a wrong base warning that is now gone. Examples:(uint8_t)xafterx <= 10is no longer wrongly always false;uint8_t y = x + 1; y == 0is no longer wrongly always false;int64_t > INT64_MAXis a correct new warning.
- Mixed-sign comparisons:
intagainst0x80000000uand0xFFFFFFFFu,signed char/charagainst0x80000000u, also with--funsigned-char. All results are correct. - Values from different call sites: the new warnings are correct (
g(12,0)gives index 12,g(3,5)gives -2). I found no wrong pairing of values from different paths. - Earlier reproducers (C37, C102, C108, C117, C119, C121): all give correct results.
Timing:
cppcheck -q --enable=style,warning --platform=unix64 /work/base/lib/vf_settokenvalue.cpp
pr 49578ms base 40545ms pr 50527ms base 39820ms
- With
--showtime=summary, base showsvalueFlowAfterMove ... 1/2/3and the PR shows... 1/2/3/4. The time per pass is about the same. --debug-warningsgives novalueFlowMaxIterationsmessage for either version, so the PR does reach its fixpoint, one pass later.- On
test/cfg/std.cthe times are equal (about 4.4 s), and the output on both files is identical.
Automated review of beae574 by Claude. The pull request was built and tested locally.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new false positives, false negatives or crashes. The one problem still open is the slowdown on lib/vf_settokenvalue.cpp that C130 reported. It still reproduces on this version: 51.7 s with the PR against 42.4 s with base, with the same warnings (about +22%).
The #15000 reproducer is reported. All earlier findings that I re-ran are fixed, as listed below. About 90 new cast, arithmetic, loop and platform probes either gave the same result as base or gave a correct new result or removed a wrong base result.
Comments
75 comments, 1 open, 0 new
@jfdeverge, please fix, resolve or reply to the open and new comments: #75.
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.
Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestType, TestStl, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0. I did not run the Python CLI tests.
Timing (C130, still open):
time pr/cppcheck -q --enable=style,warning --platform=unix64 base/lib/vf_settokenvalue.cpp -> real 0m51.7s
time base/cppcheck -q --enable=style,warning --platform=unix64 base/lib/vf_settokenvalue.cpp -> real 0m42.4s
Both versions give the same warnings.
New probes, PR compared with base. All runs use cppcheck -q --enable=style,warning[,portability] --template='{line}:{id}:{message}'.
a.c, 23 cases on unix64: casts combined with*,<<,%,>>,/ -1, unary-onint8_t,*=/<<=/-=on cast values, anduint64_t/int64_tedge values.- New result:
long long y = (unsigned)x; y -= 4294967296LL; y >= 0is always false. This is correct. - Base wrongly reports
uint64_t y = (uint64_t)x; y + 1 == 0as always false. The PR does not.
- New result:
b.cpp, with--library=std: casts used as array indexes,std::vectorindexes, shift counts, divisors, loop starts andswitchoperands. The output is identical to base.c.c: values from different call sites and branches (g(12,0); g(3,5),?:pairs, struct members).- New results:
a[x-y]at index 12 and -2, ands.m+1>256is always false. Both are correct.
- New results:
d.con unix32, win64, unix64 and with--funsigned-char:long/size_t/ptrdiff_tcasts and plainchar.- Base gives several wrong results that the PR no longer gives, for example
(unsigned long)x+1ul==0andchar c=(unsigned char)x; c<0. - The PR's new results are correct.
- Base gives several wrong results that the PR no longer gives, for example
e.cpp:enum class, plain enums, template casts,booland differences of two casts.- New results:
(F)(uint8_t)x == FB(300),d < -4294967295LLanda-b < -255are always false. All are correct.
- New results:
Earlier reproducers re-run on the PR:
- C37
(uint32_t)x-1u==0xFFFFFFFFu - C90
~on a cast - C92
y -= 1 - C94
shorti++ - C96
(char)x=='A' - C84
char c == 0xFF - C77
a[i+1] - C102 flag enum
- C112 and C114 clamp-then-narrow
- C122 and C128 loop start
- C79
&&loop - C53
i-- > -3 - C98
wchar_ton win64 - C55 and C58 float cases
All give the expected results now. The containerOutOfBounds false positive from C51 is gone. The remaining v.size()<entries+2 always true comes from base as well.
Automated review of 3c0d1a8 by Claude. The pull request was built and tested locally.
|
This pull request has merge conflicts that must be resolved. |
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems. This is the most heavily reviewed version so far. All the earlier findings I re-ran are fixed: plain char == 0xFF, the flag enum, a[i+1] with an unsigned loop index, (uint32_t)x - 1u wrapping, the float uninitvar case, short == 0xFFFFu, the ~x != 1 case, the || loop zerodiv, clamp-then-narrow, and the negativeIndex case with an unsigned loop start. The one earlier finding that is still open is the slowdown on lib/vf_settokenvalue.cpp from C130/C131. Nobody has answered it and I did not measure it again. comments.md also says the PR has merge conflicts with main again (C132).
Comments
75 comments, 1 open, 0 new
@jfdeverge, please fix, resolve or reply to the open and new comments: #75.
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.
Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestType, TestStl, TestOther, TestFunctions, TestUninitVar and TestSymbolDatabase all give Tests failed: 0.
CLI tests: pytest other_test.py -k "15000 or floating or unsigned_loop or bounded or cast or missing_include" gives 8 passed.
PR compared with base: all runs use cppcheck -q --enable=style,warning --platform=unix64, and s.c was also run with --platform=win64.
p1.c: about 24 cast and arithmetic cases:<<,*,/,%,~,^=,|=,<<=,*=and unary-on(uint8_t),(int8_t)and(uint16_t)values, plus in-place++and+=.- The base false positive
uint8_t c=(uint8_t)x; c=c+1; c==0"always false" is gone. - New result:
int i=(int)x; i++; i==-2147483648is reported as always false. That value can only come from signed overflow, so I don't count it as a false positive.
- The base false positive
p2.c:- float→int casts, pointer difference cast to
uint32_t, and sign-extending casts tosize_t,uint64_tanduint32_t; _Bool,switchon a cast, loops that start from a cast, and(int64_t)(uint32_t)x << 32.- The PR gives no new false positives here.
(int)d > 2147483647changes ID from compareValueOutOfTypeRangeError to knownConditionTrueFalse; both are correct.
- float→int casts, pointer difference cast to
p3.cpp: templates withstatic_cast, functional casts,++/+=/--onuint8_t/uint16_t, and divisors built from casts. The output is identical to base.s.c: reproducers of the main earlier findings (C84, C98, C102, C77, C37, C55, C120, C116, C104, C112, C122, C92). All give the expected results with the PR.
I did not measure timing again.
Automated review of ff67541 by Claude. The pull request was built and tested locally.
|
AI: about performance issue in review 75, it is fixed by move of the single valueFlowSubFunction to the end of the pass list rather than duplicating it. |
|
Test results for commit ff67541 (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-51-20-36-10.eu-north-1.compute.amazonaws.com/pr-8819/ Posted automatically by the cppcheck PR test runner. +N: warnings only with this PR, -N: warnings only with main. The AI review is written by Claude and can be wrong. |
|
Hi all, I think this is a good step for human check, the latest AI report provides an overall improvement status. But AI identified two regressions. The "acceptable regression" is not fully acceptable to me so you could (if you agree) create a new ticket and I can work on it. The "regression" is about a "note:", not sure it is meaningful to try to keep. |
pfultz2
left a comment
There was a problem hiding this comment.
Some cleanups. Each suggestion can be applied on its own. The other comments need changes in more than one place.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found one new problem. It is an incomplete part of the enum-type fix and not a regression. getEnumType() now widens an enum whose enumerators don't fit in int to unsigned int (or wider), but parsedecl() at lib/symboldatabase.cpp:7845 copies only .type from it. Variables of such an enum still get the default sign signed, while their enumerators are unsigned. The variable then gets the signed truncated value, so E e = B; if (e > 2147483647) with B = 0xFFFFFFFF is reported as "always false" (assigned value is -1). In C++ this is wrong, because the underlying type is unsigned int. Base also gives a false positive here, with a different message. The exact cases from C102/C103 (f == F_HIGH) are fixed now.
The case from #15000 is reported, all the related unit tests pass, and in about 60 hand-written cast and arithmetic cases I found no other wrong results. The PR also removes a base false positive: uint8_t x = c; x += 10; if (x < 10). Every regression case from the earlier reviews that I re-ran (C37, C51, C55, C58, C102) is fixed.
Comments
27 comments, 0 open, 1 new
@jfdeverge, please fix, resolve or reply to the open and new comments: #27.
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both succeeded.
Unit tests: TestCondition, TestValueFlow, TestType, TestOther, TestBufferOverrun, TestStl, TestUninitVar, TestFunctions and TestSymbolDatabase all pass. In test/cli/other_test.py, -k "float or cast or 15000" gives 3 passed.
Hand-written tests: run with cppcheck -q --enable=style,warning --platform=unix64 (also unix32, win64 and win32A for the platform-dependent cases), comparing the PR with base:
- The #15000 reproducer and variations (casts through
int64_t/uint32_t/uint16_t/int8_t, unary minus,%, subtraction of a large constant,-=inside loops, struct members,|/^/>>): every warning is correct, and the cases that are not reported are only false negatives. - Platform-dependent
long/wchar_t/size_tcasts: the results are correct on all four platforms. - Re-runs of the regression cases from C37, C51, C55, C58 and C102: they are all fixed. The
negativeIndex,i+1==0ands+1u==0uwarnings are back, and the float uninitvar and floatConversionOverflow false positives are gone.
Problem (enum variables keep the signed sign):
void use(int);
enum E { A = 0, B = 0xFFFFFFFF };
void m4() { E e = B; if (e > 2147483647) use(4); }
void m1(E e) { if (e > 0xFFFFFFFFu) use(1); }
enum Flags { F_NONE = 0, F_HIGH = 0x80000000 };
void c() { Flags f = F_HIGH; if (f > 0) use(3); }cppcheck -q --enable=style,warning --platform=unix64 g.cpp, output with the PR:
g.cpp:3:28: style: Condition 'e>2147483647' is always false [knownConditionTrueFalse]
g.cpp:3:19: note: Assignment 'e=B', assigned value is -1
g.cpp:4:..: style: Comparing expression of type 'signed int' against value 4294967295. Condition is always false. [compareValueOutOfTypeRangeError]
g.cpp:6:36: style: Condition 'f>0' is always false [knownConditionTrueFalse]
g.cpp:6:22: note: Assignment 'f=F_HIGH', assigned value is -2147483648
- What
--debugshows:B always 4294967295on the enumerator bute always -1on the variable. - Why the warnings are wrong: in C++ both enums have
unsigned intas underlying type, soe > 2147483647andf > 0are true. - Base: gives a false positive for the same code, with a
compareValueOutOfTypeRangeErrormessage. - Line 4: the conclusion happens to be correct, but the message names the wrong type.
Not tested: the GUI was not built because the PR does not change gui/. I only ran the Python tests selected by -k.
Automated review of 15be3ad by Claude. The pull request was built and tested locally.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
New false positive: an unsigned variable compared with a negative signed constant gets the wrong value in the branch. After if (u == -1) with unsigned u, the true branch gives u the value -1 (--debug: u always -1) where it should be 4294967295. The PR now also gives the literal 0xFFFFFFFFu its unsigned value (4294967295). Together these produce wrong results: if (u == -1) { if (u == 0xFFFFFFFFu) } is reported as oppositeInnerCondition, and if (u != -1) return; if (u == 0xFFFFFFFFu) is reported as "always false". Base gets both right ("always true"). castConstantToOperandType()/getUnsignedDomainSizes() only convert an unsigned constant compared with a signed operand. The mirror case, a negative signed constant compared with an unsigned operand of at least the constant's rank, is not converted. Comparing with -1 as a sentinel is common, so these false positives will show up in real code.
All the earlier findings that I re-ran give the right result now (details in the earlier list). I found no other new problems.
Comments
124 comments, 0 open, 1 new
@jfdeverge, please fix, resolve or reply to the open and new comments: #124.
Testing
Build: make cppcheck testrunner in pr/ and make cppcheck in base/ both succeeded.
Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestStl, TestType, TestOther, TestFunctions, TestUninitVar, TestSymbolDatabase and TestNullPointer all give Tests failed: 0. In test/cli/other_test.py, the new tests (-k "floating_strict or unsigned_loop_index" and -k 15000) pass.
Reproducer: the #15000 case gives Condition '(((long long)((unsigned int)tmp))-1LL)>4294967295LL' is always false [knownConditionTrueFalse] on unix64 and win64. Base gives nothing.
Earlier findings: I re-ran about 35 reproducers from the earlier reviews against base and PR. These were: the wrap-around cases, the s+1u==0u and i+1==0 cases, negativeIndex with a loop condition, float uninitvar, clamp-then-narrow and the && form of it, the mixed-sign literal and variable cases, short == 0xFFFFu, plain char == 0xFF, char == 300, wchar_t on win64, the flag enum and E e = B, ~(uint32_t)x, in-place y -= 1/i++ after casts, (char)0, the || for loop, the unsigned loop start, the resize guard, --platform=unspecified, ~x != 1, (unsigned)x with negative x, and bitfield valueType-bits in the dump. All of them now give the correct result.
New probes: casts combined with unary -, <<, >>, %, /, *, &, |, ^, ?:, float to int and 64-bit operands gave no new false positives (n1.c). The PR also removes a wrong base result for 10u - (uint8_t)x. Among the mixed-sign comparison probes, the PR fixes several wrong base results (short s > 0xFFFFu, int8_t == 0xFFFFFFFFu, uint64_t u == -1, unsigned long u == -1L), but it adds the problem below.
New false positive: unsigned operand compared with a negative signed constant
n4.c:
void use(int);
void a1(unsigned u) { if (u != -1) return; if (u == 0xFFFFFFFFu) use(1); }
void a3(unsigned u) { if (u == -1) { if (u > 100u) use(3); } }
void a5(unsigned u) { const unsigned M = 0xFFFFFFFFu; if (u == -1) { if (u == M) use(5); } }
void a9(unsigned u) { if (u == -2) { if (u == 0xFFFFFFFEu) use(9); } }
void c15(unsigned u) { if (u == -1) { if (u == 0xFFFFFFFFu) use(15); } }cppcheck -q --enable=style,warning --platform=unix64 n4.c (unix32 behaves the same)
PR:
n4.c:2:50: style: Condition 'u==0xFFFFFFFFu' is always false [knownConditionTrueFalse]
n4.c:3:44: style: Condition 'u>100u' is always false [knownConditionTrueFalse]
n4.c:4:76: warning: Opposite inner 'if' condition leads to a dead code block. [oppositeInnerCondition]
n4.c:5:44: warning: Opposite inner 'if' condition leads to a dead code block. [oppositeInnerCondition]
n4.c:6:45: warning: Opposite inner 'if' condition leads to a dead code block. [oppositeInnerCondition]
Base gives the correct results: 'u==0xFFFFFFFFu' is always true, 'u>100u' is always true, 'u==M' is always true, 'u==0xFFFFFFFEu' is always true. In every case the inner condition really is always true. --debug with the PR shows u always -1 inside if (u == -1) { ... }, while 0xFFFFFFFFu always 4294967295.
Automated review of d2a8dbb by Claude. The pull request was built and tested locally.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems in this version. The two newest findings are fixed:
- C233: after
if (u == -1)with anunsigned u, all the reproducers now give the same correct "always true" results as base. - C231: a variable of a high-bit enum is now typed
unsigned int.
All other earlier reproducers I re-ran give correct results. The #15000 reproducer is reported as knownConditionTrueFalse.
On my new probes I found no new false positive or crash. Every result that differs from base is either a correct new warning or a wrong base warning that is now gone. The probes covered casts with arithmetic, out-of-range and mixed-sign comparisons, isOppositeCond, and calls into other functions from branches that can never run.
Comments
53 comments, 0 open, 0 new
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built.
Unit tests: these all give Tests failed: 0: TestCondition, TestValueFlow, TestBufferOverrun, TestStl, TestType, TestOther, TestFunctions, TestUninitVar, TestSymbolDatabase, TestNullPointer and TestAstUtils.
Python CLI tests: pytest other_test.py -k "15000 or floating_strict or unsigned_loop_index or missing_include" gives 7 passed.
Reproducer: the #15000 code from the description, run with --platform=unix64:
- PR:
9:knownConditionTrueFalse:Condition '(((long long)((unsigned int)tmp))-1LL)>4294967295LL' is always false - Base: nothing.
Earlier findings:
- The C232/C233
n4.ccases (u == -1followed byu == 0xFFFFFFFFu,u > 100u,u == M,u == 0xFFFFFFFEu) now give the same correct "always true" results as base. - The C231 enum cases now give correct results:
E e = B; e > 2147483647→ always trueFlags f = F_HIGH; f > 0→ always truee > 0xFFFFFFFFu→ namesunsigned int
- I also re-ran these older reproducers and all give correct results: C37, C53, C55, C58, C77, C79, C84, C90, C98 (win64), C102, C104, C112, C116 and the resize guard.
New probes, PR against base, --enable=style,warning --platform=unix64:
- Casts and arithmetic (
p1.c, 30 cases):- Narrowing and widening casts,
<<=,*,/,>>and unary-on cast values. (int64_t)x < 0,(uint16_t)(uint8_t)x > 255andswitchonuint8_t.- New results:
x < 5ufollowed byx < 0is now always false, and(uint16_t)(uint8_t)x > 255is now always false. Both are correct. - Removed: base's wrong
c = -c; c == 255"always false".
- Narrowing and widening casts,
- Out-of-range comparisons (
cv.cpp,neg.c):- Bitfields,
bool,char16_t/char32_t,wchar_t, 64-bit limits, andu == -1/u == -1L/-1 == uwith unsigned operands. - The PR removes base's wrong "always false" for
uint32_t u == -1,uint64_t u == -1andunsigned long u == -1L. - New result:
int64_t u < INT64_MINis always false, which is correct. bool b; b == 2no longer getscompareValueOutOfTypeRangeError, butcompareBoolExpressionWithIntstill reports it.
- Bitfields,
- Opposite conditions (
oc.c, mixed-sign constants):- New results:
x >= 0x80000000ufollowed byx < 0is now always true, and thex >= 0version always false. Both are correct. - Base's existing wrong
incorrectLogicOperatoronx == 0xFFFFFFFFu && x == -1is unchanged. The PR did not cause it.
- New results:
- Calls to other functions from branches that can never run (
sf*.c, newisInUnreachableBranch/skipUnreachableBranchinvalueFlowSubFunction):- Calls in loop bodies guarded by a flag that changes inside the loop are still followed, the same as base.
- The PR drops base's false positive for
const int dbg = 0; if (dbg) h(25);.
Not completed: I tried to time lib/vf_settokenvalue.cpp (the C130 slowdown), but the container has neither /usr/bin/time nor bc, so I got no times. The warnings were the same for base and PR.
Automated review of 794deec by Claude. The pull request was built and tested locally.
|
This pull request has merge conflicts that must be resolved. |
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems in this version. The #15000 reproducer is reported as knownConditionTrueFalse and base reports nothing. The rewritten checkCompareValueOutOfTypeRange gave correct results on about 40 mixed-sign, out-of-range, char and bool comparisons. About 90 probes covered cast-bounded arithmetic, loops, in-place updates, goto/switch/lambda changes and values from different paths. None of them gave a false positive or a crash. Every result that differs from base is a correct new warning or a wrong base warning that is now gone. Five wrong base results are gone, for example u32 > -1L, s8 == 0xFFFFFFFFu and the unsigned wrap after p <= 10.
One small point, not a defect: in valueFlowSubFunction, isInUnreachableBranch(scope->bodyStart) is called with a function scope. Walking nestedIn from a function scope only reaches class, namespace and global scopes, never an if/else scope, so that check looks like it can never fire. The per-token skipUnreachableBranch is the one that does the work.
The PR still has merge conflicts (C239).
Comments
98 comments, 0 open, 0 new
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both succeeded.
Unit tests: TestCondition, TestValueFlow, TestBufferOverrun, TestStl, TestType, TestOther, TestFunctions, TestUninitVar, TestSymbolDatabase, TestNullPointer and TestAstUtils all give Tests failed: 0.
Python CLI tests: pytest other_test.py -k "15000 or floating_strict or unsigned_loop_index" gives 3 passed.
Reproducer (--platform=unix64):
- PR:
Condition '(((int64_t)((uint32_t)tmp))-1LL)>4294967295LL' is always false - Base: nothing.
Probes (--enable=style,warning --platform=unix64, PR against base):
p1.c/p2.c(about 45 cases): casts combined with+ - * / % << >> & | ^ ~, unary-,?:, float to int,y--/y -= 1/c += 200after a narrowing cast, and 64-bit operands.- New correct results:
~y < 0xFFFFFF00uwithy = (unsigned char)x,(long)(int)x + 1 > 2147483648L,y % 100 > 99. - Base false positives that are gone:
uint8_t y; y--; y == 255,uint8_t z = y + 1; z == 0,(uint16_t)(y + 1) == 0,(x % 10u) - 5u > 4u.
- New correct results:
p3.cpp/p7.c(control flow): values changed in loops,goto,switchfallthrough, a lambda capture by reference, a pointer, a reference, a call that takes the address,do/while, andforloops bounded by a cast value. No false positives. A new correct result:n < v.size()afterv.size() > 300withn = static_cast<uint8_t>(x)is always true.p6.c(combinations across paths):p - qwherepandqcome from the same or opposite branches, and ranges of the two operands. No false positive across paths.- New correct results:
p - q > 255andp - q < -255. - Gone: base's wrong
p - 10 > 245uafterif (p > 10) return;.
- New correct results:
p8.c: base'sfor (unsigned i = y; i > 0; i--) if (i - 1 > 254u)"always false" is a base false positive, and the PR drops it correctly.p4.c/p5.c(compareValueOutOfTypeRange):int8_t,uint8_t,int16_t,uint16_t,int32_t,uint32_t,int64_t,uint64_t,long,unsigned long,char,_Booland bitfields against in-range, boundary, negative and unsigned constants. All PR results are correct.- Base results that were wrong and are gone:
s8 == 0xFFFFFFFFu,s8 > 0xFFFFFF7Fu,s8 < 0x80u,ul == -1, andul > -1L(base said "always true", the PR says "always false", which is correct).
- Base results that were wrong and are gone:
- Earlier findings re-run (
e.cpp): C37, C51 (resize guard), C84 (char c == 0xFF), C90 (~), C96 ((char)0zerodiv), C102 (flag enum), C112 (clamp-then-narrow) and C232 (u == -1). All give the correct result now.
Timing: with -Ilib, checking lib/checkcondition.cpp, lib/token.cpp and lib/mathlib.cpp took 5m10s with the PR and 4m53s with base, about 6% slower. The warnings were the same. The unit tests were running at the same time, so the numbers are rough.
Automated review of 4bbaae3 by Claude. The pull request was built and tested locally.
|
Test results for commit 4bbaae3 (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-51-20-36-10.eu-north-1.compute.amazonaws.com/pr-8819/ Posted automatically by the cppcheck PR test runner. +N: warnings only with this PR, -N: warnings only with main. The AI review is written by Claude and can be wrong. |
|
This pull request has merge conflicts that must be resolved. |
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems in this version. The #15000 reproducer is still reported. The changed unit-test suites pass. My probes found no regressions, either from the cast-range propagation or from the new dropInvalid() commit for valueFlowSubFunction. That commit drops only the written argument from the MultiValueFlowAnalyzer and keeps tracking the other arguments. On the sources I compared, base and the PR gave the same warnings, and the hand-written subfunction cases gave the same results. One probe showed that the PR fixes a base false positive: (unsigned)-y > 0xFFFFFF00u with y = (uint8_t)x. The PR still has merge conflicts, which the bot reported in C242.
Comments
94 comments, 0 open, 0 new
Testing
Build: make -j8 cppcheck testrunner in pr/ and make cppcheck in base/ both succeeded.
Unit tests: ./testrunner TestCondition TestValueFlow TestBufferOverrun TestStl TestType TestOther TestFunctions TestUninitVar TestSymbolDatabase TestNullPointer TestAstUtils ran 1502 tests with Tests failed: 0.
New commit (dropInvalid in MultiValueFlowAnalyzer): sf1.c has 8 callee/caller pairs. In each pair, one argument is written in the callee (by plain assignment, an assignment from another argument, a write in a branch, writes in a loop, a write through a local pointer alias, or a loop assignment) and another argument is used afterwards. The uses are division by zero, a null dereference and an out-of-bounds index. Running with --enable=style,warning --platform=unix64, the PR and base give exactly the same output, so I saw no new false positives.
Differential run: I ran cppcheck -q --enable=style,warning --platform=unix64 on samples/, test/cfg/std.c, test/cfg/posix.c and test/cfg/gnu.c. The output of base and the PR is identical.
Cast-range probes (q.c, 14 cases): casts to bool, <<, int8_t*int8_t, int16_t reinterpretation, unary minus, ~, <<= and *= on narrowed values. Results:
- New correct result:
-y < -255is always false. - Wrong base result that is gone:
(unsigned)-y > 0xFFFFFF00uwithuint8_t y = (uint8_t)x(base said "always false", but it is true fory == 1). - All other results match base. The only cases that are not detected are false negatives in both versions, for example
(y << 1) > 510andint8_t y; y*y > 16384.
Performance and hangs: I generated 300 chained cast/clamp statements and a 200-deep nest of (unsigned char) casts. The PR took 225 ms and 52 ms, base took 203 ms and 50 ms. Nothing hung.
Automated review of 7e709f7 by Claude. The pull request was built and tested locally.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found one new problem, a false positive. A loop whose start value is a cast to a narrow signed type now gets an error-severity negativeIndex at that type's minimum. For example, for (int i = (int8_t)n; i < 5; i++) a[i] = 0; gives accessed at index -128. The floorReached logic in valueFlowForLoop was added to keep the reachable unsigned floor (0, as C129 asked). It also treats the floor of any narrower signed cast (int8_t, short) as a witnessed start value, so the trivial cast range is now treated as evidence. The same loop with an int8_t parameter gives nothing, and neither does base. I found no other new problems. The #15000 reproducer is reported, the changed unit-test suites and the new CLI tests pass, and my probes of isOppositeCond, mixed-sign comparisons, for loops and subfunction calls give the same results as base or correct new ones. The mixed-sign oppositeInnerCondition false positives that remain (for example x < 0xFFFFFFF0u followed by x > 0) are also in base.
Comments
95 comments, 0 open, 1 new
@jfdeverge, please fix, resolve or reply to the open and new comments: #95.
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.
Unit tests: ./testrunner TestCondition TestValueFlow TestBufferOverrun TestStl TestType TestOther TestFunctions TestUninitVar TestSymbolDatabase TestNullPointer TestAstUtils ran 1503 tests with Tests failed: 0.
CLI tests: pytest other_test.py -k "15000 or floating_strict or unsigned_loop_index" gives 3 passed.
New false positive: negativeIndex at the minimum of a signed cast type (e.c)
#include <stdint.h>
int a[10];
void m1(int n) { for (int i = (int8_t)n; i < 5; i++) { a[i+5] = 0; } }
void m2(int8_t n) { for (int i = n; i < 5; i++) { a[i+5] = 0; } }
void m3(int n) { for (int i = (int8_t)n; i < 5; i++) { a[i] = 0; } }
void m4(int n) { int s = (int8_t)n; for (int i = s; i < 5; i++) { a[i] = 0; } }
void m5(int n) { for (int i = (uint8_t)n; i < 10; i++) { a[i] = 0; } }
void m6(int n) { for (int i = (short)n; i < 10; i++) { a[i] = 0; } }
void m7(int n) { for (int i = (int)n; i < 10; i++) { a[i] = 0; } }
void m8(long long n) { for (int i = (int)n; i < 10; i++) { a[i] = 0; } }Command: cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{severity}:{id}:{message}' e.c
- Base: no output.
- PR:
3:error:negativeIndex:Array 'a[10]' accessed at index -123, which is out of bounds.
5:error:negativeIndex:Array 'a[10]' accessed at index -128, which is out of bounds.
6:error:negativeIndex:Array 'a[10]' accessed at index -32768, which is out of bounds.
- Without
--enable: the error is still reported. - Inconsistency: an
int8_tparameter (m2) and an(int)cast fromlong long(m8) are not reported.
--debug for m3 shows ( always {!<=-129,!>=128} and i {<=4,!>=5,!<=-129,-128}. The possible -128 is made up from the cast's type floor alone.
Probes that match base or are correct new results:
isOppositeCond/incorrectLogicOperatorwith mixed-sign constants, about 35 cases (x == 0xFFFFFFFFu/x == -1,</>against0xFFFFFFF0u,0x80000000u,10u, unsignedu != -1). The new results are correct, for examplex >= 0xFFFFFFF0ufollowed byx > 0is always false, andshort x < 10ufollowed byx < -5is always false. The remaining wrongoppositeInnerConditionresults, such asx < 0x80000000ufollowed byx > 5, are the same in base.- For loops with conditional, cast,
&&and||start values, and aLLONG_MINlimit. They match base apart from the cases above.i < -9223372036854775807LL-1is newly reported as always false, which is correct. - Subfunction calls with one argument written in the callee (the
dropInvalidchange): the output is identical to base.
The GUI is not changed, so I did not build it.
Automated review of 037467b by Claude. The pull request was built and tested locally.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new false positives, crashes or hangs. The #15000 reproducer is reported. In my probes the PR also removes several base false positives, for example uint16_t b = a + 1; if (b == 0), y = x % 8; y -= 1; if (y == 0xFFFFFFFFu) and range-guarded casts such as if (x < -3 || x > 3) return; if ((uint8_t)x == 255).
I found two new problems, both in the unsigned no-wrap logic:
- False negative (regression from base):
getUnsignedArithmeticRangegets an upper bound only from value facts and from%. Because of that, the PR can no longer prove that(x & 0xFF) + 1u,(x >> 24) + 1uory = x & 0xFF; y + 1udoes not wrap, so the correctalways falsewarnings that base gives for... + 1u == 0uare lost. - Leftover false positive (base has it too): the "historical small-increment" shortcut in
isUnsignedArithmeticNoWraptreats a wrap check as explicit only when it is the direct parent comparison. Soif (a + 1 == 0)is now fixed, butunsigned b = a + 1; if (b == 0)is still reported as always false.
C245, the newest earlier finding (negativeIndex at the minimum of a signed cast), is fixed in this version.
Comments
97 comments, 0 open, 2 new
@jfdeverge, please fix, resolve or reply to the open and new comments: #96, #97.
For #96 (false negative), it is enough to create a Trac ticket and link it here. It does not need to be fixed in this PR.
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both succeeded.
Unit tests: ./testrunner TestCondition TestValueFlow TestType TestBufferOverrun TestStl TestOther TestFunctions TestUninitVar TestNullPointer TestSymbolDatabase TestAstUtils ran 1503 tests with 0 failures.
CLI tests: pytest other_test.py -k "15000 or floating_strict or unsigned_loop" gave 3 passed.
Differential runs (PR against base):
--enable=style,warning --platform=unix64onexternals/tinyxml2/tinyxml2.cpp,lib/mathlib.cppandlib/astutils.cpp: the output is identical.- Run time on
lib/astutils.cpp: 101.1 s with the PR, 100.3 s with base.
Hand-written probes: about 90 cases covering casts, clamps, enums (including enum class with an underlying type and widened enums), loops, compound assignments, array indexes and division. The re-checked earlier items C108 and C245 are fixed. All other differences from base are correct new warnings or base false positives that are gone, except the two items below.
1. Lost warnings (false negatives, regression from base)
t2.c:
void use(int);
void a(unsigned x) { if ((x & 0xFF) + 1u == 0u) use(1); }
void b(unsigned x) { unsigned y = x & 0xFF; if (y + 1u == 0u) use(2); }
void c(unsigned x) { if ((x % 10u) + 1u == 0u) use(3); }
void d(unsigned x) { if ((x >> 24) + 1u == 0u) use(4); }
void g(unsigned long x) { if ((x & 0xFFul) + 1ul == 0ul) use(6); }Command: cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{id}:{message}' t2.c
PR:
4:knownConditionTrueFalse:Condition '(x%10u)+1u==0u' is always false
Base:
2:knownConditionTrueFalse:Condition '(x&0xFF)+1u==0u' is always false
3:knownConditionTrueFalse:Condition 'y+1u==0u' is always false
4:knownConditionTrueFalse:Condition '(x%10u)+1u==0u' is always false
5:knownConditionTrueFalse:Condition '(x>>24)+1u==0u' is always false
7:knownConditionTrueFalse:Condition '(x&0xFFul)+1ul==0ul' is always false
- What
--debugshows: base gives+ always !<=0and== always 0. The PR gives+ always !<=-1and== {!<=-1,!>=2}, because&and>>have no upper-bound value for the no-wrap proof to use.
2. Assignment form of the wrap check is still a false positive (base has it too)
t9.c:
void use(int);
void l7(unsigned a) { unsigned b = a + 1; if (b == 0) use(7); }
void l7b(unsigned a) { if (a + 1 == 0) use(7); }
void l7c(unsigned a) { unsigned b = a + 1u; if (b == 0) use(7); }Command: cppcheck -q --enable=style --platform=unix64 --template='{line}:{id}:{message}' t9.c
PR:
2:knownConditionTrueFalse:Condition 'b==0' is always false
4:knownConditionTrueFalse:Condition 'b==0' is always false
Base reports lines 2, 3 and 4.
- What the PR fixed: the inline form (line 3).
- What remains: the assignment forms. For
a == UINT_MAX,bis 0. - What
--debugshows: on line 2,+ always !<=0andb {symbolic=(a+1),!<=0}.
Not done: the GUI was not built because the PR does not change gui/.
Automated review of 8f4801a by Claude. The pull request was built and tested locally.
| return UnsignedArithmeticRange{}; | ||
| range.lower = truncateUnsignedValue(knownUnsignedPoint, resultBits); | ||
| range.upper = range.lower; | ||
| } else if (tok->str() == "%" && tok->astOperand2()) { |
There was a problem hiding this comment.
AI review
The no-wrap proof gets an upper bound only from the value facts and from %. Unsigned & with a known mask and >> with a known shift amount also bound their result, but they carry no such value facts (& always !<=-1). So isUnsignedArithmeticNoWrap fails for them, and the impossible bounds are dropped. This loses correct warnings that base gives (--platform=unix64):
void a(unsigned x) { if ((x & 0xFF) + 1u == 0u) use(1); } // base: always false, PR: nothing
void b(unsigned x) { unsigned y = x & 0xFF; if (y + 1u == 0u) use(2); } // base: always false, PR: nothing
void d(unsigned x) { if ((x >> 24) + 1u == 0u) use(4); } // base: always false, PR: nothingThe (x % 10u) + 1u == 0u case is still reported. Bounding a & mask by mask, and a >> k by typeMax >> k, in the same way as % would keep these warnings. The b case also needs this through the symbolic source. A test would help.
| expression = parent; | ||
| parent = parent->astParent(); | ||
| } | ||
| if (parent && parent->isComparisonOp()) { |
There was a problem hiding this comment.
AI review
The small-increment shortcut only steps aside when the + is directly compared with a constant. When the result is stored first, the same wrap check is still reported as always false:
void l7(unsigned a) { unsigned b = a + 1; if (b == 0) use(7); } // PR and base: Condition 'b==0' is always false
void l7b(unsigned a) { if (a + 1 == 0) use(7); } // PR: nothing (fixed), base: always falseFor a == UINT_MAX, b is 0. --debug shows = always !<=0 and b {symbolic=(a+1),!<=0}. Base has the same false positive, so this is not a regression. But the comment above says that explicit wrap checks such as x + 1 == 0 stay subject to the range proof, and here they don't. A TODO test for the assignment form would at least record it.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
New finding: the "explicit wrap check" exemption in canAssumeNoWrap (lib/vf_common.cpp:1364) decides the comparison direction from the operator alone. It ignores which side the + is on, and it does not cover >=. So 1u > a + 1u (the same test as a + 1u < 1u) and a + 5u >= 5u are still reported as always false or always true. Both are false positives: for a == UINT_MAX (or UINT_MAX-4) the sum wraps. Base has the same false positives, so this is not a regression. But the code comment says that wrap checks such as x + c < c stay subject to the range proof, and the PR already fixed the mirror forms a + 1u < 1u and 1u <= a + 1u.
The earlier findings that I re-ran are fixed: C247 (&/>> bounds), C231 (enum sign), C233 (u == -1), C245 (signed cast loop floor), C37 (wrap through the cast upper bound), and the #15000 reproducer is reported. C248 (unsigned b = a + 1; if (b == 0)) still reproduces and nobody has answered it. Unit tests and the related CLI tests pass.
Comments
72 comments, 1 open, 1 new
@jfdeverge, please fix, resolve or reply to the open and new comments: #71, #72.
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.
Unit tests: ./testrunner TestCondition TestValueFlow TestType TestBufferOverrun TestStl TestOther TestFunctions TestUninitVar TestNullPointer TestSymbolDatabase TestAstUtils ran 1503 tests with Tests failed: 0.
CLI tests: pytest other_test.py -k "15000 or floating_strict or unsigned_loop" gave 3 passed.
Reproducer of #15000: the PR gives Condition '(((long long)((unsigned int)tmp))-1LL)>4294967295LL' is always false. Base gives nothing.
Earlier findings re-checked (C247, C248, C231, C233, C245, C37):
- C247 is fixed:
(x & 0xFF) + 1u == 0u,y = x & 0xFF; y + 1u == 0uand(x >> 24) + 1u == 0uare reported again. - C248 still reproduces:
unsigned b = a + 1; if (b == 0)givesCondition 'b==0' is always false. - The others are fixed.
- The PR also correctly drops base false positives such as
(x & m) + 1u == 0uwith a knownm == 0xFFFFFFFF.
New problem: wrap-check exemption depends on the operator, not the operand side
t4.c:
void use(int);
void g1(unsigned a) { if (1u > a + 1u) use(1); }
void g2(unsigned a) { if (2u > a + 2u) use(2); }
void g3(unsigned a) { if (a + 5u >= 5u) use(3); }
void g4(unsigned a) { if (0u < a + 1u) use(4); }
void f1(unsigned a) { if (a + 1u < 1u) use(11); }Command: cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{id}:{message}' t4.c
PR:
2:knownConditionTrueFalse:Condition '1u>a+1u' is always false
3:knownConditionTrueFalse:Condition '2u>a+2u' is always false
4:knownConditionTrueFalse:Condition 'a+5u>=5u' is always true
- Base: reports the same three, plus lines 5 and 6.
- What the PR fixed: lines 5 and 6 are no longer reported.
- What is still wrong: lines 2–4 are wrong for
a == UINT_MAX(lines 2, 3) and fora == UINT_MAX-4(line 4).
Related forms that are still reported (base reports them too):
if (!(a + 1u))is reported as always false.if (a + 1u)is reported as always true.
Not done: the GUI was not built because the PR does not change gui/.
Automated review of 89ed553 by Claude. The pull request was built and tested locally.
| MathLib::bigint compareConstant{}; | ||
| if (getKnownPointIntValue(compareValue, compareConstant) && | ||
| (compareConstant < addendValue || | ||
| (compareConstant == addendValue && Token::Match(parent, "<|<=")))) |
There was a problem hiding this comment.
AI review
The exemption only works when the + is the left operand and the operator is </<=. It does not look at which side expression is on. It also leaves out the negated form >= (and > for the swapped order). In those cases the small-increment assumption is used, and an explicit wrap check is reported as a constant:
void g1(unsigned a) { if (1u > a + 1u) use(1); } // PR: always false (true for a == UINT_MAX)
void g2(unsigned a) { if (2u > a + 2u) use(2); } // PR: always false
void g3(unsigned a) { if (a + 5u >= 5u) use(3); } // PR: always true (false for a == UINT_MAX-4)The mirror forms a + 1u < 1u and 1u <= a + 1u are no longer reported, so the PR handles only half of the cases. Base has the same false positives, so this is not a regression. Possible fix:
- swap the operator with
invertOperatorForOperandSwapwhenexpressionis the right operand; - for
compareConstant == addendValue, treat<|<=|>=|>as a wrap check.
A few tests with the constant on the left would cover this.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found one new false positive. The new impossible bounds on integral casts (lib/valueflow.cpp:1209) are also set inside template instantiations. A condition that depends on the template argument is then reported as constant, which base does not do: template<class T> void store(long v) { long y = static_cast<T>(v); if (y > 255) use(y); }, used with both uint8_t and uint32_t, gives Condition 'y>255' is always false. That is only true for one of the instantiations.
Apart from that:
- The #15000 reproducer is reported on unix32, unix64, win32A and win64.
- The changed unit-test suites pass.
- My other probes gave either the same result as base, a correct new warning, or a base false positive that is now gone.
Of the earlier findings, only C248 is still open: unsigned b = a + 1; if (b == 0) is still reported, and nobody has answered it.
Comments
99 comments, 1 open, 1 new
@jfdeverge, please fix, resolve or reply to the open and new comments: #97, #99.
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both succeeded.
Unit tests: ./testrunner TestCondition TestValueFlow TestType TestBufferOverrun TestStl TestOther TestFunctions TestUninitVar TestNullPointer TestSymbolDatabase TestAstUtils ran 1503 tests with Tests failed: 0.
Reproducer of #15000: Condition '(((long long)((unsigned int)tmp))-1LL)>4294967295LL' is always false on unix32, win32A, win64 and unix64. Base reports nothing.
Earlier findings re-checked:
- Fixed: C251 (
1u > a + 1u,a + 5u >= 5uare no longer reported), C247 ((x & 0xFF) + 1u == 0uand(x >> 24) + 1u == 0uare reported again), C245 ((int8_t)nloop start), C233 (u == -1), C231 (enum with a high-bit enumerator), C37 ((unsigned)x - 1u == 0xFFFFFFFFu). - Still open: C248.
unsigned b = a + 1; if (b == 0)givesCondition 'b==0' is always false.
Probes: about 60 cases, PR compared with base, --enable=style,warning --platform=unix64:
p1.c,p2.c: casts with arithmetic, shifts, compound assignment, loops, address taken,switch,do/while, and the difference of two cast values.p3.cpp:enum class, bitfields,bool,vector::size(),wchar_t,?:.
All differences from base were correct new warnings, for example (int64_t)(uint16_t)x - (int64_t)(uint16_t)z > 65535 is always false, or base false positives that are gone, such as uint8_t c = (uint8_t)x; c++; if (c == 0). The exception is the template case below.
Performance: 400 chained cast/clamp statements took 0.43 s with the PR and 0.40 s with base. test/cfg/std.c took 4.65 s with the PR and 4.61 s with base, with identical output.
New false positive: condition that depends on a template argument
p6.cpp:
#include <cstdint>
void use(long);
template<class T> void store(long v) { long y = static_cast<T>(v); if (y > 255) use(y); }
void a(long v) { store<uint8_t>(v); store<uint32_t>(v); }Command: cppcheck -q --enable=style,warning --platform=unix64 --template='{line}:{column}:{id}:{message}' p6.cpp
- PR:
3:74:knownConditionTrueFalse:Condition 'y>255' is always false - Base: no output.
The same happens for template<class T> void f(int x) { int y = static_cast<T>(x); if (y + 1 > 256) ... } and for T y = static_cast<T>(x); if (y - 1 > 255).
The GUI is not changed, so I did not build it.
Automated review of a7a112c by Claude. The pull request was built and tested locally.
| upper.bound = ValueFlow::Value::Bound::Lower; | ||
| upper.setImpossible(); | ||
| setTokenValue(tok, std::move(upper), settings); | ||
| } else if (tok->isCast() && tok->valueType() && tok->valueType()->isIntegral() && !tok->valueType()->pointer) { |
There was a problem hiding this comment.
AI review
The impossible bounds are also added to casts whose target type is a template argument in an instantiation. A condition that depends on T is then reported as constant. Base does not report it:
template<class T> void store(long v) { long y = static_cast<T>(v); if (y > 255) use(y); }
void a(long v) { store<uint8_t>(v); store<uint32_t>(v); }With --enable=style --platform=unix64, the PR gives Condition 'y>255' is always false, but for T = uint32_t the condition can be true. Maybe skip casts whose type tokens are template arguments (isTemplateArg(), as at line 610), and add a test.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems in this version.
The #15000 reproducer is reported, the changed unit tests and CLI tests pass, and my probes either match base or give correct new results.
Of the earlier findings:
- C253 (the template-argument cast false positive) is fixed by
isTemplateArgumentCast. - C248 is still open and nobody has answered it.
unsigned b = a + 1; if (b == 0)is still reported as always false. Base has the same false positive, so it is not a regression.
Comments
100 comments, 1 open, 0 new
@jfdeverge, please fix, resolve or reply to the open and new comments: #98.
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both succeeded.
Unit tests: ./testrunner TestCondition TestValueFlow TestType TestBufferOverrun TestStl TestOther TestFunctions TestUninitVar TestNullPointer TestSymbolDatabase TestAstUtils ran 1503 tests with Tests failed: 0.
CLI tests: pytest test/cli/other_test.py -k "15000 or floating_strict or unsigned_loop" gave 3 passed.
Earlier findings re-checked (--enable=style,warning --platform=unix64):
-
C253 is fixed:
template<class T> void store(long v) { long y = static_cast<T>(v); if (y > 255) use(y); }, instantiated with bothuint8_tanduint32_t, gives no warning. The variants below give no warning either:- a member typedef
typedef T type; (type)v using U = T; (U)vtypename std::make_unsigned<T>::typedecltype(T{})- a functional cast
T(v)
A cast to a fixed type inside a template (
(uint8_t)vintemplate<class T> void n(T v)) is still reported, which is correct. - a member typedef
-
C248 is still there:
void l7(unsigned a) { unsigned b = a + 1; if (b == 0) use(7); }givesCondition 'b==0' is always false. -
C108 items are fixed:
for (unsigned i = 0; i < 10; i++) a[i + 1] = 0;givesarrayIndexOutOfBoundsat index 10.char c; if (c == 0xFF)givescompareValueOutOfTypeRangeError.- The
v.resize(entries + 2); v[0] = 1;guard gives nocontainerOutOfBounds.
New probes (PR compared with base):
r1.c, 24 cast/arithmetic cases: bitfields,EOF, compound<<=,*=,/=,%=,>>=, unary-and~, narrow++/--, loops after a cast, and a 64-bit product of casts.- The PR adds a correct
(long)(int)x > 2147483647Lalways false. - It removes three base false positives:
uint8_t y=(uint8_t)x; y += 1; if (y == 0), the same withy = y + 1, anduint16_t y-- == 65535. - All other results are the same as base.
- The PR adds a correct
r2.c, array index, division and shift-count cases with casts: no output from either version.r3.c,shiftTooManyBitsandfloatConversionOverflow(both changed inchecktype.cpp): ternary shift counts, loop shift counts and bounded doubles give output identical to base.r4.c, casts tounsigned long,long,char,wchar_t,_Boolandshort, and double casts: I ran it on unix64, win64 and unix32. The only differences from base are correct new warnings:(short)x+0>=32768is always false.(unsigned int)(unsigned char)x>255uis always false.- On win64,
(wchar_t)x < 0givesunsignedLessThanZero.
- Real code:
simplecpp.cpp,lib/mathlib.cpp,lib/token.cppandlib/path.cppwith--enable=style,warning,portabilitygive the same output as base. The only difference is a line number that moved because the PR changeslib/token.cpp.
I did not build the GUI because the PR does not change gui/.
Automated review of adc5d1e by Claude. The pull request was built and tested locally.
There was missing detection of 'MISRA C:2012 Rule 14.3" on some specific code structure generated by Matlab Simulink coder.
We identified these issues by comparing its results with reports previously generated by our company’s internal tool on the same software.
The bug report would have looked like below.
Problem
Cppcheck did not report a MISRA C:2012 Rule 14.3 violation when a comparison
used an integer expression whose range was provably bounded by casts and
constant arithmetic. The existing check handled a variable compared with a
value outside the variable's declared type range, but did not evaluate this
equivalent expression form.
Minimal Reproducer
After the clamp and casts, the left-hand expression cannot exceed
UINT32_MAX - 1. Therefore the final condition is always false and producesthe
knownConditionTrueFalsediagnostic. The company's end-to-end MISRApostprocessor mapping was not exercised here.
Observed Behavior
Before the fix, the final comparison produced no diagnostic. This allowed the
generated-code pattern to pass through the cppcheck-based MISRA pipeline
without the expected Rule 14.3 finding.