xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp (revision 67c6ad6f30e35c7670bce9bca902caa4b1c8c0e8)
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 = getPointeeDefVal(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 = getPointeeDefVal(Call.getArgSVal(0), State);
1474   const auto Size = getPointeeDefVal(Call.getArgSVal(1), State);
1475   if (!LinePtr || !Size || !LinePtr->getAsRegion())
1476     return;
1477 
1478   State = setDynamicExtent(State, LinePtr->getAsRegion(), *Size, SVB);
1479   C.addTransition(MallocUpdateRefState(C, CE, State, AF_Malloc, *LinePtr));
1480 }
1481 
1482 void MallocChecker::checkReallocN(const CallEvent &Call,
1483                                   CheckerContext &C) const {
1484   ProgramStateRef State = C.getState();
1485   State = ReallocMemAux(C, Call, /*ShouldFreeOnFail=*/false, State, AF_Malloc,
1486                         /*SuffixWithN=*/true);
1487   State = ProcessZeroAllocCheck(Call, 1, State);
1488   State = ProcessZeroAllocCheck(Call, 2, State);
1489   C.addTransition(State);
1490 }
1491 
1492 void MallocChecker::checkOwnershipAttr(const CallEvent &Call,
1493                                        CheckerContext &C) const {
1494   ProgramStateRef State = C.getState();
1495   const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1496   if (!CE)
1497     return;
1498   const FunctionDecl *FD = C.getCalleeDecl(CE);
1499   if (!FD)
1500     return;
1501   if (ShouldIncludeOwnershipAnnotatedFunctions ||
1502       ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
1503     // Check all the attributes, if there are any.
1504     // There can be multiple of these attributes.
1505     if (FD->hasAttrs())
1506       for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
1507         switch (I->getOwnKind()) {
1508         case OwnershipAttr::Returns:
1509           State = MallocMemReturnsAttr(C, Call, I, State);
1510           break;
1511         case OwnershipAttr::Takes:
1512         case OwnershipAttr::Holds:
1513           State = FreeMemAttr(C, Call, I, State);
1514           break;
1515         }
1516       }
1517   }
1518   C.addTransition(State);
1519 }
1520 
1521 void MallocChecker::checkPostCall(const CallEvent &Call,
1522                                   CheckerContext &C) const {
1523   if (C.wasInlined)
1524     return;
1525   if (!Call.getOriginExpr())
1526     return;
1527 
1528   ProgramStateRef State = C.getState();
1529 
1530   if (const CheckFn *Callback = FreeingMemFnMap.lookup(Call)) {
1531     (*Callback)(this, Call, C);
1532     return;
1533   }
1534 
1535   if (const CheckFn *Callback = AllocatingMemFnMap.lookup(Call)) {
1536     (*Callback)(this, Call, C);
1537     return;
1538   }
1539 
1540   if (const CheckFn *Callback = ReallocatingMemFnMap.lookup(Call)) {
1541     (*Callback)(this, Call, C);
1542     return;
1543   }
1544 
1545   if (isStandardNewDelete(Call)) {
1546     checkCXXNewOrCXXDelete(Call, C);
1547     return;
1548   }
1549 
1550   checkOwnershipAttr(Call, C);
1551 }
1552 
1553 // Performs a 0-sized allocations check.
1554 ProgramStateRef MallocChecker::ProcessZeroAllocCheck(
1555     const CallEvent &Call, const unsigned IndexOfSizeArg, ProgramStateRef State,
1556     std::optional<SVal> RetVal) {
1557   if (!State)
1558     return nullptr;
1559 
1560   if (!RetVal)
1561     RetVal = Call.getReturnValue();
1562 
1563   const Expr *Arg = nullptr;
1564 
1565   if (const CallExpr *CE = dyn_cast<CallExpr>(Call.getOriginExpr())) {
1566     Arg = CE->getArg(IndexOfSizeArg);
1567   } else if (const CXXNewExpr *NE =
1568                  dyn_cast<CXXNewExpr>(Call.getOriginExpr())) {
1569     if (NE->isArray()) {
1570       Arg = *NE->getArraySize();
1571     } else {
1572       return State;
1573     }
1574   } else
1575     llvm_unreachable("not a CallExpr or CXXNewExpr");
1576 
1577   assert(Arg);
1578 
1579   auto DefArgVal =
1580       State->getSVal(Arg, Call.getLocationContext()).getAs<DefinedSVal>();
1581 
1582   if (!DefArgVal)
1583     return State;
1584 
1585   // Check if the allocation size is 0.
1586   ProgramStateRef TrueState, FalseState;
1587   SValBuilder &SvalBuilder = State->getStateManager().getSValBuilder();
1588   DefinedSVal Zero =
1589       SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
1590 
1591   std::tie(TrueState, FalseState) =
1592       State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
1593 
1594   if (TrueState && !FalseState) {
1595     SymbolRef Sym = RetVal->getAsLocSymbol();
1596     if (!Sym)
1597       return State;
1598 
1599     const RefState *RS = State->get<RegionState>(Sym);
1600     if (RS) {
1601       if (RS->isAllocated())
1602         return TrueState->set<RegionState>(Sym,
1603                                           RefState::getAllocatedOfSizeZero(RS));
1604       else
1605         return State;
1606     } else {
1607       // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1608       // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1609       // tracked. Add zero-reallocated Sym to the state to catch references
1610       // to zero-allocated memory.
1611       return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1612     }
1613   }
1614 
1615   // Assume the value is non-zero going forward.
1616   assert(FalseState);
1617   return FalseState;
1618 }
1619 
1620 static QualType getDeepPointeeType(QualType T) {
1621   QualType Result = T, PointeeType = T->getPointeeType();
1622   while (!PointeeType.isNull()) {
1623     Result = PointeeType;
1624     PointeeType = PointeeType->getPointeeType();
1625   }
1626   return Result;
1627 }
1628 
1629 /// \returns true if the constructor invoked by \p NE has an argument of a
1630 /// pointer/reference to a record type.
1631 static bool hasNonTrivialConstructorCall(const CXXNewExpr *NE) {
1632 
1633   const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1634   if (!ConstructE)
1635     return false;
1636 
1637   if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1638     return false;
1639 
1640   const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1641 
1642   // Iterate over the constructor parameters.
1643   for (const auto *CtorParam : CtorD->parameters()) {
1644 
1645     QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1646     if (CtorParamPointeeT.isNull())
1647       continue;
1648 
1649     CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1650 
1651     if (CtorParamPointeeT->getAsCXXRecordDecl())
1652       return true;
1653   }
1654 
1655   return false;
1656 }
1657 
1658 ProgramStateRef
1659 MallocChecker::processNewAllocation(const CXXAllocatorCall &Call,
1660                                     CheckerContext &C,
1661                                     AllocationFamily Family) const {
1662   if (!isStandardNewDelete(Call))
1663     return nullptr;
1664 
1665   const CXXNewExpr *NE = Call.getOriginExpr();
1666   const ParentMap &PM = C.getLocationContext()->getParentMap();
1667   ProgramStateRef State = C.getState();
1668 
1669   // Non-trivial constructors have a chance to escape 'this', but marking all
1670   // invocations of trivial constructors as escaped would cause too great of
1671   // reduction of true positives, so let's just do that for constructors that
1672   // have an argument of a pointer-to-record type.
1673   if (!PM.isConsumedExpr(NE) && hasNonTrivialConstructorCall(NE))
1674     return State;
1675 
1676   // The return value from operator new is bound to a specified initialization
1677   // value (if any) and we don't want to loose this value. So we call
1678   // MallocUpdateRefState() instead of MallocMemAux() which breaks the
1679   // existing binding.
1680   SVal Target = Call.getObjectUnderConstruction();
1681   State = MallocUpdateRefState(C, NE, State, Family, Target);
1682   State = ProcessZeroAllocCheck(Call, 0, State, Target);
1683   return State;
1684 }
1685 
1686 void MallocChecker::checkNewAllocator(const CXXAllocatorCall &Call,
1687                                       CheckerContext &C) const {
1688   if (!C.wasInlined) {
1689     ProgramStateRef State = processNewAllocation(
1690         Call, C,
1691         (Call.getOriginExpr()->isArray() ? AF_CXXNewArray : AF_CXXNew));
1692     C.addTransition(State);
1693   }
1694 }
1695 
1696 static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1697   // If the first selector piece is one of the names below, assume that the
1698   // object takes ownership of the memory, promising to eventually deallocate it
1699   // with free().
1700   // Ex:  [NSData dataWithBytesNoCopy:bytes length:10];
1701   // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1702   StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
1703   return FirstSlot == "dataWithBytesNoCopy" ||
1704          FirstSlot == "initWithBytesNoCopy" ||
1705          FirstSlot == "initWithCharactersNoCopy";
1706 }
1707 
1708 static std::optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1709   Selector S = Call.getSelector();
1710 
1711   // FIXME: We should not rely on fully-constrained symbols being folded.
1712   for (unsigned i = 1; i < S.getNumArgs(); ++i)
1713     if (S.getNameForSlot(i).equals("freeWhenDone"))
1714       return !Call.getArgSVal(i).isZeroConstant();
1715 
1716   return std::nullopt;
1717 }
1718 
1719 void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1720                                          CheckerContext &C) const {
1721   if (C.wasInlined)
1722     return;
1723 
1724   if (!isKnownDeallocObjCMethodName(Call))
1725     return;
1726 
1727   if (std::optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1728     if (!*FreeWhenDone)
1729       return;
1730 
1731   if (Call.hasNonZeroCallbackArg())
1732     return;
1733 
1734   bool IsKnownToBeAllocatedMemory;
1735   ProgramStateRef State =
1736       FreeMemAux(C, Call.getArgExpr(0), Call, C.getState(),
1737                  /*Hold=*/true, IsKnownToBeAllocatedMemory, AF_Malloc,
1738                  /*ReturnsNullOnFailure=*/true);
1739 
1740   C.addTransition(State);
1741 }
1742 
1743 ProgramStateRef
1744 MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallEvent &Call,
1745                                     const OwnershipAttr *Att,
1746                                     ProgramStateRef State) const {
1747   if (!State)
1748     return nullptr;
1749 
1750   if (Att->getModule()->getName() != "malloc")
1751     return nullptr;
1752 
1753   if (!Att->args().empty()) {
1754     return MallocMemAux(C, Call,
1755                         Call.getArgExpr(Att->args_begin()->getASTIndex()),
1756                         UndefinedVal(), State, AF_Malloc);
1757   }
1758   return MallocMemAux(C, Call, UnknownVal(), UndefinedVal(), State, AF_Malloc);
1759 }
1760 
1761 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1762                                             const CallEvent &Call,
1763                                             const Expr *SizeEx, SVal Init,
1764                                             ProgramStateRef State,
1765                                             AllocationFamily Family) {
1766   if (!State)
1767     return nullptr;
1768 
1769   assert(SizeEx);
1770   return MallocMemAux(C, Call, C.getSVal(SizeEx), Init, State, Family);
1771 }
1772 
1773 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1774                                             const CallEvent &Call, SVal Size,
1775                                             SVal Init, ProgramStateRef State,
1776                                             AllocationFamily Family) {
1777   if (!State)
1778     return nullptr;
1779 
1780   const Expr *CE = Call.getOriginExpr();
1781 
1782   // We expect the malloc functions to return a pointer.
1783   if (!Loc::isLocType(CE->getType()))
1784     return nullptr;
1785 
1786   // Bind the return value to the symbolic value from the heap region.
1787   // TODO: move use of this functions to an EvalCall callback, becasue
1788   // BindExpr() should'nt be used elsewhere.
1789   unsigned Count = C.blockCount();
1790   SValBuilder &SVB = C.getSValBuilder();
1791   const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1792   DefinedSVal RetVal =
1793       ((Family == AF_Alloca) ? SVB.getAllocaRegionVal(CE, LCtx, Count)
1794                              : SVB.getConjuredHeapSymbolVal(CE, LCtx, Count)
1795                                    .castAs<DefinedSVal>());
1796   State = State->BindExpr(CE, C.getLocationContext(), RetVal);
1797 
1798   // Fill the region with the initialization value.
1799   State = State->bindDefaultInitial(RetVal, Init, LCtx);
1800 
1801   // If Size is somehow undefined at this point, this line prevents a crash.
1802   if (Size.isUndef())
1803     Size = UnknownVal();
1804 
1805   // Set the region's extent.
1806   State = setDynamicExtent(State, RetVal.getAsRegion(),
1807                            Size.castAs<DefinedOrUnknownSVal>(), SVB);
1808 
1809   return MallocUpdateRefState(C, CE, State, Family);
1810 }
1811 
1812 static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E,
1813                                             ProgramStateRef State,
1814                                             AllocationFamily Family,
1815                                             std::optional<SVal> RetVal) {
1816   if (!State)
1817     return nullptr;
1818 
1819   // Get the return value.
1820   if (!RetVal)
1821     RetVal = C.getSVal(E);
1822 
1823   // We expect the malloc functions to return a pointer.
1824   if (!RetVal->getAs<Loc>())
1825     return nullptr;
1826 
1827   SymbolRef Sym = RetVal->getAsLocSymbol();
1828   // This is a return value of a function that was not inlined, such as malloc()
1829   // or new(). We've checked that in the caller. Therefore, it must be a symbol.
1830   assert(Sym);
1831 
1832   // Set the symbol's state to Allocated.
1833   return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1834 }
1835 
1836 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1837                                            const CallEvent &Call,
1838                                            const OwnershipAttr *Att,
1839                                            ProgramStateRef State) const {
1840   if (!State)
1841     return nullptr;
1842 
1843   if (Att->getModule()->getName() != "malloc")
1844     return nullptr;
1845 
1846   bool IsKnownToBeAllocated = false;
1847 
1848   for (const auto &Arg : Att->args()) {
1849     ProgramStateRef StateI =
1850         FreeMemAux(C, Call, State, Arg.getASTIndex(),
1851                    Att->getOwnKind() == OwnershipAttr::Holds,
1852                    IsKnownToBeAllocated, AF_Malloc);
1853     if (StateI)
1854       State = StateI;
1855   }
1856   return State;
1857 }
1858 
1859 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1860                                           const CallEvent &Call,
1861                                           ProgramStateRef State, unsigned Num,
1862                                           bool Hold, bool &IsKnownToBeAllocated,
1863                                           AllocationFamily Family,
1864                                           bool ReturnsNullOnFailure) const {
1865   if (!State)
1866     return nullptr;
1867 
1868   if (Call.getNumArgs() < (Num + 1))
1869     return nullptr;
1870 
1871   return FreeMemAux(C, Call.getArgExpr(Num), Call, State, Hold,
1872                     IsKnownToBeAllocated, Family, ReturnsNullOnFailure);
1873 }
1874 
1875 /// Checks if the previous call to free on the given symbol failed - if free
1876 /// failed, returns true. Also, returns the corresponding return value symbol.
1877 static bool didPreviousFreeFail(ProgramStateRef State,
1878                                 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
1879   const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1880   if (Ret) {
1881     assert(*Ret && "We should not store the null return symbol");
1882     ConstraintManager &CMgr = State->getConstraintManager();
1883     ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1884     RetStatusSymbol = *Ret;
1885     return FreeFailed.isConstrainedTrue();
1886   }
1887   return false;
1888 }
1889 
1890 static bool printMemFnName(raw_ostream &os, CheckerContext &C, const Expr *E) {
1891   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1892     // FIXME: This doesn't handle indirect calls.
1893     const FunctionDecl *FD = CE->getDirectCallee();
1894     if (!FD)
1895       return false;
1896 
1897     os << *FD;
1898     if (!FD->isOverloadedOperator())
1899       os << "()";
1900     return true;
1901   }
1902 
1903   if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1904     if (Msg->isInstanceMessage())
1905       os << "-";
1906     else
1907       os << "+";
1908     Msg->getSelector().print(os);
1909     return true;
1910   }
1911 
1912   if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1913     os << "'"
1914        << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1915        << "'";
1916     return true;
1917   }
1918 
1919   if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1920     os << "'"
1921        << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1922        << "'";
1923     return true;
1924   }
1925 
1926   return false;
1927 }
1928 
1929 static void printExpectedAllocName(raw_ostream &os, AllocationFamily Family) {
1930 
1931   switch(Family) {
1932     case AF_Malloc: os << "malloc()"; return;
1933     case AF_CXXNew: os << "'new'"; return;
1934     case AF_CXXNewArray: os << "'new[]'"; return;
1935     case AF_IfNameIndex: os << "'if_nameindex()'"; return;
1936     case AF_InnerBuffer: os << "container-specific allocator"; return;
1937     case AF_Alloca:
1938     case AF_None: llvm_unreachable("not a deallocation expression");
1939   }
1940 }
1941 
1942 static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) {
1943   switch(Family) {
1944     case AF_Malloc: os << "free()"; return;
1945     case AF_CXXNew: os << "'delete'"; return;
1946     case AF_CXXNewArray: os << "'delete[]'"; return;
1947     case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
1948     case AF_InnerBuffer: os << "container-specific deallocator"; return;
1949     case AF_Alloca:
1950     case AF_None: llvm_unreachable("suspicious argument");
1951   }
1952 }
1953 
1954 ProgramStateRef
1955 MallocChecker::FreeMemAux(CheckerContext &C, const Expr *ArgExpr,
1956                           const CallEvent &Call, ProgramStateRef State,
1957                           bool Hold, bool &IsKnownToBeAllocated,
1958                           AllocationFamily Family, bool ReturnsNullOnFailure,
1959                           std::optional<SVal> ArgValOpt) const {
1960 
1961   if (!State)
1962     return nullptr;
1963 
1964   SVal ArgVal = ArgValOpt.value_or(C.getSVal(ArgExpr));
1965   if (!isa<DefinedOrUnknownSVal>(ArgVal))
1966     return nullptr;
1967   DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1968 
1969   // Check for null dereferences.
1970   if (!isa<Loc>(location))
1971     return nullptr;
1972 
1973   // The explicit NULL case, no operation is performed.
1974   ProgramStateRef notNullState, nullState;
1975   std::tie(notNullState, nullState) = State->assume(location);
1976   if (nullState && !notNullState)
1977     return nullptr;
1978 
1979   // Unknown values could easily be okay
1980   // Undefined values are handled elsewhere
1981   if (ArgVal.isUnknownOrUndef())
1982     return nullptr;
1983 
1984   const MemRegion *R = ArgVal.getAsRegion();
1985   const Expr *ParentExpr = Call.getOriginExpr();
1986 
1987   // NOTE: We detected a bug, but the checker under whose name we would emit the
1988   // error could be disabled. Generally speaking, the MallocChecker family is an
1989   // integral part of the Static Analyzer, and disabling any part of it should
1990   // only be done under exceptional circumstances, such as frequent false
1991   // positives. If this is the case, we can reasonably believe that there are
1992   // serious faults in our understanding of the source code, and even if we
1993   // don't emit an warning, we should terminate further analysis with a sink
1994   // node.
1995 
1996   // Nonlocs can't be freed, of course.
1997   // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1998   if (!R) {
1999     // Exception:
2000     // If the macro ZERO_SIZE_PTR is defined, this could be a kernel source
2001     // code. In that case, the ZERO_SIZE_PTR defines a special value used for a
2002     // zero-sized memory block which is allowed to be freed, despite not being a
2003     // null pointer.
2004     if (Family != AF_Malloc || !isArgZERO_SIZE_PTR(State, C, ArgVal))
2005       HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2006                            Family);
2007     return nullptr;
2008   }
2009 
2010   R = R->StripCasts();
2011 
2012   // Blocks might show up as heap data, but should not be free()d
2013   if (isa<BlockDataRegion>(R)) {
2014     HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2015                          Family);
2016     return nullptr;
2017   }
2018 
2019   const MemSpaceRegion *MS = R->getMemorySpace();
2020 
2021   // Parameters, locals, statics, globals, and memory returned by
2022   // __builtin_alloca() shouldn't be freed.
2023   if (!isa<UnknownSpaceRegion, HeapSpaceRegion>(MS)) {
2024     // Regions returned by malloc() are represented by SymbolicRegion objects
2025     // within HeapSpaceRegion. Of course, free() can work on memory allocated
2026     // outside the current function, so UnknownSpaceRegion is also a
2027     // possibility here.
2028 
2029     if (isa<AllocaRegion>(R))
2030       HandleFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
2031     else
2032       HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2033                            Family);
2034 
2035     return nullptr;
2036   }
2037 
2038   const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
2039   // Various cases could lead to non-symbol values here.
2040   // For now, ignore them.
2041   if (!SrBase)
2042     return nullptr;
2043 
2044   SymbolRef SymBase = SrBase->getSymbol();
2045   const RefState *RsBase = State->get<RegionState>(SymBase);
2046   SymbolRef PreviousRetStatusSymbol = nullptr;
2047 
2048   IsKnownToBeAllocated =
2049       RsBase && (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero());
2050 
2051   if (RsBase) {
2052 
2053     // Memory returned by alloca() shouldn't be freed.
2054     if (RsBase->getAllocationFamily() == AF_Alloca) {
2055       HandleFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
2056       return nullptr;
2057     }
2058 
2059     // Check for double free first.
2060     if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
2061         !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
2062       HandleDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
2063                        SymBase, PreviousRetStatusSymbol);
2064       return nullptr;
2065 
2066     // If the pointer is allocated or escaped, but we are now trying to free it,
2067     // check that the call to free is proper.
2068     } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
2069                RsBase->isEscaped()) {
2070 
2071       // Check if an expected deallocation function matches the real one.
2072       bool DeallocMatchesAlloc = RsBase->getAllocationFamily() == Family;
2073       if (!DeallocMatchesAlloc) {
2074         HandleMismatchedDealloc(C, ArgExpr->getSourceRange(), ParentExpr,
2075                                 RsBase, SymBase, Hold);
2076         return nullptr;
2077       }
2078 
2079       // Check if the memory location being freed is the actual location
2080       // allocated, or an offset.
2081       RegionOffset Offset = R->getAsOffset();
2082       if (Offset.isValid() &&
2083           !Offset.hasSymbolicOffset() &&
2084           Offset.getOffset() != 0) {
2085         const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
2086         HandleOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2087                          Family, AllocExpr);
2088         return nullptr;
2089       }
2090     }
2091   }
2092 
2093   if (SymBase->getType()->isFunctionPointerType()) {
2094     HandleFunctionPtrFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2095                           Family);
2096     return nullptr;
2097   }
2098 
2099   // Clean out the info on previous call to free return info.
2100   State = State->remove<FreeReturnValue>(SymBase);
2101 
2102   // Keep track of the return value. If it is NULL, we will know that free
2103   // failed.
2104   if (ReturnsNullOnFailure) {
2105     SVal RetVal = C.getSVal(ParentExpr);
2106     SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
2107     if (RetStatusSymbol) {
2108       C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
2109       State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
2110     }
2111   }
2112 
2113   // If we don't know anything about this symbol, a free on it may be totally
2114   // valid. If this is the case, lets assume that the allocation family of the
2115   // freeing function is the same as the symbols allocation family, and go with
2116   // that.
2117   assert(!RsBase || (RsBase && RsBase->getAllocationFamily() == Family));
2118 
2119   // Normal free.
2120   if (Hold)
2121     return State->set<RegionState>(SymBase,
2122                                    RefState::getRelinquished(Family,
2123                                                              ParentExpr));
2124 
2125   return State->set<RegionState>(SymBase,
2126                                  RefState::getReleased(Family, ParentExpr));
2127 }
2128 
2129 std::optional<MallocChecker::CheckKind>
2130 MallocChecker::getCheckIfTracked(AllocationFamily Family,
2131                                  bool IsALeakCheck) const {
2132   switch (Family) {
2133   case AF_Malloc:
2134   case AF_Alloca:
2135   case AF_IfNameIndex: {
2136     if (ChecksEnabled[CK_MallocChecker])
2137       return CK_MallocChecker;
2138     return std::nullopt;
2139   }
2140   case AF_CXXNew:
2141   case AF_CXXNewArray: {
2142     if (IsALeakCheck) {
2143       if (ChecksEnabled[CK_NewDeleteLeaksChecker])
2144         return CK_NewDeleteLeaksChecker;
2145     }
2146     else {
2147       if (ChecksEnabled[CK_NewDeleteChecker])
2148         return CK_NewDeleteChecker;
2149     }
2150     return std::nullopt;
2151   }
2152   case AF_InnerBuffer: {
2153     if (ChecksEnabled[CK_InnerPointerChecker])
2154       return CK_InnerPointerChecker;
2155     return std::nullopt;
2156   }
2157   case AF_None: {
2158     llvm_unreachable("no family");
2159   }
2160   }
2161   llvm_unreachable("unhandled family");
2162 }
2163 
2164 std::optional<MallocChecker::CheckKind>
2165 MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
2166                                  bool IsALeakCheck) const {
2167   if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
2168     return CK_MallocChecker;
2169 
2170   const RefState *RS = C.getState()->get<RegionState>(Sym);
2171   assert(RS);
2172   return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
2173 }
2174 
2175 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
2176   if (std::optional<nonloc::ConcreteInt> IntVal =
2177           V.getAs<nonloc::ConcreteInt>())
2178     os << "an integer (" << IntVal->getValue() << ")";
2179   else if (std::optional<loc::ConcreteInt> ConstAddr =
2180                V.getAs<loc::ConcreteInt>())
2181     os << "a constant address (" << ConstAddr->getValue() << ")";
2182   else if (std::optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
2183     os << "the address of the label '" << Label->getLabel()->getName() << "'";
2184   else
2185     return false;
2186 
2187   return true;
2188 }
2189 
2190 bool MallocChecker::SummarizeRegion(raw_ostream &os,
2191                                     const MemRegion *MR) {
2192   switch (MR->getKind()) {
2193   case MemRegion::FunctionCodeRegionKind: {
2194     const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
2195     if (FD)
2196       os << "the address of the function '" << *FD << '\'';
2197     else
2198       os << "the address of a function";
2199     return true;
2200   }
2201   case MemRegion::BlockCodeRegionKind:
2202     os << "block text";
2203     return true;
2204   case MemRegion::BlockDataRegionKind:
2205     // FIXME: where the block came from?
2206     os << "a block";
2207     return true;
2208   default: {
2209     const MemSpaceRegion *MS = MR->getMemorySpace();
2210 
2211     if (isa<StackLocalsSpaceRegion>(MS)) {
2212       const VarRegion *VR = dyn_cast<VarRegion>(MR);
2213       const VarDecl *VD;
2214       if (VR)
2215         VD = VR->getDecl();
2216       else
2217         VD = nullptr;
2218 
2219       if (VD)
2220         os << "the address of the local variable '" << VD->getName() << "'";
2221       else
2222         os << "the address of a local stack variable";
2223       return true;
2224     }
2225 
2226     if (isa<StackArgumentsSpaceRegion>(MS)) {
2227       const VarRegion *VR = dyn_cast<VarRegion>(MR);
2228       const VarDecl *VD;
2229       if (VR)
2230         VD = VR->getDecl();
2231       else
2232         VD = nullptr;
2233 
2234       if (VD)
2235         os << "the address of the parameter '" << VD->getName() << "'";
2236       else
2237         os << "the address of a parameter";
2238       return true;
2239     }
2240 
2241     if (isa<GlobalsSpaceRegion>(MS)) {
2242       const VarRegion *VR = dyn_cast<VarRegion>(MR);
2243       const VarDecl *VD;
2244       if (VR)
2245         VD = VR->getDecl();
2246       else
2247         VD = nullptr;
2248 
2249       if (VD) {
2250         if (VD->isStaticLocal())
2251           os << "the address of the static variable '" << VD->getName() << "'";
2252         else
2253           os << "the address of the global variable '" << VD->getName() << "'";
2254       } else
2255         os << "the address of a global variable";
2256       return true;
2257     }
2258 
2259     return false;
2260   }
2261   }
2262 }
2263 
2264 void MallocChecker::HandleNonHeapDealloc(CheckerContext &C, SVal ArgVal,
2265                                          SourceRange Range,
2266                                          const Expr *DeallocExpr,
2267                                          AllocationFamily Family) const {
2268 
2269   if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) {
2270     C.addSink();
2271     return;
2272   }
2273 
2274   std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2275   if (!CheckKind)
2276     return;
2277 
2278   if (ExplodedNode *N = C.generateErrorNode()) {
2279     if (!BT_BadFree[*CheckKind])
2280       BT_BadFree[*CheckKind].reset(new BugType(
2281           CheckNames[*CheckKind], "Bad free", categories::MemoryError));
2282 
2283     SmallString<100> buf;
2284     llvm::raw_svector_ostream os(buf);
2285 
2286     const MemRegion *MR = ArgVal.getAsRegion();
2287     while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2288       MR = ER->getSuperRegion();
2289 
2290     os << "Argument to ";
2291     if (!printMemFnName(os, C, DeallocExpr))
2292       os << "deallocator";
2293 
2294     os << " is ";
2295     bool Summarized = MR ? SummarizeRegion(os, MR)
2296                          : SummarizeValue(os, ArgVal);
2297     if (Summarized)
2298       os << ", which is not memory allocated by ";
2299     else
2300       os << "not memory allocated by ";
2301 
2302     printExpectedAllocName(os, Family);
2303 
2304     auto R = std::make_unique<PathSensitiveBugReport>(*BT_BadFree[*CheckKind],
2305                                                       os.str(), N);
2306     R->markInteresting(MR);
2307     R->addRange(Range);
2308     C.emitReport(std::move(R));
2309   }
2310 }
2311 
2312 void MallocChecker::HandleFreeAlloca(CheckerContext &C, SVal ArgVal,
2313                                      SourceRange Range) const {
2314 
2315   std::optional<MallocChecker::CheckKind> CheckKind;
2316 
2317   if (ChecksEnabled[CK_MallocChecker])
2318     CheckKind = CK_MallocChecker;
2319   else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
2320     CheckKind = CK_MismatchedDeallocatorChecker;
2321   else {
2322     C.addSink();
2323     return;
2324   }
2325 
2326   if (ExplodedNode *N = C.generateErrorNode()) {
2327     if (!BT_FreeAlloca[*CheckKind])
2328       BT_FreeAlloca[*CheckKind].reset(new BugType(
2329           CheckNames[*CheckKind], "Free alloca()", categories::MemoryError));
2330 
2331     auto R = std::make_unique<PathSensitiveBugReport>(
2332         *BT_FreeAlloca[*CheckKind],
2333         "Memory allocated by alloca() should not be deallocated", N);
2334     R->markInteresting(ArgVal.getAsRegion());
2335     R->addRange(Range);
2336     C.emitReport(std::move(R));
2337   }
2338 }
2339 
2340 void MallocChecker::HandleMismatchedDealloc(CheckerContext &C,
2341                                             SourceRange Range,
2342                                             const Expr *DeallocExpr,
2343                                             const RefState *RS, SymbolRef Sym,
2344                                             bool OwnershipTransferred) const {
2345 
2346   if (!ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
2347     C.addSink();
2348     return;
2349   }
2350 
2351   if (ExplodedNode *N = C.generateErrorNode()) {
2352     if (!BT_MismatchedDealloc)
2353       BT_MismatchedDealloc.reset(
2354           new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
2355                       "Bad deallocator", categories::MemoryError));
2356 
2357     SmallString<100> buf;
2358     llvm::raw_svector_ostream os(buf);
2359 
2360     const Expr *AllocExpr = cast<Expr>(RS->getStmt());
2361     SmallString<20> AllocBuf;
2362     llvm::raw_svector_ostream AllocOs(AllocBuf);
2363     SmallString<20> DeallocBuf;
2364     llvm::raw_svector_ostream DeallocOs(DeallocBuf);
2365 
2366     if (OwnershipTransferred) {
2367       if (printMemFnName(DeallocOs, C, DeallocExpr))
2368         os << DeallocOs.str() << " cannot";
2369       else
2370         os << "Cannot";
2371 
2372       os << " take ownership of memory";
2373 
2374       if (printMemFnName(AllocOs, C, AllocExpr))
2375         os << " allocated by " << AllocOs.str();
2376     } else {
2377       os << "Memory";
2378       if (printMemFnName(AllocOs, C, AllocExpr))
2379         os << " allocated by " << AllocOs.str();
2380 
2381       os << " should be deallocated by ";
2382         printExpectedDeallocName(os, RS->getAllocationFamily());
2383 
2384         if (printMemFnName(DeallocOs, C, DeallocExpr))
2385           os << ", not " << DeallocOs.str();
2386     }
2387 
2388     auto R = std::make_unique<PathSensitiveBugReport>(*BT_MismatchedDealloc,
2389                                                       os.str(), N);
2390     R->markInteresting(Sym);
2391     R->addRange(Range);
2392     R->addVisitor<MallocBugVisitor>(Sym);
2393     C.emitReport(std::move(R));
2394   }
2395 }
2396 
2397 void MallocChecker::HandleOffsetFree(CheckerContext &C, SVal ArgVal,
2398                                      SourceRange Range, const Expr *DeallocExpr,
2399                                      AllocationFamily Family,
2400                                      const Expr *AllocExpr) const {
2401 
2402   if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) {
2403     C.addSink();
2404     return;
2405   }
2406 
2407   std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2408   if (!CheckKind)
2409     return;
2410 
2411   ExplodedNode *N = C.generateErrorNode();
2412   if (!N)
2413     return;
2414 
2415   if (!BT_OffsetFree[*CheckKind])
2416     BT_OffsetFree[*CheckKind].reset(new BugType(
2417         CheckNames[*CheckKind], "Offset free", categories::MemoryError));
2418 
2419   SmallString<100> buf;
2420   llvm::raw_svector_ostream os(buf);
2421   SmallString<20> AllocNameBuf;
2422   llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
2423 
2424   const MemRegion *MR = ArgVal.getAsRegion();
2425   assert(MR && "Only MemRegion based symbols can have offset free errors");
2426 
2427   RegionOffset Offset = MR->getAsOffset();
2428   assert((Offset.isValid() &&
2429           !Offset.hasSymbolicOffset() &&
2430           Offset.getOffset() != 0) &&
2431          "Only symbols with a valid offset can have offset free errors");
2432 
2433   int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
2434 
2435   os << "Argument to ";
2436   if (!printMemFnName(os, C, DeallocExpr))
2437     os << "deallocator";
2438   os << " is offset by "
2439      << offsetBytes
2440      << " "
2441      << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
2442      << " from the start of ";
2443   if (AllocExpr && printMemFnName(AllocNameOs, C, AllocExpr))
2444     os << "memory allocated by " << AllocNameOs.str();
2445   else
2446     os << "allocated memory";
2447 
2448   auto R = std::make_unique<PathSensitiveBugReport>(*BT_OffsetFree[*CheckKind],
2449                                                     os.str(), N);
2450   R->markInteresting(MR->getBaseRegion());
2451   R->addRange(Range);
2452   C.emitReport(std::move(R));
2453 }
2454 
2455 void MallocChecker::HandleUseAfterFree(CheckerContext &C, SourceRange Range,
2456                                        SymbolRef Sym) const {
2457 
2458   if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker] &&
2459       !ChecksEnabled[CK_InnerPointerChecker]) {
2460     C.addSink();
2461     return;
2462   }
2463 
2464   std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2465   if (!CheckKind)
2466     return;
2467 
2468   if (ExplodedNode *N = C.generateErrorNode()) {
2469     if (!BT_UseFree[*CheckKind])
2470       BT_UseFree[*CheckKind].reset(new BugType(
2471           CheckNames[*CheckKind], "Use-after-free", categories::MemoryError));
2472 
2473     AllocationFamily AF =
2474         C.getState()->get<RegionState>(Sym)->getAllocationFamily();
2475 
2476     auto R = std::make_unique<PathSensitiveBugReport>(
2477         *BT_UseFree[*CheckKind],
2478         AF == AF_InnerBuffer
2479             ? "Inner pointer of container used after re/deallocation"
2480             : "Use of memory after it is freed",
2481         N);
2482 
2483     R->markInteresting(Sym);
2484     R->addRange(Range);
2485     R->addVisitor<MallocBugVisitor>(Sym);
2486 
2487     if (AF == AF_InnerBuffer)
2488       R->addVisitor(allocation_state::getInnerPointerBRVisitor(Sym));
2489 
2490     C.emitReport(std::move(R));
2491   }
2492 }
2493 
2494 void MallocChecker::HandleDoubleFree(CheckerContext &C, SourceRange Range,
2495                                      bool Released, SymbolRef Sym,
2496                                      SymbolRef PrevSym) const {
2497 
2498   if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) {
2499     C.addSink();
2500     return;
2501   }
2502 
2503   std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2504   if (!CheckKind)
2505     return;
2506 
2507   if (ExplodedNode *N = C.generateErrorNode()) {
2508     if (!BT_DoubleFree[*CheckKind])
2509       BT_DoubleFree[*CheckKind].reset(new BugType(
2510           CheckNames[*CheckKind], "Double free", categories::MemoryError));
2511 
2512     auto R = std::make_unique<PathSensitiveBugReport>(
2513         *BT_DoubleFree[*CheckKind],
2514         (Released ? "Attempt to free released memory"
2515                   : "Attempt to free non-owned memory"),
2516         N);
2517     R->addRange(Range);
2518     R->markInteresting(Sym);
2519     if (PrevSym)
2520       R->markInteresting(PrevSym);
2521     R->addVisitor<MallocBugVisitor>(Sym);
2522     C.emitReport(std::move(R));
2523   }
2524 }
2525 
2526 void MallocChecker::HandleDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
2527 
2528   if (!ChecksEnabled[CK_NewDeleteChecker]) {
2529     C.addSink();
2530     return;
2531   }
2532 
2533   std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2534   if (!CheckKind)
2535     return;
2536 
2537   if (ExplodedNode *N = C.generateErrorNode()) {
2538     if (!BT_DoubleDelete)
2539       BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
2540                                         "Double delete",
2541                                         categories::MemoryError));
2542 
2543     auto R = std::make_unique<PathSensitiveBugReport>(
2544         *BT_DoubleDelete, "Attempt to delete released memory", N);
2545 
2546     R->markInteresting(Sym);
2547     R->addVisitor<MallocBugVisitor>(Sym);
2548     C.emitReport(std::move(R));
2549   }
2550 }
2551 
2552 void MallocChecker::HandleUseZeroAlloc(CheckerContext &C, SourceRange Range,
2553                                        SymbolRef Sym) const {
2554 
2555   if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) {
2556     C.addSink();
2557     return;
2558   }
2559 
2560   std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2561 
2562   if (!CheckKind)
2563     return;
2564 
2565   if (ExplodedNode *N = C.generateErrorNode()) {
2566     if (!BT_UseZerroAllocated[*CheckKind])
2567       BT_UseZerroAllocated[*CheckKind].reset(
2568           new BugType(CheckNames[*CheckKind], "Use of zero allocated",
2569                       categories::MemoryError));
2570 
2571     auto R = std::make_unique<PathSensitiveBugReport>(
2572         *BT_UseZerroAllocated[*CheckKind],
2573         "Use of memory allocated with size zero", N);
2574 
2575     R->addRange(Range);
2576     if (Sym) {
2577       R->markInteresting(Sym);
2578       R->addVisitor<MallocBugVisitor>(Sym);
2579     }
2580     C.emitReport(std::move(R));
2581   }
2582 }
2583 
2584 void MallocChecker::HandleFunctionPtrFree(CheckerContext &C, SVal ArgVal,
2585                                           SourceRange Range,
2586                                           const Expr *FreeExpr,
2587                                           AllocationFamily Family) const {
2588   if (!ChecksEnabled[CK_MallocChecker]) {
2589     C.addSink();
2590     return;
2591   }
2592 
2593   std::optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2594   if (!CheckKind)
2595     return;
2596 
2597   if (ExplodedNode *N = C.generateErrorNode()) {
2598     if (!BT_BadFree[*CheckKind])
2599       BT_BadFree[*CheckKind].reset(new BugType(
2600           CheckNames[*CheckKind], "Bad free", categories::MemoryError));
2601 
2602     SmallString<100> Buf;
2603     llvm::raw_svector_ostream Os(Buf);
2604 
2605     const MemRegion *MR = ArgVal.getAsRegion();
2606     while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2607       MR = ER->getSuperRegion();
2608 
2609     Os << "Argument to ";
2610     if (!printMemFnName(Os, C, FreeExpr))
2611       Os << "deallocator";
2612 
2613     Os << " is a function pointer";
2614 
2615     auto R = std::make_unique<PathSensitiveBugReport>(*BT_BadFree[*CheckKind],
2616                                                       Os.str(), N);
2617     R->markInteresting(MR);
2618     R->addRange(Range);
2619     C.emitReport(std::move(R));
2620   }
2621 }
2622 
2623 ProgramStateRef
2624 MallocChecker::ReallocMemAux(CheckerContext &C, const CallEvent &Call,
2625                              bool ShouldFreeOnFail, ProgramStateRef State,
2626                              AllocationFamily Family, bool SuffixWithN) const {
2627   if (!State)
2628     return nullptr;
2629 
2630   const CallExpr *CE = cast<CallExpr>(Call.getOriginExpr());
2631 
2632   if (SuffixWithN && CE->getNumArgs() < 3)
2633     return nullptr;
2634   else if (CE->getNumArgs() < 2)
2635     return nullptr;
2636 
2637   const Expr *arg0Expr = CE->getArg(0);
2638   SVal Arg0Val = C.getSVal(arg0Expr);
2639   if (!isa<DefinedOrUnknownSVal>(Arg0Val))
2640     return nullptr;
2641   DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
2642 
2643   SValBuilder &svalBuilder = C.getSValBuilder();
2644 
2645   DefinedOrUnknownSVal PtrEQ = svalBuilder.evalEQ(
2646       State, arg0Val, svalBuilder.makeNullWithType(arg0Expr->getType()));
2647 
2648   // Get the size argument.
2649   const Expr *Arg1 = CE->getArg(1);
2650 
2651   // Get the value of the size argument.
2652   SVal TotalSize = C.getSVal(Arg1);
2653   if (SuffixWithN)
2654     TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2655   if (!isa<DefinedOrUnknownSVal>(TotalSize))
2656     return nullptr;
2657 
2658   // Compare the size argument to 0.
2659   DefinedOrUnknownSVal SizeZero =
2660       svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
2661                          svalBuilder.makeIntValWithWidth(
2662                              svalBuilder.getContext().getSizeType(), 0));
2663 
2664   ProgramStateRef StatePtrIsNull, StatePtrNotNull;
2665   std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
2666   ProgramStateRef StateSizeIsZero, StateSizeNotZero;
2667   std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
2668   // We only assume exceptional states if they are definitely true; if the
2669   // state is under-constrained, assume regular realloc behavior.
2670   bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2671   bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2672 
2673   // If the ptr is NULL and the size is not 0, the call is equivalent to
2674   // malloc(size).
2675   if (PrtIsNull && !SizeIsZero) {
2676     ProgramStateRef stateMalloc = MallocMemAux(
2677         C, Call, TotalSize, UndefinedVal(), StatePtrIsNull, Family);
2678     return stateMalloc;
2679   }
2680 
2681   if (PrtIsNull && SizeIsZero)
2682     return State;
2683 
2684   assert(!PrtIsNull);
2685 
2686   bool IsKnownToBeAllocated = false;
2687 
2688   // If the size is 0, free the memory.
2689   if (SizeIsZero)
2690     // The semantics of the return value are:
2691     // If size was equal to 0, either NULL or a pointer suitable to be passed
2692     // to free() is returned. We just free the input pointer and do not add
2693     // any constrains on the output pointer.
2694     if (ProgramStateRef stateFree = FreeMemAux(
2695             C, Call, StateSizeIsZero, 0, false, IsKnownToBeAllocated, Family))
2696       return stateFree;
2697 
2698   // Default behavior.
2699   if (ProgramStateRef stateFree =
2700           FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocated, Family)) {
2701 
2702     ProgramStateRef stateRealloc =
2703         MallocMemAux(C, Call, TotalSize, UnknownVal(), stateFree, Family);
2704     if (!stateRealloc)
2705       return nullptr;
2706 
2707     OwnershipAfterReallocKind Kind = OAR_ToBeFreedAfterFailure;
2708     if (ShouldFreeOnFail)
2709       Kind = OAR_FreeOnFailure;
2710     else if (!IsKnownToBeAllocated)
2711       Kind = OAR_DoNotTrackAfterFailure;
2712 
2713     // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
2714     SymbolRef FromPtr = arg0Val.getLocSymbolInBase();
2715     SVal RetVal = C.getSVal(CE);
2716     SymbolRef ToPtr = RetVal.getAsSymbol();
2717     assert(FromPtr && ToPtr &&
2718            "By this point, FreeMemAux and MallocMemAux should have checked "
2719            "whether the argument or the return value is symbolic!");
2720 
2721     // Record the info about the reallocated symbol so that we could properly
2722     // process failed reallocation.
2723     stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
2724                                                    ReallocPair(FromPtr, Kind));
2725     // The reallocated symbol should stay alive for as long as the new symbol.
2726     C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
2727     return stateRealloc;
2728   }
2729   return nullptr;
2730 }
2731 
2732 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C,
2733                                          const CallEvent &Call,
2734                                          ProgramStateRef State) {
2735   if (!State)
2736     return nullptr;
2737 
2738   if (Call.getNumArgs() < 2)
2739     return nullptr;
2740 
2741   SValBuilder &svalBuilder = C.getSValBuilder();
2742   SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
2743   SVal TotalSize =
2744       evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1));
2745 
2746   return MallocMemAux(C, Call, TotalSize, zeroVal, State, AF_Malloc);
2747 }
2748 
2749 MallocChecker::LeakInfo MallocChecker::getAllocationSite(const ExplodedNode *N,
2750                                                          SymbolRef Sym,
2751                                                          CheckerContext &C) {
2752   const LocationContext *LeakContext = N->getLocationContext();
2753   // Walk the ExplodedGraph backwards and find the first node that referred to
2754   // the tracked symbol.
2755   const ExplodedNode *AllocNode = N;
2756   const MemRegion *ReferenceRegion = nullptr;
2757 
2758   while (N) {
2759     ProgramStateRef State = N->getState();
2760     if (!State->get<RegionState>(Sym))
2761       break;
2762 
2763     // Find the most recent expression bound to the symbol in the current
2764     // context.
2765     if (!ReferenceRegion) {
2766       if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2767         SVal Val = State->getSVal(MR);
2768         if (Val.getAsLocSymbol() == Sym) {
2769           const VarRegion *VR = MR->getBaseRegion()->getAs<VarRegion>();
2770           // Do not show local variables belonging to a function other than
2771           // where the error is reported.
2772           if (!VR || (VR->getStackFrame() == LeakContext->getStackFrame()))
2773             ReferenceRegion = MR;
2774         }
2775       }
2776     }
2777 
2778     // Allocation node, is the last node in the current or parent context in
2779     // which the symbol was tracked.
2780     const LocationContext *NContext = N->getLocationContext();
2781     if (NContext == LeakContext ||
2782         NContext->isParentOf(LeakContext))
2783       AllocNode = N;
2784     N = N->pred_empty() ? nullptr : *(N->pred_begin());
2785   }
2786 
2787   return LeakInfo(AllocNode, ReferenceRegion);
2788 }
2789 
2790 void MallocChecker::HandleLeak(SymbolRef Sym, ExplodedNode *N,
2791                                CheckerContext &C) const {
2792 
2793   if (!ChecksEnabled[CK_MallocChecker] &&
2794       !ChecksEnabled[CK_NewDeleteLeaksChecker])
2795     return;
2796 
2797   const RefState *RS = C.getState()->get<RegionState>(Sym);
2798   assert(RS && "cannot leak an untracked symbol");
2799   AllocationFamily Family = RS->getAllocationFamily();
2800 
2801   if (Family == AF_Alloca)
2802     return;
2803 
2804   std::optional<MallocChecker::CheckKind> CheckKind =
2805       getCheckIfTracked(Family, true);
2806 
2807   if (!CheckKind)
2808     return;
2809 
2810   assert(N);
2811   if (!BT_Leak[*CheckKind]) {
2812     // Leaks should not be reported if they are post-dominated by a sink:
2813     // (1) Sinks are higher importance bugs.
2814     // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2815     //     with __noreturn functions such as assert() or exit(). We choose not
2816     //     to report leaks on such paths.
2817     BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak",
2818                                           categories::MemoryError,
2819                                           /*SuppressOnSink=*/true));
2820   }
2821 
2822   // Most bug reports are cached at the location where they occurred.
2823   // With leaks, we want to unique them by the location where they were
2824   // allocated, and only report a single path.
2825   PathDiagnosticLocation LocUsedForUniqueing;
2826   const ExplodedNode *AllocNode = nullptr;
2827   const MemRegion *Region = nullptr;
2828   std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
2829 
2830   const Stmt *AllocationStmt = AllocNode->getStmtForDiagnostics();
2831   if (AllocationStmt)
2832     LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2833                                               C.getSourceManager(),
2834                                               AllocNode->getLocationContext());
2835 
2836   SmallString<200> buf;
2837   llvm::raw_svector_ostream os(buf);
2838   if (Region && Region->canPrintPretty()) {
2839     os << "Potential leak of memory pointed to by ";
2840     Region->printPretty(os);
2841   } else {
2842     os << "Potential memory leak";
2843   }
2844 
2845   auto R = std::make_unique<PathSensitiveBugReport>(
2846       *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2847       AllocNode->getLocationContext()->getDecl());
2848   R->markInteresting(Sym);
2849   R->addVisitor<MallocBugVisitor>(Sym, true);
2850   if (ShouldRegisterNoOwnershipChangeVisitor)
2851     R->addVisitor<NoOwnershipChangeVisitor>(Sym, this);
2852   C.emitReport(std::move(R));
2853 }
2854 
2855 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2856                                      CheckerContext &C) const
2857 {
2858   ProgramStateRef state = C.getState();
2859   RegionStateTy OldRS = state->get<RegionState>();
2860   RegionStateTy::Factory &F = state->get_context<RegionState>();
2861 
2862   RegionStateTy RS = OldRS;
2863   SmallVector<SymbolRef, 2> Errors;
2864   for (auto [Sym, State] : RS) {
2865     if (SymReaper.isDead(Sym)) {
2866       if (State.isAllocated() || State.isAllocatedOfSizeZero())
2867         Errors.push_back(Sym);
2868       // Remove the dead symbol from the map.
2869       RS = F.remove(RS, Sym);
2870     }
2871   }
2872 
2873   if (RS == OldRS) {
2874     // We shouldn't have touched other maps yet.
2875     assert(state->get<ReallocPairs>() ==
2876            C.getState()->get<ReallocPairs>());
2877     assert(state->get<FreeReturnValue>() ==
2878            C.getState()->get<FreeReturnValue>());
2879     return;
2880   }
2881 
2882   // Cleanup the Realloc Pairs Map.
2883   ReallocPairsTy RP = state->get<ReallocPairs>();
2884   for (auto [Sym, ReallocPair] : RP) {
2885     if (SymReaper.isDead(Sym) || SymReaper.isDead(ReallocPair.ReallocatedSym)) {
2886       state = state->remove<ReallocPairs>(Sym);
2887     }
2888   }
2889 
2890   // Cleanup the FreeReturnValue Map.
2891   FreeReturnValueTy FR = state->get<FreeReturnValue>();
2892   for (auto [Sym, RetSym] : FR) {
2893     if (SymReaper.isDead(Sym) || SymReaper.isDead(RetSym)) {
2894       state = state->remove<FreeReturnValue>(Sym);
2895     }
2896   }
2897 
2898   // Generate leak node.
2899   ExplodedNode *N = C.getPredecessor();
2900   if (!Errors.empty()) {
2901     static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
2902     N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2903     if (N) {
2904       for (SymbolRef Sym : Errors) {
2905         HandleLeak(Sym, N, C);
2906       }
2907     }
2908   }
2909 
2910   C.addTransition(state->set<RegionState>(RS), N);
2911 }
2912 
2913 void MallocChecker::checkPreCall(const CallEvent &Call,
2914                                  CheckerContext &C) const {
2915 
2916   if (const auto *DC = dyn_cast<CXXDeallocatorCall>(&Call)) {
2917     const CXXDeleteExpr *DE = DC->getOriginExpr();
2918 
2919     if (!ChecksEnabled[CK_NewDeleteChecker])
2920       if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
2921         checkUseAfterFree(Sym, C, DE->getArgument());
2922 
2923     if (!isStandardNewDelete(DC->getDecl()))
2924       return;
2925 
2926     ProgramStateRef State = C.getState();
2927     bool IsKnownToBeAllocated;
2928     State = FreeMemAux(C, DE->getArgument(), Call, State,
2929                        /*Hold*/ false, IsKnownToBeAllocated,
2930                        (DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew));
2931 
2932     C.addTransition(State);
2933     return;
2934   }
2935 
2936   if (const auto *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2937     SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2938     if (!Sym || checkDoubleDelete(Sym, C))
2939       return;
2940   }
2941 
2942   // We need to handle getline pre-conditions here before the pointed region
2943   // gets invalidated by StreamChecker
2944   if (const auto *PreFN = PreFnMap.lookup(Call)) {
2945     (*PreFN)(this, Call, C);
2946     return;
2947   }
2948 
2949   // We will check for double free in the post visit.
2950   if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2951     const FunctionDecl *FD = FC->getDecl();
2952     if (!FD)
2953       return;
2954 
2955     if (ChecksEnabled[CK_MallocChecker] && isFreeingCall(Call))
2956       return;
2957   }
2958 
2959   // Check if the callee of a method is deleted.
2960   if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2961     SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2962     if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2963       return;
2964   }
2965 
2966   // Check arguments for being used after free.
2967   for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2968     SVal ArgSVal = Call.getArgSVal(I);
2969     if (isa<Loc>(ArgSVal)) {
2970       SymbolRef Sym = ArgSVal.getAsSymbol();
2971       if (!Sym)
2972         continue;
2973       if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2974         return;
2975     }
2976   }
2977 }
2978 
2979 void MallocChecker::checkPreStmt(const ReturnStmt *S,
2980                                  CheckerContext &C) const {
2981   checkEscapeOnReturn(S, C);
2982 }
2983 
2984 // In the CFG, automatic destructors come after the return statement.
2985 // This callback checks for returning memory that is freed by automatic
2986 // destructors, as those cannot be reached in checkPreStmt().
2987 void MallocChecker::checkEndFunction(const ReturnStmt *S,
2988                                      CheckerContext &C) const {
2989   checkEscapeOnReturn(S, C);
2990 }
2991 
2992 void MallocChecker::checkEscapeOnReturn(const ReturnStmt *S,
2993                                         CheckerContext &C) const {
2994   if (!S)
2995     return;
2996 
2997   const Expr *E = S->getRetValue();
2998   if (!E)
2999     return;
3000 
3001   // Check if we are returning a symbol.
3002   ProgramStateRef State = C.getState();
3003   SVal RetVal = C.getSVal(E);
3004   SymbolRef Sym = RetVal.getAsSymbol();
3005   if (!Sym)
3006     // If we are returning a field of the allocated struct or an array element,
3007     // the callee could still free the memory.
3008     // TODO: This logic should be a part of generic symbol escape callback.
3009     if (const MemRegion *MR = RetVal.getAsRegion())
3010       if (isa<FieldRegion, ElementRegion>(MR))
3011         if (const SymbolicRegion *BMR =
3012               dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
3013           Sym = BMR->getSymbol();
3014 
3015   // Check if we are returning freed memory.
3016   if (Sym)
3017     checkUseAfterFree(Sym, C, E);
3018 }
3019 
3020 // TODO: Blocks should be either inlined or should call invalidate regions
3021 // upon invocation. After that's in place, special casing here will not be
3022 // needed.
3023 void MallocChecker::checkPostStmt(const BlockExpr *BE,
3024                                   CheckerContext &C) const {
3025 
3026   // Scan the BlockDecRefExprs for any object the retain count checker
3027   // may be tracking.
3028   if (!BE->getBlockDecl()->hasCaptures())
3029     return;
3030 
3031   ProgramStateRef state = C.getState();
3032   const BlockDataRegion *R =
3033     cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
3034 
3035   auto ReferencedVars = R->referenced_vars();
3036   if (ReferencedVars.empty())
3037     return;
3038 
3039   SmallVector<const MemRegion*, 10> Regions;
3040   const LocationContext *LC = C.getLocationContext();
3041   MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
3042 
3043   for (const auto &Var : ReferencedVars) {
3044     const VarRegion *VR = Var.getCapturedRegion();
3045     if (VR->getSuperRegion() == R) {
3046       VR = MemMgr.getVarRegion(VR->getDecl(), LC);
3047     }
3048     Regions.push_back(VR);
3049   }
3050 
3051   state =
3052     state->scanReachableSymbols<StopTrackingCallback>(Regions).getState();
3053   C.addTransition(state);
3054 }
3055 
3056 static bool isReleased(SymbolRef Sym, CheckerContext &C) {
3057   assert(Sym);
3058   const RefState *RS = C.getState()->get<RegionState>(Sym);
3059   return (RS && RS->isReleased());
3060 }
3061 
3062 bool MallocChecker::suppressDeallocationsInSuspiciousContexts(
3063     const CallEvent &Call, CheckerContext &C) const {
3064   if (Call.getNumArgs() == 0)
3065     return false;
3066 
3067   StringRef FunctionStr = "";
3068   if (const auto *FD = dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
3069     if (const Stmt *Body = FD->getBody())
3070       if (Body->getBeginLoc().isValid())
3071         FunctionStr =
3072             Lexer::getSourceText(CharSourceRange::getTokenRange(
3073                                      {FD->getBeginLoc(), Body->getBeginLoc()}),
3074                                  C.getSourceManager(), C.getLangOpts());
3075 
3076   // We do not model the Integer Set Library's retain-count based allocation.
3077   if (!FunctionStr.contains("__isl_"))
3078     return false;
3079 
3080   ProgramStateRef State = C.getState();
3081 
3082   for (const Expr *Arg : cast<CallExpr>(Call.getOriginExpr())->arguments())
3083     if (SymbolRef Sym = C.getSVal(Arg).getAsSymbol())
3084       if (const RefState *RS = State->get<RegionState>(Sym))
3085         State = State->set<RegionState>(Sym, RefState::getEscaped(RS));
3086 
3087   C.addTransition(State);
3088   return true;
3089 }
3090 
3091 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
3092                                       const Stmt *S) const {
3093 
3094   if (isReleased(Sym, C)) {
3095     HandleUseAfterFree(C, S->getSourceRange(), Sym);
3096     return true;
3097   }
3098 
3099   return false;
3100 }
3101 
3102 void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
3103                                           const Stmt *S) const {
3104   assert(Sym);
3105 
3106   if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
3107     if (RS->isAllocatedOfSizeZero())
3108       HandleUseZeroAlloc(C, RS->getStmt()->getSourceRange(), Sym);
3109   }
3110   else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
3111     HandleUseZeroAlloc(C, S->getSourceRange(), Sym);
3112   }
3113 }
3114 
3115 bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
3116 
3117   if (isReleased(Sym, C)) {
3118     HandleDoubleDelete(C, Sym);
3119     return true;
3120   }
3121   return false;
3122 }
3123 
3124 // Check if the location is a freed symbolic region.
3125 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
3126                                   CheckerContext &C) const {
3127   SymbolRef Sym = l.getLocSymbolInBase();
3128   if (Sym) {
3129     checkUseAfterFree(Sym, C, S);
3130     checkUseZeroAllocated(Sym, C, S);
3131   }
3132 }
3133 
3134 // If a symbolic region is assumed to NULL (or another constant), stop tracking
3135 // it - assuming that allocation failed on this path.
3136 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
3137                                               SVal Cond,
3138                                               bool Assumption) const {
3139   RegionStateTy RS = state->get<RegionState>();
3140   for (SymbolRef Sym : llvm::make_first_range(RS)) {
3141     // If the symbol is assumed to be NULL, remove it from consideration.
3142     ConstraintManager &CMgr = state->getConstraintManager();
3143     ConditionTruthVal AllocFailed = CMgr.isNull(state, Sym);
3144     if (AllocFailed.isConstrainedTrue())
3145       state = state->remove<RegionState>(Sym);
3146   }
3147 
3148   // Realloc returns 0 when reallocation fails, which means that we should
3149   // restore the state of the pointer being reallocated.
3150   ReallocPairsTy RP = state->get<ReallocPairs>();
3151   for (auto [Sym, ReallocPair] : RP) {
3152     // If the symbol is assumed to be NULL, remove it from consideration.
3153     ConstraintManager &CMgr = state->getConstraintManager();
3154     ConditionTruthVal AllocFailed = CMgr.isNull(state, Sym);
3155     if (!AllocFailed.isConstrainedTrue())
3156       continue;
3157 
3158     SymbolRef ReallocSym = ReallocPair.ReallocatedSym;
3159     if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
3160       if (RS->isReleased()) {
3161         switch (ReallocPair.Kind) {
3162         case OAR_ToBeFreedAfterFailure:
3163           state = state->set<RegionState>(ReallocSym,
3164               RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
3165           break;
3166         case OAR_DoNotTrackAfterFailure:
3167           state = state->remove<RegionState>(ReallocSym);
3168           break;
3169         default:
3170           assert(ReallocPair.Kind == OAR_FreeOnFailure);
3171         }
3172       }
3173     }
3174     state = state->remove<ReallocPairs>(Sym);
3175   }
3176 
3177   return state;
3178 }
3179 
3180 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
3181                                               const CallEvent *Call,
3182                                               ProgramStateRef State,
3183                                               SymbolRef &EscapingSymbol) const {
3184   assert(Call);
3185   EscapingSymbol = nullptr;
3186 
3187   // For now, assume that any C++ or block call can free memory.
3188   // TODO: If we want to be more optimistic here, we'll need to make sure that
3189   // regions escape to C++ containers. They seem to do that even now, but for
3190   // mysterious reasons.
3191   if (!isa<SimpleFunctionCall, ObjCMethodCall>(Call))
3192     return true;
3193 
3194   // Check Objective-C messages by selector name.
3195   if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
3196     // If it's not a framework call, or if it takes a callback, assume it
3197     // can free memory.
3198     if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
3199       return true;
3200 
3201     // If it's a method we know about, handle it explicitly post-call.
3202     // This should happen before the "freeWhenDone" check below.
3203     if (isKnownDeallocObjCMethodName(*Msg))
3204       return false;
3205 
3206     // If there's a "freeWhenDone" parameter, but the method isn't one we know
3207     // about, we can't be sure that the object will use free() to deallocate the
3208     // memory, so we can't model it explicitly. The best we can do is use it to
3209     // decide whether the pointer escapes.
3210     if (std::optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
3211       return *FreeWhenDone;
3212 
3213     // If the first selector piece ends with "NoCopy", and there is no
3214     // "freeWhenDone" parameter set to zero, we know ownership is being
3215     // transferred. Again, though, we can't be sure that the object will use
3216     // free() to deallocate the memory, so we can't model it explicitly.
3217     StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
3218     if (FirstSlot.ends_with("NoCopy"))
3219       return true;
3220 
3221     // If the first selector starts with addPointer, insertPointer,
3222     // or replacePointer, assume we are dealing with NSPointerArray or similar.
3223     // This is similar to C++ containers (vector); we still might want to check
3224     // that the pointers get freed by following the container itself.
3225     if (FirstSlot.starts_with("addPointer") ||
3226         FirstSlot.starts_with("insertPointer") ||
3227         FirstSlot.starts_with("replacePointer") ||
3228         FirstSlot.equals("valueWithPointer")) {
3229       return true;
3230     }
3231 
3232     // We should escape receiver on call to 'init'. This is especially relevant
3233     // to the receiver, as the corresponding symbol is usually not referenced
3234     // after the call.
3235     if (Msg->getMethodFamily() == OMF_init) {
3236       EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
3237       return true;
3238     }
3239 
3240     // Otherwise, assume that the method does not free memory.
3241     // Most framework methods do not free memory.
3242     return false;
3243   }
3244 
3245   // At this point the only thing left to handle is straight function calls.
3246   const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
3247   if (!FD)
3248     return true;
3249 
3250   // If it's one of the allocation functions we can reason about, we model
3251   // its behavior explicitly.
3252   if (isMemCall(*Call))
3253     return false;
3254 
3255   // If it's not a system call, assume it frees memory.
3256   if (!Call->isInSystemHeader())
3257     return true;
3258 
3259   // White list the system functions whose arguments escape.
3260   const IdentifierInfo *II = FD->getIdentifier();
3261   if (!II)
3262     return true;
3263   StringRef FName = II->getName();
3264 
3265   // White list the 'XXXNoCopy' CoreFoundation functions.
3266   // We specifically check these before
3267   if (FName.ends_with("NoCopy")) {
3268     // Look for the deallocator argument. We know that the memory ownership
3269     // is not transferred only if the deallocator argument is
3270     // 'kCFAllocatorNull'.
3271     for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
3272       const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
3273       if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
3274         StringRef DeallocatorName = DE->getFoundDecl()->getName();
3275         if (DeallocatorName == "kCFAllocatorNull")
3276           return false;
3277       }
3278     }
3279     return true;
3280   }
3281 
3282   // Associating streams with malloced buffers. The pointer can escape if
3283   // 'closefn' is specified (and if that function does free memory),
3284   // but it will not if closefn is not specified.
3285   // Currently, we do not inspect the 'closefn' function (PR12101).
3286   if (FName == "funopen")
3287     if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
3288       return false;
3289 
3290   // Do not warn on pointers passed to 'setbuf' when used with std streams,
3291   // these leaks might be intentional when setting the buffer for stdio.
3292   // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
3293   if (FName == "setbuf" || FName =="setbuffer" ||
3294       FName == "setlinebuf" || FName == "setvbuf") {
3295     if (Call->getNumArgs() >= 1) {
3296       const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
3297       if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
3298         if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
3299           if (D->getCanonicalDecl()->getName().contains("std"))
3300             return true;
3301     }
3302   }
3303 
3304   // A bunch of other functions which either take ownership of a pointer or
3305   // wrap the result up in a struct or object, meaning it can be freed later.
3306   // (See RetainCountChecker.) Not all the parameters here are invalidated,
3307   // but the Malloc checker cannot differentiate between them. The right way
3308   // of doing this would be to implement a pointer escapes callback.
3309   if (FName == "CGBitmapContextCreate" ||
3310       FName == "CGBitmapContextCreateWithData" ||
3311       FName == "CVPixelBufferCreateWithBytes" ||
3312       FName == "CVPixelBufferCreateWithPlanarBytes" ||
3313       FName == "OSAtomicEnqueue") {
3314     return true;
3315   }
3316 
3317   if (FName == "postEvent" &&
3318       FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
3319     return true;
3320   }
3321 
3322   if (FName == "connectImpl" &&
3323       FD->getQualifiedNameAsString() == "QObject::connectImpl") {
3324     return true;
3325   }
3326 
3327   if (FName == "singleShotImpl" &&
3328       FD->getQualifiedNameAsString() == "QTimer::singleShotImpl") {
3329     return true;
3330   }
3331 
3332   // Handle cases where we know a buffer's /address/ can escape.
3333   // Note that the above checks handle some special cases where we know that
3334   // even though the address escapes, it's still our responsibility to free the
3335   // buffer.
3336   if (Call->argumentsMayEscape())
3337     return true;
3338 
3339   // Otherwise, assume that the function does not free memory.
3340   // Most system calls do not free the memory.
3341   return false;
3342 }
3343 
3344 ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
3345                                              const InvalidatedSymbols &Escaped,
3346                                              const CallEvent *Call,
3347                                              PointerEscapeKind Kind) const {
3348   return checkPointerEscapeAux(State, Escaped, Call, Kind,
3349                                /*IsConstPointerEscape*/ false);
3350 }
3351 
3352 ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
3353                                               const InvalidatedSymbols &Escaped,
3354                                               const CallEvent *Call,
3355                                               PointerEscapeKind Kind) const {
3356   // If a const pointer escapes, it may not be freed(), but it could be deleted.
3357   return checkPointerEscapeAux(State, Escaped, Call, Kind,
3358                                /*IsConstPointerEscape*/ true);
3359 }
3360 
3361 static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
3362   return (RS->getAllocationFamily() == AF_CXXNewArray ||
3363           RS->getAllocationFamily() == AF_CXXNew);
3364 }
3365 
3366 ProgramStateRef MallocChecker::checkPointerEscapeAux(
3367     ProgramStateRef State, const InvalidatedSymbols &Escaped,
3368     const CallEvent *Call, PointerEscapeKind Kind,
3369     bool IsConstPointerEscape) const {
3370   // If we know that the call does not free memory, or we want to process the
3371   // call later, keep tracking the top level arguments.
3372   SymbolRef EscapingSymbol = nullptr;
3373   if (Kind == PSK_DirectEscapeOnCall &&
3374       !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
3375                                                     EscapingSymbol) &&
3376       !EscapingSymbol) {
3377     return State;
3378   }
3379 
3380   for (SymbolRef sym : Escaped) {
3381     if (EscapingSymbol && EscapingSymbol != sym)
3382       continue;
3383 
3384     if (const RefState *RS = State->get<RegionState>(sym))
3385       if (RS->isAllocated() || RS->isAllocatedOfSizeZero())
3386         if (!IsConstPointerEscape || checkIfNewOrNewArrayFamily(RS))
3387           State = State->set<RegionState>(sym, RefState::getEscaped(RS));
3388   }
3389   return State;
3390 }
3391 
3392 bool MallocChecker::isArgZERO_SIZE_PTR(ProgramStateRef State, CheckerContext &C,
3393                                        SVal ArgVal) const {
3394   if (!KernelZeroSizePtrValue)
3395     KernelZeroSizePtrValue =
3396         tryExpandAsInteger("ZERO_SIZE_PTR", C.getPreprocessor());
3397 
3398   const llvm::APSInt *ArgValKnown =
3399       C.getSValBuilder().getKnownValue(State, ArgVal);
3400   return ArgValKnown && *KernelZeroSizePtrValue &&
3401          ArgValKnown->getSExtValue() == **KernelZeroSizePtrValue;
3402 }
3403 
3404 static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
3405                                          ProgramStateRef prevState) {
3406   ReallocPairsTy currMap = currState->get<ReallocPairs>();
3407   ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
3408 
3409   for (const ReallocPairsTy::value_type &Pair : prevMap) {
3410     SymbolRef sym = Pair.first;
3411     if (!currMap.lookup(sym))
3412       return sym;
3413   }
3414 
3415   return nullptr;
3416 }
3417 
3418 static bool isReferenceCountingPointerDestructor(const CXXDestructorDecl *DD) {
3419   if (const IdentifierInfo *II = DD->getParent()->getIdentifier()) {
3420     StringRef N = II->getName();
3421     if (N.contains_insensitive("ptr") || N.contains_insensitive("pointer")) {
3422       if (N.contains_insensitive("ref") || N.contains_insensitive("cnt") ||
3423           N.contains_insensitive("intrusive") ||
3424           N.contains_insensitive("shared")) {
3425         return true;
3426       }
3427     }
3428   }
3429   return false;
3430 }
3431 
3432 PathDiagnosticPieceRef MallocBugVisitor::VisitNode(const ExplodedNode *N,
3433                                                    BugReporterContext &BRC,
3434                                                    PathSensitiveBugReport &BR) {
3435   ProgramStateRef state = N->getState();
3436   ProgramStateRef statePrev = N->getFirstPred()->getState();
3437 
3438   const RefState *RSCurr = state->get<RegionState>(Sym);
3439   const RefState *RSPrev = statePrev->get<RegionState>(Sym);
3440 
3441   const Stmt *S = N->getStmtForDiagnostics();
3442   // When dealing with containers, we sometimes want to give a note
3443   // even if the statement is missing.
3444   if (!S && (!RSCurr || RSCurr->getAllocationFamily() != AF_InnerBuffer))
3445     return nullptr;
3446 
3447   const LocationContext *CurrentLC = N->getLocationContext();
3448 
3449   // If we find an atomic fetch_add or fetch_sub within the destructor in which
3450   // the pointer was released (before the release), this is likely a destructor
3451   // of a shared pointer.
3452   // Because we don't model atomics, and also because we don't know that the
3453   // original reference count is positive, we should not report use-after-frees
3454   // on objects deleted in such destructors. This can probably be improved
3455   // through better shared pointer modeling.
3456   if (ReleaseDestructorLC) {
3457     if (const auto *AE = dyn_cast<AtomicExpr>(S)) {
3458       AtomicExpr::AtomicOp Op = AE->getOp();
3459       if (Op == AtomicExpr::AO__c11_atomic_fetch_add ||
3460           Op == AtomicExpr::AO__c11_atomic_fetch_sub) {
3461         if (ReleaseDestructorLC == CurrentLC ||
3462             ReleaseDestructorLC->isParentOf(CurrentLC)) {
3463           BR.markInvalid(getTag(), S);
3464         }
3465       }
3466     }
3467   }
3468 
3469   // FIXME: We will eventually need to handle non-statement-based events
3470   // (__attribute__((cleanup))).
3471 
3472   // Find out if this is an interesting point and what is the kind.
3473   StringRef Msg;
3474   std::unique_ptr<StackHintGeneratorForSymbol> StackHint = nullptr;
3475   SmallString<256> Buf;
3476   llvm::raw_svector_ostream OS(Buf);
3477 
3478   if (Mode == Normal) {
3479     if (isAllocated(RSCurr, RSPrev, S)) {
3480       Msg = "Memory is allocated";
3481       StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3482           Sym, "Returned allocated memory");
3483     } else if (isReleased(RSCurr, RSPrev, S)) {
3484       const auto Family = RSCurr->getAllocationFamily();
3485       switch (Family) {
3486         case AF_Alloca:
3487         case AF_Malloc:
3488         case AF_CXXNew:
3489         case AF_CXXNewArray:
3490         case AF_IfNameIndex:
3491           Msg = "Memory is released";
3492           StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3493               Sym, "Returning; memory was released");
3494           break;
3495         case AF_InnerBuffer: {
3496           const MemRegion *ObjRegion =
3497               allocation_state::getContainerObjRegion(statePrev, Sym);
3498           const auto *TypedRegion = cast<TypedValueRegion>(ObjRegion);
3499           QualType ObjTy = TypedRegion->getValueType();
3500           OS << "Inner buffer of '" << ObjTy << "' ";
3501 
3502           if (N->getLocation().getKind() == ProgramPoint::PostImplicitCallKind) {
3503             OS << "deallocated by call to destructor";
3504             StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3505                 Sym, "Returning; inner buffer was deallocated");
3506           } else {
3507             OS << "reallocated by call to '";
3508             const Stmt *S = RSCurr->getStmt();
3509             if (const auto *MemCallE = dyn_cast<CXXMemberCallExpr>(S)) {
3510               OS << MemCallE->getMethodDecl()->getDeclName();
3511             } else if (const auto *OpCallE = dyn_cast<CXXOperatorCallExpr>(S)) {
3512               OS << OpCallE->getDirectCallee()->getDeclName();
3513             } else if (const auto *CallE = dyn_cast<CallExpr>(S)) {
3514               auto &CEMgr = BRC.getStateManager().getCallEventManager();
3515               CallEventRef<> Call =
3516                   CEMgr.getSimpleCall(CallE, state, CurrentLC, {nullptr, 0});
3517               if (const auto *D = dyn_cast_or_null<NamedDecl>(Call->getDecl()))
3518                 OS << D->getDeclName();
3519               else
3520                 OS << "unknown";
3521             }
3522             OS << "'";
3523             StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3524                 Sym, "Returning; inner buffer was reallocated");
3525           }
3526           Msg = OS.str();
3527           break;
3528         }
3529         case AF_None:
3530           llvm_unreachable("Unhandled allocation family!");
3531       }
3532 
3533       // See if we're releasing memory while inlining a destructor
3534       // (or one of its callees). This turns on various common
3535       // false positive suppressions.
3536       bool FoundAnyDestructor = false;
3537       for (const LocationContext *LC = CurrentLC; LC; LC = LC->getParent()) {
3538         if (const auto *DD = dyn_cast<CXXDestructorDecl>(LC->getDecl())) {
3539           if (isReferenceCountingPointerDestructor(DD)) {
3540             // This immediately looks like a reference-counting destructor.
3541             // We're bad at guessing the original reference count of the object,
3542             // so suppress the report for now.
3543             BR.markInvalid(getTag(), DD);
3544           } else if (!FoundAnyDestructor) {
3545             assert(!ReleaseDestructorLC &&
3546                    "There can be only one release point!");
3547             // Suspect that it's a reference counting pointer destructor.
3548             // On one of the next nodes might find out that it has atomic
3549             // reference counting operations within it (see the code above),
3550             // and if so, we'd conclude that it likely is a reference counting
3551             // pointer destructor.
3552             ReleaseDestructorLC = LC->getStackFrame();
3553             // It is unlikely that releasing memory is delegated to a destructor
3554             // inside a destructor of a shared pointer, because it's fairly hard
3555             // to pass the information that the pointer indeed needs to be
3556             // released into it. So we're only interested in the innermost
3557             // destructor.
3558             FoundAnyDestructor = true;
3559           }
3560         }
3561       }
3562     } else if (isRelinquished(RSCurr, RSPrev, S)) {
3563       Msg = "Memory ownership is transferred";
3564       StackHint = std::make_unique<StackHintGeneratorForSymbol>(Sym, "");
3565     } else if (hasReallocFailed(RSCurr, RSPrev, S)) {
3566       Mode = ReallocationFailed;
3567       Msg = "Reallocation failed";
3568       StackHint = std::make_unique<StackHintGeneratorForReallocationFailed>(
3569           Sym, "Reallocation failed");
3570 
3571       if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
3572         // Is it possible to fail two reallocs WITHOUT testing in between?
3573         assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
3574           "We only support one failed realloc at a time.");
3575         BR.markInteresting(sym);
3576         FailedReallocSymbol = sym;
3577       }
3578     }
3579 
3580   // We are in a special mode if a reallocation failed later in the path.
3581   } else if (Mode == ReallocationFailed) {
3582     assert(FailedReallocSymbol && "No symbol to look for.");
3583 
3584     // Is this is the first appearance of the reallocated symbol?
3585     if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
3586       // We're at the reallocation point.
3587       Msg = "Attempt to reallocate memory";
3588       StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3589           Sym, "Returned reallocated memory");
3590       FailedReallocSymbol = nullptr;
3591       Mode = Normal;
3592     }
3593   }
3594 
3595   if (Msg.empty()) {
3596     assert(!StackHint);
3597     return nullptr;
3598   }
3599 
3600   assert(StackHint);
3601 
3602   // Generate the extra diagnostic.
3603   PathDiagnosticLocation Pos;
3604   if (!S) {
3605     assert(RSCurr->getAllocationFamily() == AF_InnerBuffer);
3606     auto PostImplCall = N->getLocation().getAs<PostImplicitCall>();
3607     if (!PostImplCall)
3608       return nullptr;
3609     Pos = PathDiagnosticLocation(PostImplCall->getLocation(),
3610                                  BRC.getSourceManager());
3611   } else {
3612     Pos = PathDiagnosticLocation(S, BRC.getSourceManager(),
3613                                  N->getLocationContext());
3614   }
3615 
3616   auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true);
3617   BR.addCallStackHint(P, std::move(StackHint));
3618   return P;
3619 }
3620 
3621 void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
3622                                const char *NL, const char *Sep) const {
3623 
3624   RegionStateTy RS = State->get<RegionState>();
3625 
3626   if (!RS.isEmpty()) {
3627     Out << Sep << "MallocChecker :" << NL;
3628     for (auto [Sym, Data] : RS) {
3629       const RefState *RefS = State->get<RegionState>(Sym);
3630       AllocationFamily Family = RefS->getAllocationFamily();
3631       std::optional<MallocChecker::CheckKind> CheckKind =
3632           getCheckIfTracked(Family);
3633       if (!CheckKind)
3634         CheckKind = getCheckIfTracked(Family, true);
3635 
3636       Sym->dumpToStream(Out);
3637       Out << " : ";
3638       Data.dump(Out);
3639       if (CheckKind)
3640         Out << " (" << CheckNames[*CheckKind].getName() << ")";
3641       Out << NL;
3642     }
3643   }
3644 }
3645 
3646 namespace clang {
3647 namespace ento {
3648 namespace allocation_state {
3649 
3650 ProgramStateRef
3651 markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin) {
3652   AllocationFamily Family = AF_InnerBuffer;
3653   return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin));
3654 }
3655 
3656 } // end namespace allocation_state
3657 } // end namespace ento
3658 } // end namespace clang
3659 
3660 // Intended to be used in InnerPointerChecker to register the part of
3661 // MallocChecker connected to it.
3662 void ento::registerInnerPointerCheckerAux(CheckerManager &mgr) {
3663   MallocChecker *checker = mgr.getChecker<MallocChecker>();
3664   checker->ChecksEnabled[MallocChecker::CK_InnerPointerChecker] = true;
3665   checker->CheckNames[MallocChecker::CK_InnerPointerChecker] =
3666       mgr.getCurrentCheckerName();
3667 }
3668 
3669 void ento::registerDynamicMemoryModeling(CheckerManager &mgr) {
3670   auto *checker = mgr.registerChecker<MallocChecker>();
3671   checker->ShouldIncludeOwnershipAnnotatedFunctions =
3672       mgr.getAnalyzerOptions().getCheckerBooleanOption(checker, "Optimistic");
3673   checker->ShouldRegisterNoOwnershipChangeVisitor =
3674       mgr.getAnalyzerOptions().getCheckerBooleanOption(
3675           checker, "AddNoOwnershipChangeNotes");
3676 }
3677 
3678 bool ento::shouldRegisterDynamicMemoryModeling(const CheckerManager &mgr) {
3679   return true;
3680 }
3681 
3682 #define REGISTER_CHECKER(name)                                                 \
3683   void ento::register##name(CheckerManager &mgr) {                             \
3684     MallocChecker *checker = mgr.getChecker<MallocChecker>();                  \
3685     checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
3686     checker->CheckNames[MallocChecker::CK_##name] =                            \
3687         mgr.getCurrentCheckerName();                                           \
3688   }                                                                            \
3689                                                                                \
3690   bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
3691 
3692 REGISTER_CHECKER(MallocChecker)
3693 REGISTER_CHECKER(NewDeleteChecker)
3694 REGISTER_CHECKER(NewDeleteLeaksChecker)
3695 REGISTER_CHECKER(MismatchedDeallocatorChecker)
3696