Skip to content

[-Wunsafe-buffer-usage] Fix false positives for constant cases #92432

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
67 changes: 53 additions & 14 deletions clang/lib/Analysis/UnsafeBufferUsage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -420,25 +420,63 @@ AST_MATCHER(ArraySubscriptExpr, isSafeArraySubscript) {
// already duplicated
// - call both from Sema and from here

const auto *BaseDRE =
dyn_cast<DeclRefExpr>(Node.getBase()->IgnoreParenImpCasts());
if (!BaseDRE)
if (const auto *BaseDRE =
dyn_cast<DeclRefExpr>(Node.getBase()->IgnoreParenImpCasts())) {
if (!BaseDRE->getDecl())
return false;
if (const auto *CATy = Finder->getASTContext().getAsConstantArrayType(
BaseDRE->getDecl()->getType())) {
if (const auto *IdxLit = dyn_cast<IntegerLiteral>(Node.getIdx())) {
Copy link
Member

Choose a reason for hiding this comment

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

It feels like this block is repeated, more or less, several times. Is there a way to factor it?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

True but the block is also trivial and I am not convinced factoring it out as a separate function is worth it or leads to better code.

Copy link
Member

Choose a reason for hiding this comment

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

I was thinking more a lambda. I don't know LLVM's coding conventions very well, though.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't think it's worth it.

Copy link
Collaborator

Choose a reason for hiding this comment

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

I suspect that this could have been a:

const Expr *BaseE = Node.getBase()->IgnoreParenImpCasts();
if (isa<DeclRefExpr, StringLiteral>(BaseE)) {
  if (const auto *CATy = Finder->getASTContext().getAsConstantArrayType(BaseE->getType())) {
    ...
  }
}

Which would also eliminate duplication. (Unless DeclRefExpr->getDecl()->getType() is somehow significantly different from DeclRefExpr->getType().)

Another thing we can try is to simply eliminate the isa entirely. Like, we know that it's "an" expression, and its type is a constant-size array type. Do we really need more? Why not simply trust the type system? (It's not like the C type system has ever lied to us right? 😅)

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())
return true;
}
}
}

if (const auto *BaseSL =
dyn_cast<StringLiteral>(Node.getBase()->IgnoreParenImpCasts())) {
if (const auto *CATy =
Finder->getASTContext().getAsConstantArrayType(BaseSL->getType())) {
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())
return true;
}
}
}

return false;
}

AST_MATCHER(BinaryOperator, isSafePtrArithmetic) {
if (Node.getOpcode() != BinaryOperatorKind::BO_Add)
return false;
if (!BaseDRE->getDecl())

const auto *LHSDRE = dyn_cast<DeclRefExpr>(Node.getLHS()->IgnoreImpCasts());
Copy link
Collaborator

@haoNoQ haoNoQ May 20, 2024

Choose a reason for hiding this comment

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

I guess we might as well support the "abc" + 3 case here. With the ultimate goal of ultimately supporting

static const char *const abc = "abc";

abc[3];
abc + 3;

But also arguably not urgent.

if (!LHSDRE)
return false;

const auto *CATy = Finder->getASTContext().getAsConstantArrayType(
BaseDRE->getDecl()->getType());
LHSDRE->getDecl()->getType());
if (!CATy)
return false;

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())
return true;
}
const auto *RHSIntLit = dyn_cast<IntegerLiteral>(Node.getRHS());
if (!RHSIntLit)
return false;

const APInt BufferOffset = RHSIntLit->getValue();

if (BufferOffset.isNonNegative() &&
Copy link
Member

Choose a reason for hiding this comment

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

I don't speak AST, but does this still handle (i.e. not warn on) cases like constexpr char* p = (buf + 1) - 1;? Or is the presence of any subtraction enough to trigger a warning?

What about constexpr char* p = buf + 1; constexpr char* p2 = p - 1;? Should we be able to detect that this is safe, and not warn?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

True, this is not covered - just like more complex arithmetic expressions with are not yet covered with fixits.
But I'd rather land the incomplete solution that possibly addresses majority of false positives in real code now and improve the solution later.

Copy link
Member

Choose a reason for hiding this comment

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

That seems reasonable, but if that's the route, I might want to file a bug pre-emptively on further cases that should, or should not, be considered for future work.

One of my thoughts with the refactor suggestion below was that if the arithmetic/detection got more complex, it would be easier to implement consistently in a single place.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This code is just a short-term solution until we get to do it properly. I don't want to invest effort into polishing the code because we should replace it.

See this FIXME:
https://github.com/llvm/llvm-project/blob/main/clang/lib/Analysis/UnsafeBufferUsage.cpp#L416

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Feel free to file issues but at this point I think it's not a good use of our time because only the very trivial case gets recognized.
Ultimately the cases that should be supported are likely to be found in Sema tests for the functionality referred to by the FIXME above.

Copy link
Collaborator

Choose a reason for hiding this comment

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

There's this whole Expr->EvaluateAsInt() thing which is arguably even simpler to use than your existing code, and it constant-folds pretty well. We should probably just use that, instead of matching integer literals.

But it still won't handle the case where there's nested layers of arithmetic over the base pointer, like (ptr + 1) - 1. It'll only handle like ptr + (1 - 1). We'll have to support that separately. I suspect that it's still relatively easy to do with plain old recursion but this probably doesn't need to block this patch.

BufferOffset.getLimitedValue() < CATy->getLimitedSize())
return true;

return false;
}
Expand Down Expand Up @@ -692,7 +730,8 @@ class PointerArithmeticGadget : public WarningGadget {
hasLHS(expr(hasPointerType()).bind(PointerArithmeticPointerTag)),
hasRHS(HasIntegerType));

return stmt(binaryOperator(anyOf(PtrAtLeft, PtrAtRight))
return stmt(binaryOperator(anyOf(PtrAtLeft, PtrAtRight),
unless(isSafePtrArithmetic()))
.bind(PointerArithmeticTag));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// RUN: %clang_cc1 -std=c++20 -Wno-everything -Wunsafe-buffer-usage \
// RUN: -fsafe-buffer-usage-suggestions \
// RUN: -verify %s

void char_literal() {
if ("abc"[2] == 'c')
return;
if ("def"[3] == '0')
return;
}

void const_size_buffer_arithmetic() {
char kBuf[64] = {};
const char* p = kBuf + 1;
}

// expected-no-diagnostics
Copy link
Collaborator

Choose a reason for hiding this comment

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

Extreme nitpicking: I usually put those on top of the file because otherwise I'd be super confused where all those expected warnings are at. We also really don't want it to end up in the middle of the file if folks add more code at the bottom without reading the comment.

Loading