Skip to content

[-Wunsafe-buffer-usage] Add findUnsafePointers #135421

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

Merged

Conversation

jkorous-apple
Copy link
Contributor

No description provided.

@llvmbot llvmbot added clang Clang issues not falling into any other category clang:analysis labels Apr 11, 2025
@llvmbot
Copy link
Member

llvmbot commented Apr 11, 2025

@llvm/pr-subscribers-clang-analysis

@llvm/pr-subscribers-clang

Author: Jan Korous (jkorous-apple)

Changes

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

2 Files Affected:

  • (modified) clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h (+3)
  • (modified) clang/lib/Analysis/UnsafeBufferUsage.cpp (+75)
diff --git a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
index 267cde64f8f23..9b53f1dc1d759 100644
--- a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
+++ b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
@@ -19,6 +19,7 @@
 #include "clang/AST/Stmt.h"
 #include "clang/Basic/SourceLocation.h"
 #include "llvm/Support/Debug.h"
+#include <set>
 
 namespace clang {
 
@@ -186,6 +187,8 @@ namespace internal {
 bool anyConflict(const llvm::SmallVectorImpl<FixItHint> &FixIts,
                  const SourceManager &SM);
 } // namespace internal
+
+std::set<const Expr *> findUnsafePointers(const FunctionDecl *FD);
 } // end namespace clang
 
 #endif /* LLVM_CLANG_ANALYSIS_ANALYSES_UNSAFEBUFFERUSAGE_H */
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 0dbb683729427..4eaf8ba61eaec 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -1163,6 +1163,8 @@ class WarningGadget : public Gadget {
   virtual void handleUnsafeOperation(UnsafeBufferUsageHandler &Handler,
                                      bool IsRelatedToDecl,
                                      ASTContext &Ctx) const = 0;
+
+  virtual SmallVector<const Expr *, 1> getUnsafePtrs() const = 0;
 };
 
 /// Fixable gadgets correspond to code patterns that aren't always unsafe but
@@ -1245,6 +1247,10 @@ class IncrementGadget : public WarningGadget {
 
     return std::move(Uses);
   }
+
+  SmallVector<const Expr *, 1> getUnsafePtrs() const override {
+    return {Op->getSubExpr()->IgnoreParenImpCasts()};
+  }
 };
 
 /// A decrement of a pointer-type value is unsafe as it may run the pointer
@@ -1288,6 +1294,10 @@ class DecrementGadget : public WarningGadget {
 
     return {};
   }
+
+  SmallVector<const Expr *, 1> getUnsafePtrs() const override {
+    return {Op->getSubExpr()->IgnoreParenImpCasts()};
+  }
 };
 
 /// Array subscript expressions on raw pointers as if they're arrays. Unsafe as
@@ -1337,6 +1347,10 @@ class ArraySubscriptGadget : public WarningGadget {
 
     return {};
   }
+
+  SmallVector<const Expr *, 1> getUnsafePtrs() const override {
+    return {ASE->getBase()->IgnoreParenImpCasts()};
+  }
 };
 
 /// A pointer arithmetic expression of one of the forms:
@@ -1400,6 +1414,11 @@ class PointerArithmeticGadget : public WarningGadget {
 
     return {};
   }
+
+  SmallVector<const Expr *, 1> getUnsafePtrs() const override {
+    return {Ptr->IgnoreParenImpCasts()};
+  }
+
   // FIXME: pointer adding zero should be fine
   // FIXME: this gadge will need a fix-it
 };
@@ -1457,6 +1476,8 @@ class SpanTwoParamConstructorGadget : public WarningGadget {
     }
     return {};
   }
+
+  SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
 };
 
 /// A pointer initialization expression of the form:
@@ -1689,6 +1710,8 @@ class UnsafeBufferUsageAttrGadget : public WarningGadget {
   SourceLocation getSourceLoc() const override { return Op->getBeginLoc(); }
 
   DeclUseList getClaimedVarUseSites() const override { return {}; }
+
+  SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
 };
 
 /// A call of a constructor that performs unchecked buffer operations
@@ -1727,6 +1750,8 @@ class UnsafeBufferUsageCtorAttrGadget : public WarningGadget {
   SourceLocation getSourceLoc() const override { return Op->getBeginLoc(); }
 
   DeclUseList getClaimedVarUseSites() const override { return {}; }
+
+  SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
 };
 
 // Warning gadget for unsafe invocation of span::data method.
@@ -1793,6 +1818,8 @@ class DataInvocationGadget : public WarningGadget {
       return true;
     return false;
   }
