blob: caf70ca3706f28a3a3a63022102ec66cc9b5ceb9 [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"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000017#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000018#include "clang/StaticAnalyzer/Core/CheckerManager.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000020#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Jordan Rosef540c542012-07-26 21:39:41 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Anna Zaks15d0ae12012-02-11 23:46:36 +000025#include "clang/Basic/SourceManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000026#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000027#include "llvm/ADT/SmallString.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000028#include "llvm/ADT/STLExtras.h"
Jordan Rose615a0922012-09-22 01:24:42 +000029#include "llvm/ADT/StringExtras.h"
Anna Zaks60a1fa42012-02-22 03:14:20 +000030#include <climits>
31
Zhongxing Xu589c0f22009-11-12 08:38:56 +000032using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000033using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000034
35namespace {
36
Zhongxing Xu7fb14642009-12-11 00:55:44 +000037class RefState {
Anna Zaks050cdd72012-06-20 20:57:46 +000038 enum Kind { // Reference to allocated memory.
39 Allocated,
40 // Reference to released/freed memory.
41 Released,
Anna Zaks050cdd72012-06-20 20:57:46 +000042 // The responsibility for freeing resources has transfered from
43 // this reference. A relinquished symbol should not be freed.
Ted Kremenekdde201b2010-08-06 21:12:55 +000044 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000045 const Stmt *S;
46
Zhongxing Xu7fb14642009-12-11 00:55:44 +000047public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000048 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
49
Anna Zaks050cdd72012-06-20 20:57:46 +000050 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000051 bool isReleased() const { return K == Released; }
Anna Zaks050cdd72012-06-20 20:57:46 +000052 bool isRelinquished() const { return K == Relinquished; }
Anna Zaksca23eb22012-02-29 18:42:47 +000053
Anna Zaksc8bb3be2012-02-13 18:05:39 +000054 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000055
56 bool operator==(const RefState &X) const {
57 return K == X.K && S == X.S;
58 }
59
Anna Zaks050cdd72012-06-20 20:57:46 +000060 static RefState getAllocated(const Stmt *s) {
61 return RefState(Allocated, s);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000062 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000063 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000064 static RefState getRelinquished(const Stmt *s) {
65 return RefState(Relinquished, s);
66 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000067
68 void Profile(llvm::FoldingSetNodeID &ID) const {
69 ID.AddInteger(K);
70 ID.AddPointer(S);
71 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000072};
73
Anna Zaks9dc298b2012-09-12 22:57:34 +000074enum ReallocPairKind {
75 RPToBeFreedAfterFailure,
76 // The symbol has been freed when reallocation failed.
77 RPIsFreeOnFailure,
78 // The symbol does not need to be freed after reallocation fails.
79 RPDoNotTrackAfterFailure
80};
81
Anna Zaks55dd9562012-08-24 02:28:20 +000082/// \class ReallocPair
83/// \brief Stores information about the symbol being reallocated by a call to
84/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaks40add292012-02-15 00:11:25 +000085struct ReallocPair {
Anna Zaks55dd9562012-08-24 02:28:20 +000086 // \brief The symbol which realloc reallocated.
Anna Zaks40add292012-02-15 00:11:25 +000087 SymbolRef ReallocatedSym;
Anna Zaks9dc298b2012-09-12 22:57:34 +000088 ReallocPairKind Kind;
Anna Zaks55dd9562012-08-24 02:28:20 +000089
Anna Zaks9dc298b2012-09-12 22:57:34 +000090 ReallocPair(SymbolRef S, ReallocPairKind K) :
91 ReallocatedSym(S), Kind(K) {}
Anna Zaks40add292012-02-15 00:11:25 +000092 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks9dc298b2012-09-12 22:57:34 +000093 ID.AddInteger(Kind);
Anna Zaks40add292012-02-15 00:11:25 +000094 ID.AddPointer(ReallocatedSym);
95 }
96 bool operator==(const ReallocPair &X) const {
97 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks9dc298b2012-09-12 22:57:34 +000098 Kind == X.Kind;
Anna Zaks40add292012-02-15 00:11:25 +000099 }
100};
101
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000102typedef std::pair<const Stmt*, const MemRegion*> LeakInfo;
103
Anna Zaksb319e022012-02-08 20:13:28 +0000104class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000105 check::EndPath,
106 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;
Anna Zaksaf498a22011-10-25 19:56:48 +0000141 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000142 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000143 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000144 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000145 void checkLocation(SVal l, bool isLoad, const Stmt *S,
146 CheckerContext &C) const;
147 void checkBind(SVal location, SVal val, const Stmt*S,
148 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000149 ProgramStateRef
150 checkRegionChanges(ProgramStateRef state,
151 const StoreManager::InvalidatedSymbols *invalidated,
152 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000153 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +0000154 const CallEvent *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000155 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
156 return true;
157 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000158
Anna Zaks93c5a242012-05-02 00:05:20 +0000159 void printState(raw_ostream &Out, ProgramStateRef State,
160 const char *NL, const char *Sep) const;
161
Zhongxing Xu7b760962009-11-13 07:25:27 +0000162private:
Anna Zaks66c40402012-02-14 21:55:24 +0000163 void initIdentifierInfo(ASTContext &C) const;
164
165 /// Check if this is one of the functions which can allocate/reallocate memory
166 /// pointed to by one of its arguments.
167 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000168 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
169 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000170
Anna Zaks87cb5be2012-02-22 19:24:52 +0000171 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
172 const CallExpr *CE,
173 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000174 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000175 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000176 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000177 return MallocMemAux(C, CE,
178 state->getSVal(SizeEx, C.getLocationContext()),
179 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000180 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000181
Ted Kremenek8bef8232012-01-26 21:29:00 +0000182 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000183 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000184 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000185
Anna Zaks87cb5be2012-02-22 19:24:52 +0000186 /// Update the RefState to reflect the new memory allocation.
187 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
188 const CallExpr *CE,
189 ProgramStateRef state);
190
191 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
192 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000193 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000194 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000195 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000196 bool &ReleasedAllocated,
197 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000198 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
199 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000200 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000201 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000202 bool &ReleasedAllocated,
203 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000204
Anna Zaks87cb5be2012-02-22 19:24:52 +0000205 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
206 bool FreesMemOnFailure) const;
207 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000208
Anna Zaks14345182012-05-18 01:16:10 +0000209 ///\brief Check if the memory associated with this symbol was released.
210 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
211
Anna Zaks91c2a112012-02-08 23:16:56 +0000212 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
213 const Stmt *S = 0) const;
214
Anna Zaks66c40402012-02-14 21:55:24 +0000215 /// Check if the function is not known to us. So, for example, we could
216 /// conservatively assume it can free/reallocate it's pointer arguments.
Jordan Rose740d4902012-07-02 19:27:35 +0000217 bool doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000218 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000219
Ted Kremenek9c378f72011-08-12 23:37:29 +0000220 static bool SummarizeValue(raw_ostream &os, SVal V);
221 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000222 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000223
Anna Zaksca8e36e2012-02-23 21:38:21 +0000224 /// Find the location of the allocation for Sym on the path leading to the
225 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000226 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
227 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000228
Anna Zaksda046772012-02-11 21:02:40 +0000229 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
230
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000231 /// The bug visitor which allows us to print extra diagnostics along the
232 /// BugReport path. For example, showing the allocation site of the leaked
233 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000234 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000235 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000236 enum NotificationMode {
237 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000238 ReallocationFailed
239 };
240
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000241 // The allocated region symbol tracked by the main analysis.
242 SymbolRef Sym;
243
Anna Zaks88feba02012-05-10 01:37:40 +0000244 // The mode we are in, i.e. what kind of diagnostics will be emitted.
245 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000246
Anna Zaks88feba02012-05-10 01:37:40 +0000247 // A symbol from when the primary region should have been reallocated.
248 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000249
Anna Zaks88feba02012-05-10 01:37:40 +0000250 bool IsLeak;
251
252 public:
253 MallocBugVisitor(SymbolRef S, bool isLeak = false)
254 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000255
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000256 virtual ~MallocBugVisitor() {}
257
258 void Profile(llvm::FoldingSetNodeID &ID) const {
259 static int X = 0;
260 ID.AddPointer(&X);
261 ID.AddPointer(Sym);
262 }
263
Anna Zaksfe571602012-02-16 22:26:07 +0000264 inline bool isAllocated(const RefState *S, const RefState *SPrev,
265 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000266 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000267 return (Stmt && isa<CallExpr>(Stmt) &&
268 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000269 }
270
Anna Zaksfe571602012-02-16 22:26:07 +0000271 inline bool isReleased(const RefState *S, const RefState *SPrev,
272 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000273 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000274 return (Stmt && isa<CallExpr>(Stmt) &&
275 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
276 }
277
Anna Zaks5b7aa342012-06-22 02:04:31 +0000278 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
279 const Stmt *Stmt) {
280 // Did not track -> relinquished. Other state (allocated) -> relinquished.
281 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
282 isa<ObjCPropertyRefExpr>(Stmt)) &&
283 (S && S->isRelinquished()) &&
284 (!SPrev || !SPrev->isRelinquished()));
285 }
286
Anna Zaksfe571602012-02-16 22:26:07 +0000287 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
288 const Stmt *Stmt) {
289 // If the expression is not a call, and the state change is
290 // released -> allocated, it must be the realloc return value
291 // check. If we have to handle more cases here, it might be cleaner just
292 // to track this extra bit in the state itself.
293 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
294 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000295 }
296
297 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
298 const ExplodedNode *PrevN,
299 BugReporterContext &BRC,
300 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000301
302 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
303 const ExplodedNode *EndPathNode,
304 BugReport &BR) {
305 if (!IsLeak)
306 return 0;
307
308 PathDiagnosticLocation L =
309 PathDiagnosticLocation::createEndOfPath(EndPathNode,
310 BRC.getSourceManager());
311 // Do not add the statement itself as a range in case of leak.
312 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
313 }
314
Anna Zaks56a938f2012-03-16 23:24:20 +0000315 private:
316 class StackHintGeneratorForReallocationFailed
317 : public StackHintGeneratorForSymbol {
318 public:
319 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
320 : StackHintGeneratorForSymbol(S, M) {}
321
322 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000323 // Printed parameters start at 1, not 0.
324 ++ArgIndex;
325
Anna Zaks56a938f2012-03-16 23:24:20 +0000326 SmallString<200> buf;
327 llvm::raw_svector_ostream os(buf);
328
Jordan Rose615a0922012-09-22 01:24:42 +0000329 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
330 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000331
332 return os.str();
333 }
334
335 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000336 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000337 }
338 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000339 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000340};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000341} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000342
Jordan Rose166d5022012-11-02 01:54:06 +0000343REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
344REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000345
Anna Zaks4141e4d2012-11-13 03:18:01 +0000346// A map from the freed symbol to the symbol representing the return value of
347// the free function.
348REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
349
Anna Zaks4fb54872012-02-11 21:02:35 +0000350namespace {
351class StopTrackingCallback : public SymbolVisitor {
352 ProgramStateRef state;
353public:
354 StopTrackingCallback(ProgramStateRef st) : state(st) {}
355 ProgramStateRef getState() const { return state; }
356
357 bool VisitSymbol(SymbolRef sym) {
358 state = state->remove<RegionState>(sym);
359 return true;
360 }
361};
362} // end anonymous namespace
363
Anna Zaks66c40402012-02-14 21:55:24 +0000364void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000365 if (II_malloc)
366 return;
367 II_malloc = &Ctx.Idents.get("malloc");
368 II_free = &Ctx.Idents.get("free");
369 II_realloc = &Ctx.Idents.get("realloc");
370 II_reallocf = &Ctx.Idents.get("reallocf");
371 II_calloc = &Ctx.Idents.get("calloc");
372 II_valloc = &Ctx.Idents.get("valloc");
373 II_strdup = &Ctx.Idents.get("strdup");
374 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000375}
376
Anna Zaks66c40402012-02-14 21:55:24 +0000377bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000378 if (isFreeFunction(FD, C))
379 return true;
380
381 if (isAllocationFunction(FD, C))
382 return true;
383
384 return false;
385}
386
387bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
388 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000389 if (!FD)
390 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000391
Jordan Rose5ef6e942012-07-10 23:13:01 +0000392 if (FD->getKind() == Decl::Function) {
393 IdentifierInfo *FunI = FD->getIdentifier();
394 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000395
Jordan Rose5ef6e942012-07-10 23:13:01 +0000396 if (FunI == II_malloc || FunI == II_realloc ||
397 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
398 FunI == II_strdup || FunI == II_strndup)
399 return true;
400 }
Anna Zaks66c40402012-02-14 21:55:24 +0000401
Anna Zaks14345182012-05-18 01:16:10 +0000402 if (Filter.CMallocOptimistic && FD->hasAttrs())
403 for (specific_attr_iterator<OwnershipAttr>
404 i = FD->specific_attr_begin<OwnershipAttr>(),
405 e = FD->specific_attr_end<OwnershipAttr>();
406 i != e; ++i)
407 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
408 return true;
409 return false;
410}
411
412bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
413 if (!FD)
414 return false;
415
Jordan Rose5ef6e942012-07-10 23:13:01 +0000416 if (FD->getKind() == Decl::Function) {
417 IdentifierInfo *FunI = FD->getIdentifier();
418 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000419
Jordan Rose5ef6e942012-07-10 23:13:01 +0000420 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
421 return true;
422 }
Anna Zaks66c40402012-02-14 21:55:24 +0000423
Anna Zaks14345182012-05-18 01:16:10 +0000424 if (Filter.CMallocOptimistic && FD->hasAttrs())
425 for (specific_attr_iterator<OwnershipAttr>
426 i = FD->specific_attr_begin<OwnershipAttr>(),
427 e = FD->specific_attr_end<OwnershipAttr>();
428 i != e; ++i)
429 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
430 (*i)->getOwnKind() == OwnershipAttr::Holds)
431 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000432 return false;
433}
434
Anna Zaksb319e022012-02-08 20:13:28 +0000435void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000436 if (C.wasInlined)
437 return;
438
Anna Zaksb319e022012-02-08 20:13:28 +0000439 const FunctionDecl *FD = C.getCalleeDecl(CE);
440 if (!FD)
441 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000442
Anna Zaks87cb5be2012-02-22 19:24:52 +0000443 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000444 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000445
446 if (FD->getKind() == Decl::Function) {
447 initIdentifierInfo(C.getASTContext());
448 IdentifierInfo *FunI = FD->getIdentifier();
449
450 if (FunI == II_malloc || FunI == II_valloc) {
451 if (CE->getNumArgs() < 1)
452 return;
453 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
454 } else if (FunI == II_realloc) {
455 State = ReallocMem(C, CE, false);
456 } else if (FunI == II_reallocf) {
457 State = ReallocMem(C, CE, true);
458 } else if (FunI == II_calloc) {
459 State = CallocMem(C, CE);
460 } else if (FunI == II_free) {
Anna Zaks55dd9562012-08-24 02:28:20 +0000461 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose5ef6e942012-07-10 23:13:01 +0000462 } else if (FunI == II_strdup) {
463 State = MallocUpdateRefState(C, CE, State);
464 } else if (FunI == II_strndup) {
465 State = MallocUpdateRefState(C, CE, State);
466 }
467 }
468
469 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000470 // Check all the attributes, if there are any.
471 // There can be multiple of these attributes.
472 if (FD->hasAttrs())
473 for (specific_attr_iterator<OwnershipAttr>
474 i = FD->specific_attr_begin<OwnershipAttr>(),
475 e = FD->specific_attr_end<OwnershipAttr>();
476 i != e; ++i) {
477 switch ((*i)->getOwnKind()) {
478 case OwnershipAttr::Returns:
479 State = MallocMemReturnsAttr(C, CE, *i);
480 break;
481 case OwnershipAttr::Takes:
482 case OwnershipAttr::Holds:
483 State = FreeMemAttr(C, CE, *i);
484 break;
485 }
486 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000487 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000488 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000489}
490
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000491static bool isFreeWhenDoneSetToZero(const ObjCMethodCall &Call) {
492 Selector S = Call.getSelector();
Anna Zaks3e4f65d2012-06-22 22:08:09 +0000493 for (unsigned i = 1; i < S.getNumArgs(); ++i)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000494 if (S.getNameForSlot(i).equals("freeWhenDone"))
495 if (Call.getArgSVal(i).isConstant(0))
496 return true;
497
498 return false;
499}
500
Anna Zaks4141e4d2012-11-13 03:18:01 +0000501void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
502 CheckerContext &C) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000503 // If the first selector is dataWithBytesNoCopy, assume that the memory will
504 // be released with 'free' by the new object.
505 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
506 // Unless 'freeWhenDone' param set to 0.
507 // TODO: Check that the memory was allocated with malloc.
Anna Zaks55dd9562012-08-24 02:28:20 +0000508 bool ReleasedAllocatedMemory = false;
Jordan Rosede507ea2012-07-02 19:28:04 +0000509 Selector S = Call.getSelector();
Anna Zaks7186dc62012-06-22 22:42:30 +0000510 if ((S.getNameForSlot(0) == "dataWithBytesNoCopy" ||
511 S.getNameForSlot(0) == "initWithBytesNoCopy" ||
512 S.getNameForSlot(0) == "initWithCharactersNoCopy") &&
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000513 !isFreeWhenDoneSetToZero(Call)){
Anna Zaks5b7aa342012-06-22 02:04:31 +0000514 unsigned int argIdx = 0;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000515 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(argIdx),
516 Call.getOriginExpr(), C.getState(), true,
517 ReleasedAllocatedMemory,
518 /* RetNullOnFailure*/ true);
519
520 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000521 }
522}
523
Anna Zaks87cb5be2012-02-22 19:24:52 +0000524ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
525 const CallExpr *CE,
526 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000527 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000528 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000529
Sean Huntcf807c42010-08-18 23:23:40 +0000530 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000531 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000532 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000533 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000534 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000535}
536
Anna Zaksb319e022012-02-08 20:13:28 +0000537ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000538 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000539 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000540 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000541
542 // Bind the return value to the symbolic value from the heap region.
543 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
544 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000545 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000546 SValBuilder &svalBuilder = C.getSValBuilder();
547 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
548 DefinedSVal RetVal =
549 cast<DefinedSVal>(svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count));
550 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000551
Anna Zaksb16ce452012-02-15 00:11:22 +0000552 // We expect the malloc functions to return a pointer.
Anna Zakse17fdb22012-06-07 03:57:32 +0000553 if (!isa<Loc>(RetVal))
Anna Zaksb16ce452012-02-15 00:11:22 +0000554 return 0;
555
Jordy Rose32f26562010-07-04 00:00:41 +0000556 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000557 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000558
Jordy Rose32f26562010-07-04 00:00:41 +0000559 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000560 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000561 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000562 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000563 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000564 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000565 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000566 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
567 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
568 DefinedOrUnknownSVal extentMatchesSize =
569 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000570
Anna Zaks60a1fa42012-02-22 03:14:20 +0000571 state = state->assume(extentMatchesSize, true);
572 assert(state);
573 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000574
Anna Zaks87cb5be2012-02-22 19:24:52 +0000575 return MallocUpdateRefState(C, CE, state);
576}
577
578ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
579 const CallExpr *CE,
580 ProgramStateRef state) {
581 // Get the return value.
582 SVal retVal = state->getSVal(CE, C.getLocationContext());
583
584 // We expect the malloc functions to return a pointer.
585 if (!isa<Loc>(retVal))
586 return 0;
587
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000588 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000589 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000590
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000591 // Set the symbol's state to Allocated.
Anna Zaks050cdd72012-06-20 20:57:46 +0000592 return state->set<RegionState>(Sym, RefState::getAllocated(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000593
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000594}
595
Anna Zaks87cb5be2012-02-22 19:24:52 +0000596ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
597 const CallExpr *CE,
598 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000599 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000600 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000601
Anna Zaksb3d72752012-03-01 22:06:06 +0000602 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000603 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000604
Sean Huntcf807c42010-08-18 23:23:40 +0000605 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
606 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000607 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000608 Att->getOwnKind() == OwnershipAttr::Holds,
609 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000610 if (StateI)
611 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000612 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000613 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000614}
615
Ted Kremenek8bef8232012-01-26 21:29:00 +0000616ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000617 const CallExpr *CE,
618 ProgramStateRef state,
619 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000620 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000621 bool &ReleasedAllocated,
622 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000623 if (CE->getNumArgs() < (Num + 1))
624 return 0;
625
Anna Zaks4141e4d2012-11-13 03:18:01 +0000626 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
627 ReleasedAllocated, ReturnsNullOnFailure);
628}
629
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000630/// Checks if the previous call to free on the given symbol failed - if free
631/// failed, returns true. Also, returns the corresponding return value symbol.
632bool didPreviousFreeFail(ProgramStateRef State,
633 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
634 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000635 if (Ret) {
636 assert(*Ret && "We should not store the null return symbol");
637 ConstraintManager &CMgr = State->getConstraintManager();
638 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000639 RetStatusSymbol = *Ret;
640 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000641 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000642 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000643}
644
645ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
646 const Expr *ArgExpr,
647 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000648 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000649 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000650 bool &ReleasedAllocated,
651 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000652
Anna Zaks4141e4d2012-11-13 03:18:01 +0000653 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000654 if (!isa<DefinedOrUnknownSVal>(ArgVal))
655 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000656 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
657
658 // Check for null dereferences.
659 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000660 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000661
Anna Zaksb276bd92012-02-14 00:26:13 +0000662 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000663 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000664 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000665 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000666 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000667
Jordy Rose43859f62010-06-07 19:32:37 +0000668 // Unknown values could easily be okay
669 // Undefined values are handled elsewhere
670 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000671 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000672
Jordy Rose43859f62010-06-07 19:32:37 +0000673 const MemRegion *R = ArgVal.getAsRegion();
674
675 // Nonlocs can't be freed, of course.
676 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
677 if (!R) {
678 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000679 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000680 }
681
682 R = R->StripCasts();
683
684 // Blocks might show up as heap data, but should not be free()d
685 if (isa<BlockDataRegion>(R)) {
686 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000687 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000688 }
689
690 const MemSpaceRegion *MS = R->getMemorySpace();
691
692 // Parameters, locals, statics, and globals shouldn't be freed.
693 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
694 // FIXME: at the time this code was written, malloc() regions were
695 // represented by conjured symbols, which are all in UnknownSpaceRegion.
696 // This means that there isn't actually anything from HeapSpaceRegion
697 // that should be freed, even though we allow it here.
698 // Of course, free() can work on memory allocated outside the current
699 // function, so UnknownSpaceRegion is always a possibility.
700 // False negatives are better than false positives.
701
702 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000703 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000704 }
705
706 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
707 // Various cases could lead to non-symbol values here.
708 // For now, ignore them.
709 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000710 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000711
712 SymbolRef Sym = SR->getSymbol();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000713 const RefState *RS = State->get<RegionState>(Sym);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000714 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000715
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000716 // Check double free.
Anna Zaks4141e4d2012-11-13 03:18:01 +0000717 if (RS &&
718 (RS->isReleased() || RS->isRelinquished()) &&
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000719 !didPreviousFreeFail(State, Sym, PreviousRetStatusSymbol)) {
Anna Zaks4141e4d2012-11-13 03:18:01 +0000720
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000721 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000722 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000723 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000724 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000725 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000726 (RS->isReleased() ? "Attempt to free released memory" :
727 "Attempt to free non-owned memory"), N);
Anna Zaksfe571602012-02-16 22:26:07 +0000728 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000729 R->markInteresting(Sym);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000730 if (PreviousRetStatusSymbol)
731 R->markInteresting(PreviousRetStatusSymbol);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000732 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +0000733 C.emitReport(R);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000734 }
Anna Zaksb319e022012-02-08 20:13:28 +0000735 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000736 }
737
Anna Zaks55dd9562012-08-24 02:28:20 +0000738 ReleasedAllocated = (RS != 0);
739
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000740 // Clean out the info on previous call to free return info.
741 State = State->remove<FreeReturnValue>(Sym);
742
Anna Zaks4141e4d2012-11-13 03:18:01 +0000743 // Keep track of the return value. If it is NULL, we will know that free
744 // failed.
745 if (ReturnsNullOnFailure) {
746 SVal RetVal = C.getSVal(ParentExpr);
747 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
748 if (RetStatusSymbol) {
749 C.getSymbolManager().addSymbolDependency(Sym, RetStatusSymbol);
750 State = State->set<FreeReturnValue>(Sym, RetStatusSymbol);
751 }
752 }
753
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000754 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000755 if (Hold)
Anna Zaks4141e4d2012-11-13 03:18:01 +0000756 return State->set<RegionState>(Sym, RefState::getRelinquished(ParentExpr));
757 return State->set<RegionState>(Sym, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000758}
759
Ted Kremenek9c378f72011-08-12 23:37:29 +0000760bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000761 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
762 os << "an integer (" << IntVal->getValue() << ")";
763 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
764 os << "a constant address (" << ConstAddr->getValue() << ")";
765 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000766 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000767 else
768 return false;
769
770 return true;
771}
772
Ted Kremenek9c378f72011-08-12 23:37:29 +0000773bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000774 const MemRegion *MR) {
775 switch (MR->getKind()) {
776 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000777 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +0000778 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000779 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000780 else
781 os << "the address of a function";
782 return true;
783 }
784 case MemRegion::BlockTextRegionKind:
785 os << "block text";
786 return true;
787 case MemRegion::BlockDataRegionKind:
788 // FIXME: where the block came from?
789 os << "a block";
790 return true;
791 default: {
792 const MemSpaceRegion *MS = MR->getMemorySpace();
793
Anna Zakseb31a762012-01-04 23:54:01 +0000794 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000795 const VarRegion *VR = dyn_cast<VarRegion>(MR);
796 const VarDecl *VD;
797 if (VR)
798 VD = VR->getDecl();
799 else
800 VD = NULL;
801
802 if (VD)
803 os << "the address of the local variable '" << VD->getName() << "'";
804 else
805 os << "the address of a local stack variable";
806 return true;
807 }
Anna Zakseb31a762012-01-04 23:54:01 +0000808
809 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000810 const VarRegion *VR = dyn_cast<VarRegion>(MR);
811 const VarDecl *VD;
812 if (VR)
813 VD = VR->getDecl();
814 else
815 VD = NULL;
816
817 if (VD)
818 os << "the address of the parameter '" << VD->getName() << "'";
819 else
820 os << "the address of a parameter";
821 return true;
822 }
Anna Zakseb31a762012-01-04 23:54:01 +0000823
824 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000825 const VarRegion *VR = dyn_cast<VarRegion>(MR);
826 const VarDecl *VD;
827 if (VR)
828 VD = VR->getDecl();
829 else
830 VD = NULL;
831
832 if (VD) {
833 if (VD->isStaticLocal())
834 os << "the address of the static variable '" << VD->getName() << "'";
835 else
836 os << "the address of the global variable '" << VD->getName() << "'";
837 } else
838 os << "the address of a global variable";
839 return true;
840 }
Anna Zakseb31a762012-01-04 23:54:01 +0000841
842 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000843 }
844 }
845}
846
847void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000848 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000849 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000850 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000851 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000852
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000853 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000854 llvm::raw_svector_ostream os(buf);
855
856 const MemRegion *MR = ArgVal.getAsRegion();
857 if (MR) {
858 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
859 MR = ER->getSuperRegion();
860
861 // Special case for alloca()
862 if (isa<AllocaRegion>(MR))
863 os << "Argument to free() was allocated by alloca(), not malloc()";
864 else {
865 os << "Argument to free() is ";
866 if (SummarizeRegion(os, MR))
867 os << ", which is not memory allocated by malloc()";
868 else
869 os << "not memory allocated by malloc()";
870 }
871 } else {
872 os << "Argument to free() is ";
873 if (SummarizeValue(os, ArgVal))
874 os << ", which is not memory allocated by malloc()";
875 else
876 os << "not memory allocated by malloc()";
877 }
878
Anna Zakse172e8b2011-08-17 23:00:25 +0000879 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000880 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000881 R->addRange(range);
Jordan Rose785950e2012-11-02 01:53:40 +0000882 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +0000883 }
884}
885
Anna Zaks87cb5be2012-02-22 19:24:52 +0000886ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
887 const CallExpr *CE,
888 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000889 if (CE->getNumArgs() < 2)
890 return 0;
891
Ted Kremenek8bef8232012-01-26 21:29:00 +0000892 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000893 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000894 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000895 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
896 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000897 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000898 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000899
Ted Kremenek846eabd2010-12-01 21:28:31 +0000900 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000901
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000902 DefinedOrUnknownSVal PtrEQ =
903 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000904
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000905 // Get the size argument. If there is no size arg then give up.
906 const Expr *Arg1 = CE->getArg(1);
907 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000908 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000909
910 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000911 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
912 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000913 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000914 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000915
916 // Compare the size argument to 0.
917 DefinedOrUnknownSVal SizeZero =
918 svalBuilder.evalEQ(state, Arg1Val,
919 svalBuilder.makeIntValWithPtrWidth(0, false));
920
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000921 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
922 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
923 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
924 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
925 // We only assume exceptional states if they are definitely true; if the
926 // state is under-constrained, assume regular realloc behavior.
927 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
928 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
929
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000930 // If the ptr is NULL and the size is not 0, the call is equivalent to
931 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000932 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000933 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000934 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000935 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000936 }
937
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000938 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000939 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000940
Anna Zaks30838b92012-02-13 20:57:07 +0000941 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000942 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000943 SymbolRef FromPtr = arg0Val.getAsSymbol();
944 SVal RetVal = state->getSVal(CE, LCtx);
945 SymbolRef ToPtr = RetVal.getAsSymbol();
946 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000947 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000948
Anna Zaks55dd9562012-08-24 02:28:20 +0000949 bool ReleasedAllocated = false;
950
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000951 // If the size is 0, free the memory.
952 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +0000953 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
954 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000955 // The semantics of the return value are:
956 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +0000957 // to free() is returned. We just free the input pointer and do not add
958 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +0000959 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000960 }
961
962 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +0000963 if (ProgramStateRef stateFree =
964 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
965
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000966 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
967 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000968 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000969 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +0000970
Anna Zaks9dc298b2012-09-12 22:57:34 +0000971 ReallocPairKind Kind = RPToBeFreedAfterFailure;
972 if (FreesOnFail)
973 Kind = RPIsFreeOnFailure;
974 else if (!ReleasedAllocated)
975 Kind = RPDoNotTrackAfterFailure;
976
Anna Zaks55dd9562012-08-24 02:28:20 +0000977 // Record the info about the reallocated symbol so that we could properly
978 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +0000979 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +0000980 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +0000981 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +0000982 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000983 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000984 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000985 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000986}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000987
Anna Zaks87cb5be2012-02-22 19:24:52 +0000988ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +0000989 if (CE->getNumArgs() < 2)
990 return 0;
991
Ted Kremenek8bef8232012-01-26 21:29:00 +0000992 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000993 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000994 const LocationContext *LCtx = C.getLocationContext();
995 SVal count = state->getSVal(CE->getArg(0), LCtx);
996 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000997 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
998 svalBuilder.getContext().getSizeType());
999 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001000
Anna Zaks87cb5be2012-02-22 19:24:52 +00001001 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001002}
1003
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001004LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001005MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1006 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001007 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001008 // Walk the ExplodedGraph backwards and find the first node that referred to
1009 // the tracked symbol.
1010 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001011 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001012
1013 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001014 ProgramStateRef State = N->getState();
1015 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001016 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001017
1018 // Find the most recent expression bound to the symbol in the current
1019 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001020 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001021 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1022 SVal Val = State->getSVal(MR);
1023 if (Val.getAsLocSymbol() == Sym)
1024 ReferenceRegion = MR;
1025 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001026 }
1027
Anna Zaks7752d292012-02-27 23:40:55 +00001028 // Allocation node, is the last node in the current context in which the
1029 // symbol was tracked.
1030 if (N->getLocationContext() == LeakContext)
1031 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001032 N = N->pred_empty() ? NULL : *(N->pred_begin());
1033 }
1034
1035 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001036 const Stmt *AllocationStmt = 0;
Jordan Rose852aa0d2012-07-10 22:07:52 +00001037 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
1038 AllocationStmt = Exit->getCalleeContext()->getCallSite();
1039 else if (StmtPoint *SP = dyn_cast<StmtPoint>(&P))
1040 AllocationStmt = SP->getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +00001041
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001042 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001043}
1044
Anna Zaksda046772012-02-11 21:02:40 +00001045void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1046 CheckerContext &C) const {
1047 assert(N);
1048 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001049 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001050 // Leaks should not be reported if they are post-dominated by a sink:
1051 // (1) Sinks are higher importance bugs.
1052 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1053 // with __noreturn functions such as assert() or exit(). We choose not
1054 // to report leaks on such paths.
1055 BT_Leak->setSuppressOnSink(true);
1056 }
1057
Anna Zaksca8e36e2012-02-23 21:38:21 +00001058 // Most bug reports are cached at the location where they occurred.
1059 // With leaks, we want to unique them by the location where they were
1060 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001061 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001062 const Stmt *AllocStmt = 0;
1063 const MemRegion *Region = 0;
1064 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
1065 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +00001066 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
1067 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001068
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001069 SmallString<200> buf;
1070 llvm::raw_svector_ostream os(buf);
1071 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001072 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001073 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001074 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001075 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001076 }
1077
1078 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001079 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001080 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001081 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001082}
1083
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001084void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1085 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001086{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001087 if (!SymReaper.hasDeadSymbols())
1088 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001089
Ted Kremenek8bef8232012-01-26 21:29:00 +00001090 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001091 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001092 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001093
Anna Zaksf8c17b72012-02-09 06:48:19 +00001094 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001095 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1096 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001097 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001098 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001099 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001100 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001101
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001102 }
1103 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001104
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001105 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001106 ReallocPairsTy RP = state->get<ReallocPairs>();
1107 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001108 if (SymReaper.isDead(I->first) ||
1109 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001110 state = state->remove<ReallocPairs>(I->first);
1111 }
1112 }
1113
Anna Zaks4141e4d2012-11-13 03:18:01 +00001114 // Cleanup the FreeReturnValue Map.
1115 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1116 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1117 if (SymReaper.isDead(I->first) ||
1118 SymReaper.isDead(I->second)) {
1119 state = state->remove<FreeReturnValue>(I->first);
1120 }
1121 }
1122
Anna Zaksca8e36e2012-02-23 21:38:21 +00001123 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001124 ExplodedNode *N = C.getPredecessor();
1125 if (!Errors.empty()) {
1126 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1127 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001128 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001129 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001130 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001131 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001132 }
Anna Zaks54458702012-10-29 22:51:54 +00001133
Anna Zaksca8e36e2012-02-23 21:38:21 +00001134 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001135}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001136
Anna Zaksda046772012-02-11 21:02:40 +00001137void MallocChecker::checkEndPath(CheckerContext &C) const {
1138 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +00001139 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +00001140
Anna Zaksa19581a2012-02-20 22:25:23 +00001141 // If inside inlined call, skip it.
1142 if (C.getLocationContext()->getParent() != 0)
1143 return;
1144
Jordy Rose09cef092010-08-18 04:26:59 +00001145 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +00001146 RefState RS = I->second;
1147 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +00001148 ExplodedNode *N = C.addTransition(state);
1149 if (N)
1150 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +00001151 }
1152 }
1153}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001154
Anna Zaks66c40402012-02-14 21:55:24 +00001155void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001156 // We will check for double free in the post visit.
1157 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001158 return;
1159
1160 // Check use after free, when a freed pointer is passed to a call.
1161 ProgramStateRef State = C.getState();
1162 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1163 E = CE->arg_end(); I != E; ++I) {
1164 const Expr *A = *I;
1165 if (A->getType().getTypePtr()->isAnyPointerType()) {
1166 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1167 if (!Sym)
1168 continue;
1169 if (checkUseAfterFree(Sym, C, A))
1170 return;
1171 }
1172 }
1173}
1174
Anna Zaks91c2a112012-02-08 23:16:56 +00001175void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1176 const Expr *E = S->getRetValue();
1177 if (!E)
1178 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001179
1180 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001181 ProgramStateRef State = C.getState();
1182 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001183 SymbolRef Sym = RetVal.getAsSymbol();
1184 if (!Sym)
1185 // If we are returning a field of the allocated struct or an array element,
1186 // the callee could still free the memory.
1187 // TODO: This logic should be a part of generic symbol escape callback.
1188 if (const MemRegion *MR = RetVal.getAsRegion())
1189 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1190 if (const SymbolicRegion *BMR =
1191 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1192 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001193
Anna Zaks0860cd02012-02-11 21:44:39 +00001194 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001195 if (Sym)
1196 if (checkUseAfterFree(Sym, C, E))
1197 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001198
Jordan Rose0d53ab42012-08-08 18:23:31 +00001199 // If this function body is not inlined, stop tracking any returned symbols.
1200 if (C.getLocationContext()->getParent() == 0) {
1201 State =
1202 State->scanReachableSymbols<StopTrackingCallback>(RetVal).getState();
1203 C.addTransition(State);
1204 }
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001205}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001206
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001207// TODO: Blocks should be either inlined or should call invalidate regions
1208// upon invocation. After that's in place, special casing here will not be
1209// needed.
1210void MallocChecker::checkPostStmt(const BlockExpr *BE,
1211 CheckerContext &C) const {
1212
1213 // Scan the BlockDecRefExprs for any object the retain count checker
1214 // may be tracking.
1215 if (!BE->getBlockDecl()->hasCaptures())
1216 return;
1217
1218 ProgramStateRef state = C.getState();
1219 const BlockDataRegion *R =
1220 cast<BlockDataRegion>(state->getSVal(BE,
1221 C.getLocationContext()).getAsRegion());
1222
1223 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1224 E = R->referenced_vars_end();
1225
1226 if (I == E)
1227 return;
1228
1229 SmallVector<const MemRegion*, 10> Regions;
1230 const LocationContext *LC = C.getLocationContext();
1231 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1232
1233 for ( ; I != E; ++I) {
1234 const VarRegion *VR = *I;
1235 if (VR->getSuperRegion() == R) {
1236 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1237 }
1238 Regions.push_back(VR);
1239 }
1240
1241 state =
1242 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1243 Regions.data() + Regions.size()).getState();
1244 C.addTransition(state);
1245}
1246
Anna Zaks14345182012-05-18 01:16:10 +00001247bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001248 assert(Sym);
1249 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001250 return (RS && RS->isReleased());
1251}
1252
1253bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1254 const Stmt *S) const {
1255 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001256 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001257 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001258 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001259
Anna Zaksfebdc322012-02-16 22:26:12 +00001260 BugReport *R = new BugReport(*BT_UseFree,
1261 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001262 if (S)
1263 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001264 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001265 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +00001266 C.emitReport(R);
Anna Zaks91c2a112012-02-08 23:16:56 +00001267 return true;
1268 }
1269 }
1270 return false;
1271}
1272
Zhongxing Xuc8023782010-03-10 04:58:55 +00001273// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001274void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1275 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001276 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001277 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001278 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001279}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001280
Anna Zaks4fb54872012-02-11 21:02:35 +00001281//===----------------------------------------------------------------------===//
1282// Check various ways a symbol can be invalidated.
1283// TODO: This logic (the next 3 functions) is copied/similar to the
1284// RetainRelease checker. We might want to factor this out.
1285//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001286
Anna Zaks4fb54872012-02-11 21:02:35 +00001287// Stop tracking symbols when a value escapes as a result of checkBind.
1288// A value escapes in three possible cases:
1289// (1) we are binding to something that is not a memory region.
1290// (2) we are binding to a memregion that does not have stack storage
1291// (3) we are binding to a memregion with stack storage that the store
1292// does not understand.
1293void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1294 CheckerContext &C) const {
1295 // Are we storing to something that causes the value to "escape"?
1296 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001297 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001298
Anna Zaks4fb54872012-02-11 21:02:35 +00001299 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1300 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001301
Anna Zaks4fb54872012-02-11 21:02:35 +00001302 if (!escapes) {
1303 // To test (3), generate a new state with the binding added. If it is
1304 // the same state, then it escapes (since the store cannot represent
1305 // the binding).
Anna Zaks93c5a242012-05-02 00:05:20 +00001306 // Do this only if we know that the store is not supposed to generate the
1307 // same state.
1308 SVal StoredVal = state->getSVal(regionLoc->getRegion());
1309 if (StoredVal != val)
1310 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001311 }
1312 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001313
1314 // If our store can represent the binding and we aren't storing to something
1315 // that doesn't have local storage then just return and have the simulation
1316 // state continue as is.
1317 if (!escapes)
1318 return;
1319
1320 // Otherwise, find all symbols referenced by 'val' that we are tracking
1321 // and stop tracking them.
1322 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1323 C.addTransition(state);
1324}
1325
1326// If a symbolic region is assumed to NULL (or another constant), stop tracking
1327// it - assuming that allocation failed on this path.
1328ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1329 SVal Cond,
1330 bool Assumption) const {
1331 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001332 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001333 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001334 ConstraintManager &CMgr = state->getConstraintManager();
1335 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1336 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001337 state = state->remove<RegionState>(I.getKey());
1338 }
1339
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001340 // Realloc returns 0 when reallocation fails, which means that we should
1341 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001342 ReallocPairsTy RP = state->get<ReallocPairs>();
1343 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001344 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001345 ConstraintManager &CMgr = state->getConstraintManager();
1346 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001347 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001348 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001349
Anna Zaks9dc298b2012-09-12 22:57:34 +00001350 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1351 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1352 if (RS->isReleased()) {
1353 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001354 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001355 RefState::getAllocated(RS->getStmt()));
1356 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1357 state = state->remove<RegionState>(ReallocSym);
1358 else
1359 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001360 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001361 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001362 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001363 }
1364
Anna Zaks4fb54872012-02-11 21:02:35 +00001365 return state;
1366}
1367
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001368// Check if the function is known to us. So, for example, we could
Jordan Rose740d4902012-07-02 19:27:35 +00001369// conservatively assume it can free/reallocate its pointer arguments.
Anna Zaks66c40402012-02-14 21:55:24 +00001370// (We assume that the pointers cannot escape through calls to system
1371// functions not handled by this checker.)
Jordan Rose740d4902012-07-02 19:27:35 +00001372bool MallocChecker::doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001373 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001374 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001375
1376 // For now, assume that any C++ call can free memory.
1377 // TODO: If we want to be more optimistic here, we'll need to make sure that
1378 // regions escape to C++ containers. They seem to do that even now, but for
1379 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001380 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001381 return false;
1382
Jordan Rose740d4902012-07-02 19:27:35 +00001383 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001384 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001385 // If it's not a framework call, or if it takes a callback, assume it
1386 // can free memory.
1387 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001388 return false;
1389
Jordan Rose740d4902012-07-02 19:27:35 +00001390 Selector S = Msg->getSelector();
Anna Zaks52a04812012-06-20 23:35:57 +00001391
Jordan Rose740d4902012-07-02 19:27:35 +00001392 // Whitelist the ObjC methods which do free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001393 // - Anything containing 'freeWhenDone' param set to 1.
1394 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
Anna Zaks3e4f65d2012-06-22 22:08:09 +00001395 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001396 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1397 if (Call->getArgSVal(i).isConstant(1))
1398 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001399 else
1400 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001401 }
1402 }
1403
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001404 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001405 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001406 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
Jordan Rose740d4902012-07-02 19:27:35 +00001407 StringRef FirstSlot = S.getNameForSlot(0);
1408 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001409 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001410
Anna Zaks5f757682012-06-19 05:10:32 +00001411 // If the first selector starts with addPointer, insertPointer,
1412 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1413 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001414 // that the pointers get freed by following the container itself.
1415 if (FirstSlot.startswith("addPointer") ||
1416 FirstSlot.startswith("insertPointer") ||
1417 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001418 return false;
1419 }
1420
Jordan Rose740d4902012-07-02 19:27:35 +00001421 // Otherwise, assume that the method does not free memory.
1422 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001423 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001424 }
1425
Jordan Rose740d4902012-07-02 19:27:35 +00001426 // At this point the only thing left to handle is straight function calls.
1427 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1428 if (!FD)
1429 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001430
Jordan Rose740d4902012-07-02 19:27:35 +00001431 ASTContext &ASTC = State->getStateManager().getContext();
1432
1433 // If it's one of the allocation functions we can reason about, we model
1434 // its behavior explicitly.
1435 if (isMemFunction(FD, ASTC))
1436 return true;
1437
1438 // If it's not a system call, assume it frees memory.
1439 if (!Call->isInSystemHeader())
1440 return false;
1441
1442 // White list the system functions whose arguments escape.
1443 const IdentifierInfo *II = FD->getIdentifier();
1444 if (!II)
1445 return false;
1446 StringRef FName = II->getName();
1447
Jordan Rose740d4902012-07-02 19:27:35 +00001448 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001449 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001450 if (FName.endswith("NoCopy")) {
1451 // Look for the deallocator argument. We know that the memory ownership
1452 // is not transferred only if the deallocator argument is
1453 // 'kCFAllocatorNull'.
1454 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1455 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1456 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1457 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1458 if (DeallocatorName == "kCFAllocatorNull")
1459 return true;
1460 }
1461 }
1462 return false;
1463 }
1464
Jordan Rose740d4902012-07-02 19:27:35 +00001465 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001466 // 'closefn' is specified (and if that function does free memory),
1467 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001468 // Currently, we do not inspect the 'closefn' function (PR12101).
1469 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001470 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1471 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001472
1473 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1474 // these leaks might be intentional when setting the buffer for stdio.
1475 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1476 if (FName == "setbuf" || FName =="setbuffer" ||
1477 FName == "setlinebuf" || FName == "setvbuf") {
1478 if (Call->getNumArgs() >= 1) {
1479 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1480 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1481 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1482 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1483 return false;
1484 }
1485 }
1486
1487 // A bunch of other functions which either take ownership of a pointer or
1488 // wrap the result up in a struct or object, meaning it can be freed later.
1489 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1490 // but the Malloc checker cannot differentiate between them. The right way
1491 // of doing this would be to implement a pointer escapes callback.
1492 if (FName == "CGBitmapContextCreate" ||
1493 FName == "CGBitmapContextCreateWithData" ||
1494 FName == "CVPixelBufferCreateWithBytes" ||
1495 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1496 FName == "OSAtomicEnqueue") {
1497 return false;
1498 }
1499
Jordan Rose85d7e012012-07-02 19:27:51 +00001500 // Handle cases where we know a buffer's /address/ can escape.
1501 // Note that the above checks handle some special cases where we know that
1502 // even though the address escapes, it's still our responsibility to free the
1503 // buffer.
1504 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001505 return false;
1506
1507 // Otherwise, assume that the function does not free memory.
1508 // Most system calls do not free the memory.
1509 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001510}
1511
Anna Zaks4fb54872012-02-11 21:02:35 +00001512// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1513// escapes, when we are tracking p), do not track the symbol as we cannot reason
1514// about it anymore.
1515ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001516MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001517 const StoreManager::InvalidatedSymbols *invalidated,
1518 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001519 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001520 const CallEvent *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001521 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001522 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001523 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001524
Anna Zaks66c40402012-02-14 21:55:24 +00001525 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001526 // regions (explicit and implicit) escaped.
1527
1528 // Otherwise, whitelist explicit pointers; we still can track them.
1529 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001530 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1531 E = ExplicitRegions.end(); I != E; ++I) {
1532 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1533 WhitelistedSymbols.insert(R->getSymbol());
1534 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001535 }
1536
1537 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1538 E = invalidated->end(); I!=E; ++I) {
1539 SymbolRef sym = *I;
1540 if (WhitelistedSymbols.count(sym))
1541 continue;
Anna Zaks5b7aa342012-06-22 02:04:31 +00001542 // The symbol escaped. Note, we assume that if the symbol is released,
1543 // passing it out will result in a use after free. We also keep tracking
1544 // relinquished symbols.
1545 if (const RefState *RS = State->get<RegionState>(sym)) {
1546 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001547 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001548 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001549 }
Anna Zaks66c40402012-02-14 21:55:24 +00001550 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001551}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001552
Jordy Rose393f98b2012-03-18 07:43:35 +00001553static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1554 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001555 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1556 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001557
Jordan Rose166d5022012-11-02 01:54:06 +00001558 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001559 I != E; ++I) {
1560 SymbolRef sym = I.getKey();
1561 if (!currMap.lookup(sym))
1562 return sym;
1563 }
1564
1565 return NULL;
1566}
1567
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001568PathDiagnosticPiece *
1569MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1570 const ExplodedNode *PrevN,
1571 BugReporterContext &BRC,
1572 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001573 ProgramStateRef state = N->getState();
1574 ProgramStateRef statePrev = PrevN->getState();
1575
1576 const RefState *RS = state->get<RegionState>(Sym);
1577 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001578 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001579 return 0;
1580
Anna Zaksfe571602012-02-16 22:26:07 +00001581 const Stmt *S = 0;
1582 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001583 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001584
1585 // Retrieve the associated statement.
1586 ProgramPoint ProgLoc = N->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +00001587 if (StmtPoint *SP = dyn_cast<StmtPoint>(&ProgLoc))
1588 S = SP->getStmt();
1589 else if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&ProgLoc))
1590 S = Exit->getCalleeContext()->getCallSite();
Anna Zaksfe571602012-02-16 22:26:07 +00001591 // If an assumption was made on a branch, it should be caught
1592 // here by looking at the state transition.
Jordan Rose852aa0d2012-07-10 22:07:52 +00001593 else if (BlockEdge *Edge = dyn_cast<BlockEdge>(&ProgLoc)) {
1594 const CFGBlock *srcBlk = Edge->getSrc();
Anna Zaksfe571602012-02-16 22:26:07 +00001595 S = srcBlk->getTerminator();
1596 }
1597 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001598 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001599
Jordan Rose28038f32012-07-10 22:07:42 +00001600 // FIXME: We will eventually need to handle non-statement-based events
1601 // (__attribute__((cleanup))).
1602
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001603 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001604 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001605 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001606 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001607 StackHint = new StackHintGeneratorForSymbol(Sym,
1608 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001609 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001610 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001611 StackHint = new StackHintGeneratorForSymbol(Sym,
1612 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001613 } else if (isRelinquished(RS, RSPrev, S)) {
1614 Msg = "Memory ownership is transfered";
1615 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001616 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001617 Mode = ReallocationFailed;
1618 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001619 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001620 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001621
Jordy Roseb000fb52012-03-24 03:15:09 +00001622 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1623 // Is it possible to fail two reallocs WITHOUT testing in between?
1624 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1625 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001626 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001627 FailedReallocSymbol = sym;
1628 }
Anna Zaksfe571602012-02-16 22:26:07 +00001629 }
1630
1631 // We are in a special mode if a reallocation failed later in the path.
1632 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001633 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001634
Jordy Roseb000fb52012-03-24 03:15:09 +00001635 // Is this is the first appearance of the reallocated symbol?
1636 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001637 // We're at the reallocation point.
1638 Msg = "Attempt to reallocate memory";
1639 StackHint = new StackHintGeneratorForSymbol(Sym,
1640 "Returned reallocated memory");
1641 FailedReallocSymbol = NULL;
1642 Mode = Normal;
1643 }
Anna Zaksfe571602012-02-16 22:26:07 +00001644 }
1645
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001646 if (!Msg)
1647 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001648 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001649
1650 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001651 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001652 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001653 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001654}
1655
Anna Zaks93c5a242012-05-02 00:05:20 +00001656void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1657 const char *NL, const char *Sep) const {
1658
1659 RegionStateTy RS = State->get<RegionState>();
1660
1661 if (!RS.isEmpty())
1662 Out << "Has Malloc data" << NL;
1663}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001664
Anna Zaks231361a2012-02-08 23:16:52 +00001665#define REGISTER_CHECKER(name) \
1666void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001667 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001668 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001669}
Anna Zaks231361a2012-02-08 23:16:52 +00001670
1671REGISTER_CHECKER(MallocPessimistic)
1672REGISTER_CHECKER(MallocOptimistic)