Thanks to visit codestin.com
Credit goes to github.com

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

Conversation

jkorous-apple
Copy link
Contributor

addresses #92191

@llvmbot llvmbot added clang Clang issues not falling into any other category clang:analysis labels May 16, 2024
@llvmbot
Copy link
Member

llvmbot commented May 16, 2024

@llvm/pr-subscribers-clang

Author: None (jkorous-apple)

Changes

addresses #92191


Full diff: https://github.com/llvm/llvm-project/pull/92432.diff

2 Files Affected:

  • (modified) clang/lib/Analysis/UnsafeBufferUsage.cpp (+53-14)
  • (added) clang/test/SemaCXX/warn-unsafe-buffer-usage-constant-buffer-constant-index.cpp (+17)
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index c42e70d5b95ac..dc265b9039a5f 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -420,25 +420,64 @@ 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())) {
+        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());
+  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() &&
+      BufferOffset.getLimitedValue() < CATy->getLimitedSize())
+    return true;
 
   return false;
 }
@@ -692,7 +731,7 @@ 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));
   }
 
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-constant-buffer-constant-index.cpp b/clang/test/SemaCXX/warn-unsafe-buffer-usage-constant-buffer-constant-index.cpp
new file mode 100644
index 0000000000000..abacfcfee0296
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-constant-buffer-constant-index.cpp
@@ -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

@llvmbot
Copy link
Member

llvmbot commented May 16, 2024

@llvm/pr-subscribers-clang-analysis

Author: None (jkorous-apple)

Changes

addresses #92191


Full diff: https://github.com/llvm/llvm-project/pull/92432.diff

2 Files Affected:

  • (modified) clang/lib/Analysis/UnsafeBufferUsage.cpp (+53-14)
  • (added) clang/test/SemaCXX/warn-unsafe-buffer-usage-constant-buffer-constant-index.cpp (+17)
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index c42e70d5b95ac..dc265b9039a5f 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -420,25 +420,64 @@ 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())) {
+        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());
+  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() &&
+      BufferOffset.getLimitedValue() < CATy->getLimitedSize())
+    return true;
 
   return false;
 }
@@ -692,7 +731,7 @@ 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));
   }
 
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-constant-buffer-constant-index.cpp b/clang/test/SemaCXX/warn-unsafe-buffer-usage-constant-buffer-constant-index.cpp
new file mode 100644
index 0000000000000..abacfcfee0296
--- /dev/null
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-constant-buffer-constant-index.cpp
@@ -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

github-actions bot commented May 16, 2024

✅ With the latest revision this PR passed the C/C++ code formatter.


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.

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? 😅)

Copy link
Member

@pkasting pkasting left a comment

Choose a reason for hiding this comment

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

Drive-by

return false;
if (!BaseDRE->getDecl())

const auto *LHSDRE =
Copy link
Contributor

Choose a reason for hiding this comment

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

For both the AST matchers, I'm just curious if we really need to make sure the left-hand side is a DRE? Could we just try to test if its' type is a constant array type regardless of its' expression kind?

Copy link
Collaborator

@haoNoQ haoNoQ left a comment

Choose a reason for hiding this comment

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

Overall looks great!

I think I see a couple easy improvements, this isn't blocking but let's take a moment to consider them 😊

return false;
if (const auto *CATy = Finder->getASTContext().getAsConstantArrayType(
BaseDRE->getDecl()->getType())) {
if (const auto *IdxLit = dyn_cast<IntegerLiteral>(Node.getIdx())) {
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 BufferOffset = RHSIntLit->getValue();

if (BufferOffset.isNonNegative() &&
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.

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.

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.

@malavikasamak
Copy link
Contributor

Identifying safe operations on String literals has already landed as part of: #115552. However, identifying safe pointer arithmetic is not yet available. So, maybe we should revisit this PR once again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
clang:analysis clang Clang issues not falling into any other category
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants