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