blob: de615a88b3e04e285dafb894ef05b32a8a687461 [file] [log] [blame]
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001//=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines malloc/free checker, which checks for potential memory
11// leaks, double free, and use-after-free problems.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +000015#include "ClangSACheckers.h"
Anna Zakse56167e2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/AST/Attr.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000020#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +000021#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rose4f7df9b2012-07-26 21:39:41 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek001fd5b2011-08-15 22:09:50 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
25#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenekf8cbac42011-02-10 01:03:03 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000027#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer3307c5082012-02-04 12:31:12 +000028#include "llvm/ADT/STLExtras.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "llvm/ADT/SmallString.h"
Jordan Rosec102b352012-09-22 01:24:42 +000030#include "llvm/ADT/StringExtras.h"
Anna Zaks199e8e52012-02-22 03:14:20 +000031#include <climits>
32
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000033using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000034using namespace ento;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +000035
36namespace {
37
Anton Yartsev05789592013-03-28 17:05:19 +000038// Used to check correspondence between allocators and deallocators.
39enum AllocationFamily {
40 AF_None,
41 AF_Malloc,
42 AF_CXXNew,
43 AF_CXXNewArray
44};
45
Zhongxing Xu1239de12009-12-11 00:55:44 +000046class RefState {
Anna Zaks9050ffd2012-06-20 20:57:46 +000047 enum Kind { // Reference to allocated memory.
48 Allocated,
49 // Reference to released/freed memory.
50 Released,
Alp Toker5faf0c02013-12-02 03:50:25 +000051 // The responsibility for freeing resources has transferred from
Anna Zaks9050ffd2012-06-20 20:57:46 +000052 // this reference. A relinquished symbol should not be freed.
Anna Zaks93a21a82013-04-09 00:30:28 +000053 Relinquished,
54 // We are no longer guaranteed to have observed all manipulations
55 // of this pointer/memory. For example, it could have been
56 // passed as a parameter to an opaque function.
57 Escaped
58 };
Anton Yartsev05789592013-03-28 17:05:19 +000059
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000060 const Stmt *S;
Anton Yartsev05789592013-03-28 17:05:19 +000061 unsigned K : 2; // Kind enum, but stored as a bitfield.
62 unsigned Family : 30; // Rest of 32-bit word, currently just an allocation
63 // family.
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000064
Anton Yartsev05789592013-03-28 17:05:19 +000065 RefState(Kind k, const Stmt *s, unsigned family)
Anna Zaks93a21a82013-04-09 00:30:28 +000066 : S(s), K(k), Family(family) {
67 assert(family != AF_None);
68 }
Zhongxing Xu1239de12009-12-11 00:55:44 +000069public:
Anna Zaks9050ffd2012-06-20 20:57:46 +000070 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000071 bool isReleased() const { return K == Released; }
Anna Zaks9050ffd2012-06-20 20:57:46 +000072 bool isRelinquished() const { return K == Relinquished; }
Anna Zaks93a21a82013-04-09 00:30:28 +000073 bool isEscaped() const { return K == Escaped; }
74 AllocationFamily getAllocationFamily() const {
Anton Yartsev05789592013-03-28 17:05:19 +000075 return (AllocationFamily)Family;
76 }
Anna Zaksd56c8792012-02-13 18:05:39 +000077 const Stmt *getStmt() const { return S; }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000078
79 bool operator==(const RefState &X) const {
Anton Yartsev05789592013-03-28 17:05:19 +000080 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000081 }
82
Anton Yartsev05789592013-03-28 17:05:19 +000083 static RefState getAllocated(unsigned family, const Stmt *s) {
84 return RefState(Allocated, s, family);
Zhongxing Xub0e15df2009-12-31 06:13:07 +000085 }
Anton Yartsev05789592013-03-28 17:05:19 +000086 static RefState getReleased(unsigned family, const Stmt *s) {
87 return RefState(Released, s, family);
88 }
89 static RefState getRelinquished(unsigned family, const Stmt *s) {
90 return RefState(Relinquished, s, family);
Ted Kremenek0bbf24d2010-08-06 21:12:55 +000091 }
Anna Zaks93a21a82013-04-09 00:30:28 +000092 static RefState getEscaped(const RefState *RS) {
93 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
94 }
Zhongxing Xu4668c7e2009-11-17 07:54:15 +000095
96 void Profile(llvm::FoldingSetNodeID &ID) const {
97 ID.AddInteger(K);
98 ID.AddPointer(S);
Anton Yartsev05789592013-03-28 17:05:19 +000099 ID.AddInteger(Family);
Zhongxing Xu4668c7e2009-11-17 07:54:15 +0000100 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000101
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000102 void dump(raw_ostream &OS) const {
Jordan Rose6adadb92014-01-23 03:59:01 +0000103 switch (static_cast<Kind>(K)) {
104#define CASE(ID) case ID: OS << #ID; break;
105 CASE(Allocated)
106 CASE(Released)
107 CASE(Relinquished)
108 CASE(Escaped)
109 }
Ted Kremenek6fcefb52013-01-03 01:30:12 +0000110 }
111
Alp Tokeref6b0072014-01-04 13:47:14 +0000112 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000113};
114
Anna Zaks75cfbb62012-09-12 22:57:34 +0000115enum ReallocPairKind {
116 RPToBeFreedAfterFailure,
117 // The symbol has been freed when reallocation failed.
118 RPIsFreeOnFailure,
119 // The symbol does not need to be freed after reallocation fails.
120 RPDoNotTrackAfterFailure
121};
122
Anna Zaksfe6eb672012-08-24 02:28:20 +0000123/// \class ReallocPair
124/// \brief Stores information about the symbol being reallocated by a call to
125/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaksac068142012-02-15 00:11:25 +0000126struct ReallocPair {
Anna Zaksfe6eb672012-08-24 02:28:20 +0000127 // \brief The symbol which realloc reallocated.
Anna Zaksac068142012-02-15 00:11:25 +0000128 SymbolRef ReallocatedSym;
Anna Zaks75cfbb62012-09-12 22:57:34 +0000129 ReallocPairKind Kind;
Anna Zaksfe6eb672012-08-24 02:28:20 +0000130
Anna Zaks75cfbb62012-09-12 22:57:34 +0000131 ReallocPair(SymbolRef S, ReallocPairKind K) :
132 ReallocatedSym(S), Kind(K) {}
Anna Zaksac068142012-02-15 00:11:25 +0000133 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks75cfbb62012-09-12 22:57:34 +0000134 ID.AddInteger(Kind);
Anna Zaksac068142012-02-15 00:11:25 +0000135 ID.AddPointer(ReallocatedSym);
136 }
137 bool operator==(const ReallocPair &X) const {
138 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks75cfbb62012-09-12 22:57:34 +0000139 Kind == X.Kind;
Anna Zaksac068142012-02-15 00:11:25 +0000140 }
141};
142
Anna Zaksa043d0c2013-01-08 00:25:29 +0000143typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaksfc2e1532012-03-21 19:45:08 +0000144
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000145class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksdc154152012-12-20 00:38:25 +0000146 check::PointerEscape,
Anna Zaks333481b2013-03-28 23:15:29 +0000147 check::ConstPointerEscape,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000148 check::PreStmt<ReturnStmt>,
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000149 check::PreCall,
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000150 check::PostStmt<CallExpr>,
Anton Yartsev13df0362013-03-25 01:35:45 +0000151 check::PostStmt<CXXNewExpr>,
152 check::PreStmt<CXXDeleteExpr>,
Anna Zaks9fe80982012-03-22 00:57:20 +0000153 check::PostStmt<BlockExpr>,
Anna Zaks67291b92012-11-13 03:18:01 +0000154 check::PostObjCMessage,
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000155 check::Location,
Anna Zaksdc154152012-12-20 00:38:25 +0000156 eval::Assume>
Ted Kremenek778d2bb2012-01-04 23:48:37 +0000157{
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000158public:
Anna Zaksd5157482012-02-15 00:11:22 +0000159 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks199e8e52012-02-22 03:14:20 +0000160 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zakscd37bf42012-02-08 23:16:52 +0000161
162 /// In pessimistic mode, the checker assumes that it does not know which
163 /// functions might free the memory.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000164 enum CheckKind {
165 CK_MallocPessimistic,
166 CK_MallocOptimistic,
167 CK_NewDeleteChecker,
168 CK_NewDeleteLeaksChecker,
169 CK_MismatchedDeallocatorChecker,
170 CK_NumCheckKinds
Anna Zakscd37bf42012-02-08 23:16:52 +0000171 };
172
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000173 DefaultBool ChecksEnabled[CK_NumCheckKinds];
174 CheckName CheckNames[CK_NumCheckKinds];
Anna Zakscd37bf42012-02-08 23:16:52 +0000175
Anton Yartsevcb2ccd62013-04-10 22:21:41 +0000176 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000177 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000178 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
179 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks67291b92012-11-13 03:18:01 +0000180 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaks9fe80982012-03-22 00:57:20 +0000181 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000182 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000183 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000184 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000185 bool Assumption) const;
Anna Zaks3e0f4152011-10-06 00:43:15 +0000186 void checkLocation(SVal l, bool isLoad, const Stmt *S,
187 CheckerContext &C) const;
Anna Zaksdc154152012-12-20 00:38:25 +0000188
189 ProgramStateRef checkPointerEscape(ProgramStateRef State,
190 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +0000191 const CallEvent *Call,
192 PointerEscapeKind Kind) const;
Anna Zaks333481b2013-03-28 23:15:29 +0000193 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
194 const InvalidatedSymbols &Escaped,
195 const CallEvent *Call,
196 PointerEscapeKind Kind) const;
Zhongxing Xub0e15df2009-12-31 06:13:07 +0000197
Anna Zaks263b7e02012-05-02 00:05:20 +0000198 void printState(raw_ostream &Out, ProgramStateRef State,
199 const char *NL, const char *Sep) const;
200
Zhongxing Xuc4902a52009-11-13 07:25:27 +0000201private:
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000202 mutable OwningPtr<BugType> BT_DoubleFree[CK_NumCheckKinds];
203 mutable OwningPtr<BugType> BT_DoubleDelete;
204 mutable OwningPtr<BugType> BT_Leak[CK_NumCheckKinds];
205 mutable OwningPtr<BugType> BT_UseFree[CK_NumCheckKinds];
206 mutable OwningPtr<BugType> BT_BadFree[CK_NumCheckKinds];
207 mutable OwningPtr<BugType> BT_MismatchedDealloc;
208 mutable OwningPtr<BugType> BT_OffsetFree[CK_NumCheckKinds];
209 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
210 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
211
Anna Zaks3d348342012-02-14 21:55:24 +0000212 void initIdentifierInfo(ASTContext &C) const;
213
Anton Yartsev05789592013-03-28 17:05:19 +0000214 /// \brief Determine family of a deallocation expression.
Anton Yartseve3377fb2013-04-04 23:46:29 +0000215 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000216
217 /// \brief Print names of allocators and deallocators.
218 ///
219 /// \returns true on success.
220 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
221 const Expr *E) const;
222
223 /// \brief Print expected name of an allocator based on the deallocator's
224 /// family derived from the DeallocExpr.
225 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
226 const Expr *DeallocExpr) const;
227 /// \brief Print expected name of a deallocator based on the allocator's
228 /// family.
229 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
230
Jordan Rose613f3c02013-03-09 00:59:10 +0000231 ///@{
Anna Zaks3d348342012-02-14 21:55:24 +0000232 /// Check if this is one of the functions which can allocate/reallocate memory
233 /// pointed to by one of its arguments.
234 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks46d01602012-05-18 01:16:10 +0000235 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
236 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anton Yartsev13df0362013-03-25 01:35:45 +0000237 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose613f3c02013-03-09 00:59:10 +0000238 ///@}
Richard Smith852e9ce2013-11-27 01:46:48 +0000239 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
240 const CallExpr *CE,
241 const OwnershipAttr* Att) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000242 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000243 const Expr *SizeEx, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000244 ProgramStateRef State,
245 AllocationFamily Family = AF_Malloc) {
Ted Kremenek632e3b72012-01-06 22:09:28 +0000246 return MallocMemAux(C, CE,
Anton Yartsev05789592013-03-28 17:05:19 +0000247 State->getSVal(SizeEx, C.getLocationContext()),
248 Init, State, Family);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000249 }
Anna Zaks40a7eb32012-02-22 19:24:52 +0000250
Ted Kremenek49b1e382012-01-26 21:29:00 +0000251 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +0000252 SVal SizeEx, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000253 ProgramStateRef State,
254 AllocationFamily Family = AF_Malloc);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000255
Anna Zaks40a7eb32012-02-22 19:24:52 +0000256 /// Update the RefState to reflect the new memory allocation.
Anton Yartsev05789592013-03-28 17:05:19 +0000257 static ProgramStateRef
258 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
259 AllocationFamily Family = AF_Malloc);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000260
261 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
262 const OwnershipAttr* Att) const;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000263 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks0d6989b2012-06-22 02:04:31 +0000264 ProgramStateRef state, unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000265 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000266 bool &ReleasedAllocated,
267 bool ReturnsNullOnFailure = false) const;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000268 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
269 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000270 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000271 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000272 bool &ReleasedAllocated,
273 bool ReturnsNullOnFailure = false) const;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000274
Anna Zaks40a7eb32012-02-22 19:24:52 +0000275 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
276 bool FreesMemOnFailure) const;
277 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose3597b212010-06-07 19:32:37 +0000278
Anna Zaks46d01602012-05-18 01:16:10 +0000279 ///\brief Check if the memory associated with this symbol was released.
280 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
281
Anton Yartsev13df0362013-03-25 01:35:45 +0000282 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaksa1b227b2012-02-08 23:16:56 +0000283
Jordan Rose656fdd52014-01-08 18:46:55 +0000284 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
285
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000286 /// Check if the function is known free memory, or if it is
Jordan Rose613f3c02013-03-09 00:59:10 +0000287 /// "interesting" and should be modeled explicitly.
288 ///
Anna Zaks8ebeb642013-06-08 00:29:29 +0000289 /// \param [out] EscapingSymbol A function might not free memory in general,
290 /// but could be known to free a particular symbol. In this case, false is
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000291 /// returned and the single escaping symbol is returned through the out
292 /// parameter.
293 ///
Jordan Rose613f3c02013-03-09 00:59:10 +0000294 /// We assume that pointers do not escape through calls to system functions
295 /// not handled by this checker.
Anna Zaks8ebeb642013-06-08 00:29:29 +0000296 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
Anna Zaksa4bc5e12013-05-31 23:47:32 +0000297 ProgramStateRef State,
298 SymbolRef &EscapingSymbol) const;
Anna Zaks3d348342012-02-14 21:55:24 +0000299
Anna Zaks333481b2013-03-28 23:15:29 +0000300 // Implementation of the checkPointerEscape callabcks.
301 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
302 const InvalidatedSymbols &Escaped,
303 const CallEvent *Call,
304 PointerEscapeKind Kind,
305 bool(*CheckRefState)(const RefState*)) const;
306
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000307 ///@{
308 /// Tells if a given family/call/symbol is tracked by the current checker.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000309 /// Sets CheckKind to the kind of the checker responsible for this
310 /// family/call/symbol.
311 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family) const;
312 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
313 const Stmt *AllocDeallocStmt) const;
314 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym) const;
Anton Yartsev1e2bc9b2013-04-11 00:05:20 +0000315 ///@}
Ted Kremenek5ef32db2011-08-12 23:37:29 +0000316 static bool SummarizeValue(raw_ostream &os, SVal V);
317 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev05789592013-03-28 17:05:19 +0000318 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
319 const Expr *DeallocExpr) const;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000320 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartsevf0593d62013-04-05 11:25:10 +0000321 const Expr *DeallocExpr, const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +0000322 SymbolRef Sym, bool OwnershipTransferred) const;
Anton Yartsev05789592013-03-28 17:05:19 +0000323 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
324 const Expr *DeallocExpr,
325 const Expr *AllocExpr = 0) const;
Anton Yartsev59ed15b2013-03-13 14:39:10 +0000326 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
327 SymbolRef Sym) const;
328 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev6c2af432013-03-13 17:07:32 +0000329 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaks2b5bb972012-02-09 06:25:51 +0000330
Jordan Rose656fdd52014-01-08 18:46:55 +0000331 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
332
Anna Zaksdf901a42012-02-23 21:38:21 +0000333 /// Find the location of the allocation for Sym on the path leading to the
334 /// exploded node N.
Anna Zaksfc2e1532012-03-21 19:45:08 +0000335 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
336 CheckerContext &C) const;
Anna Zaksdf901a42012-02-23 21:38:21 +0000337
Anna Zaksd3571e5a2012-02-11 21:02:40 +0000338 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
339
Anna Zaks2b5bb972012-02-09 06:25:51 +0000340 /// The bug visitor which allows us to print extra diagnostics along the
341 /// BugReport path. For example, showing the allocation site of the leaked
342 /// region.
Jordy Rosef78877e2012-03-24 02:45:35 +0000343 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000344 protected:
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000345 enum NotificationMode {
346 Normal,
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000347 ReallocationFailed
348 };
349
Anna Zaks2b5bb972012-02-09 06:25:51 +0000350 // The allocated region symbol tracked by the main analysis.
351 SymbolRef Sym;
352
Anna Zaks62cce9e2012-05-10 01:37:40 +0000353 // The mode we are in, i.e. what kind of diagnostics will be emitted.
354 NotificationMode Mode;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000355
Anna Zaks62cce9e2012-05-10 01:37:40 +0000356 // A symbol from when the primary region should have been reallocated.
357 SymbolRef FailedReallocSymbol;
Jordy Rose21ff76e2012-03-24 03:15:09 +0000358
Anna Zaks62cce9e2012-05-10 01:37:40 +0000359 bool IsLeak;
360
361 public:
362 MallocBugVisitor(SymbolRef S, bool isLeak = false)
363 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Rose21ff76e2012-03-24 03:15:09 +0000364
Anna Zaks2b5bb972012-02-09 06:25:51 +0000365 virtual ~MallocBugVisitor() {}
366
367 void Profile(llvm::FoldingSetNodeID &ID) const {
368 static int X = 0;
369 ID.AddPointer(&X);
370 ID.AddPointer(Sym);
371 }
372
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000373 inline bool isAllocated(const RefState *S, const RefState *SPrev,
374 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000375 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev13df0362013-03-25 01:35:45 +0000376 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000377 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000378 }
379
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000380 inline bool isReleased(const RefState *S, const RefState *SPrev,
381 const Stmt *Stmt) {
Anna Zaks2b5bb972012-02-09 06:25:51 +0000382 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev13df0362013-03-25 01:35:45 +0000383 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000384 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
385 }
386
Anna Zaks0d6989b2012-06-22 02:04:31 +0000387 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
388 const Stmt *Stmt) {
389 // Did not track -> relinquished. Other state (allocated) -> relinquished.
390 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
391 isa<ObjCPropertyRefExpr>(Stmt)) &&
392 (S && S->isRelinquished()) &&
393 (!SPrev || !SPrev->isRelinquished()));
394 }
395
Anna Zaks9eb7bc82012-02-16 22:26:07 +0000396 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
397 const Stmt *Stmt) {
398 // If the expression is not a call, and the state change is
399 // released -> allocated, it must be the realloc return value
400 // check. If we have to handle more cases here, it might be cleaner just
401 // to track this extra bit in the state itself.
402 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
403 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaks2b5bb972012-02-09 06:25:51 +0000404 }
405
406 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
407 const ExplodedNode *PrevN,
408 BugReporterContext &BRC,
409 BugReport &BR);
Anna Zaks62cce9e2012-05-10 01:37:40 +0000410
411 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
412 const ExplodedNode *EndPathNode,
413 BugReport &BR) {
414 if (!IsLeak)
415 return 0;
416
417 PathDiagnosticLocation L =
418 PathDiagnosticLocation::createEndOfPath(EndPathNode,
419 BRC.getSourceManager());
420 // Do not add the statement itself as a range in case of leak.
421 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
422 }
423
Anna Zakscba4f292012-03-16 23:24:20 +0000424 private:
425 class StackHintGeneratorForReallocationFailed
426 : public StackHintGeneratorForSymbol {
427 public:
428 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
429 : StackHintGeneratorForSymbol(S, M) {}
430
431 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rosec102b352012-09-22 01:24:42 +0000432 // Printed parameters start at 1, not 0.
433 ++ArgIndex;
434
Anna Zakscba4f292012-03-16 23:24:20 +0000435 SmallString<200> buf;
436 llvm::raw_svector_ostream os(buf);
437
Jordan Rosec102b352012-09-22 01:24:42 +0000438 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
439 << " parameter failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000440
441 return os.str();
442 }
443
444 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksa7f457a2012-03-16 23:44:28 +0000445 return "Reallocation of returned value failed";
Anna Zakscba4f292012-03-16 23:24:20 +0000446 }
447 };
Anna Zaks2b5bb972012-02-09 06:25:51 +0000448 };
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000449};
Kovarththanan Rajaratnam65c65662009-11-28 06:07:30 +0000450} // end anonymous namespace
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000451
Jordan Rose0c153cb2012-11-02 01:54:06 +0000452REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
453REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000454
Anna Zaks67291b92012-11-13 03:18:01 +0000455// A map from the freed symbol to the symbol representing the return value of
456// the free function.
457REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
458
Anna Zaksbb1ef902012-02-11 21:02:35 +0000459namespace {
460class StopTrackingCallback : public SymbolVisitor {
461 ProgramStateRef state;
462public:
463 StopTrackingCallback(ProgramStateRef st) : state(st) {}
464 ProgramStateRef getState() const { return state; }
465
466 bool VisitSymbol(SymbolRef sym) {
467 state = state->remove<RegionState>(sym);
468 return true;
469 }
470};
471} // end anonymous namespace
472
Anna Zaks3d348342012-02-14 21:55:24 +0000473void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksb3436602012-05-18 22:47:40 +0000474 if (II_malloc)
475 return;
476 II_malloc = &Ctx.Idents.get("malloc");
477 II_free = &Ctx.Idents.get("free");
478 II_realloc = &Ctx.Idents.get("realloc");
479 II_reallocf = &Ctx.Idents.get("reallocf");
480 II_calloc = &Ctx.Idents.get("calloc");
481 II_valloc = &Ctx.Idents.get("valloc");
482 II_strdup = &Ctx.Idents.get("strdup");
483 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000484}
485
Anna Zaks3d348342012-02-14 21:55:24 +0000486bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks46d01602012-05-18 01:16:10 +0000487 if (isFreeFunction(FD, C))
488 return true;
489
490 if (isAllocationFunction(FD, C))
491 return true;
492
Anton Yartsev13df0362013-03-25 01:35:45 +0000493 if (isStandardNewDelete(FD, C))
494 return true;
495
Anna Zaks46d01602012-05-18 01:16:10 +0000496 return false;
497}
498
499bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
500 ASTContext &C) const {
Anna Zaksd1ff1cb2012-02-15 02:12:00 +0000501 if (!FD)
502 return false;
Anna Zaks46d01602012-05-18 01:16:10 +0000503
Jordan Rose6cd16c52012-07-10 23:13:01 +0000504 if (FD->getKind() == Decl::Function) {
505 IdentifierInfo *FunI = FD->getIdentifier();
506 initIdentifierInfo(C);
Anna Zaks3d348342012-02-14 21:55:24 +0000507
Jordan Rose6cd16c52012-07-10 23:13:01 +0000508 if (FunI == II_malloc || FunI == II_realloc ||
509 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
510 FunI == II_strdup || FunI == II_strndup)
511 return true;
512 }
Anna Zaks3d348342012-02-14 21:55:24 +0000513
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000514 if (ChecksEnabled[CK_MallocOptimistic] && FD->hasAttrs())
Anna Zaks46d01602012-05-18 01:16:10 +0000515 for (specific_attr_iterator<OwnershipAttr>
516 i = FD->specific_attr_begin<OwnershipAttr>(),
517 e = FD->specific_attr_end<OwnershipAttr>();
518 i != e; ++i)
519 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
520 return true;
521 return false;
522}
523
524bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
525 if (!FD)
526 return false;
527
Jordan Rose6cd16c52012-07-10 23:13:01 +0000528 if (FD->getKind() == Decl::Function) {
529 IdentifierInfo *FunI = FD->getIdentifier();
530 initIdentifierInfo(C);
Anna Zaks46d01602012-05-18 01:16:10 +0000531
Jordan Rose6cd16c52012-07-10 23:13:01 +0000532 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
533 return true;
534 }
Anna Zaks3d348342012-02-14 21:55:24 +0000535
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000536 if (ChecksEnabled[CK_MallocOptimistic] && FD->hasAttrs())
Anna Zaks46d01602012-05-18 01:16:10 +0000537 for (specific_attr_iterator<OwnershipAttr>
538 i = FD->specific_attr_begin<OwnershipAttr>(),
539 e = FD->specific_attr_end<OwnershipAttr>();
540 i != e; ++i)
541 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
542 (*i)->getOwnKind() == OwnershipAttr::Holds)
543 return true;
Anna Zaks3d348342012-02-14 21:55:24 +0000544 return false;
545}
546
Anton Yartsev8b662702013-03-28 16:10:38 +0000547// Tells if the callee is one of the following:
548// 1) A global non-placement new/delete operator function.
549// 2) A global placement operator function with the single placement argument
550// of type std::nothrow_t.
Anton Yartsev13df0362013-03-25 01:35:45 +0000551bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
552 ASTContext &C) const {
553 if (!FD)
554 return false;
555
556 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
557 if (Kind != OO_New && Kind != OO_Array_New &&
558 Kind != OO_Delete && Kind != OO_Array_Delete)
559 return false;
560
Anton Yartsev8b662702013-03-28 16:10:38 +0000561 // Skip all operator new/delete methods.
562 if (isa<CXXMethodDecl>(FD))
Anton Yartsev13df0362013-03-25 01:35:45 +0000563 return false;
564
565 // Return true if tested operator is a standard placement nothrow operator.
566 if (FD->getNumParams() == 2) {
567 QualType T = FD->getParamDecl(1)->getType();
568 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
569 return II->getName().equals("nothrow_t");
570 }
571
572 // Skip placement operators.
573 if (FD->getNumParams() != 1 || FD->isVariadic())
574 return false;
575
576 // One of the standard new/new[]/delete/delete[] non-placement operators.
577 return true;
578}
579
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000580void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosed6e5fd52012-09-20 01:55:32 +0000581 if (C.wasInlined)
582 return;
583
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000584 const FunctionDecl *FD = C.getCalleeDecl(CE);
585 if (!FD)
586 return;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000587
Anna Zaks40a7eb32012-02-22 19:24:52 +0000588 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000589 bool ReleasedAllocatedMemory = false;
Jordan Rose6cd16c52012-07-10 23:13:01 +0000590
591 if (FD->getKind() == Decl::Function) {
592 initIdentifierInfo(C.getASTContext());
593 IdentifierInfo *FunI = FD->getIdentifier();
594
Anton Yartseve3377fb2013-04-04 23:46:29 +0000595 if (FunI == II_malloc || FunI == II_valloc) {
596 if (CE->getNumArgs() < 1)
597 return;
598 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
599 } else if (FunI == II_realloc) {
600 State = ReallocMem(C, CE, false);
601 } else if (FunI == II_reallocf) {
602 State = ReallocMem(C, CE, true);
603 } else if (FunI == II_calloc) {
604 State = CallocMem(C, CE);
605 } else if (FunI == II_free) {
606 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
607 } else if (FunI == II_strdup) {
608 State = MallocUpdateRefState(C, CE, State);
609 } else if (FunI == II_strndup) {
610 State = MallocUpdateRefState(C, CE, State);
Anton Yartsev13df0362013-03-25 01:35:45 +0000611 }
Anton Yartseve3377fb2013-04-04 23:46:29 +0000612 else if (isStandardNewDelete(FD, C.getASTContext())) {
613 // Process direct calls to operator new/new[]/delete/delete[] functions
614 // as distinct from new/new[]/delete/delete[] expressions that are
615 // processed by the checkPostStmt callbacks for CXXNewExpr and
616 // CXXDeleteExpr.
617 OverloadedOperatorKind K = FD->getOverloadedOperator();
618 if (K == OO_New)
619 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
620 AF_CXXNew);
621 else if (K == OO_Array_New)
622 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
623 AF_CXXNewArray);
624 else if (K == OO_Delete || K == OO_Array_Delete)
625 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
626 else
627 llvm_unreachable("not a new/delete operator");
Jordan Rose6cd16c52012-07-10 23:13:01 +0000628 }
629 }
630
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000631 if (ChecksEnabled[CK_MallocOptimistic] ||
632 ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000633 // Check all the attributes, if there are any.
634 // There can be multiple of these attributes.
635 if (FD->hasAttrs())
636 for (specific_attr_iterator<OwnershipAttr>
637 i = FD->specific_attr_begin<OwnershipAttr>(),
638 e = FD->specific_attr_end<OwnershipAttr>();
639 i != e; ++i) {
640 switch ((*i)->getOwnKind()) {
641 case OwnershipAttr::Returns:
642 State = MallocMemReturnsAttr(C, CE, *i);
643 break;
644 case OwnershipAttr::Takes:
645 case OwnershipAttr::Holds:
646 State = FreeMemAttr(C, CE, *i);
647 break;
648 }
649 }
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000650 }
Anna Zaks199e8e52012-02-22 03:14:20 +0000651 C.addTransition(State);
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000652}
653
Anton Yartsev13df0362013-03-25 01:35:45 +0000654void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
655 CheckerContext &C) const {
656
657 if (NE->getNumPlacementArgs())
658 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
659 E = NE->placement_arg_end(); I != E; ++I)
660 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
661 checkUseAfterFree(Sym, C, *I);
662
Anton Yartsev13df0362013-03-25 01:35:45 +0000663 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
664 return;
665
666 ProgramStateRef State = C.getState();
667 // The return value from operator new is bound to a specified initialization
668 // value (if any) and we don't want to loose this value. So we call
669 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
670 // existing binding.
Anton Yartsev05789592013-03-28 17:05:19 +0000671 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
672 : AF_CXXNew);
Anton Yartsev13df0362013-03-25 01:35:45 +0000673 C.addTransition(State);
674}
675
676void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
677 CheckerContext &C) const {
678
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000679 if (!ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev13df0362013-03-25 01:35:45 +0000680 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
681 checkUseAfterFree(Sym, C, DE->getArgument());
682
Anton Yartsev13df0362013-03-25 01:35:45 +0000683 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
684 return;
685
686 ProgramStateRef State = C.getState();
687 bool ReleasedAllocated;
688 State = FreeMemAux(C, DE->getArgument(), DE, State,
689 /*Hold*/false, ReleasedAllocated);
690
691 C.addTransition(State);
692}
693
Jordan Rose613f3c02013-03-09 00:59:10 +0000694static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
695 // If the first selector piece is one of the names below, assume that the
696 // object takes ownership of the memory, promising to eventually deallocate it
697 // with free().
698 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
699 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
700 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
701 if (FirstSlot == "dataWithBytesNoCopy" ||
702 FirstSlot == "initWithBytesNoCopy" ||
703 FirstSlot == "initWithCharactersNoCopy")
704 return true;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000705
706 return false;
707}
708
Jordan Rose613f3c02013-03-09 00:59:10 +0000709static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
710 Selector S = Call.getSelector();
711
712 // FIXME: We should not rely on fully-constrained symbols being folded.
713 for (unsigned i = 1; i < S.getNumArgs(); ++i)
714 if (S.getNameForSlot(i).equals("freeWhenDone"))
715 return !Call.getArgSVal(i).isZeroConstant();
716
717 return None;
718}
719
Anna Zaks67291b92012-11-13 03:18:01 +0000720void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
721 CheckerContext &C) const {
Anna Zaksa7b1c472012-12-11 00:17:53 +0000722 if (C.wasInlined)
723 return;
724
Jordan Rose613f3c02013-03-09 00:59:10 +0000725 if (!isKnownDeallocObjCMethodName(Call))
726 return;
Anna Zaks67291b92012-11-13 03:18:01 +0000727
Jordan Rose613f3c02013-03-09 00:59:10 +0000728 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
729 if (!*FreeWhenDone)
730 return;
731
732 bool ReleasedAllocatedMemory;
733 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
734 Call.getOriginExpr(), C.getState(),
735 /*Hold=*/true, ReleasedAllocatedMemory,
736 /*RetNullOnFailure=*/true);
737
738 C.addTransition(State);
Anna Zaks0d6989b2012-06-22 02:04:31 +0000739}
740
Richard Smith852e9ce2013-11-27 01:46:48 +0000741ProgramStateRef
742MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
743 const OwnershipAttr *Att) const {
744 if (Att->getModule() != II_malloc)
Anna Zaks40a7eb32012-02-22 19:24:52 +0000745 return 0;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000746
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000747 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekd21139a2010-07-31 01:52:11 +0000748 if (I != E) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000749 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekd21139a2010-07-31 01:52:11 +0000750 }
Anna Zaks40a7eb32012-02-22 19:24:52 +0000751 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekd21139a2010-07-31 01:52:11 +0000752}
753
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000754ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xuc0484fa2009-12-12 12:29:38 +0000755 const CallExpr *CE,
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000756 SVal Size, SVal Init,
Anton Yartsev05789592013-03-28 17:05:19 +0000757 ProgramStateRef State,
758 AllocationFamily Family) {
Anna Zaks3563fde2012-06-07 03:57:32 +0000759
760 // Bind the return value to the symbolic value from the heap region.
761 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
762 // side effects other than what we model here.
Ted Kremenekd94854a2012-08-22 06:26:15 +0000763 unsigned Count = C.blockCount();
Anna Zaks3563fde2012-06-07 03:57:32 +0000764 SValBuilder &svalBuilder = C.getSValBuilder();
765 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie2fdacbc2013-02-20 05:52:05 +0000766 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
767 .castAs<DefinedSVal>();
Anton Yartsev05789592013-03-28 17:05:19 +0000768 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xu9cb53b82009-12-11 03:09:01 +0000769
Anna Zaksd5157482012-02-15 00:11:22 +0000770 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000771 if (!RetVal.getAs<Loc>())
Anna Zaksd5157482012-02-15 00:11:22 +0000772 return 0;
773
Jordy Rose674bd552010-07-04 00:00:41 +0000774 // Fill the region with the initialization value.
Anton Yartsev05789592013-03-28 17:05:19 +0000775 State = State->bindDefault(RetVal, Init);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +0000776
Jordy Rose674bd552010-07-04 00:00:41 +0000777 // Set the region's extent equal to the Size parameter.
Anna Zaks31886862012-02-10 01:11:00 +0000778 const SymbolicRegion *R =
Anna Zaks3563fde2012-06-07 03:57:32 +0000779 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks199e8e52012-02-22 03:14:20 +0000780 if (!R)
Anna Zaks31886862012-02-10 01:11:00 +0000781 return 0;
David Blaikie05785d12013-02-20 22:23:23 +0000782 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie2fdacbc2013-02-20 05:52:05 +0000783 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000784 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks199e8e52012-02-22 03:14:20 +0000785 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks199e8e52012-02-22 03:14:20 +0000786 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev05789592013-03-28 17:05:19 +0000787 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zaks31886862012-02-10 01:11:00 +0000788
Anton Yartsev05789592013-03-28 17:05:19 +0000789 State = State->assume(extentMatchesSize, true);
790 assert(State);
Anna Zaks199e8e52012-02-22 03:14:20 +0000791 }
Ted Kremenek90af9092010-12-02 07:49:45 +0000792
Anton Yartsev05789592013-03-28 17:05:19 +0000793 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks40a7eb32012-02-22 19:24:52 +0000794}
795
796ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev13df0362013-03-25 01:35:45 +0000797 const Expr *E,
Anton Yartsev05789592013-03-28 17:05:19 +0000798 ProgramStateRef State,
799 AllocationFamily Family) {
Anna Zaks40a7eb32012-02-22 19:24:52 +0000800 // Get the return value.
Anton Yartsev05789592013-03-28 17:05:19 +0000801 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks40a7eb32012-02-22 19:24:52 +0000802
803 // We expect the malloc functions to return a pointer.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000804 if (!retVal.getAs<Loc>())
Anna Zaks40a7eb32012-02-22 19:24:52 +0000805 return 0;
806
Ted Kremenek90af9092010-12-02 07:49:45 +0000807 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000808 assert(Sym);
Ted Kremenek90af9092010-12-02 07:49:45 +0000809
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000810 // Set the symbol's state to Allocated.
Anton Yartsev05789592013-03-28 17:05:19 +0000811 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000812}
813
Anna Zaks40a7eb32012-02-22 19:24:52 +0000814ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
815 const CallExpr *CE,
Richard Smith852e9ce2013-11-27 01:46:48 +0000816 const OwnershipAttr *Att) const {
817 if (Att->getModule() != II_malloc)
Anna Zaks40a7eb32012-02-22 19:24:52 +0000818 return 0;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000819
Anna Zaks8dc53af2012-03-01 22:06:06 +0000820 ProgramStateRef State = C.getState();
Anna Zaksfe6eb672012-08-24 02:28:20 +0000821 bool ReleasedAllocated = false;
Anna Zaks8dc53af2012-03-01 22:06:06 +0000822
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000823 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
824 I != E; ++I) {
Anna Zaks8dc53af2012-03-01 22:06:06 +0000825 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000826 Att->getOwnKind() == OwnershipAttr::Holds,
827 ReleasedAllocated);
Anna Zaks8dc53af2012-03-01 22:06:06 +0000828 if (StateI)
829 State = StateI;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000830 }
Anna Zaks8dc53af2012-03-01 22:06:06 +0000831 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000832}
833
Ted Kremenek49b1e382012-01-26 21:29:00 +0000834ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zaks31886862012-02-10 01:11:00 +0000835 const CallExpr *CE,
836 ProgramStateRef state,
837 unsigned Num,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000838 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000839 bool &ReleasedAllocated,
840 bool ReturnsNullOnFailure) const {
Anna Zaksb508d292012-04-10 23:41:11 +0000841 if (CE->getNumArgs() < (Num + 1))
842 return 0;
843
Anna Zaks67291b92012-11-13 03:18:01 +0000844 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
845 ReleasedAllocated, ReturnsNullOnFailure);
846}
847
Anna Zaksa14c1d02012-11-13 19:47:40 +0000848/// Checks if the previous call to free on the given symbol failed - if free
849/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramerba4c85e2012-11-22 15:02:44 +0000850static bool didPreviousFreeFail(ProgramStateRef State,
851 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaksa14c1d02012-11-13 19:47:40 +0000852 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks67291b92012-11-13 03:18:01 +0000853 if (Ret) {
854 assert(*Ret && "We should not store the null return symbol");
855 ConstraintManager &CMgr = State->getConstraintManager();
856 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaksa14c1d02012-11-13 19:47:40 +0000857 RetStatusSymbol = *Ret;
858 return FreeFailed.isConstrainedTrue();
Anna Zaks67291b92012-11-13 03:18:01 +0000859 }
Anna Zaksa14c1d02012-11-13 19:47:40 +0000860 return false;
Anna Zaks0d6989b2012-06-22 02:04:31 +0000861}
862
Anton Yartsev05789592013-03-28 17:05:19 +0000863AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartseve3377fb2013-04-04 23:46:29 +0000864 const Stmt *S) const {
865 if (!S)
Anton Yartsev05789592013-03-28 17:05:19 +0000866 return AF_None;
867
Anton Yartseve3377fb2013-04-04 23:46:29 +0000868 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev05789592013-03-28 17:05:19 +0000869 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartseve3377fb2013-04-04 23:46:29 +0000870
871 if (!FD)
872 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
873
Anton Yartsev05789592013-03-28 17:05:19 +0000874 ASTContext &Ctx = C.getASTContext();
875
Anton Yartseve3377fb2013-04-04 23:46:29 +0000876 if (isAllocationFunction(FD, Ctx) || isFreeFunction(FD, Ctx))
Anton Yartsev05789592013-03-28 17:05:19 +0000877 return AF_Malloc;
878
879 if (isStandardNewDelete(FD, Ctx)) {
880 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartseve3377fb2013-04-04 23:46:29 +0000881 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +0000882 return AF_CXXNew;
Anton Yartseve3377fb2013-04-04 23:46:29 +0000883 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev05789592013-03-28 17:05:19 +0000884 return AF_CXXNewArray;
885 }
886
887 return AF_None;
888 }
889
Anton Yartseve3377fb2013-04-04 23:46:29 +0000890 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
891 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
892
893 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +0000894 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
895
Anton Yartseve3377fb2013-04-04 23:46:29 +0000896 if (isa<ObjCMessageExpr>(S))
Anton Yartsev05789592013-03-28 17:05:19 +0000897 return AF_Malloc;
898
899 return AF_None;
900}
901
902bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
903 const Expr *E) const {
904 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
905 // FIXME: This doesn't handle indirect calls.
906 const FunctionDecl *FD = CE->getDirectCallee();
907 if (!FD)
908 return false;
909
910 os << *FD;
911 if (!FD->isOverloadedOperator())
912 os << "()";
913 return true;
914 }
915
916 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
917 if (Msg->isInstanceMessage())
918 os << "-";
919 else
920 os << "+";
Aaron Ballmanb190f972014-01-03 17:59:55 +0000921 Msg->getSelector().print(os);
Anton Yartsev05789592013-03-28 17:05:19 +0000922 return true;
923 }
924
925 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
926 os << "'"
927 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
928 << "'";
929 return true;
930 }
931
932 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
933 os << "'"
934 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
935 << "'";
936 return true;
937 }
938
939 return false;
940}
941
942void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
943 const Expr *E) const {
944 AllocationFamily Family = getAllocationFamily(C, E);
945
946 switch(Family) {
947 case AF_Malloc: os << "malloc()"; return;
948 case AF_CXXNew: os << "'new'"; return;
949 case AF_CXXNewArray: os << "'new[]'"; return;
950 case AF_None: llvm_unreachable("not a deallocation expression");
951 }
952}
953
954void MallocChecker::printExpectedDeallocName(raw_ostream &os,
955 AllocationFamily Family) const {
956 switch(Family) {
957 case AF_Malloc: os << "free()"; return;
958 case AF_CXXNew: os << "'delete'"; return;
959 case AF_CXXNewArray: os << "'delete[]'"; return;
960 case AF_None: llvm_unreachable("suspicious AF_None argument");
961 }
962}
963
Anna Zaks0d6989b2012-06-22 02:04:31 +0000964ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
965 const Expr *ArgExpr,
966 const Expr *ParentExpr,
Anna Zaks67291b92012-11-13 03:18:01 +0000967 ProgramStateRef State,
Anna Zaksfe6eb672012-08-24 02:28:20 +0000968 bool Hold,
Anna Zaks67291b92012-11-13 03:18:01 +0000969 bool &ReleasedAllocated,
970 bool ReturnsNullOnFailure) const {
Anna Zaks0d6989b2012-06-22 02:04:31 +0000971
Anna Zaks67291b92012-11-13 03:18:01 +0000972 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie2fdacbc2013-02-20 05:52:05 +0000973 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zaks31886862012-02-10 01:11:00 +0000974 return 0;
David Blaikie2fdacbc2013-02-20 05:52:05 +0000975 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekd21139a2010-07-31 01:52:11 +0000976
977 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000978 if (!location.getAs<Loc>())
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000979 return 0;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000980
Anna Zaksad01ef52012-02-14 00:26:13 +0000981 // The explicit NULL case, no operation is performed.
Ted Kremenek49b1e382012-01-26 21:29:00 +0000982 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000983 std::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekd21139a2010-07-31 01:52:11 +0000984 if (nullState && !notNullState)
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000985 return 0;
Ted Kremenekd21139a2010-07-31 01:52:11 +0000986
Jordy Rose3597b212010-06-07 19:32:37 +0000987 // Unknown values could easily be okay
988 // Undefined values are handled elsewhere
989 if (ArgVal.isUnknownOrUndef())
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000990 return 0;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +0000991
Jordy Rose3597b212010-06-07 19:32:37 +0000992 const MemRegion *R = ArgVal.getAsRegion();
993
994 // Nonlocs can't be freed, of course.
995 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
996 if (!R) {
Anton Yartsev05789592013-03-28 17:05:19 +0000997 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksc68bf4c2012-02-08 20:13:28 +0000998 return 0;
Jordy Rose3597b212010-06-07 19:32:37 +0000999 }
1000
1001 R = R->StripCasts();
1002
1003 // Blocks might show up as heap data, but should not be free()d
1004 if (isa<BlockDataRegion>(R)) {
Anton Yartsev05789592013-03-28 17:05:19 +00001005 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001006 return 0;
Jordy Rose3597b212010-06-07 19:32:37 +00001007 }
1008
1009 const MemSpaceRegion *MS = R->getMemorySpace();
1010
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001011 // Parameters, locals, statics, globals, and memory returned by alloca()
1012 // shouldn't be freed.
Jordy Rose3597b212010-06-07 19:32:37 +00001013 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1014 // FIXME: at the time this code was written, malloc() regions were
1015 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1016 // This means that there isn't actually anything from HeapSpaceRegion
1017 // that should be freed, even though we allow it here.
1018 // Of course, free() can work on memory allocated outside the current
1019 // function, so UnknownSpaceRegion is always a possibility.
1020 // False negatives are better than false positives.
1021
Anton Yartsev05789592013-03-28 17:05:19 +00001022 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001023 return 0;
Jordy Rose3597b212010-06-07 19:32:37 +00001024 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001025
1026 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose3597b212010-06-07 19:32:37 +00001027 // Various cases could lead to non-symbol values here.
1028 // For now, ignore them.
Anna Zaksc89ad072013-02-07 23:05:47 +00001029 if (!SrBase)
Anna Zaksc68bf4c2012-02-08 20:13:28 +00001030 return 0;
Jordy Rose3597b212010-06-07 19:32:37 +00001031
Anna Zaksc89ad072013-02-07 23:05:47 +00001032 SymbolRef SymBase = SrBase->getSymbol();
1033 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001034 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xue2bdb9a2010-01-18 03:27:34 +00001035
Anton Yartseve3377fb2013-04-04 23:46:29 +00001036 if (RsBase) {
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001037
Anna Zaks93a21a82013-04-09 00:30:28 +00001038 // Check for double free first.
1039 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
Anton Yartseve3377fb2013-04-04 23:46:29 +00001040 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1041 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1042 SymBase, PreviousRetStatusSymbol);
1043 return 0;
Anton Yartseve3377fb2013-04-04 23:46:29 +00001044
Anna Zaks93a21a82013-04-09 00:30:28 +00001045 // If the pointer is allocated or escaped, but we are now trying to free it,
1046 // check that the call to free is proper.
1047 } else if (RsBase->isAllocated() || RsBase->isEscaped()) {
1048
1049 // Check if an expected deallocation function matches the real one.
1050 bool DeallocMatchesAlloc =
1051 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1052 if (!DeallocMatchesAlloc) {
1053 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001054 ParentExpr, RsBase, SymBase, Hold);
Anna Zaks93a21a82013-04-09 00:30:28 +00001055 return 0;
1056 }
1057
1058 // Check if the memory location being freed is the actual location
1059 // allocated, or an offset.
1060 RegionOffset Offset = R->getAsOffset();
1061 if (Offset.isValid() &&
1062 !Offset.hasSymbolicOffset() &&
1063 Offset.getOffset() != 0) {
1064 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1065 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1066 AllocExpr);
1067 return 0;
1068 }
Anton Yartseve3377fb2013-04-04 23:46:29 +00001069 }
Anna Zaksc89ad072013-02-07 23:05:47 +00001070 }
1071
Jordan Rose2f8b0222013-08-15 17:22:06 +00001072 ReleasedAllocated = (RsBase != 0) && RsBase->isAllocated();
Anna Zaksfe6eb672012-08-24 02:28:20 +00001073
Anna Zaksa14c1d02012-11-13 19:47:40 +00001074 // Clean out the info on previous call to free return info.
Anna Zaksc89ad072013-02-07 23:05:47 +00001075 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaksa14c1d02012-11-13 19:47:40 +00001076
Anna Zaks67291b92012-11-13 03:18:01 +00001077 // Keep track of the return value. If it is NULL, we will know that free
1078 // failed.
1079 if (ReturnsNullOnFailure) {
1080 SVal RetVal = C.getSVal(ParentExpr);
1081 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1082 if (RetStatusSymbol) {
Anna Zaksc89ad072013-02-07 23:05:47 +00001083 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1084 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks67291b92012-11-13 03:18:01 +00001085 }
1086 }
1087
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001088 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1089 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001090 // Normal free.
Anton Yartsev05789592013-03-28 17:05:19 +00001091 if (Hold)
Anna Zaksc89ad072013-02-07 23:05:47 +00001092 return State->set<RegionState>(SymBase,
Anton Yartsev05789592013-03-28 17:05:19 +00001093 RefState::getRelinquished(Family,
1094 ParentExpr));
1095
1096 return State->set<RegionState>(SymBase,
1097 RefState::getReleased(Family, ParentExpr));
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001098}
1099
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001100Optional<MallocChecker::CheckKind>
1101MallocChecker::getCheckIfTracked(AllocationFamily Family) const {
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001102 switch (Family) {
1103 case AF_Malloc: {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001104 if (ChecksEnabled[CK_MallocOptimistic]) {
1105 return CK_MallocOptimistic;
1106 } else if (ChecksEnabled[CK_MallocPessimistic]) {
1107 return CK_MallocPessimistic;
1108 }
1109 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001110 }
1111 case AF_CXXNew:
1112 case AF_CXXNewArray: {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001113 if (ChecksEnabled[CK_NewDeleteChecker]) {
1114 return CK_NewDeleteChecker;
1115 }
1116 return Optional<MallocChecker::CheckKind>();
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001117 }
1118 case AF_None: {
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001119 llvm_unreachable("no family");
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001120 }
Anton Yartsev717aa0e2013-04-05 00:31:02 +00001121 }
Anton Yartsev2f910042013-04-05 02:12:04 +00001122 llvm_unreachable("unhandled family");
Anton Yartseve3377fb2013-04-04 23:46:29 +00001123}
1124
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001125Optional<MallocChecker::CheckKind>
1126MallocChecker::getCheckIfTracked(CheckerContext &C,
1127 const Stmt *AllocDeallocStmt) const {
1128 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt));
Anton Yartseve3377fb2013-04-04 23:46:29 +00001129}
1130
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001131Optional<MallocChecker::CheckKind>
1132MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym) const {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001133
Anton Yartsev030bcdd2013-04-05 19:08:04 +00001134 const RefState *RS = C.getState()->get<RegionState>(Sym);
1135 assert(RS);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001136 return getCheckIfTracked(RS->getAllocationFamily());
Anton Yartseve3377fb2013-04-04 23:46:29 +00001137}
1138
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001139bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikie05785d12013-02-20 22:23:23 +00001140 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001141 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001142 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose3597b212010-06-07 19:32:37 +00001143 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie05785d12013-02-20 22:23:23 +00001144 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner5a9b1ec2011-02-17 05:38:27 +00001145 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose3597b212010-06-07 19:32:37 +00001146 else
1147 return false;
1148
1149 return true;
1150}
1151
Ted Kremenek5ef32db2011-08-12 23:37:29 +00001152bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose3597b212010-06-07 19:32:37 +00001153 const MemRegion *MR) {
1154 switch (MR->getKind()) {
1155 case MemRegion::FunctionTextRegionKind: {
Anna Zaks42782342012-09-17 19:13:56 +00001156 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose3597b212010-06-07 19:32:37 +00001157 if (FD)
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001158 os << "the address of the function '" << *FD << '\'';
Jordy Rose3597b212010-06-07 19:32:37 +00001159 else
1160 os << "the address of a function";
1161 return true;
1162 }
1163 case MemRegion::BlockTextRegionKind:
1164 os << "block text";
1165 return true;
1166 case MemRegion::BlockDataRegionKind:
1167 // FIXME: where the block came from?
1168 os << "a block";
1169 return true;
1170 default: {
1171 const MemSpaceRegion *MS = MR->getMemorySpace();
1172
Anna Zaks8158ef02012-01-04 23:54:01 +00001173 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001174 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1175 const VarDecl *VD;
1176 if (VR)
1177 VD = VR->getDecl();
1178 else
1179 VD = NULL;
1180
1181 if (VD)
1182 os << "the address of the local variable '" << VD->getName() << "'";
1183 else
1184 os << "the address of a local stack variable";
1185 return true;
1186 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001187
1188 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001189 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1190 const VarDecl *VD;
1191 if (VR)
1192 VD = VR->getDecl();
1193 else
1194 VD = NULL;
1195
1196 if (VD)
1197 os << "the address of the parameter '" << VD->getName() << "'";
1198 else
1199 os << "the address of a parameter";
1200 return true;
1201 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001202
1203 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose3597b212010-06-07 19:32:37 +00001204 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1205 const VarDecl *VD;
1206 if (VR)
1207 VD = VR->getDecl();
1208 else
1209 VD = NULL;
1210
1211 if (VD) {
1212 if (VD->isStaticLocal())
1213 os << "the address of the static variable '" << VD->getName() << "'";
1214 else
1215 os << "the address of the global variable '" << VD->getName() << "'";
1216 } else
1217 os << "the address of a global variable";
1218 return true;
1219 }
Anna Zaks8158ef02012-01-04 23:54:01 +00001220
1221 return false;
Jordy Rose3597b212010-06-07 19:32:37 +00001222 }
1223 }
1224}
1225
Anton Yartsev05789592013-03-28 17:05:19 +00001226void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1227 SourceRange Range,
1228 const Expr *DeallocExpr) const {
1229
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001230 if (!ChecksEnabled[CK_MallocOptimistic] &&
1231 !ChecksEnabled[CK_MallocPessimistic] &&
1232 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001233 return;
1234
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001235 Optional<MallocChecker::CheckKind> CheckKind =
1236 getCheckIfTracked(C, DeallocExpr);
1237 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001238 return;
1239
Ted Kremenek750b7ac2010-12-20 21:19:09 +00001240 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001241 if (!BT_BadFree[*CheckKind])
1242 BT_BadFree[*CheckKind].reset(
1243 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1244
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001245 SmallString<100> buf;
Jordy Rose3597b212010-06-07 19:32:37 +00001246 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001247
Jordy Rose3597b212010-06-07 19:32:37 +00001248 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev05789592013-03-28 17:05:19 +00001249 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1250 MR = ER->getSuperRegion();
1251
1252 if (MR && isa<AllocaRegion>(MR))
1253 os << "Memory allocated by alloca() should not be deallocated";
1254 else {
1255 os << "Argument to ";
1256 if (!printAllocDeallocName(os, C, DeallocExpr))
1257 os << "deallocator";
1258
1259 os << " is ";
1260 bool Summarized = MR ? SummarizeRegion(os, MR)
1261 : SummarizeValue(os, ArgVal);
1262 if (Summarized)
1263 os << ", which is not memory allocated by ";
Jordy Rose3597b212010-06-07 19:32:37 +00001264 else
Anton Yartsev05789592013-03-28 17:05:19 +00001265 os << "not memory allocated by ";
1266
1267 printExpectedAllocName(os, C, DeallocExpr);
Jordy Rose3597b212010-06-07 19:32:37 +00001268 }
Anton Yartsev05789592013-03-28 17:05:19 +00001269
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001270 BugReport *R = new BugReport(*BT_BadFree[*CheckKind], os.str(), N);
Ted Kremenek1e809b42012-03-09 01:13:14 +00001271 R->markInteresting(MR);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001272 R->addRange(Range);
Jordan Rosee10d5a72012-11-02 01:53:40 +00001273 C.emitReport(R);
Jordy Rose3597b212010-06-07 19:32:37 +00001274 }
1275}
1276
Anton Yartseve3377fb2013-04-04 23:46:29 +00001277void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1278 SourceRange Range,
1279 const Expr *DeallocExpr,
Anton Yartsevf0593d62013-04-05 11:25:10 +00001280 const RefState *RS,
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001281 SymbolRef Sym,
1282 bool OwnershipTransferred) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001283
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001284 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001285 return;
1286
1287 if (ExplodedNode *N = C.generateSink()) {
Anton Yartseve3377fb2013-04-04 23:46:29 +00001288 if (!BT_MismatchedDealloc)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001289 BT_MismatchedDealloc.reset(
1290 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1291 "Bad deallocator", "Memory Error"));
1292
Anton Yartsev05789592013-03-28 17:05:19 +00001293 SmallString<100> buf;
1294 llvm::raw_svector_ostream os(buf);
1295
1296 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1297 SmallString<20> AllocBuf;
1298 llvm::raw_svector_ostream AllocOs(AllocBuf);
1299 SmallString<20> DeallocBuf;
1300 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1301
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001302 if (OwnershipTransferred) {
1303 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1304 os << DeallocOs.str() << " cannot";
1305 else
1306 os << "Cannot";
Anton Yartsev05789592013-03-28 17:05:19 +00001307
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001308 os << " take ownership of memory";
Anton Yartsev05789592013-03-28 17:05:19 +00001309
Anton Yartsevf5bccce2013-09-16 17:51:25 +00001310 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1311 os << " allocated by " << AllocOs.str();
1312 } else {
1313 os << "Memory";
1314 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1315 os << " allocated by " << AllocOs.str();
1316
1317 os << " should be deallocated by ";
1318 printExpectedDeallocName(os, RS->getAllocationFamily());
1319
1320 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1321 os << ", not " << DeallocOs.str();
1322 }
Anton Yartsev05789592013-03-28 17:05:19 +00001323
Anton Yartseve3377fb2013-04-04 23:46:29 +00001324 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001325 R->markInteresting(Sym);
Anton Yartsev05789592013-03-28 17:05:19 +00001326 R->addRange(Range);
Anton Yartsevf0593d62013-04-05 11:25:10 +00001327 R->addVisitor(new MallocBugVisitor(Sym));
Anton Yartsev05789592013-03-28 17:05:19 +00001328 C.emitReport(R);
1329 }
1330}
1331
Anna Zaksc89ad072013-02-07 23:05:47 +00001332void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev05789592013-03-28 17:05:19 +00001333 SourceRange Range, const Expr *DeallocExpr,
1334 const Expr *AllocExpr) const {
1335
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001336 if (!ChecksEnabled[CK_MallocOptimistic] &&
1337 !ChecksEnabled[CK_MallocPessimistic] &&
1338 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001339 return;
1340
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001341 Optional<MallocChecker::CheckKind> CheckKind =
1342 getCheckIfTracked(C, AllocExpr);
1343 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001344 return;
1345
Anna Zaksc89ad072013-02-07 23:05:47 +00001346 ExplodedNode *N = C.generateSink();
1347 if (N == NULL)
1348 return;
1349
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001350 if (!BT_OffsetFree[*CheckKind])
1351 BT_OffsetFree[*CheckKind].reset(
1352 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
Anna Zaksc89ad072013-02-07 23:05:47 +00001353
1354 SmallString<100> buf;
1355 llvm::raw_svector_ostream os(buf);
Anton Yartsev05789592013-03-28 17:05:19 +00001356 SmallString<20> AllocNameBuf;
1357 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaksc89ad072013-02-07 23:05:47 +00001358
1359 const MemRegion *MR = ArgVal.getAsRegion();
1360 assert(MR && "Only MemRegion based symbols can have offset free errors");
1361
1362 RegionOffset Offset = MR->getAsOffset();
1363 assert((Offset.isValid() &&
1364 !Offset.hasSymbolicOffset() &&
1365 Offset.getOffset() != 0) &&
1366 "Only symbols with a valid offset can have offset free errors");
1367
1368 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1369
Anton Yartsev05789592013-03-28 17:05:19 +00001370 os << "Argument to ";
1371 if (!printAllocDeallocName(os, C, DeallocExpr))
1372 os << "deallocator";
1373 os << " is offset by "
Anna Zaksc89ad072013-02-07 23:05:47 +00001374 << offsetBytes
1375 << " "
1376 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev05789592013-03-28 17:05:19 +00001377 << " from the start of ";
1378 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1379 os << "memory allocated by " << AllocNameOs.str();
1380 else
1381 os << "allocated memory";
Anna Zaksc89ad072013-02-07 23:05:47 +00001382
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001383 BugReport *R = new BugReport(*BT_OffsetFree[*CheckKind], os.str(), N);
Anna Zaksc89ad072013-02-07 23:05:47 +00001384 R->markInteresting(MR->getBaseRegion());
1385 R->addRange(Range);
1386 C.emitReport(R);
1387}
1388
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001389void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1390 SymbolRef Sym) const {
1391
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001392 if (!ChecksEnabled[CK_MallocOptimistic] &&
1393 !ChecksEnabled[CK_MallocPessimistic] &&
1394 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001395 return;
1396
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001397 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1398 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001399 return;
1400
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001401 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001402 if (!BT_UseFree[*CheckKind])
1403 BT_UseFree[*CheckKind].reset(new BugType(
1404 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001405
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001406 BugReport *R = new BugReport(*BT_UseFree[*CheckKind],
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001407 "Use of memory after it is freed", N);
1408
1409 R->markInteresting(Sym);
1410 R->addRange(Range);
1411 R->addVisitor(new MallocBugVisitor(Sym));
1412 C.emitReport(R);
1413 }
1414}
1415
1416void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1417 bool Released, SymbolRef Sym,
Anton Yartsev6c2af432013-03-13 17:07:32 +00001418 SymbolRef PrevSym) const {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001419
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001420 if (!ChecksEnabled[CK_MallocOptimistic] &&
1421 !ChecksEnabled[CK_MallocPessimistic] &&
1422 !ChecksEnabled[CK_NewDeleteChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001423 return;
1424
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001425 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1426 if (!CheckKind.hasValue())
Anton Yartseve3377fb2013-04-04 23:46:29 +00001427 return;
1428
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001429 if (ExplodedNode *N = C.generateSink()) {
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001430 if (!BT_DoubleFree[*CheckKind])
1431 BT_DoubleFree[*CheckKind].reset(
1432 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001433
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001434 BugReport *R =
1435 new BugReport(*BT_DoubleFree[*CheckKind],
1436 (Released ? "Attempt to free released memory"
1437 : "Attempt to free non-owned memory"),
1438 N);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001439 R->addRange(Range);
Anton Yartsev6c2af432013-03-13 17:07:32 +00001440 R->markInteresting(Sym);
1441 if (PrevSym)
1442 R->markInteresting(PrevSym);
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001443 R->addVisitor(new MallocBugVisitor(Sym));
1444 C.emitReport(R);
1445 }
1446}
1447
Jordan Rose656fdd52014-01-08 18:46:55 +00001448void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1449
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001450 if (!ChecksEnabled[CK_NewDeleteChecker])
Jordan Rose656fdd52014-01-08 18:46:55 +00001451 return;
1452
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001453 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1454 if (!CheckKind.hasValue())
Jordan Rose656fdd52014-01-08 18:46:55 +00001455 return;
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001456 assert(*CheckKind == CK_NewDeleteChecker && "invalid check kind");
Jordan Rose656fdd52014-01-08 18:46:55 +00001457
1458 if (ExplodedNode *N = C.generateSink()) {
1459 if (!BT_DoubleDelete)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001460 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1461 "Double delete", "Memory Error"));
Jordan Rose656fdd52014-01-08 18:46:55 +00001462
1463 BugReport *R = new BugReport(*BT_DoubleDelete,
1464 "Attempt to delete released memory", N);
1465
1466 R->markInteresting(Sym);
1467 R->addVisitor(new MallocBugVisitor(Sym));
1468 C.emitReport(R);
1469 }
1470}
1471
Anna Zaks40a7eb32012-02-22 19:24:52 +00001472ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1473 const CallExpr *CE,
1474 bool FreesOnFail) const {
Anna Zaksb508d292012-04-10 23:41:11 +00001475 if (CE->getNumArgs() < 2)
1476 return 0;
1477
Ted Kremenek49b1e382012-01-26 21:29:00 +00001478 ProgramStateRef state = C.getState();
Ted Kremenek90af9092010-12-02 07:49:45 +00001479 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek632e3b72012-01-06 22:09:28 +00001480 const LocationContext *LCtx = C.getLocationContext();
Anna Zaks31886862012-02-10 01:11:00 +00001481 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001482 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks40a7eb32012-02-22 19:24:52 +00001483 return 0;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001484 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001485
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001486 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001487
Ted Kremenek90af9092010-12-02 07:49:45 +00001488 DefinedOrUnknownSVal PtrEQ =
1489 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001490
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001491 // Get the size argument. If there is no size arg then give up.
1492 const Expr *Arg1 = CE->getArg(1);
1493 if (!Arg1)
Anna Zaks40a7eb32012-02-22 19:24:52 +00001494 return 0;
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001495
1496 // Get the value of the size argument.
Anna Zaks31886862012-02-10 01:11:00 +00001497 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie2fdacbc2013-02-20 05:52:05 +00001498 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks40a7eb32012-02-22 19:24:52 +00001499 return 0;
David Blaikie2fdacbc2013-02-20 05:52:05 +00001500 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001501
1502 // Compare the size argument to 0.
1503 DefinedOrUnknownSVal SizeZero =
1504 svalBuilder.evalEQ(state, Arg1Val,
1505 svalBuilder.makeIntValWithPtrWidth(0, false));
1506
Anna Zaksd56c8792012-02-13 18:05:39 +00001507 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001508 std::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
Anna Zaksd56c8792012-02-13 18:05:39 +00001509 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001510 std::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
Anna Zaksd56c8792012-02-13 18:05:39 +00001511 // We only assume exceptional states if they are definitely true; if the
1512 // state is under-constrained, assume regular realloc behavior.
1513 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1514 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1515
Lenny Maiorani005b5c12011-04-27 14:49:29 +00001516 // If the ptr is NULL and the size is not 0, the call is equivalent to
1517 // malloc(size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001518 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks40a7eb32012-02-22 19:24:52 +00001519 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksd56c8792012-02-13 18:05:39 +00001520 UndefinedVal(), StatePtrIsNull);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001521 return stateMalloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001522 }
1523
Anna Zaksd56c8792012-02-13 18:05:39 +00001524 if (PrtIsNull && SizeIsZero)
Anna Zaks40a7eb32012-02-22 19:24:52 +00001525 return 0;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001526
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001527 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksd56c8792012-02-13 18:05:39 +00001528 assert(!PrtIsNull);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001529 SymbolRef FromPtr = arg0Val.getAsSymbol();
1530 SVal RetVal = state->getSVal(CE, LCtx);
1531 SymbolRef ToPtr = RetVal.getAsSymbol();
1532 if (!FromPtr || !ToPtr)
Anna Zaks40a7eb32012-02-22 19:24:52 +00001533 return 0;
Anna Zaksd56c8792012-02-13 18:05:39 +00001534
Anna Zaksfe6eb672012-08-24 02:28:20 +00001535 bool ReleasedAllocated = false;
1536
Anna Zaksd56c8792012-02-13 18:05:39 +00001537 // If the size is 0, free the memory.
1538 if (SizeIsZero)
Anna Zaksfe6eb672012-08-24 02:28:20 +00001539 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1540 false, ReleasedAllocated)){
Anna Zaksd56c8792012-02-13 18:05:39 +00001541 // The semantics of the return value are:
1542 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaks52242a62012-08-03 18:30:18 +00001543 // to free() is returned. We just free the input pointer and do not add
1544 // any constrains on the output pointer.
Anna Zaks40a7eb32012-02-22 19:24:52 +00001545 return stateFree;
Anna Zaksd56c8792012-02-13 18:05:39 +00001546 }
1547
1548 // Default behavior.
Anna Zaksfe6eb672012-08-24 02:28:20 +00001549 if (ProgramStateRef stateFree =
1550 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1551
Anna Zaksd56c8792012-02-13 18:05:39 +00001552 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1553 UnknownVal(), stateFree);
Anna Zaks8fd0f2a2012-02-13 20:57:07 +00001554 if (!stateRealloc)
Anna Zaks40a7eb32012-02-22 19:24:52 +00001555 return 0;
Anna Zaksfe6eb672012-08-24 02:28:20 +00001556
Anna Zaks75cfbb62012-09-12 22:57:34 +00001557 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1558 if (FreesOnFail)
1559 Kind = RPIsFreeOnFailure;
1560 else if (!ReleasedAllocated)
1561 Kind = RPDoNotTrackAfterFailure;
1562
Anna Zaksfe6eb672012-08-24 02:28:20 +00001563 // Record the info about the reallocated symbol so that we could properly
1564 // process failed reallocation.
Anna Zaksac068142012-02-15 00:11:25 +00001565 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks75cfbb62012-09-12 22:57:34 +00001566 ReallocPair(FromPtr, Kind));
Anna Zaksfe6eb672012-08-24 02:28:20 +00001567 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksad01ef52012-02-14 00:26:13 +00001568 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks40a7eb32012-02-22 19:24:52 +00001569 return stateRealloc;
Zhongxing Xuc0484fa2009-12-12 12:29:38 +00001570 }
Anna Zaks40a7eb32012-02-22 19:24:52 +00001571 return 0;
Zhongxing Xu88cca6b2009-11-12 08:38:56 +00001572}
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001573
Anna Zaks40a7eb32012-02-22 19:24:52 +00001574ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaksb508d292012-04-10 23:41:11 +00001575 if (CE->getNumArgs() < 2)
1576 return 0;
1577
Ted Kremenek49b1e382012-01-26 21:29:00 +00001578 ProgramStateRef state = C.getState();
Ted Kremenek9d0bb1e2010-12-01 21:28:31 +00001579 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek632e3b72012-01-06 22:09:28 +00001580 const LocationContext *LCtx = C.getLocationContext();
1581 SVal count = state->getSVal(CE->getArg(0), LCtx);
1582 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenek90af9092010-12-02 07:49:45 +00001583 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1584 svalBuilder.getContext().getSizeType());
1585 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001586
Anna Zaks40a7eb32012-02-22 19:24:52 +00001587 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xu527ff6d2010-06-01 03:01:33 +00001588}
1589
Anna Zaksfc2e1532012-03-21 19:45:08 +00001590LeakInfo
Anna Zaksdf901a42012-02-23 21:38:21 +00001591MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1592 CheckerContext &C) const {
Anna Zaks43ffba22012-02-27 23:40:55 +00001593 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksdf901a42012-02-23 21:38:21 +00001594 // Walk the ExplodedGraph backwards and find the first node that referred to
1595 // the tracked symbol.
1596 const ExplodedNode *AllocNode = N;
Anna Zaksfc2e1532012-03-21 19:45:08 +00001597 const MemRegion *ReferenceRegion = 0;
Anna Zaksdf901a42012-02-23 21:38:21 +00001598
1599 while (N) {
Anna Zaksfc2e1532012-03-21 19:45:08 +00001600 ProgramStateRef State = N->getState();
1601 if (!State->get<RegionState>(Sym))
Anna Zaksdf901a42012-02-23 21:38:21 +00001602 break;
Anna Zaksfc2e1532012-03-21 19:45:08 +00001603
1604 // Find the most recent expression bound to the symbol in the current
1605 // context.
Anna Zaks7c19abe2013-04-10 21:42:02 +00001606 if (!ReferenceRegion) {
1607 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1608 SVal Val = State->getSVal(MR);
1609 if (Val.getAsLocSymbol() == Sym) {
Anna Zaks07804ef2013-04-10 22:56:33 +00001610 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
Anna Zaks7c19abe2013-04-10 21:42:02 +00001611 // Do not show local variables belonging to a function other than
1612 // where the error is reported.
1613 if (!VR ||
1614 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1615 ReferenceRegion = MR;
1616 }
1617 }
Benjamin Kramerc25c5e02012-03-21 21:03:48 +00001618 }
Anna Zaksfc2e1532012-03-21 19:45:08 +00001619
Anna Zaks43ffba22012-02-27 23:40:55 +00001620 // Allocation node, is the last node in the current context in which the
1621 // symbol was tracked.
1622 if (N->getLocationContext() == LeakContext)
1623 AllocNode = N;
Anna Zaksdf901a42012-02-23 21:38:21 +00001624 N = N->pred_empty() ? NULL : *(N->pred_begin());
1625 }
1626
Anna Zaksa043d0c2013-01-08 00:25:29 +00001627 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksdf901a42012-02-23 21:38:21 +00001628}
1629
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001630void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1631 CheckerContext &C) const {
Anton Yartsev05789592013-03-28 17:05:19 +00001632
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001633 if (!ChecksEnabled[CK_MallocOptimistic] &&
1634 !ChecksEnabled[CK_MallocPessimistic] &&
1635 !ChecksEnabled[CK_NewDeleteLeaksChecker])
Anton Yartsev05789592013-03-28 17:05:19 +00001636 return;
1637
Jordan Rose26330562013-04-05 17:55:00 +00001638 const RefState *RS = C.getState()->get<RegionState>(Sym);
1639 assert(RS && "cannot leak an untracked symbol");
1640 AllocationFamily Family = RS->getAllocationFamily();
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001641 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
1642 if (!CheckKind.hasValue())
Anton Yartsev6e499252013-04-05 02:25:02 +00001643 return;
1644
Jordan Rose26330562013-04-05 17:55:00 +00001645 // Special case for new and new[]; these are controlled by a separate checker
1646 // flag so that they can be selectively disabled.
1647 if (Family == AF_CXXNew || Family == AF_CXXNewArray)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001648 if (!ChecksEnabled[CK_NewDeleteLeaksChecker])
Jordan Rose26330562013-04-05 17:55:00 +00001649 return;
1650
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001651 assert(N);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001652 if (!BT_Leak[*CheckKind]) {
1653 BT_Leak[*CheckKind].reset(
1654 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001655 // Leaks should not be reported if they are post-dominated by a sink:
1656 // (1) Sinks are higher importance bugs.
1657 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1658 // with __noreturn functions such as assert() or exit(). We choose not
1659 // to report leaks on such paths.
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001660 BT_Leak[*CheckKind]->setSuppressOnSink(true);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001661 }
1662
Anna Zaksdf901a42012-02-23 21:38:21 +00001663 // Most bug reports are cached at the location where they occurred.
1664 // With leaks, we want to unique them by the location where they were
1665 // allocated, and only report a single path.
Anna Zaks43ffba22012-02-27 23:40:55 +00001666 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaksa043d0c2013-01-08 00:25:29 +00001667 const ExplodedNode *AllocNode = 0;
Anna Zaksfc2e1532012-03-21 19:45:08 +00001668 const MemRegion *Region = 0;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001669 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
Anna Zaksa043d0c2013-01-08 00:25:29 +00001670
1671 ProgramPoint P = AllocNode->getLocation();
1672 const Stmt *AllocationStmt = 0;
David Blaikie87396b92013-02-21 22:23:56 +00001673 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001674 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00001675 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaksa043d0c2013-01-08 00:25:29 +00001676 AllocationStmt = SP->getStmt();
Anton Yartsev6e499252013-04-05 02:25:02 +00001677 if (AllocationStmt)
Anna Zaksa043d0c2013-01-08 00:25:29 +00001678 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1679 C.getSourceManager(),
1680 AllocNode->getLocationContext());
Anna Zaksdf901a42012-02-23 21:38:21 +00001681
Anna Zaksfc2e1532012-03-21 19:45:08 +00001682 SmallString<200> buf;
1683 llvm::raw_svector_ostream os(buf);
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001684 if (Region && Region->canPrintPretty()) {
Anna Zaks6cea7d92013-04-12 18:40:21 +00001685 os << "Potential leak of memory pointed to by ";
Jordan Rosed86b3bd2012-08-08 18:23:36 +00001686 Region->printPretty(os);
Anna Zaksa1de8562013-04-06 00:41:36 +00001687 } else {
1688 os << "Potential memory leak";
Anna Zaksfc2e1532012-03-21 19:45:08 +00001689 }
1690
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001691 BugReport *R =
1692 new BugReport(*BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
1693 AllocNode->getLocationContext()->getDecl());
Ted Kremenek1e809b42012-03-09 01:13:14 +00001694 R->markInteresting(Sym);
Anna Zaks62cce9e2012-05-10 01:37:40 +00001695 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rosee10d5a72012-11-02 01:53:40 +00001696 C.emitReport(R);
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001697}
1698
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00001699void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1700 CheckerContext &C) const
Ted Kremenek90af9092010-12-02 07:49:45 +00001701{
Zhongxing Xubce831f2010-08-15 08:19:57 +00001702 if (!SymReaper.hasDeadSymbols())
1703 return;
Zhongxing Xuc7460962009-11-13 07:48:11 +00001704
Ted Kremenek49b1e382012-01-26 21:29:00 +00001705 ProgramStateRef state = C.getState();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001706 RegionStateTy RS = state->get<RegionState>();
Jordy Rose82584992010-08-18 04:33:47 +00001707 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xubce831f2010-08-15 08:19:57 +00001708
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001709 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xubce831f2010-08-15 08:19:57 +00001710 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1711 if (SymReaper.isDead(I->first)) {
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001712 if (I->second.isAllocated())
Anna Zaks78edc2f2012-02-09 06:48:19 +00001713 Errors.push_back(I->first);
Jordy Rose82584992010-08-18 04:33:47 +00001714 // Remove the dead symbol from the map.
Ted Kremenekb3b56c62010-11-24 00:54:37 +00001715 RS = F.remove(RS, I->first);
Ted Kremeneke227f492011-07-28 23:07:51 +00001716
Zhongxing Xuc7460962009-11-13 07:48:11 +00001717 }
1718 }
Ted Kremeneke227f492011-07-28 23:07:51 +00001719
Anna Zaksd56c8792012-02-13 18:05:39 +00001720 // Cleanup the Realloc Pairs Map.
Jordan Rose0c153cb2012-11-02 01:54:06 +00001721 ReallocPairsTy RP = state->get<ReallocPairs>();
1722 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksac068142012-02-15 00:11:25 +00001723 if (SymReaper.isDead(I->first) ||
1724 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksd56c8792012-02-13 18:05:39 +00001725 state = state->remove<ReallocPairs>(I->first);
1726 }
1727 }
1728
Anna Zaks67291b92012-11-13 03:18:01 +00001729 // Cleanup the FreeReturnValue Map.
1730 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1731 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1732 if (SymReaper.isDead(I->first) ||
1733 SymReaper.isDead(I->second)) {
1734 state = state->remove<FreeReturnValue>(I->first);
1735 }
1736 }
1737
Anna Zaksdf901a42012-02-23 21:38:21 +00001738 // Generate leak node.
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001739 ExplodedNode *N = C.getPredecessor();
1740 if (!Errors.empty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00001741 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001742 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Craig Topper2341c0d2013-07-04 03:08:24 +00001743 for (SmallVectorImpl<SymbolRef>::iterator
1744 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksd3571e5a2012-02-11 21:02:40 +00001745 reportLeak(*I, N, C);
Anna Zaks78edc2f2012-02-09 06:48:19 +00001746 }
Ted Kremeneke227f492011-07-28 23:07:51 +00001747 }
Anna Zaks58a2c4e2012-10-29 22:51:54 +00001748
Anna Zaksdf901a42012-02-23 21:38:21 +00001749 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xuc4902a52009-11-13 07:25:27 +00001750}
Zhongxing Xu4668c7e2009-11-17 07:54:15 +00001751
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001752void MallocChecker::checkPreCall(const CallEvent &Call,
1753 CheckerContext &C) const {
1754
Jordan Rose656fdd52014-01-08 18:46:55 +00001755 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
1756 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
1757 if (!Sym || checkDoubleDelete(Sym, C))
1758 return;
1759 }
1760
Anna Zaks46d01602012-05-18 01:16:10 +00001761 // We will check for double free in the post visit.
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001762 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
1763 const FunctionDecl *FD = FC->getDecl();
1764 if (!FD)
1765 return;
Anton Yartsev13df0362013-03-25 01:35:45 +00001766
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001767 if ((ChecksEnabled[CK_MallocOptimistic] ||
1768 ChecksEnabled[CK_MallocPessimistic]) &&
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001769 isFreeFunction(FD, C.getASTContext()))
1770 return;
Anna Zaks3d348342012-02-14 21:55:24 +00001771
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00001772 if (ChecksEnabled[CK_NewDeleteChecker] &&
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001773 isStandardNewDelete(FD, C.getASTContext()))
1774 return;
1775 }
1776
1777 // Check if the callee of a method is deleted.
1778 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
1779 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
1780 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
1781 return;
1782 }
1783
1784 // Check arguments for being used after free.
1785 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
1786 SVal ArgSVal = Call.getArgSVal(I);
1787 if (ArgSVal.getAs<Loc>()) {
1788 SymbolRef Sym = ArgSVal.getAsSymbol();
Anna Zaks3d348342012-02-14 21:55:24 +00001789 if (!Sym)
1790 continue;
Anton Yartsevcb2ccd62013-04-10 22:21:41 +00001791 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
Anna Zaks3d348342012-02-14 21:55:24 +00001792 return;
1793 }
1794 }
1795}
1796
Anna Zaksa1b227b2012-02-08 23:16:56 +00001797void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1798 const Expr *E = S->getRetValue();
1799 if (!E)
1800 return;
Anna Zaks3aa52252012-02-11 21:44:39 +00001801
1802 // Check if we are returning a symbol.
Jordan Rose356279c2012-08-08 18:23:31 +00001803 ProgramStateRef State = C.getState();
1804 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaks4ca45b12012-02-22 02:36:01 +00001805 SymbolRef Sym = RetVal.getAsSymbol();
1806 if (!Sym)
1807 // If we are returning a field of the allocated struct or an array element,
1808 // the callee could still free the memory.
1809 // TODO: This logic should be a part of generic symbol escape callback.
1810 if (const MemRegion *MR = RetVal.getAsRegion())
1811 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1812 if (const SymbolicRegion *BMR =
1813 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1814 Sym = BMR->getSymbol();
Zhongxing Xu23baa012009-11-17 08:58:18 +00001815
Anna Zaks3aa52252012-02-11 21:44:39 +00001816 // Check if we are returning freed memory.
Jordan Rose356279c2012-08-08 18:23:31 +00001817 if (Sym)
Jordan Rosef1f26142012-11-15 19:11:33 +00001818 checkUseAfterFree(Sym, C, E);
Zhongxing Xu23baa012009-11-17 08:58:18 +00001819}
Zhongxing Xub0e15df2009-12-31 06:13:07 +00001820
Anna Zaks9fe80982012-03-22 00:57:20 +00001821// TODO: Blocks should be either inlined or should call invalidate regions
1822// upon invocation. After that's in place, special casing here will not be
1823// needed.
1824void MallocChecker::checkPostStmt(const BlockExpr *BE,
1825 CheckerContext &C) const {
1826
1827 // Scan the BlockDecRefExprs for any object the retain count checker
1828 // may be tracking.
1829 if (!BE->getBlockDecl()->hasCaptures())
1830 return;
1831
1832 ProgramStateRef state = C.getState();
1833 const BlockDataRegion *R =
1834 cast<BlockDataRegion>(state->getSVal(BE,
1835 C.getLocationContext()).getAsRegion());
1836
1837 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1838 E = R->referenced_vars_end();
1839
1840 if (I == E)
1841 return;
1842
1843 SmallVector<const MemRegion*, 10> Regions;
1844 const LocationContext *LC = C.getLocationContext();
1845 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1846
1847 for ( ; I != E; ++I) {
Ted Kremenekbcf90532012-12-06 07:17:20 +00001848 const VarRegion *VR = I.getCapturedRegion();
Anna Zaks9fe80982012-03-22 00:57:20 +00001849 if (VR->getSuperRegion() == R) {
1850 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1851 }
1852 Regions.push_back(VR);
1853 }
1854
1855 state =
1856 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1857 Regions.data() + Regions.size()).getState();
1858 C.addTransition(state);
1859}
1860
Anna Zaks46d01602012-05-18 01:16:10 +00001861bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00001862 assert(Sym);
1863 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks46d01602012-05-18 01:16:10 +00001864 return (RS && RS->isReleased());
1865}
1866
1867bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1868 const Stmt *S) const {
Anna Zaksa1b227b2012-02-08 23:16:56 +00001869
Jordan Rose656fdd52014-01-08 18:46:55 +00001870 if (isReleased(Sym, C)) {
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001871 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1872 return true;
Anna Zaksa1b227b2012-02-08 23:16:56 +00001873 }
Anton Yartsev59ed15b2013-03-13 14:39:10 +00001874
Anna Zaksa1b227b2012-02-08 23:16:56 +00001875 return false;
1876}
1877
Jordan Rose656fdd52014-01-08 18:46:55 +00001878bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
1879
1880 if (isReleased(Sym, C)) {
1881 ReportDoubleDelete(C, Sym);
1882 return true;
1883 }
1884 return false;
1885}
1886
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00001887// Check if the location is a freed symbolic region.
Anna Zaks3e0f4152011-10-06 00:43:15 +00001888void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1889 CheckerContext &C) const {
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00001890 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaksa1b227b2012-02-08 23:16:56 +00001891 if (Sym)
Anna Zaks46d01602012-05-18 01:16:10 +00001892 checkUseAfterFree(Sym, C, S);
Zhongxing Xu1bb6a1a2010-03-10 04:58:55 +00001893}
Ted Kremenekd21139a2010-07-31 01:52:11 +00001894
Anna Zaksbb1ef902012-02-11 21:02:35 +00001895// If a symbolic region is assumed to NULL (or another constant), stop tracking
1896// it - assuming that allocation failed on this path.
1897ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1898 SVal Cond,
1899 bool Assumption) const {
1900 RegionStateTy RS = state->get<RegionState>();
Anna Zaksbb1ef902012-02-11 21:02:35 +00001901 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00001902 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00001903 ConstraintManager &CMgr = state->getConstraintManager();
1904 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1905 if (AllocFailed.isConstrainedTrue())
Anna Zaksbb1ef902012-02-11 21:02:35 +00001906 state = state->remove<RegionState>(I.getKey());
1907 }
1908
Anna Zaksd56c8792012-02-13 18:05:39 +00001909 // Realloc returns 0 when reallocation fails, which means that we should
1910 // restore the state of the pointer being reallocated.
Jordan Rose0c153cb2012-11-02 01:54:06 +00001911 ReallocPairsTy RP = state->get<ReallocPairs>();
1912 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek244e1d72012-09-07 22:31:01 +00001913 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Rose14fe9f32012-11-01 00:18:27 +00001914 ConstraintManager &CMgr = state->getConstraintManager();
1915 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose40bb12492012-11-01 00:25:15 +00001916 if (!AllocFailed.isConstrainedTrue())
Anna Zaks75cfbb62012-09-12 22:57:34 +00001917 continue;
Jordan Rose14fe9f32012-11-01 00:18:27 +00001918
Anna Zaks75cfbb62012-09-12 22:57:34 +00001919 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1920 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1921 if (RS->isReleased()) {
1922 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaksac068142012-02-15 00:11:25 +00001923 state = state->set<RegionState>(ReallocSym,
Anton Yartsev05789592013-03-28 17:05:19 +00001924 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks75cfbb62012-09-12 22:57:34 +00001925 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1926 state = state->remove<RegionState>(ReallocSym);
1927 else
1928 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksd56c8792012-02-13 18:05:39 +00001929 }
Anna Zaksd56c8792012-02-13 18:05:39 +00001930 }
Anna Zaks75cfbb62012-09-12 22:57:34 +00001931 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksd56c8792012-02-13 18:05:39 +00001932 }
1933
Anna Zaksbb1ef902012-02-11 21:02:35 +00001934 return state;
1935}
1936
Anna Zaks8ebeb642013-06-08 00:29:29 +00001937bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001938 const CallEvent *Call,
1939 ProgramStateRef State,
1940 SymbolRef &EscapingSymbol) const {
Jordan Rose7ab01822012-07-02 19:27:51 +00001941 assert(Call);
Anna Zaks8ebeb642013-06-08 00:29:29 +00001942 EscapingSymbol = 0;
1943
Jordan Rose2a833ca2014-01-15 17:25:15 +00001944 // For now, assume that any C++ or block call can free memory.
Anna Zaks7ac344a2012-02-24 23:56:53 +00001945 // TODO: If we want to be more optimistic here, we'll need to make sure that
1946 // regions escape to C++ containers. They seem to do that even now, but for
1947 // mysterious reasons.
Jordan Rose2a833ca2014-01-15 17:25:15 +00001948 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001949 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00001950
Jordan Rose742920c2012-07-02 19:27:35 +00001951 // Check Objective-C messages by selector name.
Jordan Rose6bad4902012-07-02 19:27:56 +00001952 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose7ab01822012-07-02 19:27:51 +00001953 // If it's not a framework call, or if it takes a callback, assume it
1954 // can free memory.
1955 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001956 return true;
Anna Zaks06a77fc2012-02-28 01:54:22 +00001957
Jordan Rose613f3c02013-03-09 00:59:10 +00001958 // If it's a method we know about, handle it explicitly post-call.
1959 // This should happen before the "freeWhenDone" check below.
1960 if (isKnownDeallocObjCMethodName(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001961 return false;
Anna Zaks886dfb82012-06-20 23:35:57 +00001962
Jordan Rose613f3c02013-03-09 00:59:10 +00001963 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1964 // about, we can't be sure that the object will use free() to deallocate the
1965 // memory, so we can't model it explicitly. The best we can do is use it to
1966 // decide whether the pointer escapes.
1967 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001968 return *FreeWhenDone;
Anna Zaks7ac344a2012-02-24 23:56:53 +00001969
Jordan Rose613f3c02013-03-09 00:59:10 +00001970 // If the first selector piece ends with "NoCopy", and there is no
1971 // "freeWhenDone" parameter set to zero, we know ownership is being
1972 // transferred. Again, though, we can't be sure that the object will use
1973 // free() to deallocate the memory, so we can't model it explicitly.
1974 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose742920c2012-07-02 19:27:35 +00001975 if (FirstSlot.endswith("NoCopy"))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001976 return true;
Anna Zaks12a8b902012-03-05 17:42:10 +00001977
Anna Zaks42908c72012-06-19 05:10:32 +00001978 // If the first selector starts with addPointer, insertPointer,
1979 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1980 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose742920c2012-07-02 19:27:35 +00001981 // that the pointers get freed by following the container itself.
1982 if (FirstSlot.startswith("addPointer") ||
1983 FirstSlot.startswith("insertPointer") ||
Jordan Rose514f9352014-01-07 21:39:48 +00001984 FirstSlot.startswith("replacePointer") ||
1985 FirstSlot.equals("valueWithPointer")) {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001986 return true;
Anna Zaks42908c72012-06-19 05:10:32 +00001987 }
1988
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001989 // We should escape receiver on call to 'init'. This is especially relevant
1990 // to the receiver, as the corresponding symbol is usually not referenced
1991 // after the call.
1992 if (Msg->getMethodFamily() == OMF_init) {
1993 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
1994 return true;
1995 }
Anna Zaks737926b2013-05-31 22:39:13 +00001996
Jordan Rose742920c2012-07-02 19:27:35 +00001997 // Otherwise, assume that the method does not free memory.
1998 // Most framework methods do not free memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00001999 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002000 }
2001
Jordan Rose742920c2012-07-02 19:27:35 +00002002 // At this point the only thing left to handle is straight function calls.
Jordan Rose2a833ca2014-01-15 17:25:15 +00002003 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
Jordan Rose742920c2012-07-02 19:27:35 +00002004 if (!FD)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002005 return true;
Anna Zaks7ac344a2012-02-24 23:56:53 +00002006
Jordan Rose742920c2012-07-02 19:27:35 +00002007 ASTContext &ASTC = State->getStateManager().getContext();
2008
2009 // If it's one of the allocation functions we can reason about, we model
2010 // its behavior explicitly.
2011 if (isMemFunction(FD, ASTC))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002012 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002013
2014 // If it's not a system call, assume it frees memory.
2015 if (!Call->isInSystemHeader())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002016 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002017
2018 // White list the system functions whose arguments escape.
2019 const IdentifierInfo *II = FD->getIdentifier();
2020 if (!II)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002021 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002022 StringRef FName = II->getName();
2023
Jordan Rose742920c2012-07-02 19:27:35 +00002024 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose7ab01822012-07-02 19:27:51 +00002025 // We specifically check these before
Jordan Rose742920c2012-07-02 19:27:35 +00002026 if (FName.endswith("NoCopy")) {
2027 // Look for the deallocator argument. We know that the memory ownership
2028 // is not transferred only if the deallocator argument is
2029 // 'kCFAllocatorNull'.
2030 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2031 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2032 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2033 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2034 if (DeallocatorName == "kCFAllocatorNull")
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002035 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002036 }
2037 }
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002038 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002039 }
2040
Jordan Rose742920c2012-07-02 19:27:35 +00002041 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose7ab01822012-07-02 19:27:51 +00002042 // 'closefn' is specified (and if that function does free memory),
2043 // but it will not if closefn is not specified.
Jordan Rose742920c2012-07-02 19:27:35 +00002044 // Currently, we do not inspect the 'closefn' function (PR12101).
2045 if (FName == "funopen")
Jordan Rose7ab01822012-07-02 19:27:51 +00002046 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002047 return false;
Jordan Rose742920c2012-07-02 19:27:35 +00002048
2049 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2050 // these leaks might be intentional when setting the buffer for stdio.
2051 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2052 if (FName == "setbuf" || FName =="setbuffer" ||
2053 FName == "setlinebuf" || FName == "setvbuf") {
2054 if (Call->getNumArgs() >= 1) {
2055 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2056 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2057 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2058 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002059 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002060 }
2061 }
2062
2063 // A bunch of other functions which either take ownership of a pointer or
2064 // wrap the result up in a struct or object, meaning it can be freed later.
2065 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2066 // but the Malloc checker cannot differentiate between them. The right way
2067 // of doing this would be to implement a pointer escapes callback.
2068 if (FName == "CGBitmapContextCreate" ||
2069 FName == "CGBitmapContextCreateWithData" ||
2070 FName == "CVPixelBufferCreateWithBytes" ||
2071 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2072 FName == "OSAtomicEnqueue") {
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002073 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002074 }
2075
Jordan Rose7ab01822012-07-02 19:27:51 +00002076 // Handle cases where we know a buffer's /address/ can escape.
2077 // Note that the above checks handle some special cases where we know that
2078 // even though the address escapes, it's still our responsibility to free the
2079 // buffer.
2080 if (Call->argumentsMayEscape())
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002081 return true;
Jordan Rose742920c2012-07-02 19:27:35 +00002082
2083 // Otherwise, assume that the function does not free memory.
2084 // Most system calls do not free the memory.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002085 return false;
Anna Zaks3d348342012-02-14 21:55:24 +00002086}
2087
Anna Zaks333481b2013-03-28 23:15:29 +00002088static bool retTrue(const RefState *RS) {
2089 return true;
2090}
2091
2092static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2093 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2094 RS->getAllocationFamily() == AF_CXXNew);
2095}
2096
Anna Zaksdc154152012-12-20 00:38:25 +00002097ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2098 const InvalidatedSymbols &Escaped,
Anna Zaksacdc13c2013-02-07 23:05:43 +00002099 const CallEvent *Call,
2100 PointerEscapeKind Kind) const {
Anna Zaks333481b2013-03-28 23:15:29 +00002101 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2102}
2103
2104ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2105 const InvalidatedSymbols &Escaped,
2106 const CallEvent *Call,
2107 PointerEscapeKind Kind) const {
2108 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2109 &checkIfNewOrNewArrayFamily);
2110}
2111
2112ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2113 const InvalidatedSymbols &Escaped,
2114 const CallEvent *Call,
2115 PointerEscapeKind Kind,
2116 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose613f3c02013-03-09 00:59:10 +00002117 // If we know that the call does not free memory, or we want to process the
2118 // call later, keep tracking the top level arguments.
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002119 SymbolRef EscapingSymbol = 0;
Jordan Rose757fbb02013-05-10 17:07:16 +00002120 if (Kind == PSK_DirectEscapeOnCall &&
Anna Zaks8ebeb642013-06-08 00:29:29 +00002121 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2122 EscapingSymbol) &&
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002123 !EscapingSymbol) {
Anna Zaks3d348342012-02-14 21:55:24 +00002124 return State;
Anna Zaksacdc13c2013-02-07 23:05:43 +00002125 }
Anna Zaks3d348342012-02-14 21:55:24 +00002126
Anna Zaksdc154152012-12-20 00:38:25 +00002127 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks333481b2013-03-28 23:15:29 +00002128 E = Escaped.end();
2129 I != E; ++I) {
Anna Zaksbb1ef902012-02-11 21:02:35 +00002130 SymbolRef sym = *I;
Anna Zaksdc154152012-12-20 00:38:25 +00002131
Anna Zaksa4bc5e12013-05-31 23:47:32 +00002132 if (EscapingSymbol && EscapingSymbol != sym)
2133 continue;
2134
Anna Zaks0d6989b2012-06-22 02:04:31 +00002135 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks93a21a82013-04-09 00:30:28 +00002136 if (RS->isAllocated() && CheckRefState(RS)) {
Anna Zaks23a62012012-08-09 00:42:24 +00002137 State = State->remove<RegionState>(sym);
Anna Zaks93a21a82013-04-09 00:30:28 +00002138 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2139 }
Anna Zaks0d6989b2012-06-22 02:04:31 +00002140 }
Anna Zaksbb1ef902012-02-11 21:02:35 +00002141 }
Anna Zaks3d348342012-02-14 21:55:24 +00002142 return State;
Ted Kremenekd21139a2010-07-31 01:52:11 +00002143}
Argyrios Kyrtzidis183f0fb2011-02-28 01:26:35 +00002144
Jordy Rosebf38f202012-03-18 07:43:35 +00002145static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2146 ProgramStateRef prevState) {
Jordan Rose0c153cb2012-11-02 01:54:06 +00002147 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2148 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rosebf38f202012-03-18 07:43:35 +00002149
Jordan Rose0c153cb2012-11-02 01:54:06 +00002150 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rosebf38f202012-03-18 07:43:35 +00002151 I != E; ++I) {
2152 SymbolRef sym = I.getKey();
2153 if (!currMap.lookup(sym))
2154 return sym;
2155 }
2156
2157 return NULL;
2158}
2159
Anna Zaks2b5bb972012-02-09 06:25:51 +00002160PathDiagnosticPiece *
2161MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2162 const ExplodedNode *PrevN,
2163 BugReporterContext &BRC,
2164 BugReport &BR) {
Jordy Rosebf38f202012-03-18 07:43:35 +00002165 ProgramStateRef state = N->getState();
2166 ProgramStateRef statePrev = PrevN->getState();
2167
2168 const RefState *RS = state->get<RegionState>(Sym);
2169 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaks52242a62012-08-03 18:30:18 +00002170 if (!RS)
Anna Zaks2b5bb972012-02-09 06:25:51 +00002171 return 0;
2172
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002173 const Stmt *S = 0;
2174 const char *Msg = 0;
Anna Zakscba4f292012-03-16 23:24:20 +00002175 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002176
2177 // Retrieve the associated statement.
2178 ProgramPoint ProgLoc = N->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +00002179 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002180 S = SP->getStmt();
David Blaikie87396b92013-02-21 22:23:56 +00002181 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rosefbe6dba2012-07-10 22:07:52 +00002182 S = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +00002183 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002184 // If an assumption was made on a branch, it should be caught
2185 // here by looking at the state transition.
2186 S = Edge->getSrc()->getTerminator();
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002187 }
Ted Kremenek7505b5a2013-01-04 19:04:36 +00002188
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002189 if (!S)
Anna Zaks2b5bb972012-02-09 06:25:51 +00002190 return 0;
Anna Zaks2b5bb972012-02-09 06:25:51 +00002191
Jordan Rose681cce92012-07-10 22:07:42 +00002192 // FIXME: We will eventually need to handle non-statement-based events
2193 // (__attribute__((cleanup))).
2194
Anna Zaks2b5bb972012-02-09 06:25:51 +00002195 // Find out if this is an interesting point and what is the kind.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002196 if (Mode == Normal) {
Anna Zaks1ff57d52012-03-15 21:13:02 +00002197 if (isAllocated(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002198 Msg = "Memory is allocated";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002199 StackHint = new StackHintGeneratorForSymbol(Sym,
2200 "Returned allocated memory");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002201 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002202 Msg = "Memory is released";
Anna Zaksa7f457a2012-03-16 23:44:28 +00002203 StackHint = new StackHintGeneratorForSymbol(Sym,
Anna Zakse4cfcd42013-04-16 00:22:55 +00002204 "Returning; memory was released");
Anna Zaks0d6989b2012-06-22 02:04:31 +00002205 } else if (isRelinquished(RS, RSPrev, S)) {
Alp Toker5faf0c02013-12-02 03:50:25 +00002206 Msg = "Memory ownership is transferred";
Anna Zaks0d6989b2012-06-22 02:04:31 +00002207 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks1ff57d52012-03-15 21:13:02 +00002208 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002209 Mode = ReallocationFailed;
2210 Msg = "Reallocation failed";
Anna Zakscba4f292012-03-16 23:24:20 +00002211 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksa7f457a2012-03-16 23:44:28 +00002212 "Reallocation failed");
Jordy Rosebf38f202012-03-18 07:43:35 +00002213
Jordy Rose21ff76e2012-03-24 03:15:09 +00002214 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2215 // Is it possible to fail two reallocs WITHOUT testing in between?
2216 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2217 "We only support one failed realloc at a time.");
Jordy Rosebf38f202012-03-18 07:43:35 +00002218 BR.markInteresting(sym);
Jordy Rose21ff76e2012-03-24 03:15:09 +00002219 FailedReallocSymbol = sym;
2220 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002221 }
2222
2223 // We are in a special mode if a reallocation failed later in the path.
2224 } else if (Mode == ReallocationFailed) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002225 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002226
Jordy Rose21ff76e2012-03-24 03:15:09 +00002227 // Is this is the first appearance of the reallocated symbol?
2228 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Rose21ff76e2012-03-24 03:15:09 +00002229 // We're at the reallocation point.
2230 Msg = "Attempt to reallocate memory";
2231 StackHint = new StackHintGeneratorForSymbol(Sym,
2232 "Returned reallocated memory");
2233 FailedReallocSymbol = NULL;
2234 Mode = Normal;
2235 }
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002236 }
2237
Anna Zaks2b5bb972012-02-09 06:25:51 +00002238 if (!Msg)
2239 return 0;
Anna Zakscba4f292012-03-16 23:24:20 +00002240 assert(StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002241
2242 // Generate the extra diagnostic.
Anna Zaks9eb7bc82012-02-16 22:26:07 +00002243 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaks2b5bb972012-02-09 06:25:51 +00002244 N->getLocationContext());
Anna Zakscba4f292012-03-16 23:24:20 +00002245 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaks2b5bb972012-02-09 06:25:51 +00002246}
2247
Anna Zaks263b7e02012-05-02 00:05:20 +00002248void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2249 const char *NL, const char *Sep) const {
2250
2251 RegionStateTy RS = State->get<RegionState>();
2252
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002253 if (!RS.isEmpty()) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002254 Out << Sep << "MallocChecker :" << NL;
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002255 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Anton Yartsev6a619222014-02-17 18:25:34 +00002256 const RefState *RefS = State->get<RegionState>(I.getKey());
2257 AllocationFamily Family = RefS->getAllocationFamily();
2258 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2259
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002260 I.getKey()->dumpToStream(Out);
2261 Out << " : ";
2262 I.getData().dump(Out);
Anton Yartsev6a619222014-02-17 18:25:34 +00002263 if (CheckKind.hasValue())
2264 Out << " (" << CheckNames[*CheckKind].getName() << ")";
Ted Kremenek6fcefb52013-01-03 01:30:12 +00002265 Out << NL;
2266 }
2267 }
Anna Zaks263b7e02012-05-02 00:05:20 +00002268}
Anna Zaks2b5bb972012-02-09 06:25:51 +00002269
Anna Zakse4cfcd42013-04-16 00:22:55 +00002270void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2271 registerCStringCheckerBasic(mgr);
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002272 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2273 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2274 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2275 mgr.getCurrentCheckName();
Anna Zakse4cfcd42013-04-16 00:22:55 +00002276 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2277 // checker.
Anton Yartsev6a619222014-02-17 18:25:34 +00002278 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002279 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
Anna Zakse4cfcd42013-04-16 00:22:55 +00002280}
Anton Yartsev7af0aa82013-04-12 23:25:40 +00002281
Alexander Kornienko4aca9b12014-02-11 21:49:21 +00002282#define REGISTER_CHECKER(name) \
2283 void ento::register##name(CheckerManager &mgr) { \
2284 registerCStringCheckerBasic(mgr); \
2285 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
2286 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2287 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2288 }
Anna Zakscd37bf42012-02-08 23:16:52 +00002289
2290REGISTER_CHECKER(MallocPessimistic)
2291REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev13df0362013-03-25 01:35:45 +00002292REGISTER_CHECKER(NewDeleteChecker)
Anton Yartsev05789592013-03-28 17:05:19 +00002293REGISTER_CHECKER(MismatchedDeallocatorChecker)