]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/StaticAnalyzer/Checkers/MallocChecker.cpp
Upgrade our copies of clang, llvm, lld, lldb, compiler-rt and libc++ to
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / StaticAnalyzer / Checkers / MallocChecker.cpp
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 = State->getSVal(FlagsEx, C.getLocationContext());
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 =
976       State->getSVal(Arg, C.getLocationContext()).getAs<DefinedSVal>();
977
978   if (!DefArgVal)
979     return State;
980
981   // Check if the allocation size is 0.
982   ProgramStateRef TrueState, FalseState;
983   SValBuilder &SvalBuilder = C.getSValBuilder();
984   DefinedSVal Zero =
985       SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
986
987   std::tie(TrueState, FalseState) =
988       State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
989
990   if (TrueState && !FalseState) {
991     SVal retVal = State->getSVal(E, C.getLocationContext());
992     SymbolRef Sym = retVal.getAsLocSymbol();
993     if (!Sym)
994       return State;
995
996     const RefState *RS = State->get<RegionState>(Sym);
997     if (RS) {
998       if (RS->isAllocated())
999         return TrueState->set<RegionState>(Sym,
1000                                           RefState::getAllocatedOfSizeZero(RS));
1001       else
1002         return State;
1003     } else {
1004       // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1005       // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1006       // tracked. Add zero-reallocated Sym to the state to catch references
1007       // to zero-allocated memory.
1008       return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1009     }
1010   }
1011
1012   // Assume the value is non-zero going forward.
1013   assert(FalseState);
1014   return FalseState;
1015 }
1016
1017 static QualType getDeepPointeeType(QualType T) {
1018   QualType Result = T, PointeeType = T->getPointeeType();
1019   while (!PointeeType.isNull()) {
1020     Result = PointeeType;
1021     PointeeType = PointeeType->getPointeeType();
1022   }
1023   return Result;
1024 }
1025
1026 static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
1027
1028   const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1029   if (!ConstructE)
1030     return false;
1031
1032   if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1033     return false;
1034
1035   const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1036
1037   // Iterate over the constructor parameters.
1038   for (const auto *CtorParam : CtorD->parameters()) {
1039
1040     QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1041     if (CtorParamPointeeT.isNull())
1042       continue;
1043
1044     CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1045
1046     if (CtorParamPointeeT->getAsCXXRecordDecl())
1047       return true;
1048   }
1049
1050   return false;
1051 }
1052
1053 void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
1054                                   CheckerContext &C) const {
1055
1056   if (NE->getNumPlacementArgs())
1057     for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
1058          E = NE->placement_arg_end(); I != E; ++I)
1059       if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
1060         checkUseAfterFree(Sym, C, *I);
1061
1062   if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
1063     return;
1064
1065   ParentMap &PM = C.getLocationContext()->getParentMap();
1066   if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
1067     return;
1068
1069   ProgramStateRef State = C.getState();
1070   // The return value from operator new is bound to a specified initialization
1071   // value (if any) and we don't want to loose this value. So we call
1072   // MallocUpdateRefState() instead of MallocMemAux() which breakes the
1073   // existing binding.
1074   State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
1075                                                            : AF_CXXNew);
1076   State = addExtentSize(C, NE, State);
1077   State = ProcessZeroAllocation(C, NE, 0, State);
1078   C.addTransition(State);
1079 }
1080
1081 // Sets the extent value of the MemRegion allocated by
1082 // new expression NE to its size in Bytes.
1083 //
1084 ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1085                                              const CXXNewExpr *NE,
1086                                              ProgramStateRef State) {
1087   if (!State)
1088     return nullptr;
1089   SValBuilder &svalBuilder = C.getSValBuilder();
1090   SVal ElementCount;
1091   const LocationContext *LCtx = C.getLocationContext();
1092   const SubRegion *Region;
1093   if (NE->isArray()) {
1094     const Expr *SizeExpr = NE->getArraySize();
1095     ElementCount = State->getSVal(SizeExpr, C.getLocationContext());
1096     // Store the extent size for the (symbolic)region
1097     // containing the elements.
1098     Region = (State->getSVal(NE, LCtx))
1099                  .getAsRegion()
1100                  ->getAs<SubRegion>()
1101                  ->getSuperRegion()
1102                  ->getAs<SubRegion>();
1103   } else {
1104     ElementCount = svalBuilder.makeIntVal(1, true);
1105     Region = (State->getSVal(NE, LCtx)).getAsRegion()->getAs<SubRegion>();
1106   }
1107   assert(Region);
1108
1109   // Set the region's extent equal to the Size in Bytes.
1110   QualType ElementType = NE->getAllocatedType();
1111   ASTContext &AstContext = C.getASTContext();
1112   CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1113
1114   if (ElementCount.getAs<NonLoc>()) {
1115     DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1116     // size in Bytes = ElementCount*TypeSize
1117     SVal SizeInBytes = svalBuilder.evalBinOpNN(
1118         State, BO_Mul, ElementCount.castAs<NonLoc>(),
1119         svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1120         svalBuilder.getArrayIndexType());
1121     DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1122         State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1123     State = State->assume(extentMatchesSize, true);
1124   }
1125   return State;
1126 }
1127
1128 void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
1129                                  CheckerContext &C) const {
1130
1131   if (!ChecksEnabled[CK_NewDeleteChecker])
1132     if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1133       checkUseAfterFree(Sym, C, DE->getArgument());
1134
1135   if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
1136     return;
1137
1138   ProgramStateRef State = C.getState();
1139   bool ReleasedAllocated;
1140   State = FreeMemAux(C, DE->getArgument(), DE, State,
1141                      /*Hold*/false, ReleasedAllocated);
1142
1143   C.addTransition(State);
1144 }
1145
1146 static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1147   // If the first selector piece is one of the names below, assume that the
1148   // object takes ownership of the memory, promising to eventually deallocate it
1149   // with free().
1150   // Ex:  [NSData dataWithBytesNoCopy:bytes length:10];
1151   // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1152   StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
1153   return FirstSlot == "dataWithBytesNoCopy" ||
1154          FirstSlot == "initWithBytesNoCopy" ||
1155          FirstSlot == "initWithCharactersNoCopy";
1156 }
1157
1158 static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1159   Selector S = Call.getSelector();
1160
1161   // FIXME: We should not rely on fully-constrained symbols being folded.
1162   for (unsigned i = 1; i < S.getNumArgs(); ++i)
1163     if (S.getNameForSlot(i).equals("freeWhenDone"))
1164       return !Call.getArgSVal(i).isZeroConstant();
1165
1166   return None;
1167 }
1168
1169 void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1170                                          CheckerContext &C) const {
1171   if (C.wasInlined)
1172     return;
1173
1174   if (!isKnownDeallocObjCMethodName(Call))
1175     return;
1176
1177   if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1178     if (!*FreeWhenDone)
1179       return;
1180
1181   bool ReleasedAllocatedMemory;
1182   ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1183                                      Call.getOriginExpr(), C.getState(),
1184                                      /*Hold=*/true, ReleasedAllocatedMemory,
1185                                      /*RetNullOnFailure=*/true);
1186
1187   C.addTransition(State);
1188 }
1189
1190 ProgramStateRef
1191 MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
1192                                     const OwnershipAttr *Att,
1193                                     ProgramStateRef State) const {
1194   if (!State)
1195     return nullptr;
1196
1197   if (Att->getModule() != II_malloc)
1198     return nullptr;
1199
1200   OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
1201   if (I != E) {
1202     return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
1203   }
1204   return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1205 }
1206
1207 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1208                                             const CallExpr *CE,
1209                                             const Expr *SizeEx, SVal Init,
1210                                             ProgramStateRef State,
1211                                             AllocationFamily Family) {
1212   if (!State)
1213     return nullptr;
1214
1215   return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
1216                       Init, State, Family);
1217 }
1218
1219 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1220                                            const CallExpr *CE,
1221                                            SVal Size, SVal Init,
1222                                            ProgramStateRef State,
1223                                            AllocationFamily Family) {
1224   if (!State)
1225     return nullptr;
1226
1227   // We expect the malloc functions to return a pointer.
1228   if (!Loc::isLocType(CE->getType()))
1229     return nullptr;
1230
1231   // Bind the return value to the symbolic value from the heap region.
1232   // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1233   // side effects other than what we model here.
1234   unsigned Count = C.blockCount();
1235   SValBuilder &svalBuilder = C.getSValBuilder();
1236   const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1237   DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1238       .castAs<DefinedSVal>();
1239   State = State->BindExpr(CE, C.getLocationContext(), RetVal);
1240
1241   // Fill the region with the initialization value.
1242   State = State->bindDefault(RetVal, Init, LCtx);
1243
1244   // Set the region's extent equal to the Size parameter.
1245   const SymbolicRegion *R =
1246       dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
1247   if (!R)
1248     return nullptr;
1249   if (Optional<DefinedOrUnknownSVal> DefinedSize =
1250           Size.getAs<DefinedOrUnknownSVal>()) {
1251     SValBuilder &svalBuilder = C.getSValBuilder();
1252     DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
1253     DefinedOrUnknownSVal extentMatchesSize =
1254         svalBuilder.evalEQ(State, Extent, *DefinedSize);
1255
1256     State = State->assume(extentMatchesSize, true);
1257     assert(State);
1258   }
1259
1260   return MallocUpdateRefState(C, CE, State, Family);
1261 }
1262
1263 ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
1264                                                     const Expr *E,
1265                                                     ProgramStateRef State,
1266                                                     AllocationFamily Family) {
1267   if (!State)
1268     return nullptr;
1269
1270   // Get the return value.
1271   SVal retVal = State->getSVal(E, C.getLocationContext());
1272
1273   // We expect the malloc functions to return a pointer.
1274   if (!retVal.getAs<Loc>())
1275     return nullptr;
1276
1277   SymbolRef Sym = retVal.getAsLocSymbol();
1278   assert(Sym);
1279
1280   // Set the symbol's state to Allocated.
1281   return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1282 }
1283
1284 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1285                                            const CallExpr *CE,
1286                                            const OwnershipAttr *Att,
1287                                            ProgramStateRef State) const {
1288   if (!State)
1289     return nullptr;
1290
1291   if (Att->getModule() != II_malloc)
1292     return nullptr;
1293
1294   bool ReleasedAllocated = false;
1295
1296   for (const auto &Arg : Att->args()) {
1297     ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
1298                                Att->getOwnKind() == OwnershipAttr::Holds,
1299                                ReleasedAllocated);
1300     if (StateI)
1301       State = StateI;
1302   }
1303   return State;
1304 }
1305
1306 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1307                                           const CallExpr *CE,
1308                                           ProgramStateRef State,
1309                                           unsigned Num,
1310                                           bool Hold,
1311                                           bool &ReleasedAllocated,
1312                                           bool ReturnsNullOnFailure) const {
1313   if (!State)
1314     return nullptr;
1315
1316   if (CE->getNumArgs() < (Num + 1))
1317     return nullptr;
1318
1319   return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
1320                     ReleasedAllocated, ReturnsNullOnFailure);
1321 }
1322
1323 /// Checks if the previous call to free on the given symbol failed - if free
1324 /// failed, returns true. Also, returns the corresponding return value symbol.
1325 static bool didPreviousFreeFail(ProgramStateRef State,
1326                                 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
1327   const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1328   if (Ret) {
1329     assert(*Ret && "We should not store the null return symbol");
1330     ConstraintManager &CMgr = State->getConstraintManager();
1331     ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1332     RetStatusSymbol = *Ret;
1333     return FreeFailed.isConstrainedTrue();
1334   }
1335   return false;
1336 }
1337
1338 AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
1339                                                     const Stmt *S) const {
1340   if (!S)
1341     return AF_None;
1342
1343   if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1344     const FunctionDecl *FD = C.getCalleeDecl(CE);
1345
1346     if (!FD)
1347       FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1348
1349     ASTContext &Ctx = C.getASTContext();
1350
1351     if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
1352       return AF_Malloc;
1353
1354     if (isStandardNewDelete(FD, Ctx)) {
1355       OverloadedOperatorKind Kind = FD->getOverloadedOperator();
1356       if (Kind == OO_New || Kind == OO_Delete)
1357         return AF_CXXNew;
1358       else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
1359         return AF_CXXNewArray;
1360     }
1361
1362     if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1363       return AF_IfNameIndex;
1364
1365     if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1366       return AF_Alloca;
1367
1368     return AF_None;
1369   }
1370
1371   if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1372     return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1373
1374   if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
1375     return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1376
1377   if (isa<ObjCMessageExpr>(S))
1378     return AF_Malloc;
1379
1380   return AF_None;
1381 }
1382
1383 bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1384                                           const Expr *E) const {
1385   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1386     // FIXME: This doesn't handle indirect calls.
1387     const FunctionDecl *FD = CE->getDirectCallee();
1388     if (!FD)
1389       return false;
1390
1391     os << *FD;
1392     if (!FD->isOverloadedOperator())
1393       os << "()";
1394     return true;
1395   }
1396
1397   if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1398     if (Msg->isInstanceMessage())
1399       os << "-";
1400     else
1401       os << "+";
1402     Msg->getSelector().print(os);
1403     return true;
1404   }
1405
1406   if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1407     os << "'"
1408        << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1409        << "'";
1410     return true;
1411   }
1412
1413   if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1414     os << "'"
1415        << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1416        << "'";
1417     return true;
1418   }
1419
1420   return false;
1421 }
1422
1423 void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1424                                            const Expr *E) const {
1425   AllocationFamily Family = getAllocationFamily(C, E);
1426
1427   switch(Family) {
1428     case AF_Malloc: os << "malloc()"; return;
1429     case AF_CXXNew: os << "'new'"; return;
1430     case AF_CXXNewArray: os << "'new[]'"; return;
1431     case AF_IfNameIndex: os << "'if_nameindex()'"; return;
1432     case AF_Alloca:
1433     case AF_None: llvm_unreachable("not a deallocation expression");
1434   }
1435 }
1436
1437 void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1438                                              AllocationFamily Family) const {
1439   switch(Family) {
1440     case AF_Malloc: os << "free()"; return;
1441     case AF_CXXNew: os << "'delete'"; return;
1442     case AF_CXXNewArray: os << "'delete[]'"; return;
1443     case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
1444     case AF_Alloca:
1445     case AF_None: llvm_unreachable("suspicious argument");
1446   }
1447 }
1448
1449 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1450                                           const Expr *ArgExpr,
1451                                           const Expr *ParentExpr,
1452                                           ProgramStateRef State,
1453                                           bool Hold,
1454                                           bool &ReleasedAllocated,
1455                                           bool ReturnsNullOnFailure) const {
1456
1457   if (!State)
1458     return nullptr;
1459
1460   SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
1461   if (!ArgVal.getAs<DefinedOrUnknownSVal>())
1462     return nullptr;
1463   DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1464
1465   // Check for null dereferences.
1466   if (!location.getAs<Loc>())
1467     return nullptr;
1468
1469   // The explicit NULL case, no operation is performed.
1470   ProgramStateRef notNullState, nullState;
1471   std::tie(notNullState, nullState) = State->assume(location);
1472   if (nullState && !notNullState)
1473     return nullptr;
1474
1475   // Unknown values could easily be okay
1476   // Undefined values are handled elsewhere
1477   if (ArgVal.isUnknownOrUndef())
1478     return nullptr;
1479
1480   const MemRegion *R = ArgVal.getAsRegion();
1481
1482   // Nonlocs can't be freed, of course.
1483   // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1484   if (!R) {
1485     ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1486     return nullptr;
1487   }
1488
1489   R = R->StripCasts();
1490
1491   // Blocks might show up as heap data, but should not be free()d
1492   if (isa<BlockDataRegion>(R)) {
1493     ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1494     return nullptr;
1495   }
1496
1497   const MemSpaceRegion *MS = R->getMemorySpace();
1498
1499   // Parameters, locals, statics, globals, and memory returned by
1500   // __builtin_alloca() shouldn't be freed.
1501   if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1502     // FIXME: at the time this code was written, malloc() regions were
1503     // represented by conjured symbols, which are all in UnknownSpaceRegion.
1504     // This means that there isn't actually anything from HeapSpaceRegion
1505     // that should be freed, even though we allow it here.
1506     // Of course, free() can work on memory allocated outside the current
1507     // function, so UnknownSpaceRegion is always a possibility.
1508     // False negatives are better than false positives.
1509
1510     if (isa<AllocaRegion>(R))
1511       ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1512     else
1513       ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1514
1515     return nullptr;
1516   }
1517
1518   const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1519   // Various cases could lead to non-symbol values here.
1520   // For now, ignore them.
1521   if (!SrBase)
1522     return nullptr;
1523
1524   SymbolRef SymBase = SrBase->getSymbol();
1525   const RefState *RsBase = State->get<RegionState>(SymBase);
1526   SymbolRef PreviousRetStatusSymbol = nullptr;
1527
1528   if (RsBase) {
1529
1530     // Memory returned by alloca() shouldn't be freed.
1531     if (RsBase->getAllocationFamily() == AF_Alloca) {
1532       ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1533       return nullptr;
1534     }
1535
1536     // Check for double free first.
1537     if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
1538         !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1539       ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1540                        SymBase, PreviousRetStatusSymbol);
1541       return nullptr;
1542
1543     // If the pointer is allocated or escaped, but we are now trying to free it,
1544     // check that the call to free is proper.
1545     } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
1546                RsBase->isEscaped()) {
1547
1548       // Check if an expected deallocation function matches the real one.
1549       bool DeallocMatchesAlloc =
1550         RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1551       if (!DeallocMatchesAlloc) {
1552         ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
1553                                 ParentExpr, RsBase, SymBase, Hold);
1554         return nullptr;
1555       }
1556
1557       // Check if the memory location being freed is the actual location
1558       // allocated, or an offset.
1559       RegionOffset Offset = R->getAsOffset();
1560       if (Offset.isValid() &&
1561           !Offset.hasSymbolicOffset() &&
1562           Offset.getOffset() != 0) {
1563         const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1564         ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1565                          AllocExpr);
1566         return nullptr;
1567       }
1568     }
1569   }
1570
1571   if (SymBase->getType()->isFunctionPointerType()) {
1572     ReportFunctionPointerFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1573     return nullptr;
1574   }
1575
1576   ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
1577                                               RsBase->isAllocatedOfSizeZero());
1578
1579   // Clean out the info on previous call to free return info.
1580   State = State->remove<FreeReturnValue>(SymBase);
1581
1582   // Keep track of the return value. If it is NULL, we will know that free
1583   // failed.
1584   if (ReturnsNullOnFailure) {
1585     SVal RetVal = C.getSVal(ParentExpr);
1586     SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1587     if (RetStatusSymbol) {
1588       C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1589       State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
1590     }
1591   }
1592
1593   AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1594                                    : getAllocationFamily(C, ParentExpr);
1595   // Normal free.
1596   if (Hold)
1597     return State->set<RegionState>(SymBase,
1598                                    RefState::getRelinquished(Family,
1599                                                              ParentExpr));
1600
1601   return State->set<RegionState>(SymBase,
1602                                  RefState::getReleased(Family, ParentExpr));
1603 }
1604
1605 Optional<MallocChecker::CheckKind>
1606 MallocChecker::getCheckIfTracked(AllocationFamily Family,
1607                                  bool IsALeakCheck) const {
1608   switch (Family) {
1609   case AF_Malloc:
1610   case AF_Alloca:
1611   case AF_IfNameIndex: {
1612     if (ChecksEnabled[CK_MallocChecker])
1613       return CK_MallocChecker;
1614
1615     return Optional<MallocChecker::CheckKind>();
1616   }
1617   case AF_CXXNew:
1618   case AF_CXXNewArray: {
1619     if (IsALeakCheck) {
1620       if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1621         return CK_NewDeleteLeaksChecker;
1622     }
1623     else {
1624       if (ChecksEnabled[CK_NewDeleteChecker])
1625         return CK_NewDeleteChecker;
1626     }
1627     return Optional<MallocChecker::CheckKind>();
1628   }
1629   case AF_None: {
1630     llvm_unreachable("no family");
1631   }
1632   }
1633   llvm_unreachable("unhandled family");
1634 }
1635
1636 Optional<MallocChecker::CheckKind>
1637 MallocChecker::getCheckIfTracked(CheckerContext &C,
1638                                  const Stmt *AllocDeallocStmt,
1639                                  bool IsALeakCheck) const {
1640   return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1641                            IsALeakCheck);
1642 }
1643
1644 Optional<MallocChecker::CheckKind>
1645 MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1646                                  bool IsALeakCheck) const {
1647   if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1648     return CK_MallocChecker;
1649
1650   const RefState *RS = C.getState()->get<RegionState>(Sym);
1651   assert(RS);
1652   return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
1653 }
1654
1655 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
1656   if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
1657     os << "an integer (" << IntVal->getValue() << ")";
1658   else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
1659     os << "a constant address (" << ConstAddr->getValue() << ")";
1660   else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
1661     os << "the address of the label '" << Label->getLabel()->getName() << "'";
1662   else
1663     return false;
1664
1665   return true;
1666 }
1667
1668 bool MallocChecker::SummarizeRegion(raw_ostream &os,
1669                                     const MemRegion *MR) {
1670   switch (MR->getKind()) {
1671   case MemRegion::FunctionCodeRegionKind: {
1672     const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
1673     if (FD)
1674       os << "the address of the function '" << *FD << '\'';
1675     else
1676       os << "the address of a function";
1677     return true;
1678   }
1679   case MemRegion::BlockCodeRegionKind:
1680     os << "block text";
1681     return true;
1682   case MemRegion::BlockDataRegionKind:
1683     // FIXME: where the block came from?
1684     os << "a block";
1685     return true;
1686   default: {
1687     const MemSpaceRegion *MS = MR->getMemorySpace();
1688
1689     if (isa<StackLocalsSpaceRegion>(MS)) {
1690       const VarRegion *VR = dyn_cast<VarRegion>(MR);
1691       const VarDecl *VD;
1692       if (VR)
1693         VD = VR->getDecl();
1694       else
1695         VD = nullptr;
1696
1697       if (VD)
1698         os << "the address of the local variable '" << VD->getName() << "'";
1699       else
1700         os << "the address of a local stack variable";
1701       return true;
1702     }
1703
1704     if (isa<StackArgumentsSpaceRegion>(MS)) {
1705       const VarRegion *VR = dyn_cast<VarRegion>(MR);
1706       const VarDecl *VD;
1707       if (VR)
1708         VD = VR->getDecl();
1709       else
1710         VD = nullptr;
1711
1712       if (VD)
1713         os << "the address of the parameter '" << VD->getName() << "'";
1714       else
1715         os << "the address of a parameter";
1716       return true;
1717     }
1718
1719     if (isa<GlobalsSpaceRegion>(MS)) {
1720       const VarRegion *VR = dyn_cast<VarRegion>(MR);
1721       const VarDecl *VD;
1722       if (VR)
1723         VD = VR->getDecl();
1724       else
1725         VD = nullptr;
1726
1727       if (VD) {
1728         if (VD->isStaticLocal())
1729           os << "the address of the static variable '" << VD->getName() << "'";
1730         else
1731           os << "the address of the global variable '" << VD->getName() << "'";
1732       } else
1733         os << "the address of a global variable";
1734       return true;
1735     }
1736
1737     return false;
1738   }
1739   }
1740 }
1741
1742 void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1743                                   SourceRange Range,
1744                                   const Expr *DeallocExpr) const {
1745
1746   if (!ChecksEnabled[CK_MallocChecker] &&
1747       !ChecksEnabled[CK_NewDeleteChecker])
1748     return;
1749
1750   Optional<MallocChecker::CheckKind> CheckKind =
1751       getCheckIfTracked(C, DeallocExpr);
1752   if (!CheckKind.hasValue())
1753     return;
1754
1755   if (ExplodedNode *N = C.generateErrorNode()) {
1756     if (!BT_BadFree[*CheckKind])
1757       BT_BadFree[*CheckKind].reset(new BugType(
1758           CheckNames[*CheckKind], "Bad free", categories::MemoryError));
1759
1760     SmallString<100> buf;
1761     llvm::raw_svector_ostream os(buf);
1762
1763     const MemRegion *MR = ArgVal.getAsRegion();
1764     while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1765       MR = ER->getSuperRegion();
1766
1767     os << "Argument to ";
1768     if (!printAllocDeallocName(os, C, DeallocExpr))
1769       os << "deallocator";
1770
1771     os << " is ";
1772     bool Summarized = MR ? SummarizeRegion(os, MR)
1773                          : SummarizeValue(os, ArgVal);
1774     if (Summarized)
1775       os << ", which is not memory allocated by ";
1776     else
1777       os << "not memory allocated by ";
1778
1779     printExpectedAllocName(os, C, DeallocExpr);
1780
1781     auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
1782     R->markInteresting(MR);
1783     R->addRange(Range);
1784     C.emitReport(std::move(R));
1785   }
1786 }
1787
1788 void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
1789                                      SourceRange Range) const {
1790
1791   Optional<MallocChecker::CheckKind> CheckKind;
1792
1793   if (ChecksEnabled[CK_MallocChecker])
1794     CheckKind = CK_MallocChecker;
1795   else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1796     CheckKind = CK_MismatchedDeallocatorChecker;
1797   else
1798     return;
1799
1800   if (ExplodedNode *N = C.generateErrorNode()) {
1801     if (!BT_FreeAlloca[*CheckKind])
1802       BT_FreeAlloca[*CheckKind].reset(new BugType(
1803           CheckNames[*CheckKind], "Free alloca()", categories::MemoryError));
1804
1805     auto R = llvm::make_unique<BugReport>(
1806         *BT_FreeAlloca[*CheckKind],
1807         "Memory allocated by alloca() should not be deallocated", N);
1808     R->markInteresting(ArgVal.getAsRegion());
1809     R->addRange(Range);
1810     C.emitReport(std::move(R));
1811   }
1812 }
1813
1814 void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1815                                             SourceRange Range,
1816                                             const Expr *DeallocExpr,
1817                                             const RefState *RS,
1818                                             SymbolRef Sym,
1819                                             bool OwnershipTransferred) const {
1820
1821   if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
1822     return;
1823
1824   if (ExplodedNode *N = C.generateErrorNode()) {
1825     if (!BT_MismatchedDealloc)
1826       BT_MismatchedDealloc.reset(
1827           new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1828                       "Bad deallocator", categories::MemoryError));
1829
1830     SmallString<100> buf;
1831     llvm::raw_svector_ostream os(buf);
1832
1833     const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1834     SmallString<20> AllocBuf;
1835     llvm::raw_svector_ostream AllocOs(AllocBuf);
1836     SmallString<20> DeallocBuf;
1837     llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1838
1839     if (OwnershipTransferred) {
1840       if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1841         os << DeallocOs.str() << " cannot";
1842       else
1843         os << "Cannot";
1844
1845       os << " take ownership of memory";
1846
1847       if (printAllocDeallocName(AllocOs, C, AllocExpr))
1848         os << " allocated by " << AllocOs.str();
1849     } else {
1850       os << "Memory";
1851       if (printAllocDeallocName(AllocOs, C, AllocExpr))
1852         os << " allocated by " << AllocOs.str();
1853
1854       os << " should be deallocated by ";
1855         printExpectedDeallocName(os, RS->getAllocationFamily());
1856
1857       if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1858         os << ", not " << DeallocOs.str();
1859     }
1860
1861     auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
1862     R->markInteresting(Sym);
1863     R->addRange(Range);
1864     R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1865     C.emitReport(std::move(R));
1866   }
1867 }
1868
1869 void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
1870                                      SourceRange Range, const Expr *DeallocExpr,
1871                                      const Expr *AllocExpr) const {
1872
1873
1874   if (!ChecksEnabled[CK_MallocChecker] &&
1875       !ChecksEnabled[CK_NewDeleteChecker])
1876     return;
1877
1878   Optional<MallocChecker::CheckKind> CheckKind =
1879       getCheckIfTracked(C, AllocExpr);
1880   if (!CheckKind.hasValue())
1881     return;
1882
1883   ExplodedNode *N = C.generateErrorNode();
1884   if (!N)
1885     return;
1886
1887   if (!BT_OffsetFree[*CheckKind])
1888     BT_OffsetFree[*CheckKind].reset(new BugType(
1889         CheckNames[*CheckKind], "Offset free", categories::MemoryError));
1890
1891   SmallString<100> buf;
1892   llvm::raw_svector_ostream os(buf);
1893   SmallString<20> AllocNameBuf;
1894   llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
1895
1896   const MemRegion *MR = ArgVal.getAsRegion();
1897   assert(MR && "Only MemRegion based symbols can have offset free errors");
1898
1899   RegionOffset Offset = MR->getAsOffset();
1900   assert((Offset.isValid() &&
1901           !Offset.hasSymbolicOffset() &&
1902           Offset.getOffset() != 0) &&
1903          "Only symbols with a valid offset can have offset free errors");
1904
1905   int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1906
1907   os << "Argument to ";
1908   if (!printAllocDeallocName(os, C, DeallocExpr))
1909     os << "deallocator";
1910   os << " is offset by "
1911      << offsetBytes
1912      << " "
1913      << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
1914      << " from the start of ";
1915   if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1916     os << "memory allocated by " << AllocNameOs.str();
1917   else
1918     os << "allocated memory";
1919
1920   auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
1921   R->markInteresting(MR->getBaseRegion());
1922   R->addRange(Range);
1923   C.emitReport(std::move(R));
1924 }
1925
1926 void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1927                                        SymbolRef Sym) const {
1928
1929   if (!ChecksEnabled[CK_MallocChecker] &&
1930       !ChecksEnabled[CK_NewDeleteChecker])
1931     return;
1932
1933   Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1934   if (!CheckKind.hasValue())
1935     return;
1936
1937   if (ExplodedNode *N = C.generateErrorNode()) {
1938     if (!BT_UseFree[*CheckKind])
1939       BT_UseFree[*CheckKind].reset(new BugType(
1940           CheckNames[*CheckKind], "Use-after-free", categories::MemoryError));
1941
1942     auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1943                                          "Use of memory after it is freed", N);
1944
1945     R->markInteresting(Sym);
1946     R->addRange(Range);
1947     R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1948     C.emitReport(std::move(R));
1949   }
1950 }
1951
1952 void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1953                                      bool Released, SymbolRef Sym,
1954                                      SymbolRef PrevSym) const {
1955
1956   if (!ChecksEnabled[CK_MallocChecker] &&
1957       !ChecksEnabled[CK_NewDeleteChecker])
1958     return;
1959
1960   Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1961   if (!CheckKind.hasValue())
1962     return;
1963
1964   if (ExplodedNode *N = C.generateErrorNode()) {
1965     if (!BT_DoubleFree[*CheckKind])
1966       BT_DoubleFree[*CheckKind].reset(new BugType(
1967           CheckNames[*CheckKind], "Double free", categories::MemoryError));
1968
1969     auto R = llvm::make_unique<BugReport>(
1970         *BT_DoubleFree[*CheckKind],
1971         (Released ? "Attempt to free released memory"
1972                   : "Attempt to free non-owned memory"),
1973         N);
1974     R->addRange(Range);
1975     R->markInteresting(Sym);
1976     if (PrevSym)
1977       R->markInteresting(PrevSym);
1978     R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1979     C.emitReport(std::move(R));
1980   }
1981 }
1982
1983 void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1984
1985   if (!ChecksEnabled[CK_NewDeleteChecker])
1986     return;
1987
1988   Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1989   if (!CheckKind.hasValue())
1990     return;
1991
1992   if (ExplodedNode *N = C.generateErrorNode()) {
1993     if (!BT_DoubleDelete)
1994       BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1995                                         "Double delete",
1996                                         categories::MemoryError));
1997
1998     auto R = llvm::make_unique<BugReport>(
1999         *BT_DoubleDelete, "Attempt to delete released memory", N);
2000
2001     R->markInteresting(Sym);
2002     R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2003     C.emitReport(std::move(R));
2004   }
2005 }
2006
2007 void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
2008                                            SourceRange Range,
2009                                            SymbolRef Sym) const {
2010
2011   if (!ChecksEnabled[CK_MallocChecker] &&
2012       !ChecksEnabled[CK_NewDeleteChecker])
2013     return;
2014
2015   Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2016
2017   if (!CheckKind.hasValue())
2018     return;
2019
2020   if (ExplodedNode *N = C.generateErrorNode()) {
2021     if (!BT_UseZerroAllocated[*CheckKind])
2022       BT_UseZerroAllocated[*CheckKind].reset(
2023           new BugType(CheckNames[*CheckKind], "Use of zero allocated",
2024                       categories::MemoryError));
2025
2026     auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
2027                                          "Use of zero-allocated memory", N);
2028
2029     R->addRange(Range);
2030     if (Sym) {
2031       R->markInteresting(Sym);
2032       R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2033     }
2034     C.emitReport(std::move(R));
2035   }
2036 }
2037
2038 void MallocChecker::ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
2039                                               SourceRange Range,
2040                                               const Expr *FreeExpr) const {
2041   if (!ChecksEnabled[CK_MallocChecker])
2042     return;
2043
2044   Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, FreeExpr);
2045   if (!CheckKind.hasValue())
2046     return;
2047
2048   if (ExplodedNode *N = C.generateErrorNode()) {
2049     if (!BT_BadFree[*CheckKind])
2050       BT_BadFree[*CheckKind].reset(
2051           new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
2052
2053     SmallString<100> Buf;
2054     llvm::raw_svector_ostream Os(Buf);
2055
2056     const MemRegion *MR = ArgVal.getAsRegion();
2057     while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2058       MR = ER->getSuperRegion();
2059
2060     Os << "Argument to ";
2061     if (!printAllocDeallocName(Os, C, FreeExpr))
2062       Os << "deallocator";
2063
2064     Os << " is a function pointer";
2065
2066     auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], Os.str(), N);
2067     R->markInteresting(MR);
2068     R->addRange(Range);
2069     C.emitReport(std::move(R));
2070   }
2071 }
2072
2073 ProgramStateRef MallocChecker::ReallocMemAux(CheckerContext &C,
2074                                              const CallExpr *CE,
2075                                              bool FreesOnFail,
2076                                              ProgramStateRef State,
2077                                              bool SuffixWithN) const {
2078   if (!State)
2079     return nullptr;
2080
2081   if (SuffixWithN && CE->getNumArgs() < 3)
2082     return nullptr;
2083   else if (CE->getNumArgs() < 2)
2084     return nullptr;
2085
2086   const Expr *arg0Expr = CE->getArg(0);
2087   const LocationContext *LCtx = C.getLocationContext();
2088   SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
2089   if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
2090     return nullptr;
2091   DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
2092
2093   SValBuilder &svalBuilder = C.getSValBuilder();
2094
2095   DefinedOrUnknownSVal PtrEQ =
2096     svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
2097
2098   // Get the size argument.
2099   const Expr *Arg1 = CE->getArg(1);
2100
2101   // Get the value of the size argument.
2102   SVal TotalSize = State->getSVal(Arg1, LCtx);
2103   if (SuffixWithN)
2104     TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2105   if (!TotalSize.getAs<DefinedOrUnknownSVal>())
2106     return nullptr;
2107
2108   // Compare the size argument to 0.
2109   DefinedOrUnknownSVal SizeZero =
2110     svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
2111                        svalBuilder.makeIntValWithPtrWidth(0, false));
2112
2113   ProgramStateRef StatePtrIsNull, StatePtrNotNull;
2114   std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
2115   ProgramStateRef StateSizeIsZero, StateSizeNotZero;
2116   std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
2117   // We only assume exceptional states if they are definitely true; if the
2118   // state is under-constrained, assume regular realloc behavior.
2119   bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2120   bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2121
2122   // If the ptr is NULL and the size is not 0, the call is equivalent to
2123   // malloc(size).
2124   if (PrtIsNull && !SizeIsZero) {
2125     ProgramStateRef stateMalloc = MallocMemAux(C, CE, TotalSize,
2126                                                UndefinedVal(), StatePtrIsNull);
2127     return stateMalloc;
2128   }
2129
2130   if (PrtIsNull && SizeIsZero)
2131     return State;
2132
2133   // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
2134   assert(!PrtIsNull);
2135   SymbolRef FromPtr = arg0Val.getAsSymbol();
2136   SVal RetVal = State->getSVal(CE, LCtx);
2137   SymbolRef ToPtr = RetVal.getAsSymbol();
2138   if (!FromPtr || !ToPtr)
2139     return nullptr;
2140
2141   bool ReleasedAllocated = false;
2142
2143   // If the size is 0, free the memory.
2144   if (SizeIsZero)
2145     if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
2146                                                false, ReleasedAllocated)){
2147       // The semantics of the return value are:
2148       // If size was equal to 0, either NULL or a pointer suitable to be passed
2149       // to free() is returned. We just free the input pointer and do not add
2150       // any constrains on the output pointer.
2151       return stateFree;
2152     }
2153
2154   // Default behavior.
2155   if (ProgramStateRef stateFree =
2156         FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
2157
2158     ProgramStateRef stateRealloc = MallocMemAux(C, CE, TotalSize,
2159                                                 UnknownVal(), stateFree);
2160     if (!stateRealloc)
2161       return nullptr;
2162
2163     ReallocPairKind Kind = RPToBeFreedAfterFailure;
2164     if (FreesOnFail)
2165       Kind = RPIsFreeOnFailure;
2166     else if (!ReleasedAllocated)
2167       Kind = RPDoNotTrackAfterFailure;
2168
2169     // Record the info about the reallocated symbol so that we could properly
2170     // process failed reallocation.
2171     stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
2172                                                    ReallocPair(FromPtr, Kind));
2173     // The reallocated symbol should stay alive for as long as the new symbol.
2174     C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
2175     return stateRealloc;
2176   }
2177   return nullptr;
2178 }
2179
2180 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
2181                                          ProgramStateRef State) {
2182   if (!State)
2183     return nullptr;
2184
2185   if (CE->getNumArgs() < 2)
2186     return nullptr;
2187
2188   SValBuilder &svalBuilder = C.getSValBuilder();
2189   SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
2190   SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
2191
2192   return MallocMemAux(C, CE, TotalSize, zeroVal, State);
2193 }
2194
2195 LeakInfo
2196 MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2197                                  CheckerContext &C) const {
2198   const LocationContext *LeakContext = N->getLocationContext();
2199   // Walk the ExplodedGraph backwards and find the first node that referred to
2200   // the tracked symbol.
2201   const ExplodedNode *AllocNode = N;
2202   const MemRegion *ReferenceRegion = nullptr;
2203
2204   while (N) {
2205     ProgramStateRef State = N->getState();
2206     if (!State->get<RegionState>(Sym))
2207       break;
2208
2209     // Find the most recent expression bound to the symbol in the current
2210     // context.
2211       if (!ReferenceRegion) {
2212         if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2213           SVal Val = State->getSVal(MR);
2214           if (Val.getAsLocSymbol() == Sym) {
2215             const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
2216             // Do not show local variables belonging to a function other than
2217             // where the error is reported.
2218             if (!VR ||
2219                 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2220               ReferenceRegion = MR;
2221           }
2222         }
2223       }
2224
2225     // Allocation node, is the last node in the current or parent context in
2226     // which the symbol was tracked.
2227     const LocationContext *NContext = N->getLocationContext();
2228     if (NContext == LeakContext ||
2229         NContext->isParentOf(LeakContext))
2230       AllocNode = N;
2231     N = N->pred_empty() ? nullptr : *(N->pred_begin());
2232   }
2233
2234   return LeakInfo(AllocNode, ReferenceRegion);
2235 }
2236
2237 void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2238                                CheckerContext &C) const {
2239
2240   if (!ChecksEnabled[CK_MallocChecker] &&
2241       !ChecksEnabled[CK_NewDeleteLeaksChecker])
2242     return;
2243
2244   const RefState *RS = C.getState()->get<RegionState>(Sym);
2245   assert(RS && "cannot leak an untracked symbol");
2246   AllocationFamily Family = RS->getAllocationFamily();
2247
2248   if (Family == AF_Alloca)
2249     return;
2250
2251   Optional<MallocChecker::CheckKind>
2252       CheckKind = getCheckIfTracked(Family, true);
2253
2254   if (!CheckKind.hasValue())
2255     return;
2256
2257   assert(N);
2258   if (!BT_Leak[*CheckKind]) {
2259     BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak",
2260                                           categories::MemoryError));
2261     // Leaks should not be reported if they are post-dominated by a sink:
2262     // (1) Sinks are higher importance bugs.
2263     // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2264     //     with __noreturn functions such as assert() or exit(). We choose not
2265     //     to report leaks on such paths.
2266     BT_Leak[*CheckKind]->setSuppressOnSink(true);
2267   }
2268
2269   // Most bug reports are cached at the location where they occurred.
2270   // With leaks, we want to unique them by the location where they were
2271   // allocated, and only report a single path.
2272   PathDiagnosticLocation LocUsedForUniqueing;
2273   const ExplodedNode *AllocNode = nullptr;
2274   const MemRegion *Region = nullptr;
2275   std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
2276
2277   const Stmt *AllocationStmt = PathDiagnosticLocation::getStmt(AllocNode);
2278   if (AllocationStmt)
2279     LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2280                                               C.getSourceManager(),
2281                                               AllocNode->getLocationContext());
2282
2283   SmallString<200> buf;
2284   llvm::raw_svector_ostream os(buf);
2285   if (Region && Region->canPrintPretty()) {
2286     os << "Potential leak of memory pointed to by ";
2287     Region->printPretty(os);
2288   } else {
2289     os << "Potential memory leak";
2290   }
2291
2292   auto R = llvm::make_unique<BugReport>(
2293       *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2294       AllocNode->getLocationContext()->getDecl());
2295   R->markInteresting(Sym);
2296   R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
2297   C.emitReport(std::move(R));
2298 }
2299
2300 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2301                                      CheckerContext &C) const
2302 {
2303   if (!SymReaper.hasDeadSymbols())
2304     return;
2305
2306   ProgramStateRef state = C.getState();
2307   RegionStateTy RS = state->get<RegionState>();
2308   RegionStateTy::Factory &F = state->get_context<RegionState>();
2309
2310   SmallVector<SymbolRef, 2> Errors;
2311   for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2312     if (SymReaper.isDead(I->first)) {
2313       if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
2314         Errors.push_back(I->first);
2315       // Remove the dead symbol from the map.
2316       RS = F.remove(RS, I->first);
2317
2318     }
2319   }
2320
2321   // Cleanup the Realloc Pairs Map.
2322   ReallocPairsTy RP = state->get<ReallocPairs>();
2323   for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2324     if (SymReaper.isDead(I->first) ||
2325         SymReaper.isDead(I->second.ReallocatedSym)) {
2326       state = state->remove<ReallocPairs>(I->first);
2327     }
2328   }
2329
2330   // Cleanup the FreeReturnValue Map.
2331   FreeReturnValueTy FR = state->get<FreeReturnValue>();
2332   for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2333     if (SymReaper.isDead(I->first) ||
2334         SymReaper.isDead(I->second)) {
2335       state = state->remove<FreeReturnValue>(I->first);
2336     }
2337   }
2338
2339   // Generate leak node.
2340   ExplodedNode *N = C.getPredecessor();
2341   if (!Errors.empty()) {
2342     static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
2343     N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2344     if (N) {
2345       for (SmallVectorImpl<SymbolRef>::iterator
2346            I = Errors.begin(), E = Errors.end(); I != E; ++I) {
2347         reportLeak(*I, N, C);
2348       }
2349     }
2350   }
2351
2352   C.addTransition(state->set<RegionState>(RS), N);
2353 }
2354
2355 void MallocChecker::checkPreCall(const CallEvent &Call,
2356                                  CheckerContext &C) const {
2357
2358   if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2359     SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2360     if (!Sym || checkDoubleDelete(Sym, C))
2361       return;
2362   }
2363
2364   // We will check for double free in the post visit.
2365   if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2366     const FunctionDecl *FD = FC->getDecl();
2367     if (!FD)
2368       return;
2369
2370     ASTContext &Ctx = C.getASTContext();
2371     if (ChecksEnabled[CK_MallocChecker] &&
2372         (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2373          isCMemFunction(FD, Ctx, AF_IfNameIndex,
2374                         MemoryOperationKind::MOK_Free)))
2375       return;
2376
2377     if (ChecksEnabled[CK_NewDeleteChecker] &&
2378         isStandardNewDelete(FD, Ctx))
2379       return;
2380   }
2381
2382   // Check if the callee of a method is deleted.
2383   if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2384     SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2385     if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2386       return;
2387   }
2388
2389   // Check arguments for being used after free.
2390   for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2391     SVal ArgSVal = Call.getArgSVal(I);
2392     if (ArgSVal.getAs<Loc>()) {
2393       SymbolRef Sym = ArgSVal.getAsSymbol();
2394       if (!Sym)
2395         continue;
2396       if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2397         return;
2398     }
2399   }
2400 }
2401
2402 void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2403   const Expr *E = S->getRetValue();
2404   if (!E)
2405     return;
2406
2407   // Check if we are returning a symbol.
2408   ProgramStateRef State = C.getState();
2409   SVal RetVal = State->getSVal(E, C.getLocationContext());
2410   SymbolRef Sym = RetVal.getAsSymbol();
2411   if (!Sym)
2412     // If we are returning a field of the allocated struct or an array element,
2413     // the callee could still free the memory.
2414     // TODO: This logic should be a part of generic symbol escape callback.
2415     if (const MemRegion *MR = RetVal.getAsRegion())
2416       if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2417         if (const SymbolicRegion *BMR =
2418               dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2419           Sym = BMR->getSymbol();
2420
2421   // Check if we are returning freed memory.
2422   if (Sym)
2423     checkUseAfterFree(Sym, C, E);
2424 }
2425
2426 // TODO: Blocks should be either inlined or should call invalidate regions
2427 // upon invocation. After that's in place, special casing here will not be
2428 // needed.
2429 void MallocChecker::checkPostStmt(const BlockExpr *BE,
2430                                   CheckerContext &C) const {
2431
2432   // Scan the BlockDecRefExprs for any object the retain count checker
2433   // may be tracking.
2434   if (!BE->getBlockDecl()->hasCaptures())
2435     return;
2436
2437   ProgramStateRef state = C.getState();
2438   const BlockDataRegion *R =
2439     cast<BlockDataRegion>(state->getSVal(BE,
2440                                          C.getLocationContext()).getAsRegion());
2441
2442   BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2443                                             E = R->referenced_vars_end();
2444
2445   if (I == E)
2446     return;
2447
2448   SmallVector<const MemRegion*, 10> Regions;
2449   const LocationContext *LC = C.getLocationContext();
2450   MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2451
2452   for ( ; I != E; ++I) {
2453     const VarRegion *VR = I.getCapturedRegion();
2454     if (VR->getSuperRegion() == R) {
2455       VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2456     }
2457     Regions.push_back(VR);
2458   }
2459
2460   state =
2461     state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2462                                     Regions.data() + Regions.size()).getState();
2463   C.addTransition(state);
2464 }
2465
2466 bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
2467   assert(Sym);
2468   const RefState *RS = C.getState()->get<RegionState>(Sym);
2469   return (RS && RS->isReleased());
2470 }
2471
2472 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2473                                       const Stmt *S) const {
2474
2475   if (isReleased(Sym, C)) {
2476     ReportUseAfterFree(C, S->getSourceRange(), Sym);
2477     return true;
2478   }
2479
2480   return false;
2481 }
2482
2483 void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2484                                           const Stmt *S) const {
2485   assert(Sym);
2486
2487   if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2488     if (RS->isAllocatedOfSizeZero())
2489       ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2490   }
2491   else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2492     ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2493   }
2494 }
2495
2496 bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2497
2498   if (isReleased(Sym, C)) {
2499     ReportDoubleDelete(C, Sym);
2500     return true;
2501   }
2502   return false;
2503 }
2504
2505 // Check if the location is a freed symbolic region.
2506 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2507                                   CheckerContext &C) const {
2508   SymbolRef Sym = l.getLocSymbolInBase();
2509   if (Sym) {
2510     checkUseAfterFree(Sym, C, S);
2511     checkUseZeroAllocated(Sym, C, S);
2512   }
2513 }
2514
2515 // If a symbolic region is assumed to NULL (or another constant), stop tracking
2516 // it - assuming that allocation failed on this path.
2517 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2518                                               SVal Cond,
2519                                               bool Assumption) const {
2520   RegionStateTy RS = state->get<RegionState>();
2521   for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2522     // If the symbol is assumed to be NULL, remove it from consideration.
2523     ConstraintManager &CMgr = state->getConstraintManager();
2524     ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2525     if (AllocFailed.isConstrainedTrue())
2526       state = state->remove<RegionState>(I.getKey());
2527   }
2528
2529   // Realloc returns 0 when reallocation fails, which means that we should
2530   // restore the state of the pointer being reallocated.
2531   ReallocPairsTy RP = state->get<ReallocPairs>();
2532   for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2533     // If the symbol is assumed to be NULL, remove it from consideration.
2534     ConstraintManager &CMgr = state->getConstraintManager();
2535     ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2536     if (!AllocFailed.isConstrainedTrue())
2537       continue;
2538
2539     SymbolRef ReallocSym = I.getData().ReallocatedSym;
2540     if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2541       if (RS->isReleased()) {
2542         if (I.getData().Kind == RPToBeFreedAfterFailure)
2543           state = state->set<RegionState>(ReallocSym,
2544               RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2545         else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2546           state = state->remove<RegionState>(ReallocSym);
2547         else
2548           assert(I.getData().Kind == RPIsFreeOnFailure);
2549       }
2550     }
2551     state = state->remove<ReallocPairs>(I.getKey());
2552   }
2553
2554   return state;
2555 }
2556
2557 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2558                                               const CallEvent *Call,
2559                                               ProgramStateRef State,
2560                                               SymbolRef &EscapingSymbol) const {
2561   assert(Call);
2562   EscapingSymbol = nullptr;
2563
2564   // For now, assume that any C++ or block call can free memory.
2565   // TODO: If we want to be more optimistic here, we'll need to make sure that
2566   // regions escape to C++ containers. They seem to do that even now, but for
2567   // mysterious reasons.
2568   if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
2569     return true;
2570
2571   // Check Objective-C messages by selector name.
2572   if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2573     // If it's not a framework call, or if it takes a callback, assume it
2574     // can free memory.
2575     if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
2576       return true;
2577
2578     // If it's a method we know about, handle it explicitly post-call.
2579     // This should happen before the "freeWhenDone" check below.
2580     if (isKnownDeallocObjCMethodName(*Msg))
2581       return false;
2582
2583     // If there's a "freeWhenDone" parameter, but the method isn't one we know
2584     // about, we can't be sure that the object will use free() to deallocate the
2585     // memory, so we can't model it explicitly. The best we can do is use it to
2586     // decide whether the pointer escapes.
2587     if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
2588       return *FreeWhenDone;
2589
2590     // If the first selector piece ends with "NoCopy", and there is no
2591     // "freeWhenDone" parameter set to zero, we know ownership is being
2592     // transferred. Again, though, we can't be sure that the object will use
2593     // free() to deallocate the memory, so we can't model it explicitly.
2594     StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
2595     if (FirstSlot.endswith("NoCopy"))
2596       return true;
2597
2598     // If the first selector starts with addPointer, insertPointer,
2599     // or replacePointer, assume we are dealing with NSPointerArray or similar.
2600     // This is similar to C++ containers (vector); we still might want to check
2601     // that the pointers get freed by following the container itself.
2602     if (FirstSlot.startswith("addPointer") ||
2603         FirstSlot.startswith("insertPointer") ||
2604         FirstSlot.startswith("replacePointer") ||
2605         FirstSlot.equals("valueWithPointer")) {
2606       return true;
2607     }
2608
2609     // We should escape receiver on call to 'init'. This is especially relevant
2610     // to the receiver, as the corresponding symbol is usually not referenced
2611     // after the call.
2612     if (Msg->getMethodFamily() == OMF_init) {
2613       EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2614       return true;
2615     }
2616
2617     // Otherwise, assume that the method does not free memory.
2618     // Most framework methods do not free memory.
2619     return false;
2620   }
2621
2622   // At this point the only thing left to handle is straight function calls.
2623   const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
2624   if (!FD)
2625     return true;
2626
2627   ASTContext &ASTC = State->getStateManager().getContext();
2628
2629   // If it's one of the allocation functions we can reason about, we model
2630   // its behavior explicitly.
2631   if (isMemFunction(FD, ASTC))
2632     return false;
2633
2634   // If it's not a system call, assume it frees memory.
2635   if (!Call->isInSystemHeader())
2636     return true;
2637
2638   // White list the system functions whose arguments escape.
2639   const IdentifierInfo *II = FD->getIdentifier();
2640   if (!II)
2641     return true;
2642   StringRef FName = II->getName();
2643
2644   // White list the 'XXXNoCopy' CoreFoundation functions.
2645   // We specifically check these before
2646   if (FName.endswith("NoCopy")) {
2647     // Look for the deallocator argument. We know that the memory ownership
2648     // is not transferred only if the deallocator argument is
2649     // 'kCFAllocatorNull'.
2650     for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2651       const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2652       if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2653         StringRef DeallocatorName = DE->getFoundDecl()->getName();
2654         if (DeallocatorName == "kCFAllocatorNull")
2655           return false;
2656       }
2657     }
2658     return true;
2659   }
2660
2661   // Associating streams with malloced buffers. The pointer can escape if
2662   // 'closefn' is specified (and if that function does free memory),
2663   // but it will not if closefn is not specified.
2664   // Currently, we do not inspect the 'closefn' function (PR12101).
2665   if (FName == "funopen")
2666     if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
2667       return false;
2668
2669   // Do not warn on pointers passed to 'setbuf' when used with std streams,
2670   // these leaks might be intentional when setting the buffer for stdio.
2671   // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2672   if (FName == "setbuf" || FName =="setbuffer" ||
2673       FName == "setlinebuf" || FName == "setvbuf") {
2674     if (Call->getNumArgs() >= 1) {
2675       const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2676       if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2677         if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2678           if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
2679             return true;
2680     }
2681   }
2682
2683   // A bunch of other functions which either take ownership of a pointer or
2684   // wrap the result up in a struct or object, meaning it can be freed later.
2685   // (See RetainCountChecker.) Not all the parameters here are invalidated,
2686   // but the Malloc checker cannot differentiate between them. The right way
2687   // of doing this would be to implement a pointer escapes callback.
2688   if (FName == "CGBitmapContextCreate" ||
2689       FName == "CGBitmapContextCreateWithData" ||
2690       FName == "CVPixelBufferCreateWithBytes" ||
2691       FName == "CVPixelBufferCreateWithPlanarBytes" ||
2692       FName == "OSAtomicEnqueue") {
2693     return true;
2694   }
2695
2696   if (FName == "postEvent" &&
2697       FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2698     return true;
2699   }
2700
2701   if (FName == "postEvent" &&
2702       FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2703     return true;
2704   }
2705
2706   if (FName == "connectImpl" &&
2707       FD->getQualifiedNameAsString() == "QObject::connectImpl") {
2708     return true;
2709   }
2710
2711   // Handle cases where we know a buffer's /address/ can escape.
2712   // Note that the above checks handle some special cases where we know that
2713   // even though the address escapes, it's still our responsibility to free the
2714   // buffer.
2715   if (Call->argumentsMayEscape())
2716     return true;
2717
2718   // Otherwise, assume that the function does not free memory.
2719   // Most system calls do not free the memory.
2720   return false;
2721 }
2722
2723 static bool retTrue(const RefState *RS) {
2724   return true;
2725 }
2726
2727 static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2728   return (RS->getAllocationFamily() == AF_CXXNewArray ||
2729           RS->getAllocationFamily() == AF_CXXNew);
2730 }
2731
2732 ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2733                                              const InvalidatedSymbols &Escaped,
2734                                              const CallEvent *Call,
2735                                              PointerEscapeKind Kind) const {
2736   return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2737 }
2738
2739 ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2740                                               const InvalidatedSymbols &Escaped,
2741                                               const CallEvent *Call,
2742                                               PointerEscapeKind Kind) const {
2743   return checkPointerEscapeAux(State, Escaped, Call, Kind,
2744                                &checkIfNewOrNewArrayFamily);
2745 }
2746
2747 ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2748                                               const InvalidatedSymbols &Escaped,
2749                                               const CallEvent *Call,
2750                                               PointerEscapeKind Kind,
2751                                   bool(*CheckRefState)(const RefState*)) const {
2752   // If we know that the call does not free memory, or we want to process the
2753   // call later, keep tracking the top level arguments.
2754   SymbolRef EscapingSymbol = nullptr;
2755   if (Kind == PSK_DirectEscapeOnCall &&
2756       !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2757                                                     EscapingSymbol) &&
2758       !EscapingSymbol) {
2759     return State;
2760   }
2761
2762   for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
2763        E = Escaped.end();
2764        I != E; ++I) {
2765     SymbolRef sym = *I;
2766
2767     if (EscapingSymbol && EscapingSymbol != sym)
2768       continue;
2769
2770     if (const RefState *RS = State->get<RegionState>(sym)) {
2771       if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2772           CheckRefState(RS)) {
2773         State = State->remove<RegionState>(sym);
2774         State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2775       }
2776     }
2777   }
2778   return State;
2779 }
2780
2781 static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2782                                          ProgramStateRef prevState) {
2783   ReallocPairsTy currMap = currState->get<ReallocPairs>();
2784   ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
2785
2786   for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
2787        I != E; ++I) {
2788     SymbolRef sym = I.getKey();
2789     if (!currMap.lookup(sym))
2790       return sym;
2791   }
2792
2793   return nullptr;
2794 }
2795
2796 std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode(
2797     const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
2798     BugReport &BR) {
2799   ProgramStateRef state = N->getState();
2800   ProgramStateRef statePrev = PrevN->getState();
2801
2802   const RefState *RS = state->get<RegionState>(Sym);
2803   const RefState *RSPrev = statePrev->get<RegionState>(Sym);
2804   if (!RS)
2805     return nullptr;
2806
2807   const Stmt *S = PathDiagnosticLocation::getStmt(N);
2808   if (!S)
2809     return nullptr;
2810
2811   // FIXME: We will eventually need to handle non-statement-based events
2812   // (__attribute__((cleanup))).
2813
2814   // Find out if this is an interesting point and what is the kind.
2815   const char *Msg = nullptr;
2816   StackHintGeneratorForSymbol *StackHint = nullptr;
2817   if (Mode == Normal) {
2818     if (isAllocated(RS, RSPrev, S)) {
2819       Msg = "Memory is allocated";
2820       StackHint = new StackHintGeneratorForSymbol(Sym,
2821                                                   "Returned allocated memory");
2822     } else if (isReleased(RS, RSPrev, S)) {
2823       Msg = "Memory is released";
2824       StackHint = new StackHintGeneratorForSymbol(Sym,
2825                                              "Returning; memory was released");
2826     } else if (isRelinquished(RS, RSPrev, S)) {
2827       Msg = "Memory ownership is transferred";
2828       StackHint = new StackHintGeneratorForSymbol(Sym, "");
2829     } else if (isReallocFailedCheck(RS, RSPrev, S)) {
2830       Mode = ReallocationFailed;
2831       Msg = "Reallocation failed";
2832       StackHint = new StackHintGeneratorForReallocationFailed(Sym,
2833                                                        "Reallocation failed");
2834
2835       if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2836         // Is it possible to fail two reallocs WITHOUT testing in between?
2837         assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2838           "We only support one failed realloc at a time.");
2839         BR.markInteresting(sym);
2840         FailedReallocSymbol = sym;
2841       }
2842     }
2843
2844   // We are in a special mode if a reallocation failed later in the path.
2845   } else if (Mode == ReallocationFailed) {
2846     assert(FailedReallocSymbol && "No symbol to look for.");
2847
2848     // Is this is the first appearance of the reallocated symbol?
2849     if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
2850       // We're at the reallocation point.
2851       Msg = "Attempt to reallocate memory";
2852       StackHint = new StackHintGeneratorForSymbol(Sym,
2853                                                  "Returned reallocated memory");
2854       FailedReallocSymbol = nullptr;
2855       Mode = Normal;
2856     }
2857   }
2858
2859   if (!Msg)
2860     return nullptr;
2861   assert(StackHint);
2862
2863   // Generate the extra diagnostic.
2864   PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2865                              N->getLocationContext());
2866   return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true, StackHint);
2867 }
2868
2869 void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2870                                const char *NL, const char *Sep) const {
2871
2872   RegionStateTy RS = State->get<RegionState>();
2873
2874   if (!RS.isEmpty()) {
2875     Out << Sep << "MallocChecker :" << NL;
2876     for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2877       const RefState *RefS = State->get<RegionState>(I.getKey());
2878       AllocationFamily Family = RefS->getAllocationFamily();
2879       Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2880       if (!CheckKind.hasValue())
2881          CheckKind = getCheckIfTracked(Family, true);
2882
2883       I.getKey()->dumpToStream(Out);
2884       Out << " : ";
2885       I.getData().dump(Out);
2886       if (CheckKind.hasValue())
2887         Out << " (" << CheckNames[*CheckKind].getName() << ")";
2888       Out << NL;
2889     }
2890   }
2891 }
2892
2893 void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2894   registerCStringCheckerBasic(mgr);
2895   MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2896   checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2897       "Optimistic", false, checker);
2898   checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2899   checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2900       mgr.getCurrentCheckName();
2901   // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2902   // checker.
2903   if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker]) {
2904     checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
2905     // FIXME: This does not set the correct name, but without this workaround
2906     //        no name will be set at all.
2907     checker->CheckNames[MallocChecker::CK_NewDeleteChecker] =
2908         mgr.getCurrentCheckName();
2909   }
2910 }
2911
2912 #define REGISTER_CHECKER(name)                                                 \
2913   void ento::register##name(CheckerManager &mgr) {                             \
2914     registerCStringCheckerBasic(mgr);                                          \
2915     MallocChecker *checker = mgr.registerChecker<MallocChecker>();             \
2916     checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(         \
2917         "Optimistic", false, checker);                                         \
2918     checker->ChecksEnabled[MallocChecker::CK_##name] = true;                   \
2919     checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2920   }
2921
2922 REGISTER_CHECKER(MallocChecker)
2923 REGISTER_CHECKER(NewDeleteChecker)
2924 REGISTER_CHECKER(MismatchedDeallocatorChecker)