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