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