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