Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 19 additions & 9 deletions clang/lib/Analysis/UnsafeBufferUsage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -436,21 +436,31 @@ AST_MATCHER(ArraySubscriptExpr, isSafeArraySubscript) {

const auto *BaseDRE =
dyn_cast<DeclRefExpr>(Node.getBase()->IgnoreParenImpCasts());
if (!BaseDRE)
return false;
if (!BaseDRE->getDecl())
return false;
const auto *CATy = Finder->getASTContext().getAsConstantArrayType(
BaseDRE->getDecl()->getType());
if (!CATy)
const auto *SLiteral =
dyn_cast<StringLiteral>(Node.getBase()->IgnoreParenImpCasts());
uint64_t size;

if (!BaseDRE && !SLiteral)
return false;

if (BaseDRE) {
if (!BaseDRE->getDecl())
return false;
const auto *CATy = Finder->getASTContext().getAsConstantArrayType(
BaseDRE->getDecl()->getType());
if (!CATy) {
return false;
}
size = CATy->getLimitedSize();
} else if (SLiteral) {
size = SLiteral->getLength() + 1;
}

if (const auto *IdxLit = dyn_cast<IntegerLiteral>(Node.getIdx())) {
const APInt ArrIdx = IdxLit->getValue();
// FIXME: ArrIdx.isNegative() we could immediately emit an error as that's a
// bug
if (ArrIdx.isNonNegative() &&
ArrIdx.getLimitedValue() < CATy->getLimitedSize())
if (ArrIdx.isNonNegative() && ArrIdx.getLimitedValue() < size)
return true;
}

Expand Down
14 changes: 14 additions & 0 deletions clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,17 @@ void constant_idx_unsafe(unsigned idx) {
// expected-note@-1{{change type of 'buffer' to 'std::array' to label it for hardening}}
buffer[10] = 0; // expected-note{{used in buffer access here}}
}

void constant_id_string(unsigned idx) {
char safe_char = "abc"[1]; // no-warning
safe_char = ""[0];
safe_char = "\0"[0];

char abcd[5] = "abc";
abcd[2]; // no-warning

char unsafe_char = "abc"[3];
unsafe_char = "abc"[-1]; //expected-warning{{unsafe buffer access}}
unsafe_char = ""[1]; //expected-warning{{unsafe buffer access}}
Copy link
Contributor

Choose a reason for hiding this comment

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

This shouldn't be a warning either.

Copy link
Contributor Author

@malavikasamak malavikasamak Nov 11, 2024

Choose a reason for hiding this comment

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

In this case, I think we should warn, as the length here including the null terminator is 1.

Copy link
Contributor

Choose a reason for hiding this comment

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

Sorry, my bad. You're right

unsafe_char = ""[idx]; //expected-warning{{unsafe buffer access}}
}
Loading