Skip to content

fix signed overflow when multiplying array dimensions - #9027

Open
Nussu06 wants to merge 3 commits into
cppcheck-opensource:mainfrom
Nussu06:array-dimensions-overflow
Open

Nussu06 wants to merge 3 commits into
cppcheck-opensource:mainfrom
Nussu06:array-dimensions-overflow

Conversation

@Nussu06

@Nussu06 Nussu06 commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

CheckBufferOverrunImpl::getBufferSize, accumulateStructMembers (used by ValueType::getSizeOf) and setValues in clangimport multiply the array dimensions of a variable in MathLib::bigint without an overflow check, so a declaration like char a[0x100000000][0x100000000]; in the checked code makes cppcheck run into signed integer overflow (UBSan at checkbufferoverrun.cpp:635 and symboldatabase.cpp:8702). When the product wraps to a small value the results are wrong as well: for char a[0x4000000000000001][4]; memset(a, 0, 10); cppcheck reports bufferAccessOutOfBounds, and sizeof of a struct holding that array is folded to 4. Added Variable::dimensionsProduct, which reports the overflow, and all three sites now treat an overflowing product as an unknown size; sizes that fit are unchanged. TestBufferOverrun::arraysize_overflow and a new case in TestValueFlow::valueFlowSizeof fail without the change, the full testrunner passes, and TestBufferOverrun, TestValueFlow and TestClangImport also pass in a build with -fsanitize=signed-integer-overflow. I don't have Trac access, could one of you create a ticket for this so I can reference it in the title?

@dmcppcheck

Copy link
Copy Markdown
Contributor

There should probably be a trac ticket for this PR. Please create it, or ask us to create it. Then the PR title should be updated.

@Nussu06

Nussu06 commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

hey can anyone create trac ticket for this pr, thanks.

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

The PR removes the signed overflow when the dimensions are multiplied together. It does not fix the wrong results it describes, because the element count is then multiplied by the element size without a check. When the count fits but the byte size does not, it still wraps, and the false positives remain. Example: int a[0x4000000000000001]; memset(a, 0, 10); still reports bufferAccessOutOfBounds. sizeof of struct U { int m[0x4000000000000001]; } is still folded to 4. The PR's own example uses char a[0x4000000000000001][4], which the new check catches only because the element size is 1. Use int a[0x4000000000000001][1] and the bug comes back. The byte-size multiplications are in getBufferSize ((dim - index) * typeSize), n *= dim in the accHelper of getSizeOf, and mul * getSizeOf(...) in clangimport. These are size_t operations, so they are not UB, but the sizes they give are wrong. The new overflow check also duplicates the existing mulOverflows() in checkbufferoverrun.cpp. Apart from this I found no problems; the new overflow check itself looks correct.

Testing

I built cppcheck and testrunner in pr/ and cppcheck in base/; both built without errors. ./testrunner TestBufferOverrun TestValueFlow TestClangImport TestSymbolDatabase: 825 tests, 0 failed.

Test file a.c:

void f1() { int a[0x4000000000000001]; memset(a, 0, 10); }
void f2() { char a[0x2000000000000001][2]; memset(a, 0, 10); }
void f3() { int a[0x4000000000000001][1]; memset(a, 0, 10); }
struct S { int m[0x4000000000000001]; };
int f4() { return sizeof(struct S); }
struct T { char m[0x4000000000000001][4]; };
int f5() { char b[2]; return b[sizeof(struct T)]; }
struct U { int m[0x4000000000000001]; };
int f6() { char b[2]; return b[sizeof(struct U)]; }

Command: cppcheck -q --enable=all a.c

case base PR
f5 (the case from the PR) arrayIndexOutOfBounds, index 4 fixed
f1 a.c:1:47: error: Buffer is accessed out of bounds: a [bufferAccessOutOfBounds] still reported
f3 a.c:3:50: error: Buffer is accessed out of bounds: a [bufferAccessOutOfBounds] still reported
f6 a.c:9:31: error: Array 'b[2]' accessed at index 4, which is out of bounds. [arrayIndexOutOfBounds] still reported

In f1, f3 and f6 the element count fits in a bigint, but the byte size wraps when it is multiplied by sizeof(int). I did not run a sanitizer build.


