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