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