[clang] [Webkit Checkers] Introduce a Webkit checker for memory unsafe casts (PR #114606)

Rashmi Mudduluru via cfe-commits cfe-commits at lists.llvm.org
Wed Nov 13 14:32:33 PST 2024


================
@@ -0,0 +1,117 @@
+//=======- MemoryUnsafeCastChecker.cpp -------------------------*- C++ -*-==//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines MemoryUnsafeCast checker, which checks for casts from a
+// base type to a derived type.
+//===----------------------------------------------------------------------===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/AST/StmtVisitor.h"
+#include "clang/Analysis/AnalysisDeclContext.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/Support/raw_ostream.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+class WalkAST : public StmtVisitor<WalkAST> {
+  BugReporter &BR;
+  const CheckerBase *Checker;
+  AnalysisDeclContext* AC;
+  ASTContext &ASTC;
+
+public:
+  WalkAST(BugReporter &br, const CheckerBase *checker, AnalysisDeclContext *ac)
+      : BR(br), Checker(checker), AC(ac), ASTC(AC->getASTContext()) {}
+
+  // Statement visitor methods.
+  void VisitChildren(Stmt *S);
+  void VisitStmt(Stmt *S) { VisitChildren(S); }
+  void VisitCastExpr(CastExpr *CE);
+};
+} // end anonymous namespace
+
+void emitWarning(QualType FromType, QualType ToType,
+                 AnalysisDeclContext *AC, BugReporter &BR,
+                 const CheckerBase *Checker,
+                 CastExpr *CE) {
+  std::string Diagnostics;
+  llvm::raw_string_ostream OS(Diagnostics);
+  OS << "Unsafe cast from base type '"
+     << FromType
+     << "' to derived type '"
+     << ToType
+     << "'",
+
+  BR.EmitBasicReport(
+    AC->getDecl(),
+    Checker,
+    /*Name=*/"Memory unsafe cast",
+    categories::SecurityError,
+    Diagnostics,
+    PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC),
+    CE->getSourceRange());
+}
+
+namespace {
+class MemoryUnsafeCastChecker : public Checker<check::ASTCodeBody> {
+  BugType BT{this, ""};
+public:
+  void checkASTCodeBody(const Decl *D, AnalysisManager& Mgr,
+                        BugReporter &BR) const {
+    WalkAST walker(BR, this, Mgr.getAnalysisDeclContext(D));
----------------
t-rasmud wrote:

I've updated the patch with AST matchers and added support for matching ObjectiveC pointers that was missing earlier.
@haoNoQ @rniwa @devincoughlin 

https://github.com/llvm/llvm-project/pull/114606


More information about the cfe-commits mailing list