[clang] [Webkit checkers] Detect a function which returns a casted this pointer (PR #240279)

Ryosuke Niwa via cfe-commits cfe-commits at lists.llvm.org
Sun Nov 8 22:49:07 PST 2026


https://github.com/rniwa created https://github.com/llvm/llvm-project/pull/240279

In local variable and call argument checkers, detect a function which returns a casted this pointer. For such a function call, treat the function like it has lifetime bound and check the object argument.

Co-authored with Claude

>From fb6669279a3333ea31fbbaa41b1610a2d00daca5 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa <rniwa at webkit.org>
Date: Sun, 8 Nov 2026 22:43:20 -0800
Subject: [PATCH] [Webkit checkers] Detect a function which returns a casted
 this pointer

In local variable and call argument checkers, detect a function which returns a casted this pointer.
For such a function call, treat the function like it has lifetime bound and check the object argument.

Co-authored with Claude
---
 .../Checkers/WebKit/ASTUtils.cpp              |  59 ++++++++-
 .../StaticAnalyzer/Checkers/WebKit/ASTUtils.h |  13 ++
 .../WebKit/RawPtrRefCallArgsChecker.cpp       |   7 ++
 .../WebKit/RawPtrRefLocalVarsChecker.cpp      |  10 ++
 .../WebKit/call-args-cast-of-this.cpp         |  60 ++++++++++
 .../WebKit/local-vars-cast-of-this.cpp        | 112 ++++++++++++++++++
 6 files changed, 259 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/Analysis/Checkers/WebKit/call-args-cast-of-this.cpp
 create mode 100644 clang/test/Analysis/Checkers/WebKit/local-vars-cast-of-this.cpp

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index d737696c0b06be..9d31217cdae57d 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -672,7 +672,53 @@ class EnsureFunctionVisitor
   }
 };
 
