blob: 26fd1c26ea7edd39f7351e32ea9bc47c69630f19 [file] [log] [blame]
Zhongxing Xu589c0f22009-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 Kyrtzidis312dbec2011-02-28 01:26:35 +000015#include "ClangSACheckers.h"
Anna Zaksf0dfc9c2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Chandler Carruth55fc8732012-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 Kyrtzidisec8605f2011-03-01 01:16:21 +000020#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000021#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rosef540c542012-07-26 21:39:41 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
25#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000027#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000028#include "llvm/ADT/STLExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000029#include "llvm/ADT/SmallString.h"
Jordan Rose615a0922012-09-22 01:24:42 +000030#include "llvm/ADT/StringExtras.h"
Anna Zaks60a1fa42012-02-22 03:14:20 +000031#include <climits>
32
Zhongxing Xu589c0f22009-11-12 08:38:56 +000033using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000034using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000035
36namespace {
37
Zhongxing Xu7fb14642009-12-11 00:55:44 +000038class RefState {
Anna Zaks050cdd72012-06-20 20:57:46 +000039 enum Kind { // Reference to allocated memory.
40 Allocated,
41 // Reference to released/freed memory.
42 Released,
Anna Zaks050cdd72012-06-20 20:57:46 +000043 // The responsibility for freeing resources has transfered from
44 // this reference. A relinquished symbol should not be freed.
Ted Kremenekdde201b2010-08-06 21:12:55 +000045 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000046 const Stmt *S;
47
Zhongxing Xu7fb14642009-12-11 00:55:44 +000048public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000049 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
50
Anna Zaks050cdd72012-06-20 20:57:46 +000051 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000052 bool isReleased() const { return K == Released; }
Anna Zaks050cdd72012-06-20 20:57:46 +000053 bool isRelinquished() const { return K == Relinquished; }
Anna Zaksca23eb22012-02-29 18:42:47 +000054
Anna Zaksc8bb3be2012-02-13 18:05:39 +000055 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000056
57 bool operator==(const RefState &X) const {
58 return K == X.K && S == X.S;
59 }
60
Anna Zaks050cdd72012-06-20 20:57:46 +000061 static RefState getAllocated(const Stmt *s) {
62 return RefState(Allocated, s);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000063 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000064 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000065 static RefState getRelinquished(const Stmt *s) {
66 return RefState(Relinquished, s);
67 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000068
69 void Profile(llvm::FoldingSetNodeID &ID) const {
70 ID.AddInteger(K);
71 ID.AddPointer(S);
72 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000073};
74
Anna Zaks9dc298b2012-09-12 22:57:34 +000075enum ReallocPairKind {
76 RPToBeFreedAfterFailure,
77 // The symbol has been freed when reallocation failed.
78 RPIsFreeOnFailure,
79 // The symbol does not need to be freed after reallocation fails.
80 RPDoNotTrackAfterFailure
81};
82
Anna Zaks55dd9562012-08-24 02:28:20 +000083/// \class ReallocPair
84/// \brief Stores information about the symbol being reallocated by a call to
85/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaks40add292012-02-15 00:11:25 +000086struct ReallocPair {
Anna Zaks55dd9562012-08-24 02:28:20 +000087 // \brief The symbol which realloc reallocated.
Anna Zaks40add292012-02-15 00:11:25 +000088 SymbolRef ReallocatedSym;
Anna Zaks9dc298b2012-09-12 22:57:34 +000089 ReallocPairKind Kind;
Anna Zaks55dd9562012-08-24 02:28:20 +000090
Anna Zaks9dc298b2012-09-12 22:57:34 +000091 ReallocPair(SymbolRef S, ReallocPairKind K) :
92 ReallocatedSym(S), Kind(K) {}
Anna Zaks40add292012-02-15 00:11:25 +000093 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks9dc298b2012-09-12 22:57:34 +000094 ID.AddInteger(Kind);
Anna Zaks40add292012-02-15 00:11:25 +000095 ID.AddPointer(ReallocatedSym);
96 }
97 bool operator==(const ReallocPair &X) const {
98 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks9dc298b2012-09-12 22:57:34 +000099 Kind == X.Kind;
Anna Zaks40add292012-02-15 00:11:25 +0000100 }
101};
102
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000103typedef std::pair<const Stmt*, const MemRegion*> LeakInfo;
104
Anna Zaksb319e022012-02-08 20:13:28 +0000105class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000106 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +0000107 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +0000108 check::PostStmt<CallExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000109 check::PostStmt<BlockExpr>,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000110 check::PostObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000111 check::Location,
112 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +0000113 eval::Assume,
114 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000115{
Anna Zaksfebdc322012-02-16 22:26:12 +0000116 mutable OwningPtr<BugType> BT_DoubleFree;
117 mutable OwningPtr<BugType> BT_Leak;
118 mutable OwningPtr<BugType> BT_UseFree;
119 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000120 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000121 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
122
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000123public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000124 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000125 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000126
127 /// In pessimistic mode, the checker assumes that it does not know which
128 /// functions might free the memory.
129 struct ChecksFilter {
130 DefaultBool CMallocPessimistic;
131 DefaultBool CMallocOptimistic;
132 };
133
134 ChecksFilter Filter;
135
Anna Zaks66c40402012-02-14 21:55:24 +0000136 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000137 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000138 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000139 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000140 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000141 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000142 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000143 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000144 void checkLocation(SVal l, bool isLoad, const Stmt *S,
145 CheckerContext &C) const;
146 void checkBind(SVal location, SVal val, const Stmt*S,
147 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000148 ProgramStateRef
149 checkRegionChanges(ProgramStateRef state,
150 const StoreManager::InvalidatedSymbols *invalidated,
151 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000152 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +0000153 const CallEvent *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000154 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
155 return true;
156 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000157
Anna Zaks93c5a242012-05-02 00:05:20 +0000158 void printState(raw_ostream &Out, ProgramStateRef State,
159 const char *NL, const char *Sep) const;
160
Zhongxing Xu7b760962009-11-13 07:25:27 +0000161private:
Anna Zaks66c40402012-02-14 21:55:24 +0000162 void initIdentifierInfo(ASTContext &C) const;
163
164 /// Check if this is one of the functions which can allocate/reallocate memory
165 /// pointed to by one of its arguments.
166 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000167 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
168 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000169
Anna Zaks87cb5be2012-02-22 19:24:52 +0000170 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
171 const CallExpr *CE,
172 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000173 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000174 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000175 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000176 return MallocMemAux(C, CE,
177 state->getSVal(SizeEx, C.getLocationContext()),
178 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000179 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000180
Ted Kremenek8bef8232012-01-26 21:29:00 +0000181 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000182 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000183 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000184
Anna Zaks87cb5be2012-02-22 19:24:52 +0000185 /// Update the RefState to reflect the new memory allocation.
186 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
187 const CallExpr *CE,
188 ProgramStateRef state);
189
190 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
191 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000192 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000193 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000194 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000195 bool &ReleasedAllocated,
196 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000197 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
198 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000199 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000200 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000201 bool &ReleasedAllocated,
202 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000203
Anna Zaks87cb5be2012-02-22 19:24:52 +0000204 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
205 bool FreesMemOnFailure) const;
206 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000207
Anna Zaks14345182012-05-18 01:16:10 +0000208 ///\brief Check if the memory associated with this symbol was released.
209 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
210
Anna Zaks91c2a112012-02-08 23:16:56 +0000211 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
212 const Stmt *S = 0) const;
213
Anna Zaks66c40402012-02-14 21:55:24 +0000214 /// Check if the function is not known to us. So, for example, we could
215 /// conservatively assume it can free/reallocate it's pointer arguments.
Jordan Rose740d4902012-07-02 19:27:35 +0000216 bool doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000217 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000218
Ted Kremenek9c378f72011-08-12 23:37:29 +0000219 static bool SummarizeValue(raw_ostream &os, SVal V);
220 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000221 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000222
Anna Zaksca8e36e2012-02-23 21:38:21 +0000223 /// Find the location of the allocation for Sym on the path leading to the
224 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000225 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
226 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000227
Anna Zaksda046772012-02-11 21:02:40 +0000228 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
229
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000230 /// The bug visitor which allows us to print extra diagnostics along the
231 /// BugReport path. For example, showing the allocation site of the leaked
232 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000233 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000234 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000235 enum NotificationMode {
236 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000237 ReallocationFailed
238 };
239
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000240 // The allocated region symbol tracked by the main analysis.
241 SymbolRef Sym;
242
Anna Zaks88feba02012-05-10 01:37:40 +0000243 // The mode we are in, i.e. what kind of diagnostics will be emitted.
244 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000245
Anna Zaks88feba02012-05-10 01:37:40 +0000246 // A symbol from when the primary region should have been reallocated.
247 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000248
Anna Zaks88feba02012-05-10 01:37:40 +0000249 bool IsLeak;
250
251 public:
252 MallocBugVisitor(SymbolRef S, bool isLeak = false)
253 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000254
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000255 virtual ~MallocBugVisitor() {}
256
257 void Profile(llvm::FoldingSetNodeID &ID) const {
258 static int X = 0;
259 ID.AddPointer(&X);
260 ID.AddPointer(Sym);
261 }
262
Anna Zaksfe571602012-02-16 22:26:07 +0000263 inline bool isAllocated(const RefState *S, const RefState *SPrev,
264 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000265 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000266 return (Stmt && isa<CallExpr>(Stmt) &&
267 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000268 }
269
Anna Zaksfe571602012-02-16 22:26:07 +0000270 inline bool isReleased(const RefState *S, const RefState *SPrev,
271 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000272 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000273 return (Stmt && isa<CallExpr>(Stmt) &&
274 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
275 }
276
Anna Zaks5b7aa342012-06-22 02:04:31 +0000277 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
278 const Stmt *Stmt) {
279 // Did not track -> relinquished. Other state (allocated) -> relinquished.
280 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
281 isa<ObjCPropertyRefExpr>(Stmt)) &&
282 (S && S->isRelinquished()) &&
283 (!SPrev || !SPrev->isRelinquished()));
284 }
285
Anna Zaksfe571602012-02-16 22:26:07 +0000286 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
287 const Stmt *Stmt) {
288 // If the expression is not a call, and the state change is
289 // released -> allocated, it must be the realloc return value
290 // check. If we have to handle more cases here, it might be cleaner just
291 // to track this extra bit in the state itself.
292 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
293 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000294 }
295
296 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
297 const ExplodedNode *PrevN,
298 BugReporterContext &BRC,
299 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000300
301 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
302 const ExplodedNode *EndPathNode,
303 BugReport &BR) {
304 if (!IsLeak)
305 return 0;
306
307 PathDiagnosticLocation L =
308 PathDiagnosticLocation::createEndOfPath(EndPathNode,
309 BRC.getSourceManager());
310 // Do not add the statement itself as a range in case of leak.
311 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
312 }
313
Anna Zaks56a938f2012-03-16 23:24:20 +0000314 private:
315 class StackHintGeneratorForReallocationFailed
316 : public StackHintGeneratorForSymbol {
317 public:
318 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
319 : StackHintGeneratorForSymbol(S, M) {}
320
321 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000322 // Printed parameters start at 1, not 0.
323 ++ArgIndex;
324
Anna Zaks56a938f2012-03-16 23:24:20 +0000325 SmallString<200> buf;
326 llvm::raw_svector_ostream os(buf);
327
Jordan Rose615a0922012-09-22 01:24:42 +0000328 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
329 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000330
331 return os.str();
332 }
333
334 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000335 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000336 }
337 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000338 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000339};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000340} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000341
Jordan Rose166d5022012-11-02 01:54:06 +0000342REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
343REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000344
Anna Zaks4141e4d2012-11-13 03:18:01 +0000345// A map from the freed symbol to the symbol representing the return value of
346// the free function.
347REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
348
Anna Zaks4fb54872012-02-11 21:02:35 +0000349namespace {
350class StopTrackingCallback : public SymbolVisitor {
351 ProgramStateRef state;
352public:
353 StopTrackingCallback(ProgramStateRef st) : state(st) {}
354 ProgramStateRef getState() const { return state; }
355
356 bool VisitSymbol(SymbolRef sym) {
357 state = state->remove<RegionState>(sym);
358 return true;
359 }
360};
361} // end anonymous namespace
362
Anna Zaks66c40402012-02-14 21:55:24 +0000363void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000364 if (II_malloc)
365 return;
366 II_malloc = &Ctx.Idents.get("malloc");
367 II_free = &Ctx.Idents.get("free");
368 II_realloc = &Ctx.Idents.get("realloc");
369 II_reallocf = &Ctx.Idents.get("reallocf");
370 II_calloc = &Ctx.Idents.get("calloc");
371 II_valloc = &Ctx.Idents.get("valloc");
372 II_strdup = &Ctx.Idents.get("strdup");
373 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000374}
375
Anna Zaks66c40402012-02-14 21:55:24 +0000376bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000377 if (isFreeFunction(FD, C))
378 return true;
379
380 if (isAllocationFunction(FD, C))
381 return true;
382
383 return false;
384}
385
386bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
387 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000388 if (!FD)
389 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000390
Jordan Rose5ef6e942012-07-10 23:13:01 +0000391 if (FD->getKind() == Decl::Function) {
392 IdentifierInfo *FunI = FD->getIdentifier();
393 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000394
Jordan Rose5ef6e942012-07-10 23:13:01 +0000395 if (FunI == II_malloc || FunI == II_realloc ||
396 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
397 FunI == II_strdup || FunI == II_strndup)
398 return true;
399 }
Anna Zaks66c40402012-02-14 21:55:24 +0000400
Anna Zaks14345182012-05-18 01:16:10 +0000401 if (Filter.CMallocOptimistic && FD->hasAttrs())
402 for (specific_attr_iterator<OwnershipAttr>
403 i = FD->specific_attr_begin<OwnershipAttr>(),
404 e = FD->specific_attr_end<OwnershipAttr>();
405 i != e; ++i)
406 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
407 return true;
408 return false;
409}
410
411bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
412 if (!FD)
413 return false;
414
Jordan Rose5ef6e942012-07-10 23:13:01 +0000415 if (FD->getKind() == Decl::Function) {
416 IdentifierInfo *FunI = FD->getIdentifier();
417 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000418
Jordan Rose5ef6e942012-07-10 23:13:01 +0000419 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
420 return true;
421 }
Anna Zaks66c40402012-02-14 21:55:24 +0000422
Anna Zaks14345182012-05-18 01:16:10 +0000423 if (Filter.CMallocOptimistic && FD->hasAttrs())
424 for (specific_attr_iterator<OwnershipAttr>
425 i = FD->specific_attr_begin<OwnershipAttr>(),
426 e = FD->specific_attr_end<OwnershipAttr>();
427 i != e; ++i)
428 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
429 (*i)->getOwnKind() == OwnershipAttr::Holds)
430 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000431 return false;
432}
433
Anna Zaksb319e022012-02-08 20:13:28 +0000434void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000435 if (C.wasInlined)
436 return;
437
Anna Zaksb319e022012-02-08 20:13:28 +0000438 const FunctionDecl *FD = C.getCalleeDecl(CE);
439 if (!FD)
440 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000441
Anna Zaks87cb5be2012-02-22 19:24:52 +0000442 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000443 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000444
445 if (FD->getKind() == Decl::Function) {
446 initIdentifierInfo(C.getASTContext());
447 IdentifierInfo *FunI = FD->getIdentifier();
448
449 if (FunI == II_malloc || FunI == II_valloc) {
450 if (CE->getNumArgs() < 1)
451 return;
452 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
453 } else if (FunI == II_realloc) {
454 State = ReallocMem(C, CE, false);
455 } else if (FunI == II_reallocf) {
456 State = ReallocMem(C, CE, true);
457 } else if (FunI == II_calloc) {
458 State = CallocMem(C, CE);
459 } else if (FunI == II_free) {
Anna Zaks55dd9562012-08-24 02:28:20 +0000460 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose5ef6e942012-07-10 23:13:01 +0000461 } else if (FunI == II_strdup) {
462 State = MallocUpdateRefState(C, CE, State);
463 } else if (FunI == II_strndup) {
464 State = MallocUpdateRefState(C, CE, State);
465 }
466 }
467
468 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000469 // Check all the attributes, if there are any.
470 // There can be multiple of these attributes.
471 if (FD->hasAttrs())
472 for (specific_attr_iterator<OwnershipAttr>
473 i = FD->specific_attr_begin<OwnershipAttr>(),
474 e = FD->specific_attr_end<OwnershipAttr>();
475 i != e; ++i) {
476 switch ((*i)->getOwnKind()) {
477 case OwnershipAttr::Returns:
478 State = MallocMemReturnsAttr(C, CE, *i);
479 break;
480 case OwnershipAttr::Takes:
481 case OwnershipAttr::Holds:
482 State = FreeMemAttr(C, CE, *i);
483 break;
484 }
485 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000486 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000487 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000488}
489
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000490static bool isFreeWhenDoneSetToZero(const ObjCMethodCall &Call) {
491 Selector S = Call.getSelector();
Anna Zaks3e4f65d2012-06-22 22:08:09 +0000492 for (unsigned i = 1; i < S.getNumArgs(); ++i)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000493 if (S.getNameForSlot(i).equals("freeWhenDone"))
494 if (Call.getArgSVal(i).isConstant(0))
495 return true;
496
497 return false;
498}
499
Anna Zaks4141e4d2012-11-13 03:18:01 +0000500void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
501 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000502 if (C.wasInlined)
503 return;
504
Anna Zaks5b7aa342012-06-22 02:04:31 +0000505 // If the first selector is dataWithBytesNoCopy, assume that the memory will
506 // be released with 'free' by the new object.
507 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
508 // Unless 'freeWhenDone' param set to 0.
509 // TODO: Check that the memory was allocated with malloc.
Anna Zaks55dd9562012-08-24 02:28:20 +0000510 bool ReleasedAllocatedMemory = false;
Jordan Rosede507ea2012-07-02 19:28:04 +0000511 Selector S = Call.getSelector();
Anna Zaks7186dc62012-06-22 22:42:30 +0000512 if ((S.getNameForSlot(0) == "dataWithBytesNoCopy" ||
513 S.getNameForSlot(0) == "initWithBytesNoCopy" ||
514 S.getNameForSlot(0) == "initWithCharactersNoCopy") &&
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000515 !isFreeWhenDoneSetToZero(Call)){
Anna Zaks5b7aa342012-06-22 02:04:31 +0000516 unsigned int argIdx = 0;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000517 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(argIdx),
518 Call.getOriginExpr(), C.getState(), true,
519 ReleasedAllocatedMemory,
520 /* RetNullOnFailure*/ true);
521
522 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000523 }
524}
525
Anna Zaks87cb5be2012-02-22 19:24:52 +0000526ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
527 const CallExpr *CE,
528 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000529 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000530 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000531
Sean Huntcf807c42010-08-18 23:23:40 +0000532 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000533 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000534 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000535 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000536 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000537}
538
Anna Zaksb319e022012-02-08 20:13:28 +0000539ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000540 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000541 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000542 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000543
544 // Bind the return value to the symbolic value from the heap region.
545 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
546 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000547 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000548 SValBuilder &svalBuilder = C.getSValBuilder();
549 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
550 DefinedSVal RetVal =
551 cast<DefinedSVal>(svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count));
552 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000553
Anna Zaksb16ce452012-02-15 00:11:22 +0000554 // We expect the malloc functions to return a pointer.
Anna Zakse17fdb22012-06-07 03:57:32 +0000555 if (!isa<Loc>(RetVal))
Anna Zaksb16ce452012-02-15 00:11:22 +0000556 return 0;
557
Jordy Rose32f26562010-07-04 00:00:41 +0000558 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000559 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000560
Jordy Rose32f26562010-07-04 00:00:41 +0000561 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000562 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000563 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000564 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000565 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000566 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000567 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000568 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
569 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
570 DefinedOrUnknownSVal extentMatchesSize =
571 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000572
Anna Zaks60a1fa42012-02-22 03:14:20 +0000573 state = state->assume(extentMatchesSize, true);
574 assert(state);
575 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000576
Anna Zaks87cb5be2012-02-22 19:24:52 +0000577 return MallocUpdateRefState(C, CE, state);
578}
579
580ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
581 const CallExpr *CE,
582 ProgramStateRef state) {
583 // Get the return value.
584 SVal retVal = state->getSVal(CE, C.getLocationContext());
585
586 // We expect the malloc functions to return a pointer.
587 if (!isa<Loc>(retVal))
588 return 0;
589
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000590 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000591 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000592
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000593 // Set the symbol's state to Allocated.
Anna Zaks050cdd72012-06-20 20:57:46 +0000594 return state->set<RegionState>(Sym, RefState::getAllocated(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000595
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000596}
597
Anna Zaks87cb5be2012-02-22 19:24:52 +0000598ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
599 const CallExpr *CE,
600 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000601 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000602 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000603
Anna Zaksb3d72752012-03-01 22:06:06 +0000604 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000605 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000606
Sean Huntcf807c42010-08-18 23:23:40 +0000607 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
608 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000609 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000610 Att->getOwnKind() == OwnershipAttr::Holds,
611 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000612 if (StateI)
613 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000614 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000615 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000616}
617
Ted Kremenek8bef8232012-01-26 21:29:00 +0000618ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000619 const CallExpr *CE,
620 ProgramStateRef state,
621 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000622 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000623 bool &ReleasedAllocated,
624 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000625 if (CE->getNumArgs() < (Num + 1))
626 return 0;
627
Anna Zaks4141e4d2012-11-13 03:18:01 +0000628 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
629 ReleasedAllocated, ReturnsNullOnFailure);
630}
631
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000632/// Checks if the previous call to free on the given symbol failed - if free
633/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000634static bool didPreviousFreeFail(ProgramStateRef State,
635 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000636 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000637 if (Ret) {
638 assert(*Ret && "We should not store the null return symbol");
639 ConstraintManager &CMgr = State->getConstraintManager();
640 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000641 RetStatusSymbol = *Ret;
642 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000643 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000644 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000645}
646
647ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
648 const Expr *ArgExpr,
649 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000650 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000651 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000652 bool &ReleasedAllocated,
653 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000654
Anna Zaks4141e4d2012-11-13 03:18:01 +0000655 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000656 if (!isa<DefinedOrUnknownSVal>(ArgVal))
657 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000658 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
659
660 // Check for null dereferences.
661 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000662 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000663
Anna Zaksb276bd92012-02-14 00:26:13 +0000664 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000665 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000666 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000667 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000668 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000669
Jordy Rose43859f62010-06-07 19:32:37 +0000670 // Unknown values could easily be okay
671 // Undefined values are handled elsewhere
672 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000673 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000674
Jordy Rose43859f62010-06-07 19:32:37 +0000675 const MemRegion *R = ArgVal.getAsRegion();
676
677 // Nonlocs can't be freed, of course.
678 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
679 if (!R) {
680 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000681 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000682 }
683
684 R = R->StripCasts();
685
686 // Blocks might show up as heap data, but should not be free()d
687 if (isa<BlockDataRegion>(R)) {
688 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000689 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000690 }
691
692 const MemSpaceRegion *MS = R->getMemorySpace();
693
694 // Parameters, locals, statics, and globals shouldn't be freed.
695 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
696 // FIXME: at the time this code was written, malloc() regions were
697 // represented by conjured symbols, which are all in UnknownSpaceRegion.
698 // This means that there isn't actually anything from HeapSpaceRegion
699 // that should be freed, even though we allow it here.
700 // Of course, free() can work on memory allocated outside the current
701 // function, so UnknownSpaceRegion is always a possibility.
702 // False negatives are better than false positives.
703
704 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000705 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000706 }
707
708 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
709 // Various cases could lead to non-symbol values here.
710 // For now, ignore them.
711 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000712 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000713
714 SymbolRef Sym = SR->getSymbol();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000715 const RefState *RS = State->get<RegionState>(Sym);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000716 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000717
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000718 // Check double free.
Anna Zaks4141e4d2012-11-13 03:18:01 +0000719 if (RS &&
720 (RS->isReleased() || RS->isRelinquished()) &&
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000721 !didPreviousFreeFail(State, Sym, PreviousRetStatusSymbol)) {
Anna Zaks4141e4d2012-11-13 03:18:01 +0000722
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000723 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000724 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000725 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000726 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000727 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000728 (RS->isReleased() ? "Attempt to free released memory" :
729 "Attempt to free non-owned memory"), N);
Anna Zaksfe571602012-02-16 22:26:07 +0000730 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000731 R->markInteresting(Sym);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000732 if (PreviousRetStatusSymbol)
733 R->markInteresting(PreviousRetStatusSymbol);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000734 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +0000735 C.emitReport(R);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000736 }
Anna Zaksb319e022012-02-08 20:13:28 +0000737 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000738 }
739
Anna Zaks55dd9562012-08-24 02:28:20 +0000740 ReleasedAllocated = (RS != 0);
741
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000742 // Clean out the info on previous call to free return info.
743 State = State->remove<FreeReturnValue>(Sym);
744
Anna Zaks4141e4d2012-11-13 03:18:01 +0000745 // Keep track of the return value. If it is NULL, we will know that free
746 // failed.
747 if (ReturnsNullOnFailure) {
748 SVal RetVal = C.getSVal(ParentExpr);
749 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
750 if (RetStatusSymbol) {
751 C.getSymbolManager().addSymbolDependency(Sym, RetStatusSymbol);
752 State = State->set<FreeReturnValue>(Sym, RetStatusSymbol);
753 }
754 }
755
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000756 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000757 if (Hold)
Anna Zaks4141e4d2012-11-13 03:18:01 +0000758 return State->set<RegionState>(Sym, RefState::getRelinquished(ParentExpr));
759 return State->set<RegionState>(Sym, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000760}
761
Ted Kremenek9c378f72011-08-12 23:37:29 +0000762bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000763 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
764 os << "an integer (" << IntVal->getValue() << ")";
765 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
766 os << "a constant address (" << ConstAddr->getValue() << ")";
767 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000768 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000769 else
770 return false;
771
772 return true;
773}
774
Ted Kremenek9c378f72011-08-12 23:37:29 +0000775bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000776 const MemRegion *MR) {
777 switch (MR->getKind()) {
778 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000779 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +0000780 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000781 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000782 else
783 os << "the address of a function";
784 return true;
785 }
786 case MemRegion::BlockTextRegionKind:
787 os << "block text";
788 return true;
789 case MemRegion::BlockDataRegionKind:
790 // FIXME: where the block came from?
791 os << "a block";
792 return true;
793 default: {
794 const MemSpaceRegion *MS = MR->getMemorySpace();
795
Anna Zakseb31a762012-01-04 23:54:01 +0000796 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000797 const VarRegion *VR = dyn_cast<VarRegion>(MR);
798 const VarDecl *VD;
799 if (VR)
800 VD = VR->getDecl();
801 else
802 VD = NULL;
803
804 if (VD)
805 os << "the address of the local variable '" << VD->getName() << "'";
806 else
807 os << "the address of a local stack variable";
808 return true;
809 }
Anna Zakseb31a762012-01-04 23:54:01 +0000810
811 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000812 const VarRegion *VR = dyn_cast<VarRegion>(MR);
813 const VarDecl *VD;
814 if (VR)
815 VD = VR->getDecl();
816 else
817 VD = NULL;
818
819 if (VD)
820 os << "the address of the parameter '" << VD->getName() << "'";
821 else
822 os << "the address of a parameter";
823 return true;
824 }
Anna Zakseb31a762012-01-04 23:54:01 +0000825
826 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000827 const VarRegion *VR = dyn_cast<VarRegion>(MR);
828 const VarDecl *VD;
829 if (VR)
830 VD = VR->getDecl();
831 else
832 VD = NULL;
833
834 if (VD) {
835 if (VD->isStaticLocal())
836 os << "the address of the static variable '" << VD->getName() << "'";
837 else
838 os << "the address of the global variable '" << VD->getName() << "'";
839 } else
840 os << "the address of a global variable";
841 return true;
842 }
Anna Zakseb31a762012-01-04 23:54:01 +0000843
844 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000845 }
846 }
847}
848
849void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000850 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000851 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000852 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000853 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000854
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000855 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000856 llvm::raw_svector_ostream os(buf);
857
858 const MemRegion *MR = ArgVal.getAsRegion();
859 if (MR) {
860 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
861 MR = ER->getSuperRegion();
862
863 // Special case for alloca()
864 if (isa<AllocaRegion>(MR))
865 os << "Argument to free() was allocated by alloca(), not malloc()";
866 else {
867 os << "Argument to free() is ";
868 if (SummarizeRegion(os, MR))
869 os << ", which is not memory allocated by malloc()";
870 else
871 os << "not memory allocated by malloc()";
872 }
873 } else {
874 os << "Argument to free() is ";
875 if (SummarizeValue(os, ArgVal))
876 os << ", which is not memory allocated by malloc()";
877 else
878 os << "not memory allocated by malloc()";
879 }
880
Anna Zakse172e8b2011-08-17 23:00:25 +0000881 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000882 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000883 R->addRange(range);
Jordan Rose785950e2012-11-02 01:53:40 +0000884 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +0000885 }
886}
887
Anna Zaks87cb5be2012-02-22 19:24:52 +0000888ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
889 const CallExpr *CE,
890 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000891 if (CE->getNumArgs() < 2)
892 return 0;
893
Ted Kremenek8bef8232012-01-26 21:29:00 +0000894 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000895 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000896 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000897 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
898 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000899 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000900 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000901
Ted Kremenek846eabd2010-12-01 21:28:31 +0000902 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000903
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000904 DefinedOrUnknownSVal PtrEQ =
905 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000906
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000907 // Get the size argument. If there is no size arg then give up.
908 const Expr *Arg1 = CE->getArg(1);
909 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000910 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000911
912 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000913 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
914 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000915 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000916 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000917
918 // Compare the size argument to 0.
919 DefinedOrUnknownSVal SizeZero =
920 svalBuilder.evalEQ(state, Arg1Val,
921 svalBuilder.makeIntValWithPtrWidth(0, false));
922
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000923 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
924 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
925 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
926 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
927 // We only assume exceptional states if they are definitely true; if the
928 // state is under-constrained, assume regular realloc behavior.
929 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
930 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
931
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000932 // If the ptr is NULL and the size is not 0, the call is equivalent to
933 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000934 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000935 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000936 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000937 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000938 }
939
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000940 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000941 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000942
Anna Zaks30838b92012-02-13 20:57:07 +0000943 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000944 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000945 SymbolRef FromPtr = arg0Val.getAsSymbol();
946 SVal RetVal = state->getSVal(CE, LCtx);
947 SymbolRef ToPtr = RetVal.getAsSymbol();
948 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000949 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000950
Anna Zaks55dd9562012-08-24 02:28:20 +0000951 bool ReleasedAllocated = false;
952
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000953 // If the size is 0, free the memory.
954 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +0000955 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
956 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000957 // The semantics of the return value are:
958 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +0000959 // to free() is returned. We just free the input pointer and do not add
960 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +0000961 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000962 }
963
964 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +0000965 if (ProgramStateRef stateFree =
966 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
967
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000968 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
969 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000970 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000971 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +0000972
Anna Zaks9dc298b2012-09-12 22:57:34 +0000973 ReallocPairKind Kind = RPToBeFreedAfterFailure;
974 if (FreesOnFail)
975 Kind = RPIsFreeOnFailure;
976 else if (!ReleasedAllocated)
977 Kind = RPDoNotTrackAfterFailure;
978
Anna Zaks55dd9562012-08-24 02:28:20 +0000979 // Record the info about the reallocated symbol so that we could properly
980 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +0000981 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +0000982 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +0000983 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +0000984 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000985 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000986 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000987 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000988}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000989
Anna Zaks87cb5be2012-02-22 19:24:52 +0000990ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +0000991 if (CE->getNumArgs() < 2)
992 return 0;
993
Ted Kremenek8bef8232012-01-26 21:29:00 +0000994 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000995 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000996 const LocationContext *LCtx = C.getLocationContext();
997 SVal count = state->getSVal(CE->getArg(0), LCtx);
998 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000999 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1000 svalBuilder.getContext().getSizeType());
1001 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001002
Anna Zaks87cb5be2012-02-22 19:24:52 +00001003 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001004}
1005
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001006LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001007MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1008 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001009 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001010 // Walk the ExplodedGraph backwards and find the first node that referred to
1011 // the tracked symbol.
1012 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001013 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001014
1015 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001016 ProgramStateRef State = N->getState();
1017 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001018 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001019
1020 // Find the most recent expression bound to the symbol in the current
1021 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001022 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001023 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1024 SVal Val = State->getSVal(MR);
1025 if (Val.getAsLocSymbol() == Sym)
1026 ReferenceRegion = MR;
1027 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001028 }
1029
Anna Zaks7752d292012-02-27 23:40:55 +00001030 // Allocation node, is the last node in the current context in which the
1031 // symbol was tracked.
1032 if (N->getLocationContext() == LeakContext)
1033 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001034 N = N->pred_empty() ? NULL : *(N->pred_begin());
1035 }
1036
1037 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001038 const Stmt *AllocationStmt = 0;
Jordan Rose852aa0d2012-07-10 22:07:52 +00001039 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
1040 AllocationStmt = Exit->getCalleeContext()->getCallSite();
1041 else if (StmtPoint *SP = dyn_cast<StmtPoint>(&P))
1042 AllocationStmt = SP->getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +00001043
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001044 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001045}
1046
Anna Zaksda046772012-02-11 21:02:40 +00001047void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1048 CheckerContext &C) const {
1049 assert(N);
1050 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001051 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001052 // Leaks should not be reported if they are post-dominated by a sink:
1053 // (1) Sinks are higher importance bugs.
1054 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1055 // with __noreturn functions such as assert() or exit(). We choose not
1056 // to report leaks on such paths.
1057 BT_Leak->setSuppressOnSink(true);
1058 }
1059
Anna Zaksca8e36e2012-02-23 21:38:21 +00001060 // Most bug reports are cached at the location where they occurred.
1061 // With leaks, we want to unique them by the location where they were
1062 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001063 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001064 const Stmt *AllocStmt = 0;
1065 const MemRegion *Region = 0;
1066 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
1067 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +00001068 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
1069 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001070
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001071 SmallString<200> buf;
1072 llvm::raw_svector_ostream os(buf);
1073 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001074 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001075 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001076 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001077 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001078 }
1079
1080 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001081 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001082 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001083 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001084}
1085
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001086void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1087 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001088{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001089 if (!SymReaper.hasDeadSymbols())
1090 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001091
Ted Kremenek8bef8232012-01-26 21:29:00 +00001092 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001093 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001094 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001095
Anna Zaksf8c17b72012-02-09 06:48:19 +00001096 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001097 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1098 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001099 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001100 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001101 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001102 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001103
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001104 }
1105 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001106
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001107 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001108 ReallocPairsTy RP = state->get<ReallocPairs>();
1109 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001110 if (SymReaper.isDead(I->first) ||
1111 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001112 state = state->remove<ReallocPairs>(I->first);
1113 }
1114 }
1115
Anna Zaks4141e4d2012-11-13 03:18:01 +00001116 // Cleanup the FreeReturnValue Map.
1117 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1118 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1119 if (SymReaper.isDead(I->first) ||
1120 SymReaper.isDead(I->second)) {
1121 state = state->remove<FreeReturnValue>(I->first);
1122 }
1123 }
1124
Anna Zaksca8e36e2012-02-23 21:38:21 +00001125 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001126 ExplodedNode *N = C.getPredecessor();
1127 if (!Errors.empty()) {
1128 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1129 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001130 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001131 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001132 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001133 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001134 }
Anna Zaks54458702012-10-29 22:51:54 +00001135
Anna Zaksca8e36e2012-02-23 21:38:21 +00001136 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001137}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001138
Anna Zaks66c40402012-02-14 21:55:24 +00001139void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001140 // We will check for double free in the post visit.
1141 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001142 return;
1143
1144 // Check use after free, when a freed pointer is passed to a call.
1145 ProgramStateRef State = C.getState();
1146 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1147 E = CE->arg_end(); I != E; ++I) {
1148 const Expr *A = *I;
1149 if (A->getType().getTypePtr()->isAnyPointerType()) {
1150 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1151 if (!Sym)
1152 continue;
1153 if (checkUseAfterFree(Sym, C, A))
1154 return;
1155 }
1156 }
1157}
1158
Anna Zaks91c2a112012-02-08 23:16:56 +00001159void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1160 const Expr *E = S->getRetValue();
1161 if (!E)
1162 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001163
1164 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001165 ProgramStateRef State = C.getState();
1166 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001167 SymbolRef Sym = RetVal.getAsSymbol();
1168 if (!Sym)
1169 // If we are returning a field of the allocated struct or an array element,
1170 // the callee could still free the memory.
1171 // TODO: This logic should be a part of generic symbol escape callback.
1172 if (const MemRegion *MR = RetVal.getAsRegion())
1173 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1174 if (const SymbolicRegion *BMR =
1175 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1176 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001177
Anna Zaks0860cd02012-02-11 21:44:39 +00001178 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001179 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001180 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001181}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001182
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001183// TODO: Blocks should be either inlined or should call invalidate regions
1184// upon invocation. After that's in place, special casing here will not be
1185// needed.
1186void MallocChecker::checkPostStmt(const BlockExpr *BE,
1187 CheckerContext &C) const {
1188
1189 // Scan the BlockDecRefExprs for any object the retain count checker
1190 // may be tracking.
1191 if (!BE->getBlockDecl()->hasCaptures())
1192 return;
1193
1194 ProgramStateRef state = C.getState();
1195 const BlockDataRegion *R =
1196 cast<BlockDataRegion>(state->getSVal(BE,
1197 C.getLocationContext()).getAsRegion());
1198
1199 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1200 E = R->referenced_vars_end();
1201
1202 if (I == E)
1203 return;
1204
1205 SmallVector<const MemRegion*, 10> Regions;
1206 const LocationContext *LC = C.getLocationContext();
1207 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1208
1209 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001210 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001211 if (VR->getSuperRegion() == R) {
1212 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1213 }
1214 Regions.push_back(VR);
1215 }
1216
1217 state =
1218 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1219 Regions.data() + Regions.size()).getState();
1220 C.addTransition(state);
1221}
1222
Anna Zaks14345182012-05-18 01:16:10 +00001223bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001224 assert(Sym);
1225 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001226 return (RS && RS->isReleased());
1227}
1228
1229bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1230 const Stmt *S) const {
1231 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001232 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001233 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001234 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001235
Anna Zaksfebdc322012-02-16 22:26:12 +00001236 BugReport *R = new BugReport(*BT_UseFree,
1237 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001238 if (S)
1239 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001240 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001241 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +00001242 C.emitReport(R);
Anna Zaks91c2a112012-02-08 23:16:56 +00001243 return true;
1244 }
1245 }
1246 return false;
1247}
1248
Zhongxing Xuc8023782010-03-10 04:58:55 +00001249// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001250void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1251 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001252 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001253 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001254 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001255}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001256
Anna Zaks4fb54872012-02-11 21:02:35 +00001257//===----------------------------------------------------------------------===//
1258// Check various ways a symbol can be invalidated.
1259// TODO: This logic (the next 3 functions) is copied/similar to the
1260// RetainRelease checker. We might want to factor this out.
1261//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001262
Anna Zaks4fb54872012-02-11 21:02:35 +00001263// Stop tracking symbols when a value escapes as a result of checkBind.
1264// A value escapes in three possible cases:
1265// (1) we are binding to something that is not a memory region.
1266// (2) we are binding to a memregion that does not have stack storage
1267// (3) we are binding to a memregion with stack storage that the store
1268// does not understand.
1269void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1270 CheckerContext &C) const {
1271 // Are we storing to something that causes the value to "escape"?
1272 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001273 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001274
Anna Zaks4fb54872012-02-11 21:02:35 +00001275 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1276 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001277
Anna Zaks4fb54872012-02-11 21:02:35 +00001278 if (!escapes) {
1279 // To test (3), generate a new state with the binding added. If it is
1280 // the same state, then it escapes (since the store cannot represent
1281 // the binding).
Anna Zaks93c5a242012-05-02 00:05:20 +00001282 // Do this only if we know that the store is not supposed to generate the
1283 // same state.
1284 SVal StoredVal = state->getSVal(regionLoc->getRegion());
1285 if (StoredVal != val)
1286 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001287 }
1288 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001289
1290 // If our store can represent the binding and we aren't storing to something
1291 // that doesn't have local storage then just return and have the simulation
1292 // state continue as is.
1293 if (!escapes)
1294 return;
1295
1296 // Otherwise, find all symbols referenced by 'val' that we are tracking
1297 // and stop tracking them.
1298 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1299 C.addTransition(state);
1300}
1301
1302// If a symbolic region is assumed to NULL (or another constant), stop tracking
1303// it - assuming that allocation failed on this path.
1304ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1305 SVal Cond,
1306 bool Assumption) const {
1307 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001308 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001309 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001310 ConstraintManager &CMgr = state->getConstraintManager();
1311 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1312 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001313 state = state->remove<RegionState>(I.getKey());
1314 }
1315
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001316 // Realloc returns 0 when reallocation fails, which means that we should
1317 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001318 ReallocPairsTy RP = state->get<ReallocPairs>();
1319 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001320 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001321 ConstraintManager &CMgr = state->getConstraintManager();
1322 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001323 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001324 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001325
Anna Zaks9dc298b2012-09-12 22:57:34 +00001326 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1327 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1328 if (RS->isReleased()) {
1329 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001330 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001331 RefState::getAllocated(RS->getStmt()));
1332 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1333 state = state->remove<RegionState>(ReallocSym);
1334 else
1335 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001336 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001337 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001338 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001339 }
1340
Anna Zaks4fb54872012-02-11 21:02:35 +00001341 return state;
1342}
1343
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001344// Check if the function is known to us. So, for example, we could
Jordan Rose740d4902012-07-02 19:27:35 +00001345// conservatively assume it can free/reallocate its pointer arguments.
Anna Zaks66c40402012-02-14 21:55:24 +00001346// (We assume that the pointers cannot escape through calls to system
1347// functions not handled by this checker.)
Jordan Rose740d4902012-07-02 19:27:35 +00001348bool MallocChecker::doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001349 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001350 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001351
1352 // For now, assume that any C++ call can free memory.
1353 // TODO: If we want to be more optimistic here, we'll need to make sure that
1354 // regions escape to C++ containers. They seem to do that even now, but for
1355 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001356 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001357 return false;
1358
Jordan Rose740d4902012-07-02 19:27:35 +00001359 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001360 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001361 // If it's not a framework call, or if it takes a callback, assume it
1362 // can free memory.
1363 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001364 return false;
1365
Jordan Rose740d4902012-07-02 19:27:35 +00001366 Selector S = Msg->getSelector();
Anna Zaks52a04812012-06-20 23:35:57 +00001367
Jordan Rose740d4902012-07-02 19:27:35 +00001368 // Whitelist the ObjC methods which do free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001369 // - Anything containing 'freeWhenDone' param set to 1.
1370 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
Anna Zaks3e4f65d2012-06-22 22:08:09 +00001371 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001372 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1373 if (Call->getArgSVal(i).isConstant(1))
1374 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001375 else
1376 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001377 }
1378 }
1379
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001380 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001381 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001382 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
Jordan Rose740d4902012-07-02 19:27:35 +00001383 StringRef FirstSlot = S.getNameForSlot(0);
1384 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001385 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001386
Anna Zaks5f757682012-06-19 05:10:32 +00001387 // If the first selector starts with addPointer, insertPointer,
1388 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1389 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001390 // that the pointers get freed by following the container itself.
1391 if (FirstSlot.startswith("addPointer") ||
1392 FirstSlot.startswith("insertPointer") ||
1393 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001394 return false;
1395 }
1396
Jordan Rose740d4902012-07-02 19:27:35 +00001397 // Otherwise, assume that the method does not free memory.
1398 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001399 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001400 }
1401
Jordan Rose740d4902012-07-02 19:27:35 +00001402 // At this point the only thing left to handle is straight function calls.
1403 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1404 if (!FD)
1405 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001406
Jordan Rose740d4902012-07-02 19:27:35 +00001407 ASTContext &ASTC = State->getStateManager().getContext();
1408
1409 // If it's one of the allocation functions we can reason about, we model
1410 // its behavior explicitly.
1411 if (isMemFunction(FD, ASTC))
1412 return true;
1413
1414 // If it's not a system call, assume it frees memory.
1415 if (!Call->isInSystemHeader())
1416 return false;
1417
1418 // White list the system functions whose arguments escape.
1419 const IdentifierInfo *II = FD->getIdentifier();
1420 if (!II)
1421 return false;
1422 StringRef FName = II->getName();
1423
Jordan Rose740d4902012-07-02 19:27:35 +00001424 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001425 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001426 if (FName.endswith("NoCopy")) {
1427 // Look for the deallocator argument. We know that the memory ownership
1428 // is not transferred only if the deallocator argument is
1429 // 'kCFAllocatorNull'.
1430 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1431 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1432 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1433 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1434 if (DeallocatorName == "kCFAllocatorNull")
1435 return true;
1436 }
1437 }
1438 return false;
1439 }
1440
Jordan Rose740d4902012-07-02 19:27:35 +00001441 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001442 // 'closefn' is specified (and if that function does free memory),
1443 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001444 // Currently, we do not inspect the 'closefn' function (PR12101).
1445 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001446 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1447 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001448
1449 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1450 // these leaks might be intentional when setting the buffer for stdio.
1451 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1452 if (FName == "setbuf" || FName =="setbuffer" ||
1453 FName == "setlinebuf" || FName == "setvbuf") {
1454 if (Call->getNumArgs() >= 1) {
1455 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1456 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1457 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1458 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1459 return false;
1460 }
1461 }
1462
1463 // A bunch of other functions which either take ownership of a pointer or
1464 // wrap the result up in a struct or object, meaning it can be freed later.
1465 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1466 // but the Malloc checker cannot differentiate between them. The right way
1467 // of doing this would be to implement a pointer escapes callback.
1468 if (FName == "CGBitmapContextCreate" ||
1469 FName == "CGBitmapContextCreateWithData" ||
1470 FName == "CVPixelBufferCreateWithBytes" ||
1471 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1472 FName == "OSAtomicEnqueue") {
1473 return false;
1474 }
1475
Jordan Rose85d7e012012-07-02 19:27:51 +00001476 // Handle cases where we know a buffer's /address/ can escape.
1477 // Note that the above checks handle some special cases where we know that
1478 // even though the address escapes, it's still our responsibility to free the
1479 // buffer.
1480 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001481 return false;
1482
1483 // Otherwise, assume that the function does not free memory.
1484 // Most system calls do not free the memory.
1485 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001486}
1487
Anna Zaks4fb54872012-02-11 21:02:35 +00001488// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1489// escapes, when we are tracking p), do not track the symbol as we cannot reason
1490// about it anymore.
1491ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001492MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001493 const StoreManager::InvalidatedSymbols *invalidated,
1494 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001495 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001496 const CallEvent *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001497 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001498 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001499 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001500
Anna Zaks66c40402012-02-14 21:55:24 +00001501 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001502 // regions (explicit and implicit) escaped.
1503
1504 // Otherwise, whitelist explicit pointers; we still can track them.
1505 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001506 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1507 E = ExplicitRegions.end(); I != E; ++I) {
1508 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1509 WhitelistedSymbols.insert(R->getSymbol());
1510 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001511 }
1512
1513 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1514 E = invalidated->end(); I!=E; ++I) {
1515 SymbolRef sym = *I;
1516 if (WhitelistedSymbols.count(sym))
1517 continue;
Anna Zaks5b7aa342012-06-22 02:04:31 +00001518 // The symbol escaped. Note, we assume that if the symbol is released,
1519 // passing it out will result in a use after free. We also keep tracking
1520 // relinquished symbols.
1521 if (const RefState *RS = State->get<RegionState>(sym)) {
1522 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001523 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001524 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001525 }
Anna Zaks66c40402012-02-14 21:55:24 +00001526 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001527}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001528
Jordy Rose393f98b2012-03-18 07:43:35 +00001529static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1530 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001531 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1532 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001533
Jordan Rose166d5022012-11-02 01:54:06 +00001534 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001535 I != E; ++I) {
1536 SymbolRef sym = I.getKey();
1537 if (!currMap.lookup(sym))
1538 return sym;
1539 }
1540
1541 return NULL;
1542}
1543
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001544PathDiagnosticPiece *
1545MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1546 const ExplodedNode *PrevN,
1547 BugReporterContext &BRC,
1548 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001549 ProgramStateRef state = N->getState();
1550 ProgramStateRef statePrev = PrevN->getState();
1551
1552 const RefState *RS = state->get<RegionState>(Sym);
1553 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001554 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001555 return 0;
1556
Anna Zaksfe571602012-02-16 22:26:07 +00001557 const Stmt *S = 0;
1558 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001559 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001560
1561 // Retrieve the associated statement.
1562 ProgramPoint ProgLoc = N->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +00001563 if (StmtPoint *SP = dyn_cast<StmtPoint>(&ProgLoc))
1564 S = SP->getStmt();
1565 else if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&ProgLoc))
1566 S = Exit->getCalleeContext()->getCallSite();
Anna Zaksfe571602012-02-16 22:26:07 +00001567 // If an assumption was made on a branch, it should be caught
1568 // here by looking at the state transition.
Jordan Rose852aa0d2012-07-10 22:07:52 +00001569 else if (BlockEdge *Edge = dyn_cast<BlockEdge>(&ProgLoc)) {
1570 const CFGBlock *srcBlk = Edge->getSrc();
Anna Zaksfe571602012-02-16 22:26:07 +00001571 S = srcBlk->getTerminator();
1572 }
1573 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001574 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001575
Jordan Rose28038f32012-07-10 22:07:42 +00001576 // FIXME: We will eventually need to handle non-statement-based events
1577 // (__attribute__((cleanup))).
1578
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001579 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001580 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001581 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001582 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001583 StackHint = new StackHintGeneratorForSymbol(Sym,
1584 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001585 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001586 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001587 StackHint = new StackHintGeneratorForSymbol(Sym,
1588 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001589 } else if (isRelinquished(RS, RSPrev, S)) {
1590 Msg = "Memory ownership is transfered";
1591 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001592 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001593 Mode = ReallocationFailed;
1594 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001595 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001596 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001597
Jordy Roseb000fb52012-03-24 03:15:09 +00001598 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1599 // Is it possible to fail two reallocs WITHOUT testing in between?
1600 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1601 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001602 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001603 FailedReallocSymbol = sym;
1604 }
Anna Zaksfe571602012-02-16 22:26:07 +00001605 }
1606
1607 // We are in a special mode if a reallocation failed later in the path.
1608 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001609 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001610
Jordy Roseb000fb52012-03-24 03:15:09 +00001611 // Is this is the first appearance of the reallocated symbol?
1612 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001613 // We're at the reallocation point.
1614 Msg = "Attempt to reallocate memory";
1615 StackHint = new StackHintGeneratorForSymbol(Sym,
1616 "Returned reallocated memory");
1617 FailedReallocSymbol = NULL;
1618 Mode = Normal;
1619 }
Anna Zaksfe571602012-02-16 22:26:07 +00001620 }
1621
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001622 if (!Msg)
1623 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001624 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001625
1626 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001627 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001628 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001629 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001630}
1631
Anna Zaks93c5a242012-05-02 00:05:20 +00001632void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1633 const char *NL, const char *Sep) const {
1634
1635 RegionStateTy RS = State->get<RegionState>();
1636
1637 if (!RS.isEmpty())
1638 Out << "Has Malloc data" << NL;
1639}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001640
Anna Zaks231361a2012-02-08 23:16:52 +00001641#define REGISTER_CHECKER(name) \
1642void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001643 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001644 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001645}
Anna Zaks231361a2012-02-08 23:16:52 +00001646
1647REGISTER_CHECKER(MallocPessimistic)
1648REGISTER_CHECKER(MallocOptimistic)