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