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