================
@@ -3068,11 +3110,195 @@ void MallocChecker::checkDeadSymbols(SymbolReaper 
&SymReaper,
   C.addTransition(state->set<RegionState>(RS), N);
 }
 
+// Allowlist of owning smart pointers we want to recognize.
+// Start with unique_ptr and shared_ptr. (intentionally exclude weak_ptr)
+static bool isSmartOwningPtrType(QualType QT) {
+  QT = QT->getCanonicalTypeUnqualified();
+
+  auto isSmartPtrName = [](StringRef Name) {
+    return Name == "unique_ptr" || Name == "shared_ptr";
+  };
+
+  // First try TemplateSpecializationType (for std smart pointers)
+  if (const auto *TST = QT->getAs<TemplateSpecializationType>()) {
+    const TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl();
+    if (!TD)
+      return false;
+
+    const auto *ND = dyn_cast_or_null<NamedDecl>(TD->getTemplatedDecl());
+    if (!ND)
+      return false;
+
+    // Check if it's in std namespace
+    if (!isWithinStdNamespace(ND))
+      return false;
+
+    return isSmartPtrName(ND->getName());
+  }
+
+  // Also try RecordType (for custom smart pointer implementations)
+  if (const auto *RD = QT->getAsCXXRecordDecl()) {
+    // Accept any custom unique_ptr or shared_ptr implementation
+    return (isSmartPtrName(RD->getName()));
+  }
+
+  return false;
+}
+
+static bool hasSmartPtrField(const CXXRecordDecl *CRD) {
+  // Check direct fields
+  if (llvm::any_of(CRD->fields(), [](const FieldDecl *FD) {
+        return isSmartOwningPtrType(FD->getType());
+      }))
+    return true;
+
+  // Check fields from base classes
+  for (const CXXBaseSpecifier &Base : CRD->bases()) {
+    if (const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl()) {
+      if (hasSmartPtrField(BaseDecl))
+        return true;
+    }
+  }
+  return false;
+}
+
+static bool isRvalueByValueRecord(const Expr *AE) {
+  if (AE->isGLValue())
+    return false;
+
+  QualType T = AE->getType();
+  if (!T->isRecordType() || T->isReferenceType())
+    return false;
+
+  // Accept common temp/construct forms but don't overfit.
+  return isa<CXXTemporaryObjectExpr, MaterializeTemporaryExpr, 
CXXConstructExpr,
+             InitListExpr, ImplicitCastExpr, CXXBindTemporaryExpr>(AE);
+}
+
+static bool isRvalueByValueRecordWithSmartPtr(const Expr *AE) {
+  if (!isRvalueByValueRecord(AE))
+    return false;
+
+  const auto *CRD = AE->getType()->getAsCXXRecordDecl();
+  return CRD && hasSmartPtrField(CRD);
+}
+
+static ProgramStateRef escapeAllAllocatedSymbols(ProgramStateRef State) {
+  RegionStateTy RS = State->get<RegionState>();
+  ProgramStateRef NewState = State;
+  for (auto [Sym, RefSt] : RS) {
+    if (RefSt.isAllocated() || RefSt.isAllocatedOfSizeZero()) {
+      NewState = NewState->set<RegionState>(Sym, RefState::getEscaped(&RefSt));
+    }
+  }
+  return NewState;
+}
+
+static void collectDirectSmartOwningPtrFieldRegions(
+    const MemRegion *Base, QualType RecQT, CheckerContext &C,
+    SmallVectorImpl<const MemRegion *> &Out) {
+  if (!Base)
+    return;
+  const auto *CRD = RecQT->getAsCXXRecordDecl();
+  if (!CRD)
+    return;
+
+  // Collect direct fields
+  for (const FieldDecl *FD : CRD->fields()) {
+    if (!isSmartOwningPtrType(FD->getType()))
+      continue;
+    SVal L = C.getState()->getLValue(FD, loc::MemRegionVal(Base));
+    if (const MemRegion *FR = L.getAsRegion())
+      Out.push_back(FR);
+  }
+
+  // Collect fields from base classes
+  for (const CXXBaseSpecifier &BaseSpec : CRD->bases()) {
+    if (const CXXRecordDecl *BaseDecl =
+            BaseSpec.getType()->getAsCXXRecordDecl()) {
+      // Get the base class region
+      SVal BaseL = C.getState()->getLValue(BaseDecl, Base->getAs<SubRegion>(),
+                                           BaseSpec.isVirtual());
+      if (const MemRegion *BaseRegion = BaseL.getAsRegion()) {
+        // Recursively collect fields from this base class
+        collectDirectSmartOwningPtrFieldRegions(BaseRegion, BaseSpec.getType(),
+                                                C, Out);
+      }
+    }
+  }
+}
+
 void MallocChecker::checkPostCall(const CallEvent &Call,
                                   CheckerContext &C) const {
+  // Keep existing post-call handlers.
   if (const auto *PostFN = PostFnMap.lookup(Call)) {
     (*PostFN)(this, C.getState(), Call, C);
-    return;
+  }
+
+  SmallVector<const MemRegion *, 8> SmartPtrFieldRoots;
+  ProgramStateRef State = C.getState();
+  bool needsStateUpdate = false;
+
+  for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
+    const Expr *AE = Call.getArgExpr(I);
+    if (!AE)
+      continue;
+    AE = AE->IgnoreParenImpCasts();
+
+    if (!isRvalueByValueRecordWithSmartPtr(AE))
+      continue;
+
+    // Find a region for the argument.
+    SVal ArgVal = Call.getArgSVal(I);
+    const MemRegion *ArgRegion = ArgVal.getAsRegion();
+    if (!ArgRegion) {
+      // Fallback: if we have a by-value record with smart pointer fields but 
no
+      // region, mark all allocated symbols as escaped
+      State = escapeAllAllocatedSymbols(State);
+      needsStateUpdate = true;
+      continue;
+    }
+
+    // Push direct smart owning pointer field regions only (precise root set).
+    collectDirectSmartOwningPtrFieldRegions(ArgRegion, AE->getType(), C,
+                                            SmartPtrFieldRoots);
+  }
+
+  // Escape only from those field roots; do nothing if empty.
+  if (!SmartPtrFieldRoots.empty()) {
+    ProgramStateRef NewState =
+        EscapeTrackedCallback::EscapeTrackedRegionsReachableFrom(
+            SmartPtrFieldRoots, State);
+    if (NewState != State) {
+      State = NewState;
+      needsStateUpdate = true;
+    } else {
+      // Fallback: if we have by-value record arguments but no smart pointer
+      // fields detected, check if any of the arguments are by-value records
+      // with smart pointer fields
+      bool hasByValueRecordWithSmartPtr = false;
+      for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
+        const Expr *AE = Call.getArgExpr(I);
+        if (!AE)
+          continue;
+        AE = AE->IgnoreParenImpCasts();
+
+        if (isRvalueByValueRecordWithSmartPtr(AE)) {
+          hasByValueRecordWithSmartPtr = true;
+          break;
+        }
+      }
+
+      if (hasByValueRecordWithSmartPtr) {
+        State = escapeAllAllocatedSymbols(State);
----------------
ivanmurashko wrote:

At 10th commit I did the following:
- Added a test case verifying that `MallocChecker` correctly reports leaks for 
malloc when smart pointers are passed to functions.
- Fixed `checkPostCall` by removing fallback logic that indiscriminately 
escaped all allocated symbols on encountering smart pointers. Now only memory 
managed by smart pointers is escaped, enabling correct leak detection for 
regular malloc calls.
- Simplified code by removing the `needsStateUpdate` flag; always call 
`C.addTransition(State)` since it internally checks for state changes.
- Added clarifying comment about `addTransition` behaviour.

https://github.com/llvm/llvm-project/pull/152751
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to