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