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