-bool EnsureFunctionAnalysis::isACallToEnsureFn(const clang::Expr *E) const {
+/// \returns true if E is `this` or `*this`, possibly wrapped in casts or in
+/// calls to pointer conversion functions (e.g. downcast<Derived>(*this)).
+static bool isThisOrConversionOfThis(const Expr *E) {
+  while (E) {
+    E = E->IgnoreParenCasts();
+    if (auto *UO = dyn_cast<UnaryOperator>(E)) {
+      if (UO->getOpcode() != UO_Deref)
+        return false;
+      E = UO->getSubExpr();
+      continue;
+    }
+    if (auto *Call = dyn_cast<CallExpr>(E)) {
+      auto *Callee = Call->getDirectCallee();
+      if (!Callee || Call->getNumArgs() != 1 || !isPtrConversion(Callee))
+        return false;
+      E = Call->getArg(0);
+      continue;
+    }
+    return isa<CXXThisExpr>(E);
+  }
+  return false;
+}
+
+/// Accepts a body whose every return statement returns `this` or `*this`,
+/// possibly converted (e.g. static_cast<Derived*>(this)).
+class ReturnsThisVisitor : public ConstStmtVisitor<ReturnsThisVisitor, bool> {
+public:
+  bool VisitStmt(const Stmt *S) {
+    for (const Stmt *Child : S->children()) {
+      if (Child && !Visit(Child))
+        return false;
+    }
+    return true;
+  }
+
+  bool VisitReturnStmt(const ReturnStmt *RS) {
+    auto *RV = RS->getRetValue();
+    return RV && isThisOrConversionOfThis(RV);
+  }
+};
+
+/// Runs VisitorT over the body of the non-virtual member function called by E,
+/// caching the result per callee.
+template <typename VisitorT>
+static bool
+analyzeMemberCallee(const Expr *E,
+                    llvm::DenseMap<const FunctionDecl *, bool> &Cache) {
   auto *MCE = dyn_cast<CXXMemberCallExpr>(E);
   if (!MCE)
     return false;
@@ -684,8 +730,17 @@ bool EnsureFunctionAnalysis::isACallToEnsureFn(const clang::Expr *E) const {
     return false;
   auto [CacheIt, IsNew] = Cache.insert(std::make_pair(Callee, false));
   if (IsNew)
-    CacheIt->second = EnsureFunctionVisitor().Visit(Body);
+    CacheIt->second = VisitorT().Visit(Body);
   return CacheIt->second;
 }
 
+bool EnsureFunctionAnalysis::isACallToEnsureFn(const clang::Expr *E) const {
+  return analyzeMemberCallee<EnsureFunctionVisitor>(E, Cache);
+}
+
+bool CastOfThisFunctionAnalysis::isACallToCastOfThisFn(
+    const clang::Expr *E) const {
+  return analyzeMemberCallee<ReturnsThisVisitor>(E, Cache);
+}
+
 } // namespace clang
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
index 68f8623814bcf1..bc9be1115036e7 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.h
@@ -105,6 +105,19 @@ class EnsureFunctionAnalysis {
   bool isACallToEnsureFn(const Expr *E) const;
 };
 
+/// \returns true if E is a call to a non-virtual member function which always
+/// returns `this` or `*this`, possibly converted to another type by a cast or
+/// a pointer conversion function. The result has the same lifetime as the
+/// receiver, so callers must check that the receiver (the implicit object
+/// argument) is safe.
+class CastOfThisFunctionAnalysis {
+  using CacheTy = llvm::DenseMap<const FunctionDecl *, bool>;
+  mutable CacheTy Cache{};
+
+public:
+  bool isACallToCastOfThisFn(const Expr *E) const;
+};
+
 /// \returns name of AST node or empty string.
 template <typename T> std::string safeGetName(const T *ASTNode) {
   const auto *const ND = llvm::dyn_cast_or_null<clang::NamedDecl>(ASTNode);
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp
index 51d592660d62f7..9952838f1f3035 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp
@@ -35,6 +35,7 @@ class RawPtrRefCallArgsChecker
 
   TrivialFunctionAnalysis TFA;
   EnsureFunctionAnalysis EFA;
+  CastOfThisFunctionAnalysis CTFA;
 
 protected:
   mutable BugReporter *BR;
@@ -324,6 +325,12 @@ class RawPtrRefCallArgsChecker
             if (isPtrOriginSafe(MCE->getImplicitObjectArgument()))
               return true;
           }
+          if (CTFA.isACallToCastOfThisFn(ArgOrigin)) {
+            auto *MCE = dyn_cast<CXXMemberCallExpr>(ArgOrigin);
+            assert(MCE);
+            if (isPtrOriginSafe(MCE->getImplicitObjectArgument()))
+              return true;
+          }
           if (Model->isSafeExpr(ArgOrigin, PtrIsLifetimeBoundToOrigin, SinkType,
                                 /*SinkMayEscape=*/false))
             return true;
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefLocalVarsChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefLocalVarsChecker.cpp
index 91945caa608486..23ef9335443185 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefLocalVarsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefLocalVarsChecker.cpp
@@ -265,6 +265,7 @@ class RawPtrRefLocalVarsChecker
     : public Checker<check::ASTDecl<TranslationUnitDecl>> {
   BugType Bug;
   EnsureFunctionAnalysis EFA;
+  CastOfThisFunctionAnalysis CTFA;
 
 protected:
   mutable BugReporter *BR;
@@ -512,6 +513,15 @@ class RawPtrRefLocalVarsChecker
           if (EFA.isACallToEnsureFn(InitArgOrigin))
             return true;
 
+          if (CTFA.isACallToCastOfThisFn(InitArgOrigin)) {
+            auto *MCE = dyn_cast<CXXMemberCallExpr>(InitArgOrigin);
+            assert(MCE);
+            const Expr *ReceiverOrigin = nullptr;
+            if (isPtrOriginSafe(V, MCE->getImplicitObjectArgument(),
+                                DeclWithIssue, ReceiverOrigin, SinkType))
+              return true;
+          }
+
           if (Model->isSafeExpr(InitArgOrigin, PtrIsLifetimeBoundToOrigin,
                                 SinkType, /*SinkMayEscape=*/false))
             return true;
diff --git a/clang/test/Analysis/Checkers/WebKit/call-args-cast-of-this.cpp b/clang/test/Analysis/Checkers/WebKit/call-args-cast-of-this.cpp
new file mode 100644
index 00000000000000..d7d7443dde21a1
--- /dev/null
+++ b/clang/test/Analysis/Checkers/WebKit/call-args-cast-of-this.cpp
@@ -0,0 +1,60 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.webkit.UncountedCallArgsChecker -verify %s
+
+#include "mock-types.h"
+
+class Derived;
+Derived* [[clang::annotate_type("webkit.pointerconversion")]] annotatedCast(RefCountable*);
+template <typename T, typename U> T* unknownCast(U* u);
+
+void consume(RefCountable*);
+void consume(const RefCountable*);
+void consumeRef(RefCountable&);
+
+class Derived : public RefCountable {
+public:
+  Derived* asDerived() { return static_cast<Derived*>(this); }
+  Derived& asDerivedRef() { return *static_cast<Derived*>(this); }
+  Derived* maybe(Derived* other) { return other ? other : static_cast<Derived*>(this); }
+  Derived* cStyle() { return (Derived*)this; }
+  Derived* reinterp() { return reinterpret_cast<Derived*>(this); }
+  Derived* dyn() { return dynamic_cast<Derived*>(this); }
+  const Derived* constThis() const { return static_cast<const Derived*>(this); }
+  Derived* constCast() const { return const_cast<Derived*>(static_cast<const Derived*>(this)); }
+  Derived& cStyleRef() { return (Derived&)*this; }
+  RefCountable* upcast() { return this; }
+  Derived* viaHelper() { return downcast<Derived>(this); }
+  Derived& viaHelperRef() { return downcast<Derived>(*this); }
+  Derived* viaAnnotated() { return annotatedCast(this); }
+  Derived* viaUnknown() { return unknownCast<Derived>(this); }
+  virtual Derived* virt() { return this; }
+};
+
+void testSafeReceiver(Ref<Derived> ref, RefPtr<Derived> refPtr) {
+  consume(ref->asDerived());
+  consumeRef(ref->asDerivedRef());
+  consume(refPtr->asDerived());
+  consume(ref->cStyle());
+  consume(ref->reinterp());
+  consume(ref->dyn());
+  consume(ref->constThis());
+  consume(ref->constCast());
+  consumeRef(ref->cStyleRef());
+  consume(ref->upcast());
+  consume(ref->viaHelper());
+  consumeRef(ref->viaHelperRef());
+  consume(ref->viaAnnotated());
+  consume(ref->viaUnknown()); // Not a known pointer conversion function.
+  // expected-warning at -1{{Function argument 'ref->viaUnknown()' (to 'consume') is a raw pointer to RefPtr-capable type 'RefCountable'}}
+  consume(ref->virt()); // Virtual functions may be overridden.
+  // expected-warning at -1{{Function argument 'ref->virt()' (to 'consume') is a raw pointer to RefPtr-capable type 'RefCountable'}}
+}
+
+struct Holder {
+  Derived* m_raw;
+  void testUnsafeReceiver() {
+    consume(m_raw->asDerived());
+    // expected-warning at -1{{Function argument 'this->m_raw->asDerived()' (to 'consume') is a raw pointer to RefPtr-capable type 'RefCountable'}}
+    consume(m_raw->maybe(m_raw));
+    // expected-warning at -1{{Function argument 'this->m_raw->maybe(this->m_raw)' (to 'consume') is a raw pointer to RefPtr-capable type 'RefCountable'}}
+  }
+};
diff --git a/clang/test/Analysis/Checkers/WebKit/local-vars-cast-of-this.cpp b/clang/test/Analysis/Checkers/WebKit/local-vars-cast-of-this.cpp
new file mode 100644
index 00000000000000..edbf375aea336b
--- /dev/null
+++ b/clang/test/Analysis/Checkers/WebKit/local-vars-cast-of-this.cpp
@@ -0,0 +1,112 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.webkit.UncountedLocalVarsChecker -verify %s
+
+#include "mock-types.h"
+
+class Derived;
+Derived* [[clang::annotate_type("webkit.pointerconversion")]] annotatedCast(RefCountable*);
+template <typename T, typename U> T* unknownCast(U* u);
+
+class Derived : public RefCountable {
+public:
+  Derived* asDerived() { return static_cast<Derived*>(this); }
+  Derived& asDerivedRef() { return *static_cast<Derived*>(this); }
+  Derived* maybe(Derived* other) { return other ? other : static_cast<Derived*>(this); }
+  Derived* cStyle() { return (Derived*)this; }
+  Derived* reinterp() { return reinterpret_cast<Derived*>(this); }
+  Derived* dyn() { return dynamic_cast<Derived*>(this); }
+  const Derived* constThis() const { return static_cast<const Derived*>(this); }
+  Derived* constCast() const { return const_cast<Derived*>(static_cast<const Derived*>(this)); }
+  Derived& cStyleRef() { return (Derived&)*this; }
+  RefCountable* upcast() { return this; }
+  Derived* viaHelper() { return downcast<Derived>(this); }
+  Derived& viaHelperRef() { return downcast<Derived>(*this); }
+  Derived* viaAnnotated() { return annotatedCast(this); }
+  Derived* viaUnknown() { return unknownCast<Derived>(this); }
+  virtual Derived* virt() { return this; }
+};
+
+void testSafeReceiver(Ref<Derived> ref, RefPtr<Derived> refPtr) {
+  {
+    Derived* d = ref->asDerived();
+    d->method();
+  }
+  {
+    Derived& d = ref->asDerivedRef();
+    d.method();
+  }
+  {
+    Derived* d = refPtr->asDerived();
+    d->method();
+  }
+  {
+    Derived* d = ref->cStyle();
+    d->method();
+  }
+  {
+    Derived* d = ref->reinterp();
+    d->method();
+  }
+  {
+    Derived* d = ref->dyn();
+    d->method();
+  }
+  {
+    const Derived* d = ref->constThis();
+    d->constMethod();
+  }
+  {
+    Derived* d = ref->constCast();
+    d->method();
+  }
+  {
+    Derived& d = ref->cStyleRef();
+    d.method();
+  }
+  {
+    RefCountable* d = ref->upcast();
+    d->method();
+  }
+  {
+    Derived* d = ref->viaHelper();
+    d->method();
+  }
+  {
+    Derived& d = ref->viaHelperRef();
+    d.method();
+  }
+  {
+    Derived* d = ref->viaAnnotated();
+    d->method();
+  }
+  {
+    Derived* d = ref->viaUnknown(); // Not a known pointer conversion function.
+    // expected-warning at -1{{Local variable 'd' is a raw pointer to RefPtr-capable type 'Derived'}}
+    d->method();
+  }
+  {
+    Derived* d = ref->virt(); // Virtual functions may be overridden.
+    // expected-warning at -1{{Local variable 'd' is a raw pointer to RefPtr-capable type 'Derived'}}
+    d->method();
+  }
+}
+
+struct Holder {
+  Derived* m_raw;
+  void testUnsafeReceiver() {
+    {
+      Derived* d = m_raw->asDerived();
+      // expected-warning at -1{{Local variable 'd' is a raw pointer to RefPtr-capable type 'Derived'}}
+      d->method();
+    }
+    {
+      Derived* d = m_raw->viaHelper();
+      // expected-warning at -1{{Local variable 'd' is a raw pointer to RefPtr-capable type 'Derived'}}
+      d->method();
+    }
+    {
+      Derived* d = m_raw->maybe(m_raw);
+      // expected-warning at -1{{Local variable 'd' is a raw pointer to RefPtr-capable type 'Derived'}}
+      d->method();
+    }
+  }
+};



More information about the cfe-commits mailing list