xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp (revision 4c6f313cb340c435f47ac032857030768c81c341)
1 //=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines a variety of memory management related checkers, such as
10 // leak, double free, and use-after-free.
11 //
12 // The following checkers are defined here:
13 //
14 //   * MallocChecker
15 //       Despite its name, it models all sorts of memory allocations and
16 //       de- or reallocation, including but not limited to malloc, free,
17 //       relloc, new, delete. It also reports on a variety of memory misuse
18 //       errors.
19 //       Many other checkers interact very closely with this checker, in fact,
20 //       most are merely options to this one. Other checkers may register
21 //       MallocChecker, but do not enable MallocChecker's reports (more details
22 //       to follow around its field, ChecksEnabled).
23 //       It also has a boolean "Optimistic" checker option, which if set to true
24 //       will cause the checker to model user defined memory management related
25 //       functions annotated via the attribute ownership_takes, ownership_holds
26 //       and ownership_returns.
27 //
28 //   * NewDeleteChecker
29 //       Enables the modeling of new, new[], delete, delete[] in MallocChecker,
30 //       and checks for related double-free and use-after-free errors.
31 //
32 //   * NewDeleteLeaksChecker
33 //       Checks for leaks related to new, new[], delete, delete[].
34 //       Depends on NewDeleteChecker.
35 //
36 //   * MismatchedDeallocatorChecker
37 //       Enables checking whether memory is deallocated with the correspending
38 //       allocation function in MallocChecker, such as malloc() allocated
39 //       regions are only freed by free(), new by delete, new[] by delete[].
40 //
41 //  InnerPointerChecker interacts very closely with MallocChecker, but unlike
42 //  the above checkers, it has it's own file, hence the many InnerPointerChecker
43 //  related headers and non-static functions.
44 //
45 //===----------------------------------------------------------------------===//
46 
47 #include "AllocationState.h"
48 #include "InterCheckerAPI.h"
49 #include "NoOwnershipChangeVisitor.h"
50 #include "clang/AST/Attr.h"
51 #include "clang/AST/DeclCXX.h"
52 #include "clang/AST/DeclTemplate.h"
53 #include "clang/AST/Expr.h"
54 #include "clang/AST/ExprCXX.h"
55 #include "clang/AST/ParentMap.h"
56 #include "clang/ASTMatchers/ASTMatchFinder.h"
57 #include "clang/ASTMatchers/ASTMatchers.h"
58 #include "clang/Analysis/ProgramPoint.h"
59 #include "clang/Basic/LLVM.h"
60 #include "clang/Basic/SourceManager.h"
61 #include "clang/Basic/TargetInfo.h"
62 #include "clang/Lex/Lexer.h"
63 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
64 #include "clang/StaticAnalyzer/Checkers/Taint.h"
65 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
66 #include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
67 #include "clang/StaticAnalyzer/Core/Checker.h"
68 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
69 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
70 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
71 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
72 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
73 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
74 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
75 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
76 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
77 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
78 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
79 #include "clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h"
80 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
81 #include "llvm/ADT/STLExtras.h"
82 #include "llvm/ADT/SetOperations.h"
83 #include "llvm/ADT/StringExtras.h"
84 #include "llvm/Support/Casting.h"
85 #include "llvm/Support/Compiler.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include <functional>
89 #include <optional>
90 #include <utility>
91 
92 using namespace clang;
93 using namespace ento;
94 using namespace std::placeholders;
95 
96 //===----------------------------------------------------------------------===//
97 // The types of allocation we're modeling. This is used to check whether a
98 // dynamically allocated object is deallocated with the correct function, like
99 // not using operator delete on an object created by malloc(), or alloca regions
100 // aren't ever deallocated manually.
101 //===----------------------------------------------------------------------===//
102 
103 namespace {
104 
105 // Used to check correspondence between allocators and deallocators.
106 enum AllocationFamilyKind {
107   AF_None,
108   AF_Malloc,
109   AF_CXXNew,
110   AF_CXXNewArray,
111   AF_IfNameIndex,
112   AF_Alloca,
113   AF_InnerBuffer,
114   AF_Custom,
115 };
116 
117 struct AllocationFamily {
118   AllocationFamilyKind Kind;
119   std::optional<StringRef> CustomName;
120 
121   explicit AllocationFamily(AllocationFamilyKind AKind,
122                             std::optional<StringRef> Name = std::nullopt)
123       : Kind(AKind), CustomName(Name) {
124     assert((Kind != AF_Custom || CustomName.has_value()) &&
125            "Custom family must specify also the name");
126 
127     // Preseve previous behavior when "malloc" class means AF_Malloc
128     if (Kind == AF_Custom && CustomName.value() == "malloc") {
129       Kind = AF_Malloc;
130       CustomName = std::nullopt;
131     }
132   }
133 
134   bool operator==(const AllocationFamily &Other) const {
135     return std::tie(Kind, CustomName) == std::tie(Other.Kind, Other.CustomName);
136   }
137 
138   bool operator!=(const AllocationFamily &Other) const {
139     return !(*this == Other);
140   }
141 
142   void Profile(llvm::FoldingSetNodeID &ID) const {
143     ID.AddInteger(Kind);
144 
145     if (Kind == AF_Custom)
146       ID.AddString(CustomName.value());
147   }
148 };
149 
150 } // end of anonymous namespace
151 
152 /// Print names of allocators and deallocators.
153 ///
154 /// \returns true on success.
155 static bool printMemFnName(raw_ostream &os, CheckerContext &C, const Expr *E);
156 
157 /// Print expected name of an allocator based on the deallocator's family
158 /// derived from the DeallocExpr.
159 static void printExpectedAllocName(raw_ostream &os, AllocationFamily Family);
160 
161 /// Print expected name of a deallocator based on the allocator's
162 /// family.
163 static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family);
164 
165 //===----------------------------------------------------------------------===//
166 // The state of a symbol, in terms of memory management.
167 //===----------------------------------------------------------------------===//
168 
169 namespace {
170 
171 class RefState {
172   enum Kind {
173     // Reference to allocated memory.
174     Allocated,
175     // Reference to zero-allocated memory.
176     AllocatedOfSizeZero,
177     // Reference to released/freed memory.
178     Released,
179     // The responsibility for freeing resources has transferred from
180     // this reference. A relinquished symbol should not be freed.
181     Relinquished,
182     // We are no longer guaranteed to have observed all manipulations
183     // of this pointer/memory. For example, it could have been
184     // passed as a parameter to an opaque function.
185     Escaped
186   };
187 
188   const Stmt *S;
189 
190   Kind K;
191   AllocationFamily Family;
192 
193   RefState(Kind k, const Stmt *s, AllocationFamily family)
194       : S(s), K(k), Family(family) {
195     assert(family.Kind != AF_None);
196   }
197 
198 public:
199   bool isAllocated() const { return K == Allocated; }
200   bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
201   bool isReleased() const { return K == Released; }
202   bool isRelinquished() const { return K == Relinquished; }
203   bool isEscaped() const { return K == Escaped; }
204   AllocationFamily getAllocationFamily() const { return Family; }
205   const Stmt *getStmt() const { return S; }
206 
207   bool operator==(const RefState &X) const {
208     return K == X.K && S == X.S && Family == X.Family;
209   }
210 
211   static RefState getAllocated(AllocationFamily family, const Stmt *s) {
212     return RefState(Allocated, s, family);
213   }
214   static RefState getAllocatedOfSizeZero(const RefState *RS) {
215     return RefState(AllocatedOfSizeZero, RS->getStmt(),
216                     RS->getAllocationFamily());
217   }
218   static RefState getReleased(AllocationFamily family, const Stmt *s) {
219     return RefState(Released, s, family);
220   }
221   static RefState getRelinquished(AllocationFamily family, const Stmt *s) {
222     return RefState(Relinquished, s, family);
223   }
224   static RefState getEscaped(const RefState *RS) {
225     return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
226   }
227 
228   void Profile(llvm::FoldingSetNodeID &ID) const {
229     ID.AddInteger(K);
230     ID.AddPointer(S);
231     Family.Profile(ID);
232   }
233 
234   LLVM_DUMP_METHOD void dump(raw_ostream &OS) const {
235     switch (K) {
236 #define CASE(ID) case ID: OS << #ID; break;
237     CASE(Allocated)
238     CASE(AllocatedOfSizeZero)
239     CASE(Released)
240     CASE(Relinquished)
241     CASE(Escaped)
242     }
243   }
244 
245   LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
246 };
247 
248 } // end of anonymous namespace
249 
250 REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
251 
252 /// Check if the memory associated with this symbol was released.
253 static bool isReleased(SymbolRef Sym, CheckerContext &C);
254 
255 /// Update the RefState to reflect the new memory allocation.
256 /// The optional \p RetVal parameter specifies the newly allocated pointer
257 /// value; if unspecified, the value of expression \p E is used.
258 static ProgramStateRef
259 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
260                      AllocationFamily Family,
261                      std::optional<SVal> RetVal = std::nullopt);
262 
263 //===----------------------------------------------------------------------===//
264 // The modeling of memory reallocation.
265 //
266 // The terminology 'toPtr' and 'fromPtr' will be used:
267 //   toPtr = realloc(fromPtr, 20);
268 //===----------------------------------------------------------------------===//
269 
270 REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
271 
272 namespace {
273 
274 /// The state of 'fromPtr' after reallocation is known to have failed.
275 enum OwnershipAfterReallocKind {
276   // The symbol needs to be freed (e.g.: realloc)
277   OAR_ToBeFreedAfterFailure,
278   // The symbol has been freed (e.g.: reallocf)
279   OAR_FreeOnFailure,
280   // The symbol doesn't have to freed (e.g.: we aren't sure if, how and where
281   // 'fromPtr' was allocated:
282   //    void Haha(int *ptr) {
283   //      ptr = realloc(ptr, 67);
284   //      // ...
285   //    }
286   // ).
287   OAR_DoNotTrackAfterFailure
288 };
289 
290 /// Stores information about the 'fromPtr' symbol after reallocation.
291 ///
292 /// This is important because realloc may fail, and that needs special modeling.
293 /// Whether reallocation failed or not will not be known until later, so we'll
294 /// store whether upon failure 'fromPtr' will be freed, or needs to be freed
295 /// later, etc.
296 struct ReallocPair {
297 
298   // The 'fromPtr'.
299   SymbolRef ReallocatedSym;
300   OwnershipAfterReallocKind Kind;
301 
302   ReallocPair(SymbolRef S, OwnershipAfterReallocKind K)
303       : ReallocatedSym(S), Kind(K) {}
304   void Profile(llvm::FoldingSetNodeID &ID) const {
305     ID.AddInteger(Kind);
306     ID.AddPointer(ReallocatedSym);
307   }
308   bool operator==(const ReallocPair &X) const {
309     return ReallocatedSym == X.ReallocatedSym &&
310            Kind == X.Kind;
311   }
312 };
313 
314 } // end of anonymous namespace
315 
316 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
317 
318 static bool isStandardNew(const FunctionDecl *FD);
319 static bool isStandardNew(const CallEvent &Call) {
320   if (!Call.getDecl() || !isa<FunctionDecl>(Call.getDecl()))
321     return false;
322   return isStandardNew(cast<FunctionDecl>(Call.getDecl()));
323 }
324 
325 static bool isStandardDelete(const FunctionDecl *FD);
326 static bool isStandardDelete(const CallEvent &Call) {
327   if (!Call.getDecl() || !isa<FunctionDecl>(Call.getDecl()))
328     return false;
329   return isStandardDelete(cast<FunctionDecl>(Call.getDecl()));
330 }
331 
332 /// Tells if the callee is one of the builtin new/delete operators, including
333 /// placement operators and other standard overloads.
334 template <typename T> static bool isStandardNewDelete(const T &FD) {
335   return isStandardDelete(FD) || isStandardNew(FD);
336 }
337 
338 //===----------------------------------------------------------------------===//
339 // Definition of the MallocChecker class.
340 //===----------------------------------------------------------------------===//
341 
342 namespace {
343 
344 class MallocChecker
345     : public Checker<check::DeadSymbols, check::PointerEscape,
346                      check::ConstPointerEscape, check::PreStmt<ReturnStmt>,
347                      check::EndFunction, check::PreCall, check::PostCall,
348                      eval::Call, check::NewAllocator,
349                      check::PostStmt<BlockExpr>, check::PostObjCMessage,
350                      check::Location, eval::Assume> {
351 public:
352   /// In pessimistic mode, the checker assumes that it does not know which
353   /// functions might free the memory.
354   /// In optimistic mode, the checker assumes that all user-defined functions
355   /// which might free a pointer are annotated.
356   bool ShouldIncludeOwnershipAnnotatedFunctions = false;
357 
358   bool ShouldRegisterNoOwnershipChangeVisitor = false;
359 
360   /// Many checkers are essentially built into this one, so enabling them will
361   /// make MallocChecker perform additional modeling and reporting.
362   enum CheckKind {
363     /// When a subchecker is enabled but MallocChecker isn't, model memory
364     /// management but do not emit warnings emitted with MallocChecker only
365     /// enabled.
366     CK_MallocChecker,
367     CK_NewDeleteChecker,
368     CK_NewDeleteLeaksChecker,
369     CK_MismatchedDeallocatorChecker,
370     CK_InnerPointerChecker,
371     CK_TaintedAllocChecker,
372     CK_NumCheckKinds
373   };
374 
375   using LeakInfo = std::pair<const ExplodedNode *, const MemRegion *>;
376 
377   bool ChecksEnabled[CK_NumCheckKinds] = {false};
378   CheckerNameRef CheckNames[CK_NumCheckKinds];
379 
380   void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
381   void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
382   bool evalCall(const CallEvent &Call, CheckerContext &C) const;
383   void checkNewAllocator(const CXXAllocatorCall &Call, CheckerContext &C) const;
384   void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
385   void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
386   void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
387   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
388   void checkEndFunction(const ReturnStmt *S, CheckerContext &C) const;
389   ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
390                             bool Assumption) const;
391   void checkLocation(SVal l, bool isLoad, const Stmt *S,
392                      CheckerContext &C) const;
393 
394   ProgramStateRef checkPointerEscape(ProgramStateRef State,
395                                     const InvalidatedSymbols &Escaped,
396                                     const CallEvent *Call,
397                                     PointerEscapeKind Kind) const;
398   ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
399                                           const InvalidatedSymbols &Escaped,
400                                           const CallEvent *Call,
401                                           PointerEscapeKind Kind) const;
402 
403   void printState(raw_ostream &Out, ProgramStateRef State,
404                   const char *NL, const char *Sep) const override;
405 
406 private:
407   mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
408   mutable std::unique_ptr<BugType> BT_DoubleDelete;
409   mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
410   mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
411   mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
412   mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
413   mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
414   mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
415   mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
416   mutable std::unique_ptr<BugType> BT_TaintedAlloc;
417 
418 #define CHECK_FN(NAME)                                                         \
419   void NAME(ProgramStateRef State, const CallEvent &Call, CheckerContext &C)   \
420       const;
421 
422   CHECK_FN(checkFree)
423   CHECK_FN(checkIfNameIndex)
424   CHECK_FN(checkBasicAlloc)
425   CHECK_FN(checkKernelMalloc)
426   CHECK_FN(checkCalloc)
427   CHECK_FN(checkAlloca)
428   CHECK_FN(checkStrdup)
429   CHECK_FN(checkIfFreeNameIndex)
430   CHECK_FN(checkCXXNewOrCXXDelete)
431   CHECK_FN(checkGMalloc0)
432   CHECK_FN(checkGMemdup)
433   CHECK_FN(checkGMallocN)
434   CHECK_FN(checkGMallocN0)
435   CHECK_FN(preGetdelim)
436   CHECK_FN(checkGetdelim)
437   CHECK_FN(checkReallocN)
438   CHECK_FN(checkOwnershipAttr)
439 
440   void checkRealloc(ProgramStateRef State, const CallEvent &Call,
441                     CheckerContext &C, bool ShouldFreeOnFail) const;
442 
443   using CheckFn =
444       std::function<void(const MallocChecker *, ProgramStateRef State,
445                          const CallEvent &Call, CheckerContext &C)>;
446 
447   const CallDescriptionMap<CheckFn> PreFnMap{
448       // NOTE: the following CallDescription also matches the C++ standard
449       // library function std::getline(); the callback will filter it out.
450       {{CDM::CLibrary, {"getline"}, 3}, &MallocChecker::preGetdelim},
451       {{CDM::CLibrary, {"getdelim"}, 4}, &MallocChecker::preGetdelim},
452   };
453 
454   const CallDescriptionMap<CheckFn> PostFnMap{
455       // NOTE: the following CallDescription also matches the C++ standard
456       // library function std::getline(); the callback will filter it out.
457       {{CDM::CLibrary, {"getline"}, 3}, &MallocChecker::checkGetdelim},
458       {{CDM::CLibrary, {"getdelim"}, 4}, &MallocChecker::checkGetdelim},
459   };
460 
461   const CallDescriptionMap<CheckFn> FreeingMemFnMap{
462       {{CDM::CLibrary, {"free"}, 1}, &MallocChecker::checkFree},
463       {{CDM::CLibrary, {"if_freenameindex"}, 1},
464        &MallocChecker::checkIfFreeNameIndex},
465       {{CDM::CLibrary, {"kfree"}, 1}, &MallocChecker::checkFree},
466       {{CDM::CLibrary, {"g_free"}, 1}, &MallocChecker::checkFree},
467   };
468 
469   bool isFreeingCall(const CallEvent &Call) const;
470   static bool isFreeingOwnershipAttrCall(const FunctionDecl *Func);
471   static bool isFreeingOwnershipAttrCall(const CallEvent &Call);
472   static bool isAllocatingOwnershipAttrCall(const FunctionDecl *Func);
473   static bool isAllocatingOwnershipAttrCall(const CallEvent &Call);
474 
475   friend class NoMemOwnershipChangeVisitor;
476 
477   CallDescriptionMap<CheckFn> AllocaMemFnMap{
478       {{CDM::CLibrary, {"alloca"}, 1}, &MallocChecker::checkAlloca},
479       {{CDM::CLibrary, {"_alloca"}, 1}, &MallocChecker::checkAlloca},
480       // The line for "alloca" also covers "__builtin_alloca", but the
481       // _with_align variant must be listed separately because it takes an
482       // extra argument:
483       {{CDM::CLibrary, {"__builtin_alloca_with_align"}, 2},
484        &MallocChecker::checkAlloca},
485   };
486 
487   CallDescriptionMap<CheckFn> AllocatingMemFnMap{
488       {{CDM::CLibrary, {"malloc"}, 1}, &MallocChecker::checkBasicAlloc},
489       {{CDM::CLibrary, {"malloc"}, 3}, &MallocChecker::checkKernelMalloc},
490       {{CDM::CLibrary, {"calloc"}, 2}, &MallocChecker::checkCalloc},
491       {{CDM::CLibrary, {"valloc"}, 1}, &MallocChecker::checkBasicAlloc},
492       {{CDM::CLibrary, {"strndup"}, 2}, &MallocChecker::checkStrdup},
493       {{CDM::CLibrary, {"strdup"}, 1}, &MallocChecker::checkStrdup},
494       {{CDM::CLibrary, {"_strdup"}, 1}, &MallocChecker::checkStrdup},
495       {{CDM::CLibrary, {"kmalloc"}, 2}, &MallocChecker::checkKernelMalloc},
496       {{CDM::CLibrary, {"if_nameindex"}, 1}, &MallocChecker::checkIfNameIndex},
497       {{CDM::CLibrary, {"wcsdup"}, 1}, &MallocChecker::checkStrdup},
498       {{CDM::CLibrary, {"_wcsdup"}, 1}, &MallocChecker::checkStrdup},
499       {{CDM::CLibrary, {"g_malloc"}, 1}, &MallocChecker::checkBasicAlloc},
500       {{CDM::CLibrary, {"g_malloc0"}, 1}, &MallocChecker::checkGMalloc0},
501       {{CDM::CLibrary, {"g_try_malloc"}, 1}, &MallocChecker::checkBasicAlloc},
502       {{CDM::CLibrary, {"g_try_malloc0"}, 1}, &MallocChecker::checkGMalloc0},
503       {{CDM::CLibrary, {"g_memdup"}, 2}, &MallocChecker::checkGMemdup},
504       {{CDM::CLibrary, {"g_malloc_n"}, 2}, &MallocChecker::checkGMallocN},
505       {{CDM::CLibrary, {"g_malloc0_n"}, 2}, &MallocChecker::checkGMallocN0},
506       {{CDM::CLibrary, {"g_try_malloc_n"}, 2}, &MallocChecker::checkGMallocN},
507       {{CDM::CLibrary, {"g_try_malloc0_n"}, 2}, &MallocChecker::checkGMallocN0},
508   };
509 
510   CallDescriptionMap<CheckFn> ReallocatingMemFnMap{
511       {{CDM::CLibrary, {"realloc"}, 2},
512        std::bind(&MallocChecker::checkRealloc, _1, _2, _3, _4, false)},
513       {{CDM::CLibrary, {"reallocf"}, 2},
514        std::bind(&MallocChecker::checkRealloc, _1, _2, _3, _4, true)},
515       {{CDM::CLibrary, {"g_realloc"}, 2},
516        std::bind(&MallocChecker::checkRealloc, _1, _2, _3, _4, false)},
517       {{CDM::CLibrary, {"g_try_realloc"}, 2},
518        std::bind(&MallocChecker::checkRealloc, _1, _2, _3, _4, false)},
519       {{CDM::CLibrary, {"g_realloc_n"}, 3}, &MallocChecker::checkReallocN},
520       {{CDM::CLibrary, {"g_try_realloc_n"}, 3}, &MallocChecker::checkReallocN},
521   };
522 
523   bool isMemCall(const CallEvent &Call) const;
524   bool hasOwnershipReturns(const CallEvent &Call) const;
525   bool hasOwnershipTakesHolds(const CallEvent &Call) const;
526   void reportTaintBug(StringRef Msg, ProgramStateRef State, CheckerContext &C,
527                       llvm::ArrayRef<SymbolRef> TaintedSyms,
528                       AllocationFamily Family) const;
529 
530   void checkTaintedness(CheckerContext &C, const CallEvent &Call,
531                         const SVal SizeSVal, ProgramStateRef State,
532                         AllocationFamily Family) const;
533 
534   // TODO: Remove mutable by moving the initializtaion to the registry function.
535   mutable std::optional<uint64_t> KernelZeroFlagVal;
536 
537   using KernelZeroSizePtrValueTy = std::optional<int>;
538   /// Store the value of macro called `ZERO_SIZE_PTR`.
539   /// The value is initialized at first use, before first use the outer
540   /// Optional is empty, afterwards it contains another Optional that indicates
541   /// if the macro value could be determined, and if yes the value itself.
542   mutable std::optional<KernelZeroSizePtrValueTy> KernelZeroSizePtrValue;
543 
544   /// Process C++ operator new()'s allocation, which is the part of C++
545   /// new-expression that goes before the constructor.
546   [[nodiscard]] ProgramStateRef
547   processNewAllocation(const CXXAllocatorCall &Call, CheckerContext &C,
548                        AllocationFamily Family) const;
549 
550   /// Perform a zero-allocation check.
551   ///
552   /// \param [in] Call The expression that allocates memory.
553   /// \param [in] IndexOfSizeArg Index of the argument that specifies the size
554   ///   of the memory that needs to be allocated. E.g. for malloc, this would be
555   ///   0.
556   /// \param [in] RetVal Specifies the newly allocated pointer value;
557   ///   if unspecified, the value of expression \p E is used.
558   [[nodiscard]] static ProgramStateRef
559   ProcessZeroAllocCheck(CheckerContext &C, const CallEvent &Call,
560                         const unsigned IndexOfSizeArg, ProgramStateRef State,
561                         std::optional<SVal> RetVal = std::nullopt);
562 
563   /// Model functions with the ownership_returns attribute.
564   ///
565   /// User-defined function may have the ownership_returns attribute, which
566   /// annotates that the function returns with an object that was allocated on
567   /// the heap, and passes the ownertship to the callee.
568   ///
569   ///   void __attribute((ownership_returns(malloc, 1))) *my_malloc(size_t);
570   ///
571   /// It has two parameters:
572   ///   - first: name of the resource (e.g. 'malloc')
573   ///   - (OPTIONAL) second: size of the allocated region
574   ///
575   /// \param [in] Call The expression that allocates memory.
576   /// \param [in] Att The ownership_returns attribute.
577   /// \param [in] State The \c ProgramState right before allocation.
578   /// \returns The ProgramState right after allocation.
579   [[nodiscard]] ProgramStateRef
580   MallocMemReturnsAttr(CheckerContext &C, const CallEvent &Call,
581                        const OwnershipAttr *Att, ProgramStateRef State) const;
582   /// Models memory allocation.
583   ///
584   /// \param [in] C Checker context.
585   /// \param [in] Call The expression that allocates memory.
586   /// \param [in] State The \c ProgramState right before allocation.
587   /// \param [in] isAlloca Is the allocation function alloca-like
588   /// \returns The ProgramState with returnValue bound
589   [[nodiscard]] ProgramStateRef MallocBindRetVal(CheckerContext &C,
590                                                  const CallEvent &Call,
591                                                  ProgramStateRef State,
592                                                  bool isAlloca) const;
593 
594   /// Models memory allocation.
595   ///
596   /// \param [in] Call The expression that allocates memory.
597   /// \param [in] SizeEx Size of the memory that needs to be allocated.
598   /// \param [in] Init The value the allocated memory needs to be initialized.
599   /// with. For example, \c calloc initializes the allocated memory to 0,
600   /// malloc leaves it undefined.
601   /// \param [in] State The \c ProgramState right before allocation.
602   /// \returns The ProgramState right after allocation.
603   [[nodiscard]] ProgramStateRef
604   MallocMemAux(CheckerContext &C, const CallEvent &Call, const Expr *SizeEx,
605                SVal Init, ProgramStateRef State, AllocationFamily Family) const;
606 
607   /// Models memory allocation.
608   ///
609   /// \param [in] Call The expression that allocates memory.
610   /// \param [in] Size Size of the memory that needs to be allocated.
611   /// \param [in] Init The value the allocated memory needs to be initialized.
612   /// with. For example, \c calloc initializes the allocated memory to 0,
613   /// malloc leaves it undefined.
614   /// \param [in] State The \c ProgramState right before allocation.
615   /// \returns The ProgramState right after allocation.
616   [[nodiscard]] ProgramStateRef MallocMemAux(CheckerContext &C,
617                                              const CallEvent &Call, SVal Size,
618                                              SVal Init, ProgramStateRef State,
619                                              AllocationFamily Family) const;
620 
621   // Check if this malloc() for special flags. At present that means M_ZERO or
622   // __GFP_ZERO (in which case, treat it like calloc).
623   [[nodiscard]] std::optional<ProgramStateRef>
624   performKernelMalloc(const CallEvent &Call, CheckerContext &C,
625                       const ProgramStateRef &State) const;
626 
627   /// Model functions with the ownership_takes and ownership_holds attributes.
628   ///
629   /// User-defined function may have the ownership_takes and/or ownership_holds
630   /// attributes, which annotates that the function frees the memory passed as a
631   /// parameter.
632   ///
633   ///   void __attribute((ownership_takes(malloc, 1))) my_free(void *);
634   ///   void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
635   ///
636   /// They have two parameters:
637   ///   - first: name of the resource (e.g. 'malloc')
638   ///   - second: index of the parameter the attribute applies to
639   ///
640   /// \param [in] Call The expression that frees memory.
641   /// \param [in] Att The ownership_takes or ownership_holds attribute.
642   /// \param [in] State The \c ProgramState right before allocation.
643   /// \returns The ProgramState right after deallocation.
644   [[nodiscard]] ProgramStateRef FreeMemAttr(CheckerContext &C,
645                                             const CallEvent &Call,
646                                             const OwnershipAttr *Att,
647                                             ProgramStateRef State) const;
648 
649   /// Models memory deallocation.
650   ///
651   /// \param [in] Call The expression that frees memory.
652   /// \param [in] State The \c ProgramState right before allocation.
653   /// \param [in] Num Index of the argument that needs to be freed. This is
654   ///   normally 0, but for custom free functions it may be different.
655   /// \param [in] Hold Whether the parameter at \p Index has the ownership_holds
656   ///   attribute.
657   /// \param [out] IsKnownToBeAllocated Whether the memory to be freed is known
658   ///   to have been allocated, or in other words, the symbol to be freed was
659   ///   registered as allocated by this checker. In the following case, \c ptr
660   ///   isn't known to be allocated.
661   ///      void Haha(int *ptr) {
662   ///        ptr = realloc(ptr, 67);
663   ///        // ...
664   ///      }
665   /// \param [in] ReturnsNullOnFailure Whether the memory deallocation function
666   ///   we're modeling returns with Null on failure.
667   /// \returns The ProgramState right after deallocation.
668   [[nodiscard]] ProgramStateRef
669   FreeMemAux(CheckerContext &C, const CallEvent &Call, ProgramStateRef State,
670              unsigned Num, bool Hold, bool &IsKnownToBeAllocated,
671              AllocationFamily Family, bool ReturnsNullOnFailure = false) const;
672 
673   /// Models memory deallocation.
674   ///
675   /// \param [in] ArgExpr The variable who's pointee needs to be freed.
676   /// \param [in] Call The expression that frees the memory.
677   /// \param [in] State The \c ProgramState right before allocation.
678   ///   normally 0, but for custom free functions it may be different.
679   /// \param [in] Hold Whether the parameter at \p Index has the ownership_holds
680   ///   attribute.
681   /// \param [out] IsKnownToBeAllocated Whether the memory to be freed is known
682   ///   to have been allocated, or in other words, the symbol to be freed was
683   ///   registered as allocated by this checker. In the following case, \c ptr
684   ///   isn't known to be allocated.
685   ///      void Haha(int *ptr) {
686   ///        ptr = realloc(ptr, 67);
687   ///        // ...
688   ///      }
689   /// \param [in] ReturnsNullOnFailure Whether the memory deallocation function
690   ///   we're modeling returns with Null on failure.
691   /// \param [in] ArgValOpt Optional value to use for the argument instead of
692   /// the one obtained from ArgExpr.
693   /// \returns The ProgramState right after deallocation.
694   [[nodiscard]] ProgramStateRef
695   FreeMemAux(CheckerContext &C, const Expr *ArgExpr, const CallEvent &Call,
696              ProgramStateRef State, bool Hold, bool &IsKnownToBeAllocated,
697              AllocationFamily Family, bool ReturnsNullOnFailure = false,
698              std::optional<SVal> ArgValOpt = {}) const;
699 
700   // TODO: Needs some refactoring, as all other deallocation modeling
701   // functions are suffering from out parameters and messy code due to how
702   // realloc is handled.
703   //
704   /// Models memory reallocation.
705   ///
706   /// \param [in] Call The expression that reallocated memory
707   /// \param [in] ShouldFreeOnFail Whether if reallocation fails, the supplied
708   ///   memory should be freed.
709   /// \param [in] State The \c ProgramState right before reallocation.
710   /// \param [in] SuffixWithN Whether the reallocation function we're modeling
711   ///   has an '_n' suffix, such as g_realloc_n.
712   /// \returns The ProgramState right after reallocation.
713   [[nodiscard]] ProgramStateRef
714   ReallocMemAux(CheckerContext &C, const CallEvent &Call, bool ShouldFreeOnFail,
715                 ProgramStateRef State, AllocationFamily Family,
716                 bool SuffixWithN = false) const;
717 
718   /// Evaluates the buffer size that needs to be allocated.
719   ///
720   /// \param [in] Blocks The amount of blocks that needs to be allocated.
721   /// \param [in] BlockBytes The size of a block.
722   /// \returns The symbolic value of \p Blocks * \p BlockBytes.
723   [[nodiscard]] static SVal evalMulForBufferSize(CheckerContext &C,
724                                                  const Expr *Blocks,
725                                                  const Expr *BlockBytes);
726 
727   /// Models zero initialized array allocation.
728   ///
729   /// \param [in] Call The expression that reallocated memory
730   /// \param [in] State The \c ProgramState right before reallocation.
731   /// \returns The ProgramState right after allocation.
732   [[nodiscard]] ProgramStateRef CallocMem(CheckerContext &C,
733                                           const CallEvent &Call,
734                                           ProgramStateRef State) const;
735 
736   /// See if deallocation happens in a suspicious context. If so, escape the
737   /// pointers that otherwise would have been deallocated and return true.
738   bool suppressDeallocationsInSuspiciousContexts(const CallEvent &Call,
739                                                  CheckerContext &C) const;
740 
741   /// If in \p S  \p Sym is used, check whether \p Sym was already freed.
742   bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
743 
744   /// If in \p S \p Sym is used, check whether \p Sym was allocated as a zero
745   /// sized memory region.
746   void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
747                              const Stmt *S) const;
748 
749   /// If in \p S \p Sym is being freed, check whether \p Sym was already freed.
750   bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
751 
752   /// Check if the function is known to free memory, or if it is
753   /// "interesting" and should be modeled explicitly.
754   ///
755   /// \param [out] EscapingSymbol A function might not free memory in general,
756   ///   but could be known to free a particular symbol. In this case, false is
757   ///   returned and the single escaping symbol is returned through the out
758   ///   parameter.
759   ///
760   /// We assume that pointers do not escape through calls to system functions
761   /// not handled by this checker.
762   bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
763                                    ProgramStateRef State,
764                                    SymbolRef &EscapingSymbol) const;
765 
766   /// Implementation of the checkPointerEscape callbacks.
767   [[nodiscard]] ProgramStateRef
768   checkPointerEscapeAux(ProgramStateRef State,
769                         const InvalidatedSymbols &Escaped,
770                         const CallEvent *Call, PointerEscapeKind Kind,
771                         bool IsConstPointerEscape) const;
772 
773   // Implementation of the checkPreStmt and checkEndFunction callbacks.
774   void checkEscapeOnReturn(const ReturnStmt *S, CheckerContext &C) const;
775 
776   ///@{
777   /// Tells if a given family/call/symbol is tracked by the current checker.
778   /// Sets CheckKind to the kind of the checker responsible for this
779   /// family/call/symbol.
780   std::optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
781                                              bool IsALeakCheck = false) const;
782 
783   std::optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
784                                              bool IsALeakCheck = false) const;
785   ///@}
786   static bool SummarizeValue(raw_ostream &os, SVal V);
787   static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
788 
789   void HandleNonHeapDealloc(CheckerContext &C, SVal ArgVal, SourceRange Range,
790                             const Expr *DeallocExpr,
791                             AllocationFamily Family) const;
792 
793   void HandleFreeAlloca(CheckerContext &C, SVal ArgVal,
794                         SourceRange Range) const;
795 
796   void HandleMismatchedDealloc(CheckerContext &C, SourceRange Range,
797                                const Expr *DeallocExpr, const RefState *RS,
798                                SymbolRef Sym, bool OwnershipTransferred) const;
799 
800   void HandleOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
801                         const Expr *DeallocExpr, AllocationFamily Family,
802                         const Expr *AllocExpr = nullptr) const;
803 
804   void HandleUseAfterFree(CheckerContext &C, SourceRange Range,
805                           SymbolRef Sym) const;
806 
807   void HandleDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
808                         SymbolRef Sym, SymbolRef PrevSym) const;
809 
810   void HandleDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
811 
812   void HandleUseZeroAlloc(CheckerContext &C, SourceRange Range,
813                           SymbolRef Sym) const;
814 
815   void HandleFunctionPtrFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
816                              const Expr *FreeExpr,
817                              AllocationFamily Family) const;
818 
819   /// Find the location of the allocation for Sym on the path leading to the
820   /// exploded node N.
821   static LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
822                                     CheckerContext &C);
823 
824   void HandleLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
825 
826   /// Test if value in ArgVal equals to value in macro `ZERO_SIZE_PTR`.
827   bool isArgZERO_SIZE_PTR(ProgramStateRef State, CheckerContext &C,
828                           SVal ArgVal) const;
829 };
830 } // end anonymous namespace
831 
832 //===----------------------------------------------------------------------===//
833 // Definition of NoOwnershipChangeVisitor.
834 //===----------------------------------------------------------------------===//
835 
836 namespace {
837 class NoMemOwnershipChangeVisitor final : public NoOwnershipChangeVisitor {
838 protected:
839   /// Syntactically checks whether the callee is a deallocating function. Since
840   /// we have no path-sensitive information on this call (we would need a
841   /// CallEvent instead of a CallExpr for that), its possible that a
842   /// deallocation function was called indirectly through a function pointer,
843   /// but we are not able to tell, so this is a best effort analysis.
844   /// See namespace `memory_passed_to_fn_call_free_through_fn_ptr` in
845   /// clang/test/Analysis/NewDeleteLeaks.cpp.
846   bool isFreeingCallAsWritten(const CallExpr &Call) const {
847     const auto *MallocChk = static_cast<const MallocChecker *>(&Checker);
848     if (MallocChk->FreeingMemFnMap.lookupAsWritten(Call) ||
849         MallocChk->ReallocatingMemFnMap.lookupAsWritten(Call))
850       return true;
851 
852     if (const auto *Func =
853             llvm::dyn_cast_or_null<FunctionDecl>(Call.getCalleeDecl()))
854       return MallocChecker::isFreeingOwnershipAttrCall(Func);
855 
856     return false;
857   }
858 
859   bool hasResourceStateChanged(ProgramStateRef CallEnterState,
860                                ProgramStateRef CallExitEndState) final {
861     return CallEnterState->get<RegionState>(Sym) !=
862            CallExitEndState->get<RegionState>(Sym);
863   }
864 
865   /// Heuristically guess whether the callee intended to free memory. This is
866   /// done syntactically, because we are trying to argue about alternative
867   /// paths of execution, and as a consequence we don't have path-sensitive
868   /// information.
869   bool doesFnIntendToHandleOwnership(const Decl *Callee,
870                                      ASTContext &ACtx) final {
871     const FunctionDecl *FD = dyn_cast<FunctionDecl>(Callee);
872 
873     // Given that the stack frame was entered, the body should always be
874     // theoretically obtainable. In case of body farms, the synthesized body
875     // is not attached to declaration, thus triggering the '!FD->hasBody()'
876     // branch. That said, would a synthesized body ever intend to handle
877     // ownership? As of today they don't. And if they did, how would we
878     // put notes inside it, given that it doesn't match any source locations?
879     if (!FD || !FD->hasBody())
880       return false;
881     using namespace clang::ast_matchers;
882 
883     auto Matches = match(findAll(stmt(anyOf(cxxDeleteExpr().bind("delete"),
884                                             callExpr().bind("call")))),
885                          *FD->getBody(), ACtx);
886     for (BoundNodes Match : Matches) {
887       if (Match.getNodeAs<CXXDeleteExpr>("delete"))
888         return true;
889 
890       if (const auto *Call = Match.getNodeAs<CallExpr>("call"))
891         if (isFreeingCallAsWritten(*Call))
892           return true;
893     }
894     // TODO: Ownership might change with an attempt to store the allocated
895     // memory, not only through deallocation. Check for attempted stores as
896     // well.
897     return false;
898   }
899 
900   PathDiagnosticPieceRef emitNote(const ExplodedNode *N) final {
901     PathDiagnosticLocation L = PathDiagnosticLocation::create(
902         N->getLocation(),
903         N->getState()->getStateManager().getContext().getSourceManager());
904     return std::make_shared<PathDiagnosticEventPiece>(
905         L, "Returning without deallocating memory or storing the pointer for "
906            "later deallocation");
907   }
908 
909 public:
910   NoMemOwnershipChangeVisitor(SymbolRef Sym, const MallocChecker *Checker)
911       : NoOwnershipChangeVisitor(Sym, Checker) {}
912 
913   void Profile(llvm::FoldingSetNodeID &ID) const override {
914     static int Tag = 0;
915     ID.AddPointer(&Tag);
916     ID.AddPointer(Sym);
917   }
918 };
919 
920 } // end anonymous namespace
921 
922 //===----------------------------------------------------------------------===//
923 // Definition of MallocBugVisitor.
924 //===----------------------------------------------------------------------===//
925 
926 namespace {
927 /// The bug visitor which allows us to print extra diagnostics along the
928 /// BugReport path. For example, showing the allocation site of the leaked
929 /// region.
930 class MallocBugVisitor final : public BugReporterVisitor {
931 protected:
932   enum NotificationMode { Normal, ReallocationFailed };
933 
934   // The allocated region symbol tracked by the main analysis.
935   SymbolRef Sym;
936 
937   // The mode we are in, i.e. what kind of diagnostics will be emitted.
938   NotificationMode Mode;
939 
940   // A symbol from when the primary region should have been reallocated.
941   SymbolRef FailedReallocSymbol;
942 
943   // A release function stack frame in which memory was released. Used for
944   // miscellaneous false positive suppression.
945   const StackFrameContext *ReleaseFunctionLC;
946 
947   bool IsLeak;
948 
949 public:
950   MallocBugVisitor(SymbolRef S, bool isLeak = false)
951       : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr),
952         ReleaseFunctionLC(nullptr), IsLeak(isLeak) {}
953 
954   static void *getTag() {
955     static int Tag = 0;
956     return &Tag;
957   }
958 
959   void Profile(llvm::FoldingSetNodeID &ID) const override {
960     ID.AddPointer(getTag());
961     ID.AddPointer(Sym);
962   }
963 
964   /// Did not track -> allocated. Other state (released) -> allocated.
965   static inline bool isAllocated(const RefState *RSCurr, const RefState *RSPrev,
966                                  const Stmt *Stmt) {
967     return (isa_and_nonnull<CallExpr, CXXNewExpr>(Stmt) &&
968             (RSCurr &&
969              (RSCurr->isAllocated() || RSCurr->isAllocatedOfSizeZero())) &&
970             (!RSPrev ||
971              !(RSPrev->isAllocated() || RSPrev->isAllocatedOfSizeZero())));
972   }
973 
974   /// Did not track -> released. Other state (allocated) -> released.
975   /// The statement associated with the release might be missing.
976   static inline bool isReleased(const RefState *RSCurr, const RefState *RSPrev,
977                                 const Stmt *Stmt) {
978     bool IsReleased =
979         (RSCurr && RSCurr->isReleased()) && (!RSPrev || !RSPrev->isReleased());
980     assert(!IsReleased || (isa_and_nonnull<CallExpr, CXXDeleteExpr>(Stmt)) ||
981            (!Stmt && RSCurr->getAllocationFamily().Kind == AF_InnerBuffer));
982     return IsReleased;
983   }
984 
985   /// Did not track -> relinquished. Other state (allocated) -> relinquished.
986   static inline bool isRelinquished(const RefState *RSCurr,
987                                     const RefState *RSPrev, const Stmt *Stmt) {
988     return (
989         isa_and_nonnull<CallExpr, ObjCMessageExpr, ObjCPropertyRefExpr>(Stmt) &&
990         (RSCurr && RSCurr->isRelinquished()) &&
991         (!RSPrev || !RSPrev->isRelinquished()));
992   }
993 
994   /// If the expression is not a call, and the state change is
995   /// released -> allocated, it must be the realloc return value
996   /// check. If we have to handle more cases here, it might be cleaner just
997   /// to track this extra bit in the state itself.
998   static inline bool hasReallocFailed(const RefState *RSCurr,
999                                       const RefState *RSPrev,
1000                                       const Stmt *Stmt) {
1001     return ((!isa_and_nonnull<CallExpr>(Stmt)) &&
1002             (RSCurr &&
1003              (RSCurr->isAllocated() || RSCurr->isAllocatedOfSizeZero())) &&
1004             (RSPrev &&
1005              !(RSPrev->isAllocated() || RSPrev->isAllocatedOfSizeZero())));
1006   }
1007 
1008   PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
1009                                    BugReporterContext &BRC,
1010                                    PathSensitiveBugReport &BR) override;
1011 
1012   PathDiagnosticPieceRef getEndPath(BugReporterContext &BRC,
1013                                     const ExplodedNode *EndPathNode,
1014                                     PathSensitiveBugReport &BR) override {
1015     if (!IsLeak)
1016       return nullptr;
1017 
1018     PathDiagnosticLocation L = BR.getLocation();
1019     // Do not add the statement itself as a range in case of leak.
1020     return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(),
1021                                                       false);
1022   }
1023 
1024 private:
1025   class StackHintGeneratorForReallocationFailed
1026       : public StackHintGeneratorForSymbol {
1027   public:
1028     StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
1029         : StackHintGeneratorForSymbol(S, M) {}
1030 
1031     std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) override {
1032       // Printed parameters start at 1, not 0.
1033       ++ArgIndex;
1034 
1035       SmallString<200> buf;
1036       llvm::raw_svector_ostream os(buf);
1037 
1038       os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
1039          << " parameter failed";
1040 
1041       return std::string(os.str());
1042     }
1043 
1044     std::string getMessageForReturn(const CallExpr *CallExpr) override {
1045       return "Reallocation of returned value failed";
1046     }
1047   };
1048 };
1049 } // end anonymous namespace
1050 
1051 // A map from the freed symbol to the symbol representing the return value of
1052 // the free function.
1053 REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
1054 
1055 namespace {
1056 class StopTrackingCallback final : public SymbolVisitor {
1057   ProgramStateRef state;
1058 
1059 public:
1060   StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
1061   ProgramStateRef getState() const { return state; }
1062 
1063   bool VisitSymbol(SymbolRef sym) override {
1064     state = state->remove<RegionState>(sym);
1065     return true;
1066   }
1067 };
1068 } // end anonymous namespace
1069 
1070 static bool isStandardNew(const FunctionDecl *FD) {
1071   if (!FD)
1072     return false;
1073 
1074   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
1075   if (Kind != OO_New && Kind != OO_Array_New)
1076     return false;
1077 
1078   // This is standard if and only if it's not defined in a user file.
1079   SourceLocation L = FD->getLocation();
1080   // If the header for operator delete is not included, it's still defined
1081   // in an invalid source location. Check to make sure we don't crash.
1082   return !L.isValid() ||
1083          FD->getASTContext().getSourceManager().isInSystemHeader(L);
1084 }
1085 
1086 static bool isStandardDelete(const FunctionDecl *FD) {
1087   if (!FD)
1088     return false;
1089 
1090   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
1091   if (Kind != OO_Delete && Kind != OO_Array_Delete)
1092     return false;
1093 
1094   // This is standard if and only if it's not defined in a user file.
1095   SourceLocation L = FD->getLocation();
1096   // If the header for operator delete is not included, it's still defined
1097   // in an invalid source location. Check to make sure we don't crash.
1098   return !L.isValid() ||
1099          FD->getASTContext().getSourceManager().isInSystemHeader(L);
1100 }
1101 
1102 //===----------------------------------------------------------------------===//
1103 // Methods of MallocChecker and MallocBugVisitor.
1104 //===----------------------------------------------------------------------===//
1105 
1106 bool MallocChecker::isFreeingOwnershipAttrCall(const CallEvent &Call) {
1107   const auto *Func = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
1108 
1109   return Func && isFreeingOwnershipAttrCall(Func);
1110 }
1111 
1112 bool MallocChecker::isFreeingOwnershipAttrCall(const FunctionDecl *Func) {
1113   if (Func->hasAttrs()) {
1114     for (const auto *I : Func->specific_attrs<OwnershipAttr>()) {
1115       OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
1116       if (OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds)
1117         return true;
1118     }
1119   }
1120   return false;
1121 }
1122 
1123 bool MallocChecker::isFreeingCall(const CallEvent &Call) const {
1124   if (FreeingMemFnMap.lookup(Call) || ReallocatingMemFnMap.lookup(Call))
1125     return true;
1126 
1127   return isFreeingOwnershipAttrCall(Call);
1128 }
1129 
1130 bool MallocChecker::isAllocatingOwnershipAttrCall(const CallEvent &Call) {
1131   const auto *Func = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
1132 
1133   return Func && isAllocatingOwnershipAttrCall(Func);
1134 }
1135 
1136 bool MallocChecker::isAllocatingOwnershipAttrCall(const FunctionDecl *Func) {
1137   for (const auto *I : Func->specific_attrs<OwnershipAttr>()) {
1138     if (I->getOwnKind() == OwnershipAttr::Returns)
1139       return true;
1140   }
1141 
1142   return false;
1143 }
1144 
1145 bool MallocChecker::isMemCall(const CallEvent &Call) const {
1146   if (FreeingMemFnMap.lookup(Call) || AllocatingMemFnMap.lookup(Call) ||
1147       AllocaMemFnMap.lookup(Call) || ReallocatingMemFnMap.lookup(Call))
1148     return true;
1149 
1150   if (!ShouldIncludeOwnershipAnnotatedFunctions)
1151     return false;
1152 
1153   const auto *Func = dyn_cast<FunctionDecl>(Call.getDecl());
1154   return Func && Func->hasAttr<OwnershipAttr>();
1155 }
1156 
1157 std::optional<ProgramStateRef>
1158 MallocChecker::performKernelMalloc(const CallEvent &Call, CheckerContext &C,
1159                                    const ProgramStateRef &State) const {
1160   // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
1161   //
1162   // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
1163   //
1164   // One of the possible flags is M_ZERO, which means 'give me back an
1165   // allocation which is already zeroed', like calloc.
1166 
1167   // 2-argument kmalloc(), as used in the Linux kernel:
1168   //
1169   // void *kmalloc(size_t size, gfp_t flags);
1170   //
1171   // Has the similar flag value __GFP_ZERO.
1172 
1173   // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
1174   // code could be shared.
1175 
1176   ASTContext &Ctx = C.getASTContext();
1177   llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
1178 
1179   if (!KernelZeroFlagVal) {
1180     switch (OS) {
1181     case llvm::Triple::FreeBSD:
1182       KernelZeroFlagVal = 0x0100;
1183       break;
1184     case llvm::Triple::NetBSD:
1185       KernelZeroFlagVal = 0x0002;
1186       break;
1187     case llvm::Triple::OpenBSD:
1188       KernelZeroFlagVal = 0x0008;
1189       break;
1190     case llvm::Triple::Linux:
1191       // __GFP_ZERO
1192       KernelZeroFlagVal = 0x8000;
1193       break;
1194     default:
1195       // FIXME: We need a more general way of getting the M_ZERO value.
1196       // See also: O_CREAT in UnixAPIChecker.cpp.
1197 
1198       // Fall back to normal malloc behavior on platforms where we don't
1199       // know M_ZERO.
1200       return std::nullopt;
1201     }
1202   }
1203 
1204   // We treat the last argument as the flags argument, and callers fall-back to
1205   // normal malloc on a None return. This works for the FreeBSD kernel malloc
1206   // as well as Linux kmalloc.
1207   if (Call.getNumArgs() < 2)
1208     return std::nullopt;
1209 
1210   const Expr *FlagsEx = Call.getArgExpr(Call.getNumArgs() - 1);
1211   const SVal V = C.getSVal(FlagsEx);
1212   if (!isa<NonLoc>(V)) {
1213     // The case where 'V' can be a location can only be due to a bad header,
1214     // so in this case bail out.
1215     return std::nullopt;
1216   }
1217 
1218   NonLoc Flags = V.castAs<NonLoc>();
1219   NonLoc ZeroFlag = C.getSValBuilder()
1220                         .makeIntVal(*KernelZeroFlagVal, FlagsEx->getType())
1221                         .castAs<NonLoc>();
1222   SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
1223                                                       Flags, ZeroFlag,
1224                                                       FlagsEx->getType());
1225   if (MaskedFlagsUC.isUnknownOrUndef())
1226     return std::nullopt;
1227   DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
1228 
1229   // Check if maskedFlags is non-zero.
1230   ProgramStateRef TrueState, FalseState;
1231   std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
1232 
1233   // If M_ZERO is set, treat this like calloc (initialized).
1234   if (TrueState && !FalseState) {
1235     SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
1236     return MallocMemAux(C, Call, Call.getArgExpr(0), ZeroVal, TrueState,
1237                         AllocationFamily(AF_Malloc));
1238   }
1239 
1240   return std::nullopt;
1241 }
1242 
1243 SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
1244                                          const Expr *BlockBytes) {
1245   SValBuilder &SB = C.getSValBuilder();
1246   SVal BlocksVal = C.getSVal(Blocks);
1247   SVal BlockBytesVal = C.getSVal(BlockBytes);
1248   ProgramStateRef State = C.getState();
1249   SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
1250                                 SB.getContext().getSizeType());
1251   return TotalSize;
1252 }
1253 
1254 void MallocChecker::checkBasicAlloc(ProgramStateRef State,
1255                                     const CallEvent &Call,
1256                                     CheckerContext &C) const {
1257   State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State,
1258                        AllocationFamily(AF_Malloc));
1259   State = ProcessZeroAllocCheck(C, Call, 0, State);
1260   C.addTransition(State);
1261 }
1262 
1263 void MallocChecker::checkKernelMalloc(ProgramStateRef State,
1264                                       const CallEvent &Call,
1265                                       CheckerContext &C) const {
1266   std::optional<ProgramStateRef> MaybeState =
1267       performKernelMalloc(Call, C, State);
1268   if (MaybeState)
1269     State = *MaybeState;
1270   else
1271     State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State,
1272                          AllocationFamily(AF_Malloc));
1273   C.addTransition(State);
1274 }
1275 
1276 static bool isStandardRealloc(const CallEvent &Call) {
1277   const FunctionDecl *FD = dyn_cast<FunctionDecl>(Call.getDecl());
1278   assert(FD);
1279   ASTContext &AC = FD->getASTContext();
1280 
1281   return FD->getDeclaredReturnType().getDesugaredType(AC) == AC.VoidPtrTy &&
1282          FD->getParamDecl(0)->getType().getDesugaredType(AC) == AC.VoidPtrTy &&
1283          FD->getParamDecl(1)->getType().getDesugaredType(AC) ==
1284              AC.getSizeType();
1285 }
1286 
1287 static bool isGRealloc(const CallEvent &Call) {
1288   const FunctionDecl *FD = dyn_cast<FunctionDecl>(Call.getDecl());
1289   assert(FD);
1290   ASTContext &AC = FD->getASTContext();
1291 
1292   return FD->getDeclaredReturnType().getDesugaredType(AC) == AC.VoidPtrTy &&
1293          FD->getParamDecl(0)->getType().getDesugaredType(AC) == AC.VoidPtrTy &&
1294          FD->getParamDecl(1)->getType().getDesugaredType(AC) ==
1295              AC.UnsignedLongTy;
1296 }
1297 
1298 void MallocChecker::checkRealloc(ProgramStateRef State, const CallEvent &Call,
1299                                  CheckerContext &C,
1300                                  bool ShouldFreeOnFail) const {
1301   // Ignore calls to functions whose type does not match the expected type of
1302   // either the standard realloc or g_realloc from GLib.
1303   // FIXME: Should we perform this kind of checking consistently for each
1304   // function? If yes, then perhaps extend the `CallDescription` interface to
1305   // handle this.
1306   if (!isStandardRealloc(Call) && !isGRealloc(Call))
1307     return;
1308 
1309   State = ReallocMemAux(C, Call, ShouldFreeOnFail, State,
1310                         AllocationFamily(AF_Malloc));
1311   State = ProcessZeroAllocCheck(C, Call, 1, State);
1312   C.addTransition(State);
1313 }
1314 
1315 void MallocChecker::checkCalloc(ProgramStateRef State, const CallEvent &Call,
1316                                 CheckerContext &C) const {
1317   State = CallocMem(C, Call, State);
1318   State = ProcessZeroAllocCheck(C, Call, 0, State);
1319   State = ProcessZeroAllocCheck(C, Call, 1, State);
1320   C.addTransition(State);
1321 }
1322 
1323 void MallocChecker::checkFree(ProgramStateRef State, const CallEvent &Call,
1324                               CheckerContext &C) const {
1325   bool IsKnownToBeAllocatedMemory = false;
1326   if (suppressDeallocationsInSuspiciousContexts(Call, C))
1327     return;
1328   State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1329                      AllocationFamily(AF_Malloc));
1330   C.addTransition(State);
1331 }
1332 
1333 void MallocChecker::checkAlloca(ProgramStateRef State, const CallEvent &Call,
1334                                 CheckerContext &C) const {
1335   State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State,
1336                        AllocationFamily(AF_Alloca));
1337   State = ProcessZeroAllocCheck(C, Call, 0, State);
1338   C.addTransition(State);
1339 }
1340 
1341 void MallocChecker::checkStrdup(ProgramStateRef State, const CallEvent &Call,
1342                                 CheckerContext &C) const {
1343   const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1344   if (!CE)
1345     return;
1346   State = MallocMemAux(C, Call, UnknownVal(), UnknownVal(), State,
1347                        AllocationFamily(AF_Malloc));
1348 
1349   C.addTransition(State);
1350 }
1351 
1352 void MallocChecker::checkIfNameIndex(ProgramStateRef State,
1353                                      const CallEvent &Call,
1354                                      CheckerContext &C) const {
1355   // Should we model this differently? We can allocate a fixed number of
1356   // elements with zeros in the last one.
1357   State = MallocMemAux(C, Call, UnknownVal(), UnknownVal(), State,
1358                        AllocationFamily(AF_IfNameIndex));
1359 
1360   C.addTransition(State);
1361 }
1362 
1363 void MallocChecker::checkIfFreeNameIndex(ProgramStateRef State,
1364                                          const CallEvent &Call,
1365                                          CheckerContext &C) const {
1366   bool IsKnownToBeAllocatedMemory = false;
1367   State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1368                      AllocationFamily(AF_IfNameIndex));
1369   C.addTransition(State);
1370 }
1371 
1372 void MallocChecker::checkCXXNewOrCXXDelete(ProgramStateRef State,
1373                                            const CallEvent &Call,
1374                                            CheckerContext &C) const {
1375   bool IsKnownToBeAllocatedMemory = false;
1376   const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1377   if (!CE)
1378     return;
1379 
1380   assert(isStandardNewDelete(Call));
1381 
1382   // Process direct calls to operator new/new[]/delete/delete[] functions
1383   // as distinct from new/new[]/delete/delete[] expressions that are
1384   // processed by the checkPostStmt callbacks for CXXNewExpr and
1385   // CXXDeleteExpr.
1386   const FunctionDecl *FD = C.getCalleeDecl(CE);
1387   switch (FD->getOverloadedOperator()) {
1388   case OO_New:
1389     State = MallocMemAux(C, Call, CE->getArg(0), UndefinedVal(), State,
1390                          AllocationFamily(AF_CXXNew));
1391     State = ProcessZeroAllocCheck(C, Call, 0, State);
1392     break;
1393   case OO_Array_New:
1394     State = MallocMemAux(C, Call, CE->getArg(0), UndefinedVal(), State,
1395                          AllocationFamily(AF_CXXNewArray));
1396     State = ProcessZeroAllocCheck(C, Call, 0, State);
1397     break;
1398   case OO_Delete:
1399     State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1400                        AllocationFamily(AF_CXXNew));
1401     break;
1402   case OO_Array_Delete:
1403     State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1404                        AllocationFamily(AF_CXXNewArray));
1405     break;
1406   default:
1407     assert(false && "not a new/delete operator");
1408     return;
1409   }
1410 
1411   C.addTransition(State);
1412 }
1413 
1414 void MallocChecker::checkGMalloc0(ProgramStateRef State, const CallEvent &Call,
1415                                   CheckerContext &C) const {
1416   SValBuilder &svalBuilder = C.getSValBuilder();
1417   SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
1418   State = MallocMemAux(C, Call, Call.getArgExpr(0), zeroVal, State,
1419                        AllocationFamily(AF_Malloc));
1420   State = ProcessZeroAllocCheck(C, Call, 0, State);
1421   C.addTransition(State);
1422 }
1423 
1424 void MallocChecker::checkGMemdup(ProgramStateRef State, const CallEvent &Call,
1425                                  CheckerContext &C) const {
1426   State = MallocMemAux(C, Call, Call.getArgExpr(1), UnknownVal(), State,
1427                        AllocationFamily(AF_Malloc));
1428   State = ProcessZeroAllocCheck(C, Call, 1, State);
1429   C.addTransition(State);
1430 }
1431 
1432 void MallocChecker::checkGMallocN(ProgramStateRef State, const CallEvent &Call,
1433                                   CheckerContext &C) const {
1434   SVal Init = UndefinedVal();
1435   SVal TotalSize = evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1));
1436   State = MallocMemAux(C, Call, TotalSize, Init, State,
1437                        AllocationFamily(AF_Malloc));
1438   State = ProcessZeroAllocCheck(C, Call, 0, State);
1439   State = ProcessZeroAllocCheck(C, Call, 1, State);
1440   C.addTransition(State);
1441 }
1442 
1443 void MallocChecker::checkGMallocN0(ProgramStateRef State, const CallEvent &Call,
1444                                    CheckerContext &C) const {
1445   SValBuilder &SB = C.getSValBuilder();
1446   SVal Init = SB.makeZeroVal(SB.getContext().CharTy);
1447   SVal TotalSize = evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1));
1448   State = MallocMemAux(C, Call, TotalSize, Init, State,
1449                        AllocationFamily(AF_Malloc));
1450   State = ProcessZeroAllocCheck(C, Call, 0, State);
1451   State = ProcessZeroAllocCheck(C, Call, 1, State);
1452   C.addTransition(State);
1453 }
1454 
1455 static bool isFromStdNamespace(const CallEvent &Call) {
1456   const Decl *FD = Call.getDecl();
1457   assert(FD && "a CallDescription cannot match a call without a Decl");
1458   return FD->isInStdNamespace();
1459 }
1460 
1461 void MallocChecker::preGetdelim(ProgramStateRef State, const CallEvent &Call,
1462                                 CheckerContext &C) const {
1463   // Discard calls to the C++ standard library function std::getline(), which
1464   // is completely unrelated to the POSIX getline() that we're checking.
1465   if (isFromStdNamespace(Call))
1466     return;
1467 
1468   const auto LinePtr = getPointeeVal(Call.getArgSVal(0), State);
1469   if (!LinePtr)
1470     return;
1471 
1472   // FreeMemAux takes IsKnownToBeAllocated as an output parameter, and it will
1473   // be true after the call if the symbol was registered by this checker.
1474   // We do not need this value here, as FreeMemAux will take care
1475   // of reporting any violation of the preconditions.
1476   bool IsKnownToBeAllocated = false;
1477   State = FreeMemAux(C, Call.getArgExpr(0), Call, State, false,
1478                      IsKnownToBeAllocated, AllocationFamily(AF_Malloc), false,
1479                      LinePtr);
1480   if (State)
1481     C.addTransition(State);
1482 }
1483 
1484 void MallocChecker::checkGetdelim(ProgramStateRef State, const CallEvent &Call,
1485                                   CheckerContext &C) const {
1486   // Discard calls to the C++ standard library function std::getline(), which
1487   // is completely unrelated to the POSIX getline() that we're checking.
1488   if (isFromStdNamespace(Call))
1489     return;
1490 
1491   // Handle the post-conditions of getline and getdelim:
1492   // Register the new conjured value as an allocated buffer.
1493   const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1494   if (!CE)
1495     return;
1496 
1497   const auto LinePtr =
1498       getPointeeVal(Call.getArgSVal(0), State)->getAs<DefinedSVal>();
1499   const auto Size =
1500       getPointeeVal(Call.getArgSVal(1), State)->getAs<DefinedSVal>();
1501   if (!LinePtr || !Size || !LinePtr->getAsRegion())
1502     return;
1503 
1504   State = setDynamicExtent(State, LinePtr->getAsRegion(), *Size);
1505   C.addTransition(MallocUpdateRefState(C, CE, State,
1506                                        AllocationFamily(AF_Malloc), *LinePtr));
1507 }
1508 
1509 void MallocChecker::checkReallocN(ProgramStateRef State, const CallEvent &Call,
1510                                   CheckerContext &C) const {
1511   State = ReallocMemAux(C, Call, /*ShouldFreeOnFail=*/false, State,
1512                         AllocationFamily(AF_Malloc),
1513                         /*SuffixWithN=*/true);
1514   State = ProcessZeroAllocCheck(C, Call, 1, State);
1515   State = ProcessZeroAllocCheck(C, Call, 2, State);
1516   C.addTransition(State);
1517 }
1518 
1519 void MallocChecker::checkOwnershipAttr(ProgramStateRef State,
1520                                        const CallEvent &Call,
1521                                        CheckerContext &C) const {
1522   const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1523   if (!CE)
1524     return;
1525   const FunctionDecl *FD = C.getCalleeDecl(CE);
1526   if (!FD)
1527     return;
1528   if (ShouldIncludeOwnershipAnnotatedFunctions ||
1529       ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
1530     // Check all the attributes, if there are any.
1531     // There can be multiple of these attributes.
1532     if (FD->hasAttrs())
1533       for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
1534         switch (I->getOwnKind()) {
1535         case OwnershipAttr::Returns:
1536           State = MallocMemReturnsAttr(C, Call, I, State);
1537           break;
1538         case OwnershipAttr::Takes:
1539         case OwnershipAttr::Holds:
1540           State = FreeMemAttr(C, Call, I, State);
1541           break;
1542         }
1543       }
1544   }
1545   C.addTransition(State);
1546 }
1547 
1548 bool MallocChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
1549   if (!Call.getOriginExpr())
1550     return false;
1551 
1552   ProgramStateRef State = C.getState();
1553 
1554   if (const CheckFn *Callback = FreeingMemFnMap.lookup(Call)) {
1555     (*Callback)(this, State, Call, C);
1556     return true;
1557   }
1558 
1559   if (const CheckFn *Callback = AllocatingMemFnMap.lookup(Call)) {
1560     State = MallocBindRetVal(C, Call, State, false);
1561     (*Callback)(this, State, Call, C);
1562     return true;
1563   }
1564 
1565   if (const CheckFn *Callback = ReallocatingMemFnMap.lookup(Call)) {
1566     State = MallocBindRetVal(C, Call, State, false);
1567     (*Callback)(this, State, Call, C);
1568     return true;
1569   }
1570 
1571   if (isStandardNew(Call)) {
1572     State = MallocBindRetVal(C, Call, State, false);
1573     checkCXXNewOrCXXDelete(State, Call, C);
1574     return true;
1575   }
1576 
1577   if (isStandardDelete(Call)) {
1578     checkCXXNewOrCXXDelete(State, Call, C);
1579     return true;
1580   }
1581 
1582   if (const CheckFn *Callback = AllocaMemFnMap.lookup(Call)) {
1583     State = MallocBindRetVal(C, Call, State, true);
1584     (*Callback)(this, State, Call, C);
1585     return true;
1586   }
1587 
1588   if (isFreeingOwnershipAttrCall(Call)) {
1589     checkOwnershipAttr(State, Call, C);
1590     return true;
1591   }
1592 
1593   if (isAllocatingOwnershipAttrCall(Call)) {
1594     State = MallocBindRetVal(C, Call, State, false);
1595     checkOwnershipAttr(State, Call, C);
1596     return true;
1597   }
1598 
1599   return false;
1600 }
1601 
1602 // Performs a 0-sized allocations check.
1603 ProgramStateRef MallocChecker::ProcessZeroAllocCheck(
1604     CheckerContext &C, const CallEvent &Call, const unsigned IndexOfSizeArg,
1605     ProgramStateRef State, std::optional<SVal> RetVal) {
1606   if (!State)
1607     return nullptr;
1608 
1609   const Expr *Arg = nullptr;
1610 
1611   if (const CallExpr *CE = dyn_cast<CallExpr>(Call.getOriginExpr())) {
1612     Arg = CE->getArg(IndexOfSizeArg);
1613   } else if (const CXXNewExpr *NE =
1614                  dyn_cast<CXXNewExpr>(Call.getOriginExpr())) {
1615     if (NE->isArray()) {
1616       Arg = *NE->getArraySize();
1617     } else {
1618       return State;
1619     }
1620   } else {
1621     assert(false && "not a CallExpr or CXXNewExpr");
1622     return nullptr;
1623   }
1624 
1625   if (!RetVal)
1626     RetVal = State->getSVal(Call.getOriginExpr(), C.getLocationContext());
1627 
1628   assert(Arg);
1629 
1630   auto DefArgVal =
1631       State->getSVal(Arg, Call.getLocationContext()).getAs<DefinedSVal>();
1632 
1633   if (!DefArgVal)
1634     return State;
1635 
1636   // Check if the allocation size is 0.
1637   ProgramStateRef TrueState, FalseState;
1638   SValBuilder &SvalBuilder = State->getStateManager().getSValBuilder();
1639   DefinedSVal Zero =
1640       SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
1641 
1642   std::tie(TrueState, FalseState) =
1643       State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
1644 
1645   if (TrueState && !FalseState) {
1646     SymbolRef Sym = RetVal->getAsLocSymbol();
1647     if (!Sym)
1648       return State;
1649 
1650     const RefState *RS = State->get<RegionState>(Sym);
1651     if (RS) {
1652       if (RS->isAllocated())
1653         return TrueState->set<RegionState>(Sym,
1654                                           RefState::getAllocatedOfSizeZero(RS));
1655       else
1656         return State;
1657     } else {
1658       // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1659       // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1660       // tracked. Add zero-reallocated Sym to the state to catch references
1661       // to zero-allocated memory.
1662       return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1663     }
1664   }
1665 
1666   // Assume the value is non-zero going forward.
1667   assert(FalseState);
1668   return FalseState;
1669 }
1670 
1671 static QualType getDeepPointeeType(QualType T) {
1672   QualType Result = T, PointeeType = T->getPointeeType();
1673   while (!PointeeType.isNull()) {
1674     Result = PointeeType;
1675     PointeeType = PointeeType->getPointeeType();
1676   }
1677   return Result;
1678 }
1679 
1680 /// \returns true if the constructor invoked by \p NE has an argument of a
1681 /// pointer/reference to a record type.
1682 static bool hasNonTrivialConstructorCall(const CXXNewExpr *NE) {
1683 
1684   const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1685   if (!ConstructE)
1686     return false;
1687 
1688   if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1689     return false;
1690 
1691   const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1692 
1693   // Iterate over the constructor parameters.
1694   for (const auto *CtorParam : CtorD->parameters()) {
1695 
1696     QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1697     if (CtorParamPointeeT.isNull())
1698       continue;
1699 
1700     CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1701 
1702     if (CtorParamPointeeT->getAsCXXRecordDecl())
1703       return true;
1704   }
1705 
1706   return false;
1707 }
1708 
1709 ProgramStateRef
1710 MallocChecker::processNewAllocation(const CXXAllocatorCall &Call,
1711                                     CheckerContext &C,
1712                                     AllocationFamily Family) const {
1713   if (!isStandardNewDelete(Call))
1714     return nullptr;
1715 
1716   const CXXNewExpr *NE = Call.getOriginExpr();
1717   const ParentMap &PM = C.getLocationContext()->getParentMap();
1718   ProgramStateRef State = C.getState();
1719 
1720   // Non-trivial constructors have a chance to escape 'this', but marking all
1721   // invocations of trivial constructors as escaped would cause too great of
1722   // reduction of true positives, so let's just do that for constructors that
1723   // have an argument of a pointer-to-record type.
1724   if (!PM.isConsumedExpr(NE) && hasNonTrivialConstructorCall(NE))
1725     return State;
1726 
1727   // The return value from operator new is bound to a specified initialization
1728   // value (if any) and we don't want to loose this value. So we call
1729   // MallocUpdateRefState() instead of MallocMemAux() which breaks the
1730   // existing binding.
1731   SVal Target = Call.getObjectUnderConstruction();
1732   if (Call.getOriginExpr()->isArray()) {
1733     if (auto SizeEx = NE->getArraySize())
1734       checkTaintedness(C, Call, C.getSVal(*SizeEx), State,
1735                        AllocationFamily(AF_CXXNewArray));
1736   }
1737 
1738   State = MallocUpdateRefState(C, NE, State, Family, Target);
1739   State = ProcessZeroAllocCheck(C, Call, 0, State, Target);
1740   return State;
1741 }
1742 
1743 void MallocChecker::checkNewAllocator(const CXXAllocatorCall &Call,
1744                                       CheckerContext &C) const {
1745   if (!C.wasInlined) {
1746     ProgramStateRef State = processNewAllocation(
1747         Call, C,
1748         AllocationFamily(Call.getOriginExpr()->isArray() ? AF_CXXNewArray
1749                                                          : AF_CXXNew));
1750     C.addTransition(State);
1751   }
1752 }
1753 
1754 static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1755   // If the first selector piece is one of the names below, assume that the
1756   // object takes ownership of the memory, promising to eventually deallocate it
1757   // with free().
1758   // Ex:  [NSData dataWithBytesNoCopy:bytes length:10];
1759   // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1760   StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
1761   return FirstSlot == "dataWithBytesNoCopy" ||
1762          FirstSlot == "initWithBytesNoCopy" ||
1763          FirstSlot == "initWithCharactersNoCopy";
1764 }
1765 
1766 static std::optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1767   Selector S = Call.getSelector();
1768 
1769   // FIXME: We should not rely on fully-constrained symbols being folded.
1770   for (unsigned i = 1; i < S.getNumArgs(); ++i)
1771     if (S.getNameForSlot(i) == "freeWhenDone")
1772       return !Call.getArgSVal(i).isZeroConstant();
1773 
1774   return std::nullopt;
1775 }
1776 
1777 void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1778                                          CheckerContext &C) const {
1779   if (C.wasInlined)
1780     return;
1781 
1782   if (!isKnownDeallocObjCMethodName(Call))
1783     return;
1784 
1785   if (std::optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1786     if (!*FreeWhenDone)
1787       return;
1788 
1789   if (Call.hasNonZeroCallbackArg())
1790     return;
1791 
1792   bool IsKnownToBeAllocatedMemory;
1793   ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0), Call, C.getState(),
1794                                      /*Hold=*/true, IsKnownToBeAllocatedMemory,
1795                                      AllocationFamily(AF_Malloc),
1796                                      /*ReturnsNullOnFailure=*/true);
1797 
1798   C.addTransition(State);
1799 }
1800 
1801 ProgramStateRef
1802 MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallEvent &Call,
1803                                     const OwnershipAttr *Att,
1804                                     ProgramStateRef State) const {
1805   if (!State)
1806     return nullptr;
1807 
1808   auto attrClassName = Att->getModule()->getName();
1809   auto Family = AllocationFamily(AF_Custom, attrClassName);
1810 
1811   if (!Att->args().empty()) {
1812     return MallocMemAux(C, Call,
1813                         Call.getArgExpr(Att->args_begin()->getASTIndex()),
1814                         UndefinedVal(), State, Family);
1815   }
1816   return MallocMemAux(C, Call, UnknownVal(), UndefinedVal(), State, Family);
1817 }
1818 
1819 ProgramStateRef MallocChecker::MallocBindRetVal(CheckerContext &C,
1820                                                 const CallEvent &Call,
1821                                                 ProgramStateRef State,
1822                                                 bool isAlloca) const {
1823   const Expr *CE = Call.getOriginExpr();
1824 
1825   // We expect the allocation functions to return a pointer.
1826   if (!Loc::isLocType(CE->getType()))
1827     return nullptr;
1828 
1829   unsigned Count = C.blockCount();
1830   SValBuilder &SVB = C.getSValBuilder();
1831   const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1832   DefinedSVal RetVal = isAlloca ? SVB.getAllocaRegionVal(CE, LCtx, Count)
1833                                 : SVB.getConjuredHeapSymbolVal(CE, LCtx, Count);
1834   return State->BindExpr(CE, C.getLocationContext(), RetVal);
1835 }
1836 
1837 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1838                                             const CallEvent &Call,
1839                                             const Expr *SizeEx, SVal Init,
1840                                             ProgramStateRef State,
1841                                             AllocationFamily Family) const {
1842   if (!State)
1843     return nullptr;
1844 
1845   assert(SizeEx);
1846   return MallocMemAux(C, Call, C.getSVal(SizeEx), Init, State, Family);
1847 }
1848 
1849 void MallocChecker::reportTaintBug(StringRef Msg, ProgramStateRef State,
1850                                    CheckerContext &C,
1851                                    llvm::ArrayRef<SymbolRef> TaintedSyms,
1852                                    AllocationFamily Family) const {
1853   if (ExplodedNode *N = C.generateNonFatalErrorNode(State, this)) {
1854     if (!BT_TaintedAlloc)
1855       BT_TaintedAlloc.reset(new BugType(CheckNames[CK_TaintedAllocChecker],
1856                                         "Tainted Memory Allocation",
1857                                         categories::TaintedData));
1858     auto R = std::make_unique<PathSensitiveBugReport>(*BT_TaintedAlloc, Msg, N);
1859     for (auto TaintedSym : TaintedSyms) {
1860       R->markInteresting(TaintedSym);
1861     }
1862     C.emitReport(std::move(R));
1863   }
1864 }
1865 
1866 void MallocChecker::checkTaintedness(CheckerContext &C, const CallEvent &Call,
1867                                      const SVal SizeSVal, ProgramStateRef State,
1868                                      AllocationFamily Family) const {
1869   if (!ChecksEnabled[CK_TaintedAllocChecker])
1870     return;
1871   std::vector<SymbolRef> TaintedSyms =
1872       taint::getTaintedSymbols(State, SizeSVal);
1873   if (TaintedSyms.empty())
1874     return;
1875 
1876   SValBuilder &SVB = C.getSValBuilder();
1877   QualType SizeTy = SVB.getContext().getSizeType();
1878   QualType CmpTy = SVB.getConditionType();
1879   // In case the symbol is tainted, we give a warning if the
1880   // size is larger than SIZE_MAX/4
1881   BasicValueFactory &BVF = SVB.getBasicValueFactory();
1882   const llvm::APSInt MaxValInt = BVF.getMaxValue(SizeTy);
1883   NonLoc MaxLength =
1884       SVB.makeIntVal(MaxValInt / APSIntType(MaxValInt).getValue(4));
1885   std::optional<NonLoc> SizeNL = SizeSVal.getAs<NonLoc>();
1886   auto Cmp = SVB.evalBinOpNN(State, BO_GE, *SizeNL, MaxLength, CmpTy)
1887                  .getAs<DefinedOrUnknownSVal>();
1888   if (!Cmp)
1889     return;
1890   auto [StateTooLarge, StateNotTooLarge] = State->assume(*Cmp);
1891   if (!StateTooLarge && StateNotTooLarge) {
1892     // We can prove that size is not too large so there is no issue.
1893     return;
1894   }
1895 
1896   std::string Callee = "Memory allocation function";
1897   if (Call.getCalleeIdentifier())
1898     Callee = Call.getCalleeIdentifier()->getName().str();
1899   reportTaintBug(
1900       Callee + " is called with a tainted (potentially attacker controlled) "
1901                "value. Make sure the value is bound checked.",
1902       State, C, TaintedSyms, Family);
1903 }
1904 
1905 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1906                                             const CallEvent &Call, SVal Size,
1907                                             SVal Init, ProgramStateRef State,
1908                                             AllocationFamily Family) const {
1909   if (!State)
1910     return nullptr;
1911 
1912   const Expr *CE = Call.getOriginExpr();
1913 
1914   // We expect the malloc functions to return a pointer.
1915   // Should have been already checked.
1916   assert(Loc::isLocType(CE->getType()) &&
1917          "Allocation functions must return a pointer");
1918 
1919   const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1920   SVal RetVal = State->getSVal(CE, C.getLocationContext());
1921 
1922   // Fill the region with the initialization value.
1923   State = State->bindDefaultInitial(RetVal, Init, LCtx);
1924 
1925   // If Size is somehow undefined at this point, this line prevents a crash.
1926   if (Size.isUndef())
1927     Size = UnknownVal();
1928 
1929   checkTaintedness(C, Call, Size, State, AllocationFamily(AF_Malloc));
1930 
1931   // Set the region's extent.
1932   State = setDynamicExtent(State, RetVal.getAsRegion(),
1933                            Size.castAs<DefinedOrUnknownSVal>());
1934 
1935   return MallocUpdateRefState(C, CE, State, Family);
1936 }
1937 
1938 static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E,
1939                                             ProgramStateRef State,
1940                                             AllocationFamily Family,
1941                                             std::optional<SVal> RetVal) {
1942   if (!State)
1943     return nullptr;
1944 
1945   // Get the return value.
1946   if (!RetVal)
1947     RetVal = State->getSVal(E, C.getLocationContext());
1948 
1949   // We expect the malloc functions to return a pointer.
1950   if (!RetVal->getAs<Loc>())
1951     return nullptr;
1952 
1953   SymbolRef Sym = RetVal->getAsLocSymbol();
1954 
1955   // NOTE: If this was an `alloca()` call, then `RetVal` holds an
1956   // `AllocaRegion`, so `Sym` will be a nullpointer because `AllocaRegion`s do
1957   // not have an associated symbol. However, this distinct region type means
1958   // that we don't need to store anything about them in `RegionState`.
1959 
1960   if (Sym)
1961     return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1962 
1963   return State;
1964 }
1965 
1966 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1967                                            const CallEvent &Call,
1968                                            const OwnershipAttr *Att,
1969                                            ProgramStateRef State) const {
1970   if (!State)
1971     return nullptr;
1972 
1973   auto attrClassName = Att->getModule()->getName();
1974   auto Family = AllocationFamily(AF_Custom, attrClassName);
1975 
1976   bool IsKnownToBeAllocated = false;
1977 
1978   for (const auto &Arg : Att->args()) {
1979     ProgramStateRef StateI =
1980         FreeMemAux(C, Call, State, Arg.getASTIndex(),
1981                    Att->getOwnKind() == OwnershipAttr::Holds,
1982                    IsKnownToBeAllocated, Family);
1983     if (StateI)
1984       State = StateI;
1985   }
1986   return State;
1987 }
1988 
1989 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1990                                           const CallEvent &Call,
1991                                           ProgramStateRef State, unsigned Num,
1992                                           bool Hold, bool &IsKnownToBeAllocated,
1993                                           AllocationFamily Family,
1994                                           bool ReturnsNullOnFailure) const {
1995   if (!State)
1996     return nullptr;
1997 
1998   if (Call.getNumArgs() < (Num + 1))
1999     return nullptr;
2000 
2001   return FreeMemAux(C, Call.getArgExpr(Num), Call, State, Hold,
2002                     IsKnownToBeAllocated, Family, ReturnsNullOnFailure);
2003 }
2004 
2005 /// Checks if the previous call to free on the given symbol failed - if free
2006 /// failed, returns true. Also, returns the corresponding return value symbol.
2007 static bool didPreviousFreeFail(ProgramStateRef State,
2008                                 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
2009   const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
2010   if (Ret) {
2011     assert(*Ret && "We should not store the null return symbol");
2012     ConstraintManager &CMgr = State->getConstraintManager();
2013     ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
2014     RetStatusSymbol = *Ret;
2015     return FreeFailed.isConstrainedTrue();
2016   }
2017   return false;
2018 }
2019 
2020 static void printOwnershipTakesList(raw_ostream &os, CheckerContext &C,
2021                                     const Expr *E) {
2022   const CallExpr *CE = dyn_cast<CallExpr>(E);
2023 
2024   if (!CE)
2025     return;
2026 
2027   const FunctionDecl *FD = CE->getDirectCallee();
2028   if (!FD)
2029     return;
2030 
2031   // Only one ownership_takes attribute is allowed.
2032   for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
2033     if (I->getOwnKind() != OwnershipAttr::Takes)
2034       continue;
2035 
2036     os << ", which takes ownership of '" << I->getModule()->getName() << '\'';
2037     break;
2038   }
2039 }
2040 
2041 static bool printMemFnName(raw_ostream &os, CheckerContext &C, const Expr *E) {
2042   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2043     // FIXME: This doesn't handle indirect calls.
2044     const FunctionDecl *FD = CE->getDirectCallee();
2045     if (!FD)
2046       return false;
2047 
2048     os << '\'' << *FD;
2049 
2050     if (!FD->isOverloadedOperator())
2051       os << "()";
2052 
2053     os << '\'';
2054     return true;
2055   }
2056 
2057   if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
2058     if (Msg->isInstanceMessage())
2059       os << "-";
2060     else
2061       os << "+";
2062     Msg->getSelector().print(os);
2063     return true;
2064   }
2065 
2066   if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
2067     os << "'"
2068        << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
2069        << "'";
2070     return true;
2071   }
2072 
2073   if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
2074     os << "'"
2075        << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
2076        << "'";
2077     return true;
2078   }
2079 
2080   return false;
2081 }
2082 
2083 static void printExpectedAllocName(raw_ostream &os, AllocationFamily Family) {
2084 
2085   switch (Family.Kind) {
2086   case AF_Malloc:
2087     os << "'malloc()'";
2088     return;
2089   case AF_CXXNew:
2090     os << "'new'";
2091     return;
2092   case AF_CXXNewArray:
2093     os << "'new[]'";
2094     return;
2095   case AF_IfNameIndex:
2096     os << "'if_nameindex()'";
2097     return;
2098   case AF_InnerBuffer:
2099     os << "container-specific allocator";
2100     return;
2101   case AF_Custom:
2102     os << Family.CustomName.value();
2103     return;
2104   case AF_Alloca:
2105   case AF_None:
2106     assert(false && "not a deallocation expression");
2107   }
2108 }
2109 
2110 static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) {
2111   switch (Family.Kind) {
2112   case AF_Malloc:
2113     os << "'free()'";
2114     return;
2115   case AF_CXXNew:
2116     os << "'delete'";
2117     return;
2118   case AF_CXXNewArray:
2119     os << "'delete[]'";
2120     return;
2121   case AF_IfNameIndex:
2122     os << "'if_freenameindex()'";
2123     return;
2124   case AF_InnerBuffer:
2125     os << "container-specific deallocator";
2126     return;
2127   case AF_Custom:
2128     os << "function that takes ownership of '" << Family.CustomName.value()
2129        << "\'";
2130     return;
2131   case AF_Alloca:
2132   case AF_None:
2133     assert(false && "not a deallocation expression");
2134   }
2135 }
2136 
2137 ProgramStateRef
2138 MallocChecker::FreeMemAux(CheckerContext &C, const Expr *ArgExpr,
2139                           const CallEvent &Call, ProgramStateRef State,
2140                           bool Hold, bool &IsKnownToBeAllocated,
2141                           AllocationFamily Family, bool ReturnsNullOnFailure,
2142                           std::optional<SVal> ArgValOpt) const {
2143 
2144   if (!State)
2145     return nullptr;
2146 
2147   SVal ArgVal = ArgValOpt.value_or(C.getSVal(ArgExpr));
2148   if (!isa<DefinedOrUnknownSVal>(ArgVal))
2149     return nullptr;
2150   DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
2151 
2152   // Check for null dereferences.
2153   if (!isa<Loc>(location))
2154     return nullptr;
2155 
2156   // The explicit NULL case, no operation is performed.
2157   ProgramStateRef notNullState, nullState;
2158   std::tie(notNullState, nullState) = State->assume(location);
2159   if (nullState && !notNullState)
2160     return nullptr;
2161 
2162   // Unknown values could easily be okay
2163   // Undefined values are handled elsewhere
2164   if (ArgVal.isUnknownOrUndef())
2165     return nullptr;
2166 
2167   const MemRegion *R = ArgVal.getAsRegion();
2168   const Expr *ParentExpr = Call.getOriginExpr();
2169 
2170   // NOTE: We detected a bug, but the checker under whose name we would emit the
2171   // error could be disabled. Generally speaking, the MallocChecker family is an
2172   // integral part of the Static Analyzer, and disabling any part of it should
2173   // only be done under exceptional circumstances, such as frequent false
2174   // positives. If this is the case, we can reasonably believe that there are
2175   // serious faults in our understanding of the source code, and even if we
2176   // don't emit an warning, we should terminate further analysis with a sink
2177   // node.
2178 
2179   // Nonlocs can't be freed, of course.
2180   // Non-region locations (labels and fixed addresses) also shouldn't be freed.
2181   if (!R) {
2182     // Exception:
2183     // If the macro ZERO_SIZE_PTR is defined, this could be a kernel source
2184     // code. In that case, the ZERO_SIZE_PTR defines a special value used for a
2185     // zero-sized memory block which is allowed to be freed, despite not being a
2186     // null pointer.
2187     if (Family.Kind != AF_Malloc || !isArgZERO_SIZE_PTR(State, C, ArgVal))
2188       HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2189                            Family);
2190     return nullptr;
2191   }
2192 
2193   R = R->StripCasts();
2194 
2195   // Blocks might show up as heap data, but should not be free()d
2196   if (isa<BlockDataRegion>(R)) {
2197     HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2198                          Family);
2199     return nullptr;
2200   }
2201 
2202   const MemSpaceRegion *MS = R->getMemorySpace();
2203 
2204   // Parameters, locals, statics, globals, and memory returned by
2205   // __builtin_alloca() shouldn't be freed.
2206   if (!isa<UnknownSpaceRegion, HeapSpaceRegion>(MS)) {
2207     // Regions returned by malloc() are represented by SymbolicRegion objects
2208     // within HeapSpaceRegion. Of course, free() can work on memory allocated
2209     // outside the current function, so UnknownSpaceRegion is also a
2210     // possibility here.
2211 
2212     if (isa<AllocaRegion>(R))
2213       HandleFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
2214     else
2215       HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2216                            Family);
2217 
2218     return nullptr;
2219   }
2220 
2221   const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
2222   // Various cases could lead to non-symbol values here.
2223   // For now, ignore them.
2224   if (!SrBase)
2225     return nullptr;
2226 
2227   SymbolRef SymBase = SrBase->getSymbol();
2228   const RefState *RsBase = State->get<RegionState>(SymBase);
2229   SymbolRef PreviousRetStatusSymbol = nullptr;
2230 
2231   IsKnownToBeAllocated =
2232       RsBase && (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero());
2233 
2234   if (RsBase) {
2235 
2236     // Memory returned by alloca() shouldn't be freed.
2237     if (RsBase->getAllocationFamily().Kind == AF_Alloca) {
2238       HandleFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
2239       return nullptr;
2240     }
2241 
2242     // Check for double free first.
2243     if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
2244         !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
2245       HandleDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
2246                        SymBase, PreviousRetStatusSymbol);
2247       return nullptr;
2248 
2249     // If the pointer is allocated or escaped, but we are now trying to free it,
2250     // check that the call to free is proper.
2251     } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
2252                RsBase->isEscaped()) {
2253 
2254       // Check if an expected deallocation function matches the real one.
2255       bool DeallocMatchesAlloc = RsBase->getAllocationFamily() == Family;
2256       if (!DeallocMatchesAlloc) {
2257         HandleMismatchedDealloc(C, ArgExpr->getSourceRange(), ParentExpr,
2258                                 RsBase, SymBase, Hold);
2259         return nullptr;
2260       }
2261 
2262       // Check if the memory location being freed is the actual location
2263       // allocated, or an offset.
2264       RegionOffset Offset = R->getAsOffset();
2265       if (Offset.isValid() &&
2266           !Offset.hasSymbolicOffset() &&
2267           Offset.getOffset() != 0) {
2268         const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
2269         HandleOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2270                          Family, AllocExpr);
2271         return nullptr;
2272       }
2273     }
2274   }
2275 
2276   if (SymBase->getType()->isFunctionPointerType()) {
2277     HandleFunctionPtrFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2278                           Family);
2279     return nullptr;
2280   }
2281 
2282   // Clean out the info on previous call to free return info.
2283   State = State->remove<FreeReturnValue>(SymBase);
2284 
2285   // Keep track of the return value. If it is NULL, we will know that free
2286   // failed.
2287   if (ReturnsNullOnFailure) {
2288     SVal RetVal = C.getSVal(ParentExpr);
2289     SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
2290     if (RetStatusSymbol) {
2291       C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
2292       State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
2293     }
2294   }
2295 
2296   // If we don't know anything about this symbol, a free on it may be totally
2297   // valid. If this is the case, lets assume that the allocation family of the
2298   // freeing function is the same as the symbols allocation family, and go with
2299   // that.
2300   assert(!RsBase || (RsBase && RsBase->getAllocationFamily() == Family));
2301 
2302   // Assume that after memory is freed, it contains unknown values. This
2303   // conforts languages standards, since reading from freed memory is considered
2304   // UB and may result in arbitrary value.
2305   State = State->invalidateRegions({location}, Call.getOriginExpr(),
2306                                    C.blockCount(), C.getLocationContext(),
2307                                    /*CausesPointerEscape=*/false,
2308                                    /*InvalidatedSymbols=*/nullptr);
2309 
2310   // Normal free.
2311   if (Hold)
2312     return State->set<RegionState>(SymBase,
2313                                    RefState::getRelinquished(Family,
2314                                                              ParentExpr));
2315 
2316   return State->set<RegionState>(SymBase,
2317                                  RefState::getReleased(Family, ParentExpr));
2318 }
2319 
2320 std::optional<MallocChecker::CheckKind>
2321 MallocChecker::getCheckIfTracked(AllocationFamily Family,
2322                                  bool IsALeakCheck) const {
2323   switch (Family.Kind) {
2324   case AF_Malloc:
2325   case AF_Alloca:
2326   case AF_Custom:
2327   case AF_IfNameIndex: {
2328     if (ChecksEnabled[CK_MallocChecker])
2329       return CK_MallocChecker;
2330     return std::nullopt;
2331   }
2332   case AF_CXXNew:
2333   case AF_CXXNewArray: {
2334     if (IsALeakCheck) {
2335       if (ChecksEnabled[CK_NewDeleteLeaksChecker])
2336         return CK_NewDeleteLeaksChecker;
2337     }
2338     else {
2339       if (ChecksEnabled[CK_NewDeleteChecker])
2340         return CK_NewDeleteChecker;
2341     }
2342     return std::nullopt;
2343   }
2344   case AF_InnerBuffer: {
2345     if (ChecksEnabled[CK_InnerPointerChecker])
2346       return CK_InnerPointerChecker;
2347     return std::nullopt;
2348   }
2349   case AF_None: {
2350     assert(false && "no family");
2351     return std::nullopt;
2352   }
2353   }
2354   assert(false && "unhandled family");
2355   return std::nullopt;
2356 }
2357 
2358 std::optional<MallocChecker::CheckKind>
2359 MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
2360                                  bool IsALeakCheck) const {
2361   if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
2362     return CK_MallocChecker;
2363 
2364   const RefState *RS = C.getState()->get<RegionState>(Sym);
2365   assert(RS);
2366   return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
2367 }
2368 
2369 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
2370   if (std::optional<nonloc::ConcreteInt> IntVal =
2371           V.getAs<nonloc::ConcreteInt>())
2372     os << "an integer (" << IntVal->getValue() << ")";
2373   else if (std::optional<loc::ConcreteInt> ConstAddr =
2374                V.getAs<loc::ConcreteInt>())
2375     os << "a constant address (" << ConstAddr->getValue() << ")";
2376   else if (std::optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
2377     os << "the address of the label '" << Label->getLabel()->getName() << "'";
2378   else
2379     return false;
2380 
2381   return true;
2382 }
2383 
2384 bool MallocChecker::SummarizeRegion(raw_ostream &os,
2385                                     const MemRegion *MR) {
2386   switch (MR->getKind()) {
2387   case MemRegion::FunctionCodeRegionKind: {
2388     const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
2389     if (FD)
2390       os << "the address of the function '" << *FD << '\'';
2391     else
2392       os << "the address of a function";
2393     return true;
2394   }
2395   case MemRegion::BlockCodeRegionKind:
2396     os << "block text";
2397     return true;
2398   case MemRegion::BlockDataRegionKind:
2399     // FIXME: where the block came from?
2400     os << "a block";
2401     return true;
2402   default: {
2403     const MemSpaceRegion *MS = MR->getMemorySpace();
2404 
2405     if (isa<StackLocalsSpaceRegion>(MS)) {
2406       const VarRegion *VR = dyn_cast<VarRegion>(MR);
2407       const VarDecl *VD;
2408       if (VR)
2409         VD = VR->getDecl();
2410       else
2411         VD = nullptr;
2412 
2413       if (VD)
2414         os << "the address of the local variable '" << VD->getName() << "'";
2415       else
2416         os << "the address of a local stack variable";
2417       return true;
2418     }
2419 
2420     if (isa<StackArgumentsSpaceRegion>(MS)) {
2421       const VarRegion *VR = dyn_cast<VarRegion>(MR);
2422       const VarDecl *VD;
2423       if (VR)
2424         VD = VR->getDecl();
2425       else
2426         VD = nullptr;
2427 
2428       if (VD)
2429         os << "the address of the parameter '" << VD->getName() << "'";
2430       else
2431         os << "the address of a parameter";
2432       return true;
2433     }
2434 
2435     if (isa<GlobalsSpaceRegion>(MS)) {
2436       const VarRegion *VR = dyn_cast<VarRegion>(MR);
2437       const VarDecl *VD;
2438       if (VR)
2439         VD = VR->getDecl();
2440       else
2441         VD = nullptr;
2442 
2443       if (VD) {
2444         if (VD->isStaticLocal())
2445           os << "the address of the static variable '" << VD->getName() << "'";
2446         else
2447           os << "the address of the global variable '" << VD->getName() << "'";
2448       } else
2449         os << "the address of a global variable";
2450       return true;
2451     }
2452 
2453     return false;
2454   }
2455   }
2456 }
2457 
2458 void MallocChecker::HandleNonHeapDealloc(CheckerContext &C, SVal ArgVal,
2459                                          SourceRange Range,
2460                                          const Expr *DeallocExpr,
2461                                          AllocationFamily Family) const {
2462 
2463   if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) {
2464     C.addSink();
2465     return;
2466   }
2467 
2468   std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2469   if (!CheckKind)
2470     return;
2471 
2472   if (ExplodedNode *N = C.generateErrorNode()) {
2473     if (!BT_BadFree[*CheckKind])
2474       BT_BadFree[*CheckKind].reset(new BugType(
2475           CheckNames[*CheckKind], "Bad free", categories::MemoryError));
2476 
2477     SmallString<100> buf;
2478     llvm::raw_svector_ostream os(buf);
2479 
2480     const MemRegion *MR = ArgVal.getAsRegion();
2481     while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2482       MR = ER->getSuperRegion();
2483 
2484     os << "Argument to ";
2485     if (!printMemFnName(os, C, DeallocExpr))
2486       os << "deallocator";
2487 
2488     os << " is ";
2489     bool Summarized = MR ? SummarizeRegion(os, MR)
2490                          : SummarizeValue(os, ArgVal);
2491     if (Summarized)
2492       os << ", which is not memory allocated by ";
2493     else
2494       os << "not memory allocated by ";
2495 
2496     printExpectedAllocName(os, Family);
2497 
2498     auto R = std::make_unique<PathSensitiveBugReport>(*BT_BadFree[*CheckKind],
2499                                                       os.str(), N);
2500     R->markInteresting(MR);
2501     R->addRange(Range);
2502     C.emitReport(std::move(R));
2503   }
2504 }
2505 
2506 void MallocChecker::HandleFreeAlloca(CheckerContext &C, SVal ArgVal,
2507                                      SourceRange Range) const {
2508 
2509   std::optional<MallocChecker::CheckKind> CheckKind;
2510 
2511   if (ChecksEnabled[CK_MallocChecker])
2512     CheckKind = CK_MallocChecker;
2513   else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
2514     CheckKind = CK_MismatchedDeallocatorChecker;
2515   else {
2516     C.addSink();
2517     return;
2518   }
2519 
2520   if (ExplodedNode *N = C.generateErrorNode()) {
2521     if (!BT_FreeAlloca[*CheckKind])
2522       BT_FreeAlloca[*CheckKind].reset(new BugType(
2523           CheckNames[*CheckKind], "Free 'alloca()'", categories::MemoryError));
2524 
2525     auto R = std::make_unique<PathSensitiveBugReport>(
2526         *BT_FreeAlloca[*CheckKind],
2527         "Memory allocated by 'alloca()' should not be deallocated", N);
2528     R->markInteresting(ArgVal.getAsRegion());
2529     R->addRange(Range);
2530     C.emitReport(std::move(R));
2531   }
2532 }
2533 
2534 void MallocChecker::HandleMismatchedDealloc(CheckerContext &C,
2535                                             SourceRange Range,
2536                                             const Expr *DeallocExpr,
2537                                             const RefState *RS, SymbolRef Sym,
2538                                             bool OwnershipTransferred) const {
2539 
2540   if (!ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
2541     C.addSink();
2542     return;
2543   }
2544 
2545   if (ExplodedNode *N = C.generateErrorNode()) {
2546     if (!BT_MismatchedDealloc)
2547       BT_MismatchedDealloc.reset(
2548           new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
2549                       "Bad deallocator", categories::MemoryError));
2550 
2551     SmallString<100> buf;
2552     llvm::raw_svector_ostream os(buf);
2553 
2554     const Expr *AllocExpr = cast<Expr>(RS->getStmt());
2555     SmallString<20> AllocBuf;
2556     llvm::raw_svector_ostream AllocOs(AllocBuf);
2557     SmallString<20> DeallocBuf;
2558     llvm::raw_svector_ostream DeallocOs(DeallocBuf);
2559 
2560     if (OwnershipTransferred) {
2561       if (printMemFnName(DeallocOs, C, DeallocExpr))
2562         os << DeallocOs.str() << " cannot";
2563       else
2564         os << "Cannot";
2565 
2566       os << " take ownership of memory";
2567 
2568       if (printMemFnName(AllocOs, C, AllocExpr))
2569         os << " allocated by " << AllocOs.str();
2570     } else {
2571       os << "Memory";
2572       if (printMemFnName(AllocOs, C, AllocExpr))
2573         os << " allocated by " << AllocOs.str();
2574 
2575       os << " should be deallocated by ";
2576         printExpectedDeallocName(os, RS->getAllocationFamily());
2577 
2578         if (printMemFnName(DeallocOs, C, DeallocExpr))
2579           os << ", not " << DeallocOs.str();
2580 
2581         printOwnershipTakesList(os, C, DeallocExpr);
2582     }
2583 
2584     auto R = std::make_unique<PathSensitiveBugReport>(*BT_MismatchedDealloc,
2585                                                       os.str(), N);
2586     R->markInteresting(Sym);
2587     R->addRange(Range);
2588     R->addVisitor<MallocBugVisitor>(Sym);
2589     C.emitReport(std::move(R));
2590   }
2591 }
2592 
2593 void MallocChecker::HandleOffsetFree(CheckerContext &C, SVal ArgVal,
2594                                      SourceRange Range, const Expr *DeallocExpr,
2595                                      AllocationFamily Family,
2596                                      const Expr *AllocExpr) const {
2597 
2598   if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) {
2599     C.addSink();
2600     return;
2601   }
2602 
2603   std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2604   if (!CheckKind)
2605     return;
2606 
2607   ExplodedNode *N = C.generateErrorNode();
2608   if (!N)
2609     return;
2610 
2611   if (!BT_OffsetFree[*CheckKind])
2612     BT_OffsetFree[*CheckKind].reset(new BugType(
2613         CheckNames[*CheckKind], "Offset free", categories::MemoryError));
2614 
2615   SmallString<100> buf;
2616   llvm::raw_svector_ostream os(buf);
2617   SmallString<20> AllocNameBuf;
2618   llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
2619 
2620   const MemRegion *MR = ArgVal.getAsRegion();
2621   assert(MR && "Only MemRegion based symbols can have offset free errors");
2622 
2623   RegionOffset Offset = MR->getAsOffset();
2624   assert((Offset.isValid() &&
2625           !Offset.hasSymbolicOffset() &&
2626           Offset.getOffset() != 0) &&
2627          "Only symbols with a valid offset can have offset free errors");
2628 
2629   int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
2630 
2631   os << "Argument to ";
2632   if (!printMemFnName(os, C, DeallocExpr))
2633     os << "deallocator";
2634   os << " is offset by "
2635      << offsetBytes
2636      << " "
2637      << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
2638      << " from the start of ";
2639   if (AllocExpr && printMemFnName(AllocNameOs, C, AllocExpr))
2640     os << "memory allocated by " << AllocNameOs.str();
2641   else
2642     os << "allocated memory";
2643 
2644   auto R = std::make_unique<PathSensitiveBugReport>(*BT_OffsetFree[*CheckKind],
2645                                                     os.str(), N);
2646   R->markInteresting(MR->getBaseRegion());
2647   R->addRange(Range);
2648   C.emitReport(std::move(R));
2649 }
2650 
2651 void MallocChecker::HandleUseAfterFree(CheckerContext &C, SourceRange Range,
2652                                        SymbolRef Sym) const {
2653 
2654   if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker] &&
2655       !ChecksEnabled[CK_InnerPointerChecker]) {
2656     C.addSink();
2657     return;
2658   }
2659 
2660   std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2661   if (!CheckKind)
2662     return;
2663 
2664   if (ExplodedNode *N = C.generateErrorNode()) {
2665     if (!BT_UseFree[*CheckKind])
2666       BT_UseFree[*CheckKind].reset(new BugType(
2667           CheckNames[*CheckKind], "Use-after-free", categories::MemoryError));
2668 
2669     AllocationFamily AF =
2670         C.getState()->get<RegionState>(Sym)->getAllocationFamily();
2671 
2672     auto R = std::make_unique<PathSensitiveBugReport>(
2673         *BT_UseFree[*CheckKind],
2674         AF.Kind == AF_InnerBuffer
2675             ? "Inner pointer of container used after re/deallocation"
2676             : "Use of memory after it is freed",
2677         N);
2678 
2679     R->markInteresting(Sym);
2680     R->addRange(Range);
2681     R->addVisitor<MallocBugVisitor>(Sym);
2682 
2683     if (AF.Kind == AF_InnerBuffer)
2684       R->addVisitor(allocation_state::getInnerPointerBRVisitor(Sym));
2685 
2686     C.emitReport(std::move(R));
2687   }
2688 }
2689 
2690 void MallocChecker::HandleDoubleFree(CheckerContext &C, SourceRange Range,
2691                                      bool Released, SymbolRef Sym,
2692                                      SymbolRef PrevSym) const {
2693 
2694   if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) {
2695     C.addSink();
2696     return;
2697   }
2698 
2699   std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2700   if (!CheckKind)
2701     return;
2702 
2703   if (ExplodedNode *N = C.generateErrorNode()) {
2704     if (!BT_DoubleFree[*CheckKind])
2705       BT_DoubleFree[*CheckKind].reset(new BugType(
2706           CheckNames[*CheckKind], "Double free", categories::MemoryError));
2707 
2708     auto R = std::make_unique<PathSensitiveBugReport>(
2709         *BT_DoubleFree[*CheckKind],
2710         (Released ? "Attempt to free released memory"
2711                   : "Attempt to free non-owned memory"),
2712         N);
2713     R->addRange(Range);
2714     R->markInteresting(Sym);
2715     if (PrevSym)
2716       R->markInteresting(PrevSym);
2717     R->addVisitor<MallocBugVisitor>(Sym);
2718     C.emitReport(std::move(R));
2719   }
2720 }
2721 
2722 void MallocChecker::HandleDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
2723 
2724   if (!ChecksEnabled[CK_NewDeleteChecker]) {
2725     C.addSink();
2726     return;
2727   }
2728 
2729   std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2730   if (!CheckKind)
2731     return;
2732 
2733   if (ExplodedNode *N = C.generateErrorNode()) {
2734     if (!BT_DoubleDelete)
2735       BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
2736                                         "Double delete",
2737                                         categories::MemoryError));
2738 
2739     auto R = std::make_unique<PathSensitiveBugReport>(
2740         *BT_DoubleDelete, "Attempt to delete released memory", N);
2741 
2742     R->markInteresting(Sym);
2743     R->addVisitor<MallocBugVisitor>(Sym);
2744     C.emitReport(std::move(R));
2745   }
2746 }
2747 
2748 void MallocChecker::HandleUseZeroAlloc(CheckerContext &C, SourceRange Range,
2749                                        SymbolRef Sym) const {
2750 
2751   if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) {
2752     C.addSink();
2753     return;
2754   }
2755 
2756   std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2757 
2758   if (!CheckKind)
2759     return;
2760 
2761   if (ExplodedNode *N = C.generateErrorNode()) {
2762     if (!BT_UseZerroAllocated[*CheckKind])
2763       BT_UseZerroAllocated[*CheckKind].reset(
2764           new BugType(CheckNames[*CheckKind], "Use of zero allocated",
2765                       categories::MemoryError));
2766 
2767     auto R = std::make_unique<PathSensitiveBugReport>(
2768         *BT_UseZerroAllocated[*CheckKind],
2769         "Use of memory allocated with size zero", N);
2770 
2771     R->addRange(Range);
2772     if (Sym) {
2773       R->markInteresting(Sym);
2774       R->addVisitor<MallocBugVisitor>(Sym);
2775     }
2776     C.emitReport(std::move(R));
2777   }
2778 }
2779 
2780 void MallocChecker::HandleFunctionPtrFree(CheckerContext &C, SVal ArgVal,
2781                                           SourceRange Range,
2782                                           const Expr *FreeExpr,
2783                                           AllocationFamily Family) const {
2784   if (!ChecksEnabled[CK_MallocChecker]) {
2785     C.addSink();
2786     return;
2787   }
2788 
2789   std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2790   if (!CheckKind)
2791     return;
2792 
2793   if (ExplodedNode *N = C.generateErrorNode()) {
2794     if (!BT_BadFree[*CheckKind])
2795       BT_BadFree[*CheckKind].reset(new BugType(
2796           CheckNames[*CheckKind], "Bad free", categories::MemoryError));
2797 
2798     SmallString<100> Buf;
2799     llvm::raw_svector_ostream Os(Buf);
2800 
2801     const MemRegion *MR = ArgVal.getAsRegion();
2802     while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2803       MR = ER->getSuperRegion();
2804 
2805     Os << "Argument to ";
2806     if (!printMemFnName(Os, C, FreeExpr))
2807       Os << "deallocator";
2808 
2809     Os << " is a function pointer";
2810 
2811     auto R = std::make_unique<PathSensitiveBugReport>(*BT_BadFree[*CheckKind],
2812                                                       Os.str(), N);
2813     R->markInteresting(MR);
2814     R->addRange(Range);
2815     C.emitReport(std::move(R));
2816   }
2817 }
2818 
2819 ProgramStateRef
2820 MallocChecker::ReallocMemAux(CheckerContext &C, const CallEvent &Call,
2821                              bool ShouldFreeOnFail, ProgramStateRef State,
2822                              AllocationFamily Family, bool SuffixWithN) const {
2823   if (!State)
2824     return nullptr;
2825 
2826   const CallExpr *CE = cast<CallExpr>(Call.getOriginExpr());
2827 
2828   if (SuffixWithN && CE->getNumArgs() < 3)
2829     return nullptr;
2830   else if (CE->getNumArgs() < 2)
2831     return nullptr;
2832 
2833   const Expr *arg0Expr = CE->getArg(0);
2834   SVal Arg0Val = C.getSVal(arg0Expr);
2835   if (!isa<DefinedOrUnknownSVal>(Arg0Val))
2836     return nullptr;
2837   DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
2838 
2839   SValBuilder &svalBuilder = C.getSValBuilder();
2840 
2841   DefinedOrUnknownSVal PtrEQ = svalBuilder.evalEQ(
2842       State, arg0Val, svalBuilder.makeNullWithType(arg0Expr->getType()));
2843 
2844   // Get the size argument.
2845   const Expr *Arg1 = CE->getArg(1);
2846 
2847   // Get the value of the size argument.
2848   SVal TotalSize = C.getSVal(Arg1);
2849   if (SuffixWithN)
2850     TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2851   if (!isa<DefinedOrUnknownSVal>(TotalSize))
2852     return nullptr;
2853 
2854   // Compare the size argument to 0.
2855   DefinedOrUnknownSVal SizeZero =
2856       svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
2857                          svalBuilder.makeIntValWithWidth(
2858                              svalBuilder.getContext().getSizeType(), 0));
2859 
2860   ProgramStateRef StatePtrIsNull, StatePtrNotNull;
2861   std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
2862   ProgramStateRef StateSizeIsZero, StateSizeNotZero;
2863   std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
2864   // We only assume exceptional states if they are definitely true; if the
2865   // state is under-constrained, assume regular realloc behavior.
2866   bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2867   bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2868 
2869   // If the ptr is NULL and the size is not 0, the call is equivalent to
2870   // malloc(size).
2871   if (PrtIsNull && !SizeIsZero) {
2872     ProgramStateRef stateMalloc = MallocMemAux(
2873         C, Call, TotalSize, UndefinedVal(), StatePtrIsNull, Family);
2874     return stateMalloc;
2875   }
2876 
2877   // Proccess as allocation of 0 bytes.
2878   if (PrtIsNull && SizeIsZero)
2879     return State;
2880 
2881   assert(!PrtIsNull);
2882 
2883   bool IsKnownToBeAllocated = false;
2884 
2885   // If the size is 0, free the memory.
2886   if (SizeIsZero)
2887     // The semantics of the return value are:
2888     // If size was equal to 0, either NULL or a pointer suitable to be passed
2889     // to free() is returned. We just free the input pointer and do not add
2890     // any constrains on the output pointer.
2891     if (ProgramStateRef stateFree = FreeMemAux(
2892             C, Call, StateSizeIsZero, 0, false, IsKnownToBeAllocated, Family))
2893       return stateFree;
2894 
2895   // Default behavior.
2896   if (ProgramStateRef stateFree =
2897           FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocated, Family)) {
2898 
2899     ProgramStateRef stateRealloc =
2900         MallocMemAux(C, Call, TotalSize, UnknownVal(), stateFree, Family);
2901     if (!stateRealloc)
2902       return nullptr;
2903 
2904     OwnershipAfterReallocKind Kind = OAR_ToBeFreedAfterFailure;
2905     if (ShouldFreeOnFail)
2906       Kind = OAR_FreeOnFailure;
2907     else if (!IsKnownToBeAllocated)
2908       Kind = OAR_DoNotTrackAfterFailure;
2909 
2910     // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
2911     SymbolRef FromPtr = arg0Val.getLocSymbolInBase();
2912     SVal RetVal = stateRealloc->getSVal(CE, C.getLocationContext());
2913     SymbolRef ToPtr = RetVal.getAsSymbol();
2914     assert(FromPtr && ToPtr &&
2915            "By this point, FreeMemAux and MallocMemAux should have checked "
2916            "whether the argument or the return value is symbolic!");
2917 
2918     // Record the info about the reallocated symbol so that we could properly
2919     // process failed reallocation.
2920     stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
2921                                                    ReallocPair(FromPtr, Kind));
2922     // The reallocated symbol should stay alive for as long as the new symbol.
2923     C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
2924     return stateRealloc;
2925   }
2926   return nullptr;
2927 }
2928 
2929 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C,
2930                                          const CallEvent &Call,
2931                                          ProgramStateRef State) const {
2932   if (!State)
2933     return nullptr;
2934 
2935   if (Call.getNumArgs() < 2)
2936     return nullptr;
2937 
2938   SValBuilder &svalBuilder = C.getSValBuilder();
2939   SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
2940   SVal TotalSize =
2941       evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1));
2942 
2943   return MallocMemAux(C, Call, TotalSize, zeroVal, State,
2944                       AllocationFamily(AF_Malloc));
2945 }
2946 
2947 MallocChecker::LeakInfo MallocChecker::getAllocationSite(const ExplodedNode *N,
2948                                                          SymbolRef Sym,
2949                                                          CheckerContext &C) {
2950   const LocationContext *LeakContext = N->getLocationContext();
2951   // Walk the ExplodedGraph backwards and find the first node that referred to
2952   // the tracked symbol.
2953   const ExplodedNode *AllocNode = N;
2954   const MemRegion *ReferenceRegion = nullptr;
2955 
2956   while (N) {
2957     ProgramStateRef State = N->getState();
2958     if (!State->get<RegionState>(Sym))
2959       break;
2960 
2961     // Find the most recent expression bound to the symbol in the current
2962     // context.
2963     if (!ReferenceRegion) {
2964       if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2965         SVal Val = State->getSVal(MR);
2966         if (Val.getAsLocSymbol() == Sym) {
2967           const VarRegion *VR = MR->getBaseRegion()->getAs<VarRegion>();
2968           // Do not show local variables belonging to a function other than
2969           // where the error is reported.
2970           if (!VR || (VR->getStackFrame() == LeakContext->getStackFrame()))
2971             ReferenceRegion = MR;
2972         }
2973       }
2974     }
2975 
2976     // Allocation node, is the last node in the current or parent context in
2977     // which the symbol was tracked.
2978     const LocationContext *NContext = N->getLocationContext();
2979     if (NContext == LeakContext ||
2980         NContext->isParentOf(LeakContext))
2981       AllocNode = N;
2982     N = N->pred_empty() ? nullptr : *(N->pred_begin());
2983   }
2984 
2985   return LeakInfo(AllocNode, ReferenceRegion);
2986 }
2987 
2988 void MallocChecker::HandleLeak(SymbolRef Sym, ExplodedNode *N,
2989                                CheckerContext &C) const {
2990 
2991   if (!ChecksEnabled[CK_MallocChecker] &&
2992       !ChecksEnabled[CK_NewDeleteLeaksChecker])
2993     return;
2994 
2995   const RefState *RS = C.getState()->get<RegionState>(Sym);
2996   assert(RS && "cannot leak an untracked symbol");
2997   AllocationFamily Family = RS->getAllocationFamily();
2998 
2999   if (Family.Kind == AF_Alloca)
3000     return;
3001 
3002   std::optional<MallocChecker::CheckKind> CheckKind =
3003       getCheckIfTracked(Family, true);
3004 
3005   if (!CheckKind)
3006     return;
3007 
3008   assert(N);
3009   if (!BT_Leak[*CheckKind]) {
3010     // Leaks should not be reported if they are post-dominated by a sink:
3011     // (1) Sinks are higher importance bugs.
3012     // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
3013     //     with __noreturn functions such as assert() or exit(). We choose not
3014     //     to report leaks on such paths.
3015     BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak",
3016                                           categories::MemoryError,
3017                                           /*SuppressOnSink=*/true));
3018   }
3019 
3020   // Most bug reports are cached at the location where they occurred.
3021   // With leaks, we want to unique them by the location where they were
3022   // allocated, and only report a single path.
3023   PathDiagnosticLocation LocUsedForUniqueing;
3024   const ExplodedNode *AllocNode = nullptr;
3025   const MemRegion *Region = nullptr;
3026   std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
3027 
3028   const Stmt *AllocationStmt = AllocNode->getStmtForDiagnostics();
3029   if (AllocationStmt)
3030     LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
3031                                               C.getSourceManager(),
3032                                               AllocNode->getLocationContext());
3033 
3034   SmallString<200> buf;
3035   llvm::raw_svector_ostream os(buf);
3036   if (Region && Region->canPrintPretty()) {
3037     os << "Potential leak of memory pointed to by ";
3038     Region->printPretty(os);
3039   } else {
3040     os << "Potential memory leak";
3041   }
3042 
3043   auto R = std::make_unique<PathSensitiveBugReport>(
3044       *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
3045       AllocNode->getLocationContext()->getDecl());
3046   R->markInteresting(Sym);
3047   R->addVisitor<MallocBugVisitor>(Sym, true);
3048   if (ShouldRegisterNoOwnershipChangeVisitor)
3049     R->addVisitor<NoMemOwnershipChangeVisitor>(Sym, this);
3050   C.emitReport(std::move(R));
3051 }
3052 
3053 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3054                                      CheckerContext &C) const
3055 {
3056   ProgramStateRef state = C.getState();
3057   RegionStateTy OldRS = state->get<RegionState>();
3058   RegionStateTy::Factory &F = state->get_context<RegionState>();
3059 
3060   RegionStateTy RS = OldRS;
3061   SmallVector<SymbolRef, 2> Errors;
3062   for (auto [Sym, State] : RS) {
3063     if (SymReaper.isDead(Sym)) {
3064       if (State.isAllocated() || State.isAllocatedOfSizeZero())
3065         Errors.push_back(Sym);
3066       // Remove the dead symbol from the map.
3067       RS = F.remove(RS, Sym);
3068     }
3069   }
3070 
3071   if (RS == OldRS) {
3072     // We shouldn't have touched other maps yet.
3073     assert(state->get<ReallocPairs>() ==
3074            C.getState()->get<ReallocPairs>());
3075     assert(state->get<FreeReturnValue>() ==
3076            C.getState()->get<FreeReturnValue>());
3077     return;
3078   }
3079 
3080   // Cleanup the Realloc Pairs Map.
3081   ReallocPairsTy RP = state->get<ReallocPairs>();
3082   for (auto [Sym, ReallocPair] : RP) {
3083     if (SymReaper.isDead(Sym) || SymReaper.isDead(ReallocPair.ReallocatedSym)) {
3084       state = state->remove<ReallocPairs>(Sym);
3085     }
3086   }
3087 
3088   // Cleanup the FreeReturnValue Map.
3089   FreeReturnValueTy FR = state->get<FreeReturnValue>();
3090   for (auto [Sym, RetSym] : FR) {
3091     if (SymReaper.isDead(Sym) || SymReaper.isDead(RetSym)) {
3092       state = state->remove<FreeReturnValue>(Sym);
3093     }
3094   }
3095 
3096   // Generate leak node.
3097   ExplodedNode *N = C.getPredecessor();
3098   if (!Errors.empty()) {
3099     static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
3100     N = C.generateNonFatalErrorNode(C.getState(), &Tag);
3101     if (N) {
3102       for (SymbolRef Sym : Errors) {
3103         HandleLeak(Sym, N, C);
3104       }
3105     }
3106   }
3107 
3108   C.addTransition(state->set<RegionState>(RS), N);
3109 }
3110 
3111 void MallocChecker::checkPostCall(const CallEvent &Call,
3112                                   CheckerContext &C) const {
3113   if (const auto *PostFN = PostFnMap.lookup(Call)) {
3114     (*PostFN)(this, C.getState(), Call, C);
3115     return;
3116   }
3117 }
3118 
3119 void MallocChecker::checkPreCall(const CallEvent &Call,
3120                                  CheckerContext &C) const {
3121 
3122   if (const auto *DC = dyn_cast<CXXDeallocatorCall>(&Call)) {
3123     const CXXDeleteExpr *DE = DC->getOriginExpr();
3124 
3125     if (!ChecksEnabled[CK_NewDeleteChecker])
3126       if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
3127         checkUseAfterFree(Sym, C, DE->getArgument());
3128 
3129     if (!isStandardNewDelete(DC->getDecl()))
3130       return;
3131 
3132     ProgramStateRef State = C.getState();
3133     bool IsKnownToBeAllocated;
3134     State = FreeMemAux(
3135         C, DE->getArgument(), Call, State,
3136         /*Hold*/ false, IsKnownToBeAllocated,
3137         AllocationFamily(DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew));
3138 
3139     C.addTransition(State);
3140     return;
3141   }
3142 
3143   if (const auto *DC = dyn_cast<CXXDestructorCall>(&Call)) {
3144     SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
3145     if (!Sym || checkDoubleDelete(Sym, C))
3146       return;
3147   }
3148 
3149   // We need to handle getline pre-conditions here before the pointed region
3150   // gets invalidated by StreamChecker
3151   if (const auto *PreFN = PreFnMap.lookup(Call)) {
3152     (*PreFN)(this, C.getState(), Call, C);
3153     return;
3154   }
3155 
3156   // We will check for double free in the post visit.
3157   if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
3158     const FunctionDecl *FD = FC->getDecl();
3159     if (!FD)
3160       return;
3161 
3162     if (ChecksEnabled[CK_MallocChecker] && isFreeingCall(Call))
3163       return;
3164   }
3165 
3166   // Check if the callee of a method is deleted.
3167   if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
3168     SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
3169     if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
3170       return;
3171   }
3172 
3173   // Check arguments for being used after free.
3174   for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
3175     SVal ArgSVal = Call.getArgSVal(I);
3176     if (isa<Loc>(ArgSVal)) {
3177       SymbolRef Sym = ArgSVal.getAsSymbol();
3178       if (!Sym)
3179         continue;
3180       if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
3181         return;
3182     }
3183   }
3184 }
3185 
3186 void MallocChecker::checkPreStmt(const ReturnStmt *S,
3187                                  CheckerContext &C) const {
3188   checkEscapeOnReturn(S, C);
3189 }
3190 
3191 // In the CFG, automatic destructors come after the return statement.
3192 // This callback checks for returning memory that is freed by automatic
3193 // destructors, as those cannot be reached in checkPreStmt().
3194 void MallocChecker::checkEndFunction(const ReturnStmt *S,
3195                                      CheckerContext &C) const {
3196   checkEscapeOnReturn(S, C);
3197 }
3198 
3199 void MallocChecker::checkEscapeOnReturn(const ReturnStmt *S,
3200                                         CheckerContext &C) const {
3201   if (!S)
3202     return;
3203 
3204   const Expr *E = S->getRetValue();
3205   if (!E)
3206     return;
3207 
3208   // Check if we are returning a symbol.
3209   ProgramStateRef State = C.getState();
3210   SVal RetVal = C.getSVal(E);
3211   SymbolRef Sym = RetVal.getAsSymbol();
3212   if (!Sym)
3213     // If we are returning a field of the allocated struct or an array element,
3214     // the callee could still free the memory.
3215     // TODO: This logic should be a part of generic symbol escape callback.
3216     if (const MemRegion *MR = RetVal.getAsRegion())
3217       if (isa<FieldRegion, ElementRegion>(MR))
3218         if (const SymbolicRegion *BMR =
3219               dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
3220           Sym = BMR->getSymbol();
3221 
3222   // Check if we are returning freed memory.
3223   if (Sym)
3224     checkUseAfterFree(Sym, C, E);
3225 }
3226 
3227 // TODO: Blocks should be either inlined or should call invalidate regions
3228 // upon invocation. After that's in place, special casing here will not be
3229 // needed.
3230 void MallocChecker::checkPostStmt(const BlockExpr *BE,
3231                                   CheckerContext &C) const {
3232 
3233   // Scan the BlockDecRefExprs for any object the retain count checker
3234   // may be tracking.
3235   if (!BE->getBlockDecl()->hasCaptures())
3236     return;
3237 
3238   ProgramStateRef state = C.getState();
3239   const BlockDataRegion *R =
3240     cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
3241 
3242   auto ReferencedVars = R->referenced_vars();
3243   if (ReferencedVars.empty())
3244     return;
3245 
3246   SmallVector<const MemRegion*, 10> Regions;
3247   const LocationContext *LC = C.getLocationContext();
3248   MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
3249 
3250   for (const auto &Var : ReferencedVars) {
3251     const VarRegion *VR = Var.getCapturedRegion();
3252     if (VR->getSuperRegion() == R) {
3253       VR = MemMgr.getVarRegion(VR->getDecl(), LC);
3254     }
3255     Regions.push_back(VR);
3256   }
3257 
3258   state =
3259     state->scanReachableSymbols<StopTrackingCallback>(Regions).getState();
3260   C.addTransition(state);
3261 }
3262 
3263 static bool isReleased(SymbolRef Sym, CheckerContext &C) {
3264   assert(Sym);
3265   const RefState *RS = C.getState()->get<RegionState>(Sym);
3266   return (RS && RS->isReleased());
3267 }
3268 
3269 bool MallocChecker::suppressDeallocationsInSuspiciousContexts(
3270     const CallEvent &Call, CheckerContext &C) const {
3271   if (Call.getNumArgs() == 0)
3272     return false;
3273 
3274   StringRef FunctionStr = "";
3275   if (const auto *FD = dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
3276     if (const Stmt *Body = FD->getBody())
3277       if (Body->getBeginLoc().isValid())
3278         FunctionStr =
3279             Lexer::getSourceText(CharSourceRange::getTokenRange(
3280                                      {FD->getBeginLoc(), Body->getBeginLoc()}),
3281                                  C.getSourceManager(), C.getLangOpts());
3282 
3283   // We do not model the Integer Set Library's retain-count based allocation.
3284   if (!FunctionStr.contains("__isl_"))
3285     return false;
3286 
3287   ProgramStateRef State = C.getState();
3288 
3289   for (const Expr *Arg : cast<CallExpr>(Call.getOriginExpr())->arguments())
3290     if (SymbolRef Sym = C.getSVal(Arg).getAsSymbol())
3291       if (const RefState *RS = State->get<RegionState>(Sym))
3292         State = State->set<RegionState>(Sym, RefState::getEscaped(RS));
3293 
3294   C.addTransition(State);
3295   return true;
3296 }
3297 
3298 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
3299                                       const Stmt *S) const {
3300 
3301   if (isReleased(Sym, C)) {
3302     HandleUseAfterFree(C, S->getSourceRange(), Sym);
3303     return true;
3304   }
3305 
3306   return false;
3307 }
3308 
3309 void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
3310                                           const Stmt *S) const {
3311   assert(Sym);
3312 
3313   if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
3314     if (RS->isAllocatedOfSizeZero())
3315       HandleUseZeroAlloc(C, RS->getStmt()->getSourceRange(), Sym);
3316   }
3317   else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
3318     HandleUseZeroAlloc(C, S->getSourceRange(), Sym);
3319   }
3320 }
3321 
3322 bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
3323 
3324   if (isReleased(Sym, C)) {
3325     HandleDoubleDelete(C, Sym);
3326     return true;
3327   }
3328   return false;
3329 }
3330 
3331 // Check if the location is a freed symbolic region.
3332 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
3333                                   CheckerContext &C) const {
3334   SymbolRef Sym = l.getLocSymbolInBase();
3335   if (Sym) {
3336     checkUseAfterFree(Sym, C, S);
3337     checkUseZeroAllocated(Sym, C, S);
3338   }
3339 }
3340 
3341 // If a symbolic region is assumed to NULL (or another constant), stop tracking
3342 // it - assuming that allocation failed on this path.
3343 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
3344                                               SVal Cond,
3345                                               bool Assumption) const {
3346   RegionStateTy RS = state->get<RegionState>();
3347   for (SymbolRef Sym : llvm::make_first_range(RS)) {
3348     // If the symbol is assumed to be NULL, remove it from consideration.
3349     ConstraintManager &CMgr = state->getConstraintManager();
3350     ConditionTruthVal AllocFailed = CMgr.isNull(state, Sym);
3351     if (AllocFailed.isConstrainedTrue())
3352       state = state->remove<RegionState>(Sym);
3353   }
3354 
3355   // Realloc returns 0 when reallocation fails, which means that we should
3356   // restore the state of the pointer being reallocated.
3357   ReallocPairsTy RP = state->get<ReallocPairs>();
3358   for (auto [Sym, ReallocPair] : RP) {
3359     // If the symbol is assumed to be NULL, remove it from consideration.
3360     ConstraintManager &CMgr = state->getConstraintManager();
3361     ConditionTruthVal AllocFailed = CMgr.isNull(state, Sym);
3362     if (!AllocFailed.isConstrainedTrue())
3363       continue;
3364 
3365     SymbolRef ReallocSym = ReallocPair.ReallocatedSym;
3366     if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
3367       if (RS->isReleased()) {
3368         switch (ReallocPair.Kind) {
3369         case OAR_ToBeFreedAfterFailure:
3370           state = state->set<RegionState>(ReallocSym,
3371               RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
3372           break;
3373         case OAR_DoNotTrackAfterFailure:
3374           state = state->remove<RegionState>(ReallocSym);
3375           break;
3376         default:
3377           assert(ReallocPair.Kind == OAR_FreeOnFailure);
3378         }
3379       }
3380     }
3381     state = state->remove<ReallocPairs>(Sym);
3382   }
3383 
3384   return state;
3385 }
3386 
3387 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
3388                                               const CallEvent *Call,
3389                                               ProgramStateRef State,
3390                                               SymbolRef &EscapingSymbol) const {
3391   assert(Call);
3392   EscapingSymbol = nullptr;
3393 
3394   // For now, assume that any C++ or block call can free memory.
3395   // TODO: If we want to be more optimistic here, we'll need to make sure that
3396   // regions escape to C++ containers. They seem to do that even now, but for
3397   // mysterious reasons.
3398   if (!isa<SimpleFunctionCall, ObjCMethodCall>(Call))
3399     return true;
3400 
3401   // Check Objective-C messages by selector name.
3402   if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
3403     // If it's not a framework call, or if it takes a callback, assume it
3404     // can free memory.
3405     if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
3406       return true;
3407 
3408     // If it's a method we know about, handle it explicitly post-call.
3409     // This should happen before the "freeWhenDone" check below.
3410     if (isKnownDeallocObjCMethodName(*Msg))
3411       return false;
3412 
3413     // If there's a "freeWhenDone" parameter, but the method isn't one we know
3414     // about, we can't be sure that the object will use free() to deallocate the
3415     // memory, so we can't model it explicitly. The best we can do is use it to
3416     // decide whether the pointer escapes.
3417     if (std::optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
3418       return *FreeWhenDone;
3419 
3420     // If the first selector piece ends with "NoCopy", and there is no
3421     // "freeWhenDone" parameter set to zero, we know ownership is being
3422     // transferred. Again, though, we can't be sure that the object will use
3423     // free() to deallocate the memory, so we can't model it explicitly.
3424     StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
3425     if (FirstSlot.ends_with("NoCopy"))
3426       return true;
3427 
3428     // If the first selector starts with addPointer, insertPointer,
3429     // or replacePointer, assume we are dealing with NSPointerArray or similar.
3430     // This is similar to C++ containers (vector); we still might want to check
3431     // that the pointers get freed by following the container itself.
3432     if (FirstSlot.starts_with("addPointer") ||
3433         FirstSlot.starts_with("insertPointer") ||
3434         FirstSlot.starts_with("replacePointer") ||
3435         FirstSlot == "valueWithPointer") {
3436       return true;
3437     }
3438 
3439     // We should escape receiver on call to 'init'. This is especially relevant
3440     // to the receiver, as the corresponding symbol is usually not referenced
3441     // after the call.
3442     if (Msg->getMethodFamily() == OMF_init) {
3443       EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
3444       return true;
3445     }
3446 
3447     // Otherwise, assume that the method does not free memory.
3448     // Most framework methods do not free memory.
3449     return false;
3450   }
3451 
3452   // At this point the only thing left to handle is straight function calls.
3453   const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
3454   if (!FD)
3455     return true;
3456 
3457   // If it's one of the allocation functions we can reason about, we model
3458   // its behavior explicitly.
3459   if (isMemCall(*Call))
3460     return false;
3461 
3462   // If it's not a system call, assume it frees memory.
3463   if (!Call->isInSystemHeader())
3464     return true;
3465 
3466   // White list the system functions whose arguments escape.
3467   const IdentifierInfo *II = FD->getIdentifier();
3468   if (!II)
3469     return true;
3470   StringRef FName = II->getName();
3471 
3472   // White list the 'XXXNoCopy' CoreFoundation functions.
3473   // We specifically check these before
3474   if (FName.ends_with("NoCopy")) {
3475     // Look for the deallocator argument. We know that the memory ownership
3476     // is not transferred only if the deallocator argument is
3477     // 'kCFAllocatorNull'.
3478     for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
3479       const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
3480       if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
3481         StringRef DeallocatorName = DE->getFoundDecl()->getName();
3482         if (DeallocatorName == "kCFAllocatorNull")
3483           return false;
3484       }
3485     }
3486     return true;
3487   }
3488 
3489   // Associating streams with malloced buffers. The pointer can escape if
3490   // 'closefn' is specified (and if that function does free memory),
3491   // but it will not if closefn is not specified.
3492   // Currently, we do not inspect the 'closefn' function (PR12101).
3493   if (FName == "funopen")
3494     if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
3495       return false;
3496 
3497   // Do not warn on pointers passed to 'setbuf' when used with std streams,
3498   // these leaks might be intentional when setting the buffer for stdio.
3499   // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
3500   if (FName == "setbuf" || FName =="setbuffer" ||
3501       FName == "setlinebuf" || FName == "setvbuf") {
3502     if (Call->getNumArgs() >= 1) {
3503       const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
3504       if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
3505         if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
3506           if (D->getCanonicalDecl()->getName().contains("std"))
3507             return true;
3508     }
3509   }
3510 
3511   // A bunch of other functions which either take ownership of a pointer or
3512   // wrap the result up in a struct or object, meaning it can be freed later.
3513   // (See RetainCountChecker.) Not all the parameters here are invalidated,
3514   // but the Malloc checker cannot differentiate between them. The right way
3515   // of doing this would be to implement a pointer escapes callback.
3516   if (FName == "CGBitmapContextCreate" ||
3517       FName == "CGBitmapContextCreateWithData" ||
3518       FName == "CVPixelBufferCreateWithBytes" ||
3519       FName == "CVPixelBufferCreateWithPlanarBytes" ||
3520       FName == "OSAtomicEnqueue") {
3521     return true;
3522   }
3523 
3524   if (FName == "postEvent" &&
3525       FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
3526     return true;
3527   }
3528 
3529   if (FName == "connectImpl" &&
3530       FD->getQualifiedNameAsString() == "QObject::connectImpl") {
3531     return true;
3532   }
3533 
3534   if (FName == "singleShotImpl" &&
3535       FD->getQualifiedNameAsString() == "QTimer::singleShotImpl") {
3536     return true;
3537   }
3538 
3539   // Handle cases where we know a buffer's /address/ can escape.
3540   // Note that the above checks handle some special cases where we know that
3541   // even though the address escapes, it's still our responsibility to free the
3542   // buffer.
3543   if (Call->argumentsMayEscape())
3544     return true;
3545 
3546   // Otherwise, assume that the function does not free memory.
3547   // Most system calls do not free the memory.
3548   return false;
3549 }
3550 
3551 ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
3552                                              const InvalidatedSymbols &Escaped,
3553                                              const CallEvent *Call,
3554                                              PointerEscapeKind Kind) const {
3555   return checkPointerEscapeAux(State, Escaped, Call, Kind,
3556                                /*IsConstPointerEscape*/ false);
3557 }
3558 
3559 ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
3560                                               const InvalidatedSymbols &Escaped,
3561                                               const CallEvent *Call,
3562                                               PointerEscapeKind Kind) const {
3563   // If a const pointer escapes, it may not be freed(), but it could be deleted.
3564   return checkPointerEscapeAux(State, Escaped, Call, Kind,
3565                                /*IsConstPointerEscape*/ true);
3566 }
3567 
3568 static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
3569   return (RS->getAllocationFamily().Kind == AF_CXXNewArray ||
3570           RS->getAllocationFamily().Kind == AF_CXXNew);
3571 }
3572 
3573 ProgramStateRef MallocChecker::checkPointerEscapeAux(
3574     ProgramStateRef State, const InvalidatedSymbols &Escaped,
3575     const CallEvent *Call, PointerEscapeKind Kind,
3576     bool IsConstPointerEscape) const {
3577   // If we know that the call does not free memory, or we want to process the
3578   // call later, keep tracking the top level arguments.
3579   SymbolRef EscapingSymbol = nullptr;
3580   if (Kind == PSK_DirectEscapeOnCall &&
3581       !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
3582                                                     EscapingSymbol) &&
3583       !EscapingSymbol) {
3584     return State;
3585   }
3586 
3587   for (SymbolRef sym : Escaped) {
3588     if (EscapingSymbol && EscapingSymbol != sym)
3589       continue;
3590 
3591     if (const RefState *RS = State->get<RegionState>(sym))
3592       if (RS->isAllocated() || RS->isAllocatedOfSizeZero())
3593         if (!IsConstPointerEscape || checkIfNewOrNewArrayFamily(RS))
3594           State = State->set<RegionState>(sym, RefState::getEscaped(RS));
3595   }
3596   return State;
3597 }
3598 
3599 bool MallocChecker::isArgZERO_SIZE_PTR(ProgramStateRef State, CheckerContext &C,
3600                                        SVal ArgVal) const {
3601   if (!KernelZeroSizePtrValue)
3602     KernelZeroSizePtrValue =
3603         tryExpandAsInteger("ZERO_SIZE_PTR", C.getPreprocessor());
3604 
3605   const llvm::APSInt *ArgValKnown =
3606       C.getSValBuilder().getKnownValue(State, ArgVal);
3607   return ArgValKnown && *KernelZeroSizePtrValue &&
3608          ArgValKnown->getSExtValue() == **KernelZeroSizePtrValue;
3609 }
3610 
3611 static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
3612                                          ProgramStateRef prevState) {
3613   ReallocPairsTy currMap = currState->get<ReallocPairs>();
3614   ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
3615 
3616   for (const ReallocPairsTy::value_type &Pair : prevMap) {
3617     SymbolRef sym = Pair.first;
3618     if (!currMap.lookup(sym))
3619       return sym;
3620   }
3621 
3622   return nullptr;
3623 }
3624 
3625 static bool isReferenceCountingPointerDestructor(const CXXDestructorDecl *DD) {
3626   if (const IdentifierInfo *II = DD->getParent()->getIdentifier()) {
3627     StringRef N = II->getName();
3628     if (N.contains_insensitive("ptr") || N.contains_insensitive("pointer")) {
3629       if (N.contains_insensitive("ref") || N.contains_insensitive("cnt") ||
3630           N.contains_insensitive("intrusive") ||
3631           N.contains_insensitive("shared") || N.ends_with_insensitive("rc")) {
3632         return true;
3633       }
3634     }
3635   }
3636   return false;
3637 }
3638 
3639 PathDiagnosticPieceRef MallocBugVisitor::VisitNode(const ExplodedNode *N,
3640                                                    BugReporterContext &BRC,
3641                                                    PathSensitiveBugReport &BR) {
3642   ProgramStateRef state = N->getState();
3643   ProgramStateRef statePrev = N->getFirstPred()->getState();
3644 
3645   const RefState *RSCurr = state->get<RegionState>(Sym);
3646   const RefState *RSPrev = statePrev->get<RegionState>(Sym);
3647 
3648   const Stmt *S = N->getStmtForDiagnostics();
3649   // When dealing with containers, we sometimes want to give a note
3650   // even if the statement is missing.
3651   if (!S && (!RSCurr || RSCurr->getAllocationFamily().Kind != AF_InnerBuffer))
3652     return nullptr;
3653 
3654   const LocationContext *CurrentLC = N->getLocationContext();
3655 
3656   // If we find an atomic fetch_add or fetch_sub within the function in which
3657   // the pointer was released (before the release), this is likely a release
3658   // point of reference-counted object (like shared pointer).
3659   //
3660   // Because we don't model atomics, and also because we don't know that the
3661   // original reference count is positive, we should not report use-after-frees
3662   // on objects deleted in such functions. This can probably be improved
3663   // through better shared pointer modeling.
3664   if (ReleaseFunctionLC && (ReleaseFunctionLC == CurrentLC ||
3665                             ReleaseFunctionLC->isParentOf(CurrentLC))) {
3666     if (const auto *AE = dyn_cast<AtomicExpr>(S)) {
3667       // Check for manual use of atomic builtins.
3668       AtomicExpr::AtomicOp Op = AE->getOp();
3669       if (Op == AtomicExpr::AO__c11_atomic_fetch_add ||
3670           Op == AtomicExpr::AO__c11_atomic_fetch_sub) {
3671         BR.markInvalid(getTag(), S);
3672         // After report is considered invalid there is no need to proceed
3673         // futher.
3674         return nullptr;
3675       }
3676     } else if (const auto *CE = dyn_cast<CallExpr>(S)) {
3677       // Check for `std::atomic` and such. This covers both regular method calls
3678       // and operator calls.
3679       if (const auto *MD =
3680               dyn_cast_or_null<CXXMethodDecl>(CE->getDirectCallee())) {
3681         const CXXRecordDecl *RD = MD->getParent();
3682         // A bit wobbly with ".contains()" because it may be like
3683         // "__atomic_base" or something.
3684         if (StringRef(RD->getNameAsString()).contains("atomic")) {
3685           BR.markInvalid(getTag(), S);
3686           // After report is considered invalid there is no need to proceed
3687           // futher.
3688           return nullptr;
3689         }
3690       }
3691     }
3692   }
3693 
3694   // FIXME: We will eventually need to handle non-statement-based events
3695   // (__attribute__((cleanup))).
3696 
3697   // Find out if this is an interesting point and what is the kind.
3698   StringRef Msg;
3699   std::unique_ptr<StackHintGeneratorForSymbol> StackHint = nullptr;
3700   SmallString<256> Buf;
3701   llvm::raw_svector_ostream OS(Buf);
3702 
3703   if (Mode == Normal) {
3704     if (isAllocated(RSCurr, RSPrev, S)) {
3705       Msg = "Memory is allocated";
3706       StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3707           Sym, "Returned allocated memory");
3708     } else if (isReleased(RSCurr, RSPrev, S)) {
3709       const auto Family = RSCurr->getAllocationFamily();
3710       switch (Family.Kind) {
3711       case AF_Alloca:
3712       case AF_Malloc:
3713       case AF_Custom:
3714       case AF_CXXNew:
3715       case AF_CXXNewArray:
3716       case AF_IfNameIndex:
3717         Msg = "Memory is released";
3718         StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3719             Sym, "Returning; memory was released");
3720         break;
3721       case AF_InnerBuffer: {
3722         const MemRegion *ObjRegion =
3723             allocation_state::getContainerObjRegion(statePrev, Sym);
3724         const auto *TypedRegion = cast<TypedValueRegion>(ObjRegion);
3725         QualType ObjTy = TypedRegion->getValueType();
3726         OS << "Inner buffer of '" << ObjTy << "' ";
3727 
3728         if (N->getLocation().getKind() == ProgramPoint::PostImplicitCallKind) {
3729           OS << "deallocated by call to destructor";
3730           StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3731               Sym, "Returning; inner buffer was deallocated");
3732         } else {
3733           OS << "reallocated by call to '";
3734           const Stmt *S = RSCurr->getStmt();
3735           if (const auto *MemCallE = dyn_cast<CXXMemberCallExpr>(S)) {
3736             OS << MemCallE->getMethodDecl()->getDeclName();
3737           } else if (const auto *OpCallE = dyn_cast<CXXOperatorCallExpr>(S)) {
3738             OS << OpCallE->getDirectCallee()->getDeclName();
3739           } else if (const auto *CallE = dyn_cast<CallExpr>(S)) {
3740             auto &CEMgr = BRC.getStateManager().getCallEventManager();
3741             CallEventRef<> Call =
3742                 CEMgr.getSimpleCall(CallE, state, CurrentLC, {nullptr, 0});
3743             if (const auto *D = dyn_cast_or_null<NamedDecl>(Call->getDecl()))
3744               OS << D->getDeclName();
3745             else
3746               OS << "unknown";
3747           }
3748           OS << "'";
3749           StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3750               Sym, "Returning; inner buffer was reallocated");
3751         }
3752         Msg = OS.str();
3753         break;
3754         }
3755         case AF_None:
3756           assert(false && "Unhandled allocation family!");
3757           return nullptr;
3758         }
3759 
3760         // Save the first destructor/function as release point.
3761         assert(!ReleaseFunctionLC && "There should be only one release point");
3762         ReleaseFunctionLC = CurrentLC->getStackFrame();
3763 
3764         // See if we're releasing memory while inlining a destructor that
3765         // decrement reference counters (or one of its callees).
3766         // This turns on various common false positive suppressions.
3767         for (const LocationContext *LC = CurrentLC; LC; LC = LC->getParent()) {
3768           if (const auto *DD = dyn_cast<CXXDestructorDecl>(LC->getDecl())) {
3769             if (isReferenceCountingPointerDestructor(DD)) {
3770               // This immediately looks like a reference-counting destructor.
3771               // We're bad at guessing the original reference count of the
3772               // object, so suppress the report for now.
3773               BR.markInvalid(getTag(), DD);
3774 
3775               // After report is considered invalid there is no need to proceed
3776               // futher.
3777               return nullptr;
3778             }
3779 
3780             // Switch suspection to outer destructor to catch patterns like:
3781             // (note that class name is distorted to bypass
3782             // isReferenceCountingPointerDestructor() logic)
3783             //
3784             // SmartPointr::~SmartPointr() {
3785             //  if (refcount.fetch_sub(1) == 1)
3786             //    release_resources();
3787             // }
3788             // void SmartPointr::release_resources() {
3789             //   free(buffer);
3790             // }
3791             //
3792             // This way ReleaseFunctionLC will point to outermost destructor and
3793             // it would be possible to catch wider range of FP.
3794             //
3795             // NOTE: it would be great to support smth like that in C, since
3796             // currently patterns like following won't be supressed:
3797             //
3798             // void doFree(struct Data *data) { free(data); }
3799             // void putData(struct Data *data)
3800             // {
3801             //   if (refPut(data))
3802             //     doFree(data);
3803             // }
3804             ReleaseFunctionLC = LC->getStackFrame();
3805           }
3806         }
3807 
3808     } else if (isRelinquished(RSCurr, RSPrev, S)) {
3809       Msg = "Memory ownership is transferred";
3810       StackHint = std::make_unique<StackHintGeneratorForSymbol>(Sym, "");
3811     } else if (hasReallocFailed(RSCurr, RSPrev, S)) {
3812       Mode = ReallocationFailed;
3813       Msg = "Reallocation failed";
3814       StackHint = std::make_unique<StackHintGeneratorForReallocationFailed>(
3815           Sym, "Reallocation failed");
3816 
3817       if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
3818         // Is it possible to fail two reallocs WITHOUT testing in between?
3819         assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
3820           "We only support one failed realloc at a time.");
3821         BR.markInteresting(sym);
3822         FailedReallocSymbol = sym;
3823       }
3824     }
3825 
3826   // We are in a special mode if a reallocation failed later in the path.
3827   } else if (Mode == ReallocationFailed) {
3828     assert(FailedReallocSymbol && "No symbol to look for.");
3829 
3830     // Is this is the first appearance of the reallocated symbol?
3831     if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
3832       // We're at the reallocation point.
3833       Msg = "Attempt to reallocate memory";
3834       StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3835           Sym, "Returned reallocated memory");
3836       FailedReallocSymbol = nullptr;
3837       Mode = Normal;
3838     }
3839   }
3840 
3841   if (Msg.empty()) {
3842     assert(!StackHint);
3843     return nullptr;
3844   }
3845 
3846   assert(StackHint);
3847 
3848   // Generate the extra diagnostic.
3849   PathDiagnosticLocation Pos;
3850   if (!S) {
3851     assert(RSCurr->getAllocationFamily().Kind == AF_InnerBuffer);
3852     auto PostImplCall = N->getLocation().getAs<PostImplicitCall>();
3853     if (!PostImplCall)
3854       return nullptr;
3855     Pos = PathDiagnosticLocation(PostImplCall->getLocation(),
3856                                  BRC.getSourceManager());
3857   } else {
3858     Pos = PathDiagnosticLocation(S, BRC.getSourceManager(),
3859                                  N->getLocationContext());
3860   }
3861 
3862   auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true);
3863   BR.addCallStackHint(P, std::move(StackHint));
3864   return P;
3865 }
3866 
3867 void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
3868                                const char *NL, const char *Sep) const {
3869 
3870   RegionStateTy RS = State->get<RegionState>();
3871 
3872   if (!RS.isEmpty()) {
3873     Out << Sep << "MallocChecker :" << NL;
3874     for (auto [Sym, Data] : RS) {
3875       const RefState *RefS = State->get<RegionState>(Sym);
3876       AllocationFamily Family = RefS->getAllocationFamily();
3877       std::optional<MallocChecker::CheckKind> CheckKind =
3878           getCheckIfTracked(Family);
3879       if (!CheckKind)
3880         CheckKind = getCheckIfTracked(Family, true);
3881 
3882       Sym->dumpToStream(Out);
3883       Out << " : ";
3884       Data.dump(Out);
3885       if (CheckKind)
3886         Out << " (" << CheckNames[*CheckKind].getName() << ")";
3887       Out << NL;
3888     }
3889   }
3890 }
3891 
3892 namespace clang {
3893 namespace ento {
3894 namespace allocation_state {
3895 
3896 ProgramStateRef
3897 markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin) {
3898   AllocationFamily Family(AF_InnerBuffer);
3899   return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin));
3900 }
3901 
3902 } // end namespace allocation_state
3903 } // end namespace ento
3904 } // end namespace clang
3905 
3906 // Intended to be used in InnerPointerChecker to register the part of
3907 // MallocChecker connected to it.
3908 void ento::registerInnerPointerCheckerAux(CheckerManager &mgr) {
3909   MallocChecker *checker = mgr.getChecker<MallocChecker>();
3910   checker->ChecksEnabled[MallocChecker::CK_InnerPointerChecker] = true;
3911   checker->CheckNames[MallocChecker::CK_InnerPointerChecker] =
3912       mgr.getCurrentCheckerName();
3913 }
3914 
3915 void ento::registerDynamicMemoryModeling(CheckerManager &mgr) {
3916   auto *checker = mgr.registerChecker<MallocChecker>();
3917   checker->ShouldIncludeOwnershipAnnotatedFunctions =
3918       mgr.getAnalyzerOptions().getCheckerBooleanOption(checker, "Optimistic");
3919   checker->ShouldRegisterNoOwnershipChangeVisitor =
3920       mgr.getAnalyzerOptions().getCheckerBooleanOption(
3921           checker, "AddNoOwnershipChangeNotes");
3922 }
3923 
3924 bool ento::shouldRegisterDynamicMemoryModeling(const CheckerManager &mgr) {
3925   return true;
3926 }
3927 
3928 #define REGISTER_CHECKER(name)                                                 \
3929   void ento::register##name(CheckerManager &mgr) {                             \
3930     MallocChecker *checker = mgr.getChecker<MallocChecker>();                  \
3931     checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
3932     checker->CheckNames[MallocChecker::CK_##name] =                            \
3933         mgr.getCurrentCheckerName();                                           \
3934   }                                                                            \
3935                                                                                \
3936   bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
3937 
3938 REGISTER_CHECKER(MallocChecker)
3939 REGISTER_CHECKER(NewDeleteChecker)
3940 REGISTER_CHECKER(NewDeleteLeaksChecker)
3941 REGISTER_CHECKER(MismatchedDeallocatorChecker)
3942 REGISTER_CHECKER(TaintedAllocChecker)
3943