Automated review of e208afc by Claude. The pull request was built and tested locally.

return i1 * dim.num;
});
MathLib::bigint dim = 0;
if (!var->dimensionsProduct(dim))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

This catches overflow only in the element count. Below, (dim - index) * typeSize can still wrap, because it is size_t arithmetic. void f() { int a[0x4000000000000001]; memset(a, 0, 10); } still gives a false positive bufferAccessOutOfBounds, and so does int a[0x4000000000000001][1]. The byte size needs the same check. The existing mulOverflows() a few lines below in this file could be used for both, instead of adding a second implementation in Variable::dimensionsProduct.

Comment thread lib/symboldatabase.cpp
return i1 * dim.num;
});
MathLib::bigint dim = 0;
if (!var.dimensionsProduct(dim))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

accHelper later does n *= dim with the element size, in size_t, and that can still wrap. With struct U { int m[0x4000000000000001]; };, sizeof(struct U) is still folded to 4, so char b[2]; b[sizeof(struct U)] reports arrayIndexOutOfBounds at index 4. The test only covers char elements, where the element size is 1.

Comment thread lib/clangimport.cpp Outdated
typeSize = 0;
break;
}
if (var.valueType())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

The same applies here: mul * getSizeOf(...) and the += into typeSize are not checked, so the struct size can still wrap when the element size is greater than 1.

@dmcppcheck

Copy link
Copy Markdown
Contributor

Test results for commit e208afc (tools/test-my-pr.py, main compared to this PR):

Test: http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-9027/
packages: 100
Differing warnings: 0 (+0 -0)
Timing: +0.1% (http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-9027/2026-11-14_06-15-12-e208afcd4929_timing.html)

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.

@Nussu06

Nussu06 commented Nov 15, 2026

Copy link
Copy Markdown
Contributor Author

Good point, the element count was only half of it. The byte size is now checked as well: getBufferSize checks (dim - index) * typeSize, the getSizeOf accHelper checks n *= dim and the running total, and clangimport checks mul * size and the +=. Any of those overflowing is treated as an unknown size. I moved mulOverflows() into MathLib so checkbufferoverrun and Variable::dimensionsProduct share the one implementation. Added the int a[0x4000000000000001] and int a[0x4000000000000001][1] memset cases and a sizeof case with int elements; f1, f3 and f6 from your a.c no longer warn, and a real overrun like int a[4]; memset(a, 0, 20); is still reported.

Still need a trac ticket for this one so I can fix up the title, could one of you open it?

@dmcppcheck

Copy link
Copy Markdown
Contributor

Test results for commit 1906bfa (tools/test-my-pr.py, main compared to this PR):

Test: http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-9027/
packages: 100
Differing warnings: 0 (+0 -0)
Timing: +0.6% (http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-9027/2026-11-15_16-41-39-1906bfaf48e6_timing.html)

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 dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

The overflow handling in ValueType::getSizeOf is still wrong for classes with base classes. When a member's size overflows, accHelper now returns 0. accumulateStructMembers then returns {0, false}. But the derivedFrom accumulate still adds the base class sizes to that 0, and the total == 0 && !result.success check no longer fires. So sizeof(Derived) is folded to just the size of the base class, plus padding. Example: struct Base { int i; }; struct Derived : Base { char b[0x6000000000000000]; char c[0x6000000000000000]; };. Here the PR folds sizeof(Derived) to a small constant and reports a new arrayIndexOutOfBounds that base does not report. The cases with one base class that the PR set out to fix (int m[0x4000000000000001], char m[0x100000000][0x100000000]) still give small wrong sizes and false positives, including bufferAccessOutOfBounds in a memset. The simple cases without base classes, the clangimport change and the shared MathLib::mulOverflows look correct to me.

Earlier comments

# Comment By Where Status
1 PR needs a trac ticket and the title should reference it @dmcppcheck general ⚠️ Open
2 Byte size (count * element size) can still wrap, so false positives remain for int elements AI review general ✅ Fixed
3 New overflow check duplicates the existing mulOverflows() AI review general ✅ Fixed
4 getBufferSize: (dim - index) * typeSize is not checked for overflow AI review lib/checkbufferoverrun.cpp:635 ✅ Fixed
5 accHelper n *= dim can wrap; sizeof(struct U {int m[...]}) is folded to 4 AI review lib/symboldatabase.cpp:8714 ✅ Fixed
6 clangimport: mul * getSizeOf and += into typeSize are not checked AI review lib/clangimport.cpp:1645 ✅ Fixed

