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