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