@Nussu06, please fix, resolve or reply to the open comments: #1.

Testing

I built cppcheck and testrunner in pr/ and cppcheck in base/; both builds succeeded. ./testrunner TestBufferOverrun TestValueFlow TestClangImport TestSymbolDatabase TestMathLib: 856 tests, 0 failed. I did not build with a sanitizer.

A new false positive (base has no warning):

// d.cpp
struct Base { int i; };
struct Derived : Base { char b[0x6000000000000000]; char c[0x6000000000000000]; };
int f() { char buf[2] = {0}; return buf[sizeof(Derived)]; }

cppcheck -q d.cpp

  • PR: d.cpp:3:40: error: Array 'buf[2]' accessed at index 5, which is out of bounds. [arrayIndexOutOfBounds]
  • base: no warning

Cases with a base class that the PR does not fix:

// d2.cpp
struct Base { int i; };
struct Derived : Base { int m[0x4000000000000001]; };
int f() { char buf[2] = {0}; return buf[sizeof(Derived)]; }
struct Derived2 : Base { char m[0x100000000][0x100000000]; };
int g() { char buf[2] = {0}; return buf[sizeof(Derived2)]; }

PR and base both report arrayIndexOutOfBounds. With the PR the indexes are 8 and 4; base gives 8 and 5. --debug-normal shows that the PR folds sizeof(Derived) to always 8 and sizeof(Derived2) to always 4.

// d3.cpp
struct Base { int i; };
struct Derived : Base { char m[0x100000000][0x100000000]; };
void h() { Derived d; memset(&d, 0, 10); }

PR and base: d3.cpp:3:30: error: Buffer is accessed out of bounds: &d [bufferAccessOutOfBounds]

Without base classes: struct A { int x; char c[0x7ffffffffffffffb]; } (the tail padding would overflow) and struct D : B (two bases of 0x7000000000000000 bytes) gave no known sizeof value with the PR, as intended.


Automated review of 1906bfa by Claude. The pull request was built and tested locally.

Comment thread lib/symboldatabase.cpp Outdated
return accuracy == Accuracy::ExactOrZero ? 0 : total;
n *= dim;
size_t padding = (a - (total % a)) % a;
if (total + padding > maxSize || n > maxSize - total - padding)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

When this check (or the mulOverflows check above) fires, accHelper returns 0. accumulateStructMembers then gives {0, false}, but further down in getSizeOf the derivedFrom accumulate still adds the sizes of the base classes to that 0. After that, total == 0 && !result.success is false, so the overflow is lost. sizeof is folded to the size of the base class.

struct Base { int i; };
struct Derived : Base { char b[0x6000000000000000]; char c[0x6000000000000000]; };
int f() { char buf[2] = {0}; return buf[sizeof(Derived)]; }

The PR reports arrayIndexOutOfBounds at index 5; base reports nothing. struct Derived : Base { int m[0x4000000000000001]; } and struct Derived2 : Base { char m[0x100000000][0x100000000]; } still fold sizeof to 8 and 4. A memset(&d, 0, 10) on such an object still reports bufferAccessOutOfBounds. When result.success is false because of an overflow, getSizeOf should return 0 for ExactOrZero before it adds the base classes. The base-class sums (v += ...) should also be checked for overflow.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f84e133. accumulateStructMembers now reports a dimension overflow in its result, and accHelper sets a flag when the byte size overflows, so getSizeOf returns 0 for ExactOrZero after the base classes are added as well. The base class sums are now checked against the bigint max too. d.cpp, d2.cpp and d3.cpp no longer warn, and a struct with bitfields like struct BF { int a : 8; char c; } still folds to 4. I added those cases, plus one where two bases together overflow, to valueFlowSizeof and arraysize_overflow. The full testrunner passes.

@Nussu06

Nussu06 commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

The base class case is addressed now (see the reply on the inline comment). The trac ticket is the only open item left. I don't have Trac access, so could one of you create one for this? I'll update the title to reference it once it exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants