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