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