Skip to content

Commit 8fed333

Browse files
author
mxms
committed
[Wunsafe-buffer-usage] Fix false positives in handling enums
Do not warn if the index is an enum and we an determine statically that it's within bounds.
1 parent 8a5c241 commit 8fed333

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

clang/lib/Analysis/UnsafeBufferUsage.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,13 @@ AST_MATCHER(ArraySubscriptExpr, isSafeArraySubscript) {
463463
return true;
464464
}
465465

466+
// Array index wasn't an integer literal, let's see if it was an enum or
467+
// something similar
468+
const auto IntConst = Node.getIdx()->getIntegerConstantExpr(Finder->getASTContext());
469+
if (IntConst && *IntConst > 0 && *IntConst < size) {
470+
return true;
471+
}
472+
466473
return false;
467474
}
468475

clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,23 @@ void constant_idx_unsafe(unsigned idx) {
3939
buffer[10] = 0; // expected-note{{used in buffer access here}}
4040
}
4141

42+
enum FooEnum {
43+
A = 0,
44+
B = 1,
45+
C = 2,
46+
D
47+
};
48+
49+
void constant_enum_safe() {
50+
int buffer[FooEnum::D] = { 0, 1, 2 };
51+
buffer[C] = 0; // no-warning
52+
}
53+
54+
void constant_enum_unsafe(FooEnum e) {
55+
int buffer[FooEnum::D] = { 0, 1, 2 };
56+
buffer[e] = 0; // expected-warning{{unsafe buffer access}}
57+
}
58+
4259
void constant_id_string(unsigned idx) {
4360
char safe_char = "abc"[1]; // no-warning
4461
safe_char = ""[0];

0 commit comments

Comments
 (0)