+
+  SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
 };
 
 class UnsafeLibcFunctionCallGadget : public WarningGadget {
@@ -1896,6 +1923,8 @@ class UnsafeLibcFunctionCallGadget : public WarningGadget {
   }
 
   DeclUseList getClaimedVarUseSites() const override { return {}; }
+
+  SmallVector<const Expr *, 1> getUnsafePtrs() const override { return {}; }
 };
 
 // Represents expressions of the form `DRE[*]` in the Unspecified Lvalue
@@ -2467,6 +2496,52 @@ template <typename NodeTy> struct CompareNode {
   }
 };
 
+std::set<const Expr *> clang::findUnsafePointers(const FunctionDecl *FD) {
+  class MockReporter : public UnsafeBufferUsageHandler {
+  public:
+    MockReporter() {}
+    void handleUnsafeOperation(const Stmt *, bool, ASTContext &) override {}
+    void handleUnsafeLibcCall(const CallExpr *, unsigned, ASTContext &,
+                              const Expr *UnsafeArg = nullptr) override {}
+    void handleUnsafeOperationInContainer(const Stmt *, bool,
+                                          ASTContext &) override {}
+    void handleUnsafeVariableGroup(const VarDecl *,
+                                   const VariableGroupsManager &, FixItList &&,
+                                   const Decl *,
+                                   const FixitStrategy &) override {}
+    bool isSafeBufferOptOut(const SourceLocation &) const override {
+      return false;
+    }
+    bool ignoreUnsafeBufferInContainer(const SourceLocation &) const override {
+      return false;
+    }
+    bool ignoreUnsafeBufferInLibcCall(const SourceLocation &) const override {
+      return false;
+    }
+    std::string getUnsafeBufferUsageAttributeTextAt(
+        SourceLocation, StringRef WSSuffix = "") const override {
+      return "";
+    }
+  };
+
+  FixableGadgetList FixableGadgets;
+  WarningGadgetList WarningGadgets;
+  DeclUseTracker Tracker;
+  MockReporter IgnoreHandler;
+
+  findGadgets(FD->getBody(), FD->getASTContext(), IgnoreHandler, false,
+              FixableGadgets, WarningGadgets, Tracker);
+
+  std::set<const Expr *> Result;
+  for (auto &G : WarningGadgets) {
+    for (const Expr *E : G->getUnsafePtrs()) {
+      Result.insert(E);
+    }
+  }
+
+  return Result;
+}
+
 struct WarningGadgetSets {
   std::map<const VarDecl *, std::set<const WarningGadget *>,
            // To keep keys sorted by their locations in the map so that the

@jkorous-apple jkorous-apple merged commit ee801cd into llvm:main Apr 11, 2025
14 checks passed
bcardosolopes added a commit to bcardosolopes/llvm-project that referenced this pull request Apr 11, 2025
* origin/main: (287 commits)
  [Sema] On Windows, silence erroneous warning when building with MSVC
  [lldb][lldbp-dap] On Windoows, silence warnings when building with MSVC
  [lldb] Fix erroneous return value
  [compiler-rt] On Windows, silence warning when building with Clang ToT
  [clang][unittests] On Windows, silence warning when building with MSVC
  [lldb] On Windows, silence warning when building with Clang ToT
  [CIR] Make LLVM & OGCG variables match the same pattern (llvm#135427)
  [mlir][SMT] upstream `SMT` dialect (llvm#131480)
  [clang] fix serialization for SubstNonTypeTemplateParmPackExpr (llvm#135428)
  [flang][openacc] Allow if_present multiple times on host_data and update (llvm#135422)
  [flang][openacc] Allow finalize clause on exit data more than once (llvm#135415)
  [flang] IEEE_SCALB and SCALE - kind=2, kind=3 (llvm#135374)
  [-Wunsafe-buffer-usage] Add findUnsafePointers (llvm#135421)
  [compiler-rt][sanitizer] add Haiku support (llvm#134772)
  [cpp23] Remove usage of std::aligned_union<> in llvm (llvm#135146)
  [mlir][tosa] Add error_if checks for Mul Op (llvm#135075)
  [VPlan] Merge cases using getResultType in inferScalarType (NFC).
  [flang][runtime] Fix recently broken big-endian formatted integer input (llvm#135417)
  [AMDGPU][Verifier] Mark calls to entry functions as invalid in the IR verifier (llvm#134910)
  [llvm][Hexagon] Promote operand v2i1 to v2i32 (llvm#135409)
  ...
juliannagele added a commit to swiftlang/llvm-project that referenced this pull request Apr 15, 2025
var-const pushed a commit to ldionne/llvm-project that referenced this pull request Apr 17, 2025
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.

2 participants