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