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