blob: 33f68b6c112248ef235096d3bcd8198421e1a176 [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::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +0000106 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +0000107 check::PostStmt<CallExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000108 check::PostStmt<BlockExpr>,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000109 check::PostObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000110 check::Location,
111 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +0000112 eval::Assume,
113 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000114{
Anna Zaksfebdc322012-02-16 22:26:12 +0000115 mutable OwningPtr<BugType> BT_DoubleFree;
116 mutable OwningPtr<BugType> BT_Leak;
117 mutable OwningPtr<BugType> BT_UseFree;
118 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000119 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000120 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
121
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000122public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000123 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000124 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000125
126 /// In pessimistic mode, the checker assumes that it does not know which
127 /// functions might free the memory.
128 struct ChecksFilter {
129 DefaultBool CMallocPessimistic;
130 DefaultBool CMallocOptimistic;
131 };
132
133 ChecksFilter Filter;
134
Anna Zaks66c40402012-02-14 21:55:24 +0000135 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000136 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000137 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000138 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000139 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000140 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000141 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000142 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000143 void checkLocation(SVal l, bool isLoad, const Stmt *S,
144 CheckerContext &C) const;
145 void checkBind(SVal location, SVal val, const Stmt*S,
146 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000147 ProgramStateRef
148 checkRegionChanges(ProgramStateRef state,
149 const StoreManager::InvalidatedSymbols *invalidated,
150 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000151 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +0000152 const CallEvent *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000153 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
154 return true;
155 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000156
Anna Zaks93c5a242012-05-02 00:05:20 +0000157 void printState(raw_ostream &Out, ProgramStateRef State,
158 const char *NL, const char *Sep) const;
159
Zhongxing Xu7b760962009-11-13 07:25:27 +0000160private:
Anna Zaks66c40402012-02-14 21:55:24 +0000161 void initIdentifierInfo(ASTContext &C) const;
162
163 /// Check if this is one of the functions which can allocate/reallocate memory
164 /// pointed to by one of its arguments.
165 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000166 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
167 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000168
Anna Zaks87cb5be2012-02-22 19:24:52 +0000169 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
170 const CallExpr *CE,
171 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000172 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000173 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000174 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000175 return MallocMemAux(C, CE,
176 state->getSVal(SizeEx, C.getLocationContext()),
177 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000178 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000179
Ted Kremenek8bef8232012-01-26 21:29:00 +0000180 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000181 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000182 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000183
Anna Zaks87cb5be2012-02-22 19:24:52 +0000184 /// Update the RefState to reflect the new memory allocation.
185 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
186 const CallExpr *CE,
187 ProgramStateRef state);
188
189 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
190 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000191 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000192 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000193 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000194 bool &ReleasedAllocated,
195 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000196 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
197 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000198 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000199 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000200 bool &ReleasedAllocated,
201 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000202
Anna Zaks87cb5be2012-02-22 19:24:52 +0000203 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
204 bool FreesMemOnFailure) const;
205 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000206
Anna Zaks14345182012-05-18 01:16:10 +0000207 ///\brief Check if the memory associated with this symbol was released.
208 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
209
Anna Zaks91c2a112012-02-08 23:16:56 +0000210 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
211 const Stmt *S = 0) const;
212
Anna Zaks66c40402012-02-14 21:55:24 +0000213 /// Check if the function is not known to us. So, for example, we could
214 /// conservatively assume it can free/reallocate it's pointer arguments.
Jordan Rose740d4902012-07-02 19:27:35 +0000215 bool doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000216 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000217
Ted Kremenek9c378f72011-08-12 23:37:29 +0000218 static bool SummarizeValue(raw_ostream &os, SVal V);
219 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000220 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000221
Anna Zaksca8e36e2012-02-23 21:38:21 +0000222 /// Find the location of the allocation for Sym on the path leading to the
223 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000224 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
225 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000226
Anna Zaksda046772012-02-11 21:02:40 +0000227 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
228
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000229 /// The bug visitor which allows us to print extra diagnostics along the
230 /// BugReport path. For example, showing the allocation site of the leaked
231 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000232 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000233 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000234 enum NotificationMode {
235 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000236 ReallocationFailed
237 };
238
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000239 // The allocated region symbol tracked by the main analysis.
240 SymbolRef Sym;
241
Anna Zaks88feba02012-05-10 01:37:40 +0000242 // The mode we are in, i.e. what kind of diagnostics will be emitted.
243 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000244
Anna Zaks88feba02012-05-10 01:37:40 +0000245 // A symbol from when the primary region should have been reallocated.
246 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000247
Anna Zaks88feba02012-05-10 01:37:40 +0000248 bool IsLeak;
249
250 public:
251 MallocBugVisitor(SymbolRef S, bool isLeak = false)
252 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000253
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000254 virtual ~MallocBugVisitor() {}
255
256 void Profile(llvm::FoldingSetNodeID &ID) const {
257 static int X = 0;
258 ID.AddPointer(&X);
259 ID.AddPointer(Sym);
260 }
261
Anna Zaksfe571602012-02-16 22:26:07 +0000262 inline bool isAllocated(const RefState *S, const RefState *SPrev,
263 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000264 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000265 return (Stmt && isa<CallExpr>(Stmt) &&
266 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000267 }
268
Anna Zaksfe571602012-02-16 22:26:07 +0000269 inline bool isReleased(const RefState *S, const RefState *SPrev,
270 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000271 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000272 return (Stmt && isa<CallExpr>(Stmt) &&
273 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
274 }
275
Anna Zaks5b7aa342012-06-22 02:04:31 +0000276 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
277 const Stmt *Stmt) {
278 // Did not track -> relinquished. Other state (allocated) -> relinquished.
279 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
280 isa<ObjCPropertyRefExpr>(Stmt)) &&
281 (S && S->isRelinquished()) &&
282 (!SPrev || !SPrev->isRelinquished()));
283 }
284
Anna Zaksfe571602012-02-16 22:26:07 +0000285 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
286 const Stmt *Stmt) {
287 // If the expression is not a call, and the state change is
288 // released -> allocated, it must be the realloc return value
289 // check. If we have to handle more cases here, it might be cleaner just
290 // to track this extra bit in the state itself.
291 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
292 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000293 }
294
295 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
296 const ExplodedNode *PrevN,
297 BugReporterContext &BRC,
298 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000299
300 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
301 const ExplodedNode *EndPathNode,
302 BugReport &BR) {
303 if (!IsLeak)
304 return 0;
305
306 PathDiagnosticLocation L =
307 PathDiagnosticLocation::createEndOfPath(EndPathNode,
308 BRC.getSourceManager());
309 // Do not add the statement itself as a range in case of leak.
310 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
311 }
312
Anna Zaks56a938f2012-03-16 23:24:20 +0000313 private:
314 class StackHintGeneratorForReallocationFailed
315 : public StackHintGeneratorForSymbol {
316 public:
317 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
318 : StackHintGeneratorForSymbol(S, M) {}
319
320 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000321 // Printed parameters start at 1, not 0.
322 ++ArgIndex;
323
Anna Zaks56a938f2012-03-16 23:24:20 +0000324 SmallString<200> buf;
325 llvm::raw_svector_ostream os(buf);
326
Jordan Rose615a0922012-09-22 01:24:42 +0000327 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
328 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000329
330 return os.str();
331 }
332
333 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000334 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000335 }
336 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000337 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000338};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000339} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000340
Jordan Rose166d5022012-11-02 01:54:06 +0000341REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
342REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000343
Anna Zaks4141e4d2012-11-13 03:18:01 +0000344// A map from the freed symbol to the symbol representing the return value of
345// the free function.
346REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
347
Anna Zaks4fb54872012-02-11 21:02:35 +0000348namespace {
349class StopTrackingCallback : public SymbolVisitor {
350 ProgramStateRef state;
351public:
352 StopTrackingCallback(ProgramStateRef st) : state(st) {}
353 ProgramStateRef getState() const { return state; }
354
355 bool VisitSymbol(SymbolRef sym) {
356 state = state->remove<RegionState>(sym);
357 return true;
358 }
359};
360} // end anonymous namespace
361
Anna Zaks66c40402012-02-14 21:55:24 +0000362void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000363 if (II_malloc)
364 return;
365 II_malloc = &Ctx.Idents.get("malloc");
366 II_free = &Ctx.Idents.get("free");
367 II_realloc = &Ctx.Idents.get("realloc");
368 II_reallocf = &Ctx.Idents.get("reallocf");
369 II_calloc = &Ctx.Idents.get("calloc");
370 II_valloc = &Ctx.Idents.get("valloc");
371 II_strdup = &Ctx.Idents.get("strdup");
372 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000373}
374
Anna Zaks66c40402012-02-14 21:55:24 +0000375bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000376 if (isFreeFunction(FD, C))
377 return true;
378
379 if (isAllocationFunction(FD, C))
380 return true;
381
382 return false;
383}
384
385bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
386 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000387 if (!FD)
388 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000389
Jordan Rose5ef6e942012-07-10 23:13:01 +0000390 if (FD->getKind() == Decl::Function) {
391 IdentifierInfo *FunI = FD->getIdentifier();
392 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000393
Jordan Rose5ef6e942012-07-10 23:13:01 +0000394 if (FunI == II_malloc || FunI == II_realloc ||
395 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
396 FunI == II_strdup || FunI == II_strndup)
397 return true;
398 }
Anna Zaks66c40402012-02-14 21:55:24 +0000399
Anna Zaks14345182012-05-18 01:16:10 +0000400 if (Filter.CMallocOptimistic && FD->hasAttrs())
401 for (specific_attr_iterator<OwnershipAttr>
402 i = FD->specific_attr_begin<OwnershipAttr>(),
403 e = FD->specific_attr_end<OwnershipAttr>();
404 i != e; ++i)
405 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
406 return true;
407 return false;
408}
409
410bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
411 if (!FD)
412 return false;
413
Jordan Rose5ef6e942012-07-10 23:13:01 +0000414 if (FD->getKind() == Decl::Function) {
415 IdentifierInfo *FunI = FD->getIdentifier();
416 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000417
Jordan Rose5ef6e942012-07-10 23:13:01 +0000418 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
419 return true;
420 }
Anna Zaks66c40402012-02-14 21:55:24 +0000421
Anna Zaks14345182012-05-18 01:16:10 +0000422 if (Filter.CMallocOptimistic && FD->hasAttrs())
423 for (specific_attr_iterator<OwnershipAttr>
424 i = FD->specific_attr_begin<OwnershipAttr>(),
425 e = FD->specific_attr_end<OwnershipAttr>();
426 i != e; ++i)
427 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
428 (*i)->getOwnKind() == OwnershipAttr::Holds)
429 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000430 return false;
431}
432
Anna Zaksb319e022012-02-08 20:13:28 +0000433void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000434 if (C.wasInlined)
435 return;
436
Anna Zaksb319e022012-02-08 20:13:28 +0000437 const FunctionDecl *FD = C.getCalleeDecl(CE);
438 if (!FD)
439 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000440
Anna Zaks87cb5be2012-02-22 19:24:52 +0000441 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000442 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000443
444 if (FD->getKind() == Decl::Function) {
445 initIdentifierInfo(C.getASTContext());
446 IdentifierInfo *FunI = FD->getIdentifier();
447
448 if (FunI == II_malloc || FunI == II_valloc) {
449 if (CE->getNumArgs() < 1)
450 return;
451 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
452 } else if (FunI == II_realloc) {
453 State = ReallocMem(C, CE, false);
454 } else if (FunI == II_reallocf) {
455 State = ReallocMem(C, CE, true);
456 } else if (FunI == II_calloc) {
457 State = CallocMem(C, CE);
458 } else if (FunI == II_free) {
Anna Zaks55dd9562012-08-24 02:28:20 +0000459 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose5ef6e942012-07-10 23:13:01 +0000460 } else if (FunI == II_strdup) {
461 State = MallocUpdateRefState(C, CE, State);
462 } else if (FunI == II_strndup) {
463 State = MallocUpdateRefState(C, CE, State);
464 }
465 }
466
467 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000468 // Check all the attributes, if there are any.
469 // There can be multiple of these attributes.
470 if (FD->hasAttrs())
471 for (specific_attr_iterator<OwnershipAttr>
472 i = FD->specific_attr_begin<OwnershipAttr>(),
473 e = FD->specific_attr_end<OwnershipAttr>();
474 i != e; ++i) {
475 switch ((*i)->getOwnKind()) {
476 case OwnershipAttr::Returns:
477 State = MallocMemReturnsAttr(C, CE, *i);
478 break;
479 case OwnershipAttr::Takes:
480 case OwnershipAttr::Holds:
481 State = FreeMemAttr(C, CE, *i);
482 break;
483 }
484 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000485 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000486 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000487}
488
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000489static bool isFreeWhenDoneSetToZero(const ObjCMethodCall &Call) {
490 Selector S = Call.getSelector();
Anna Zaks3e4f65d2012-06-22 22:08:09 +0000491 for (unsigned i = 1; i < S.getNumArgs(); ++i)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000492 if (S.getNameForSlot(i).equals("freeWhenDone"))
493 if (Call.getArgSVal(i).isConstant(0))
494 return true;
495
496 return false;
497}
498
Anna Zaks4141e4d2012-11-13 03:18:01 +0000499void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
500 CheckerContext &C) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000501 // If the first selector is dataWithBytesNoCopy, assume that the memory will
502 // be released with 'free' by the new object.
503 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
504 // Unless 'freeWhenDone' param set to 0.
505 // TODO: Check that the memory was allocated with malloc.
Anna Zaks55dd9562012-08-24 02:28:20 +0000506 bool ReleasedAllocatedMemory = false;
Jordan Rosede507ea2012-07-02 19:28:04 +0000507 Selector S = Call.getSelector();
Anna Zaks7186dc62012-06-22 22:42:30 +0000508 if ((S.getNameForSlot(0) == "dataWithBytesNoCopy" ||
509 S.getNameForSlot(0) == "initWithBytesNoCopy" ||
510 S.getNameForSlot(0) == "initWithCharactersNoCopy") &&
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000511 !isFreeWhenDoneSetToZero(Call)){
Anna Zaks5b7aa342012-06-22 02:04:31 +0000512 unsigned int argIdx = 0;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000513 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(argIdx),
514 Call.getOriginExpr(), C.getState(), true,
515 ReleasedAllocatedMemory,
516 /* RetNullOnFailure*/ true);
517
518 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000519 }
520}
521
Anna Zaks87cb5be2012-02-22 19:24:52 +0000522ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
523 const CallExpr *CE,
524 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000525 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000526 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000527
Sean Huntcf807c42010-08-18 23:23:40 +0000528 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000529 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000530 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000531 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000532 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000533}
534
Anna Zaksb319e022012-02-08 20:13:28 +0000535ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000536 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000537 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000538 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000539
540 // Bind the return value to the symbolic value from the heap region.
541 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
542 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000543 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000544 SValBuilder &svalBuilder = C.getSValBuilder();
545 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
546 DefinedSVal RetVal =
547 cast<DefinedSVal>(svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count));
548 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000549
Anna Zaksb16ce452012-02-15 00:11:22 +0000550 // We expect the malloc functions to return a pointer.
Anna Zakse17fdb22012-06-07 03:57:32 +0000551 if (!isa<Loc>(RetVal))
Anna Zaksb16ce452012-02-15 00:11:22 +0000552 return 0;
553
Jordy Rose32f26562010-07-04 00:00:41 +0000554 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000555 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000556
Jordy Rose32f26562010-07-04 00:00:41 +0000557 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000558 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000559 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000560 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000561 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000562 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000563 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000564 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
565 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
566 DefinedOrUnknownSVal extentMatchesSize =
567 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000568
Anna Zaks60a1fa42012-02-22 03:14:20 +0000569 state = state->assume(extentMatchesSize, true);
570 assert(state);
571 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000572
Anna Zaks87cb5be2012-02-22 19:24:52 +0000573 return MallocUpdateRefState(C, CE, state);
574}
575
576ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
577 const CallExpr *CE,
578 ProgramStateRef state) {
579 // Get the return value.
580 SVal retVal = state->getSVal(CE, C.getLocationContext());
581
582 // We expect the malloc functions to return a pointer.
583 if (!isa<Loc>(retVal))
584 return 0;
585
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000586 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000587 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000588
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000589 // Set the symbol's state to Allocated.
Anna Zaks050cdd72012-06-20 20:57:46 +0000590 return state->set<RegionState>(Sym, RefState::getAllocated(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000591
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000592}
593
Anna Zaks87cb5be2012-02-22 19:24:52 +0000594ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
595 const CallExpr *CE,
596 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000597 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000598 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000599
Anna Zaksb3d72752012-03-01 22:06:06 +0000600 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000601 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000602
Sean Huntcf807c42010-08-18 23:23:40 +0000603 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
604 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000605 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000606 Att->getOwnKind() == OwnershipAttr::Holds,
607 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000608 if (StateI)
609 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000610 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000611 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000612}
613
Ted Kremenek8bef8232012-01-26 21:29:00 +0000614ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000615 const CallExpr *CE,
616 ProgramStateRef state,
617 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000618 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000619 bool &ReleasedAllocated,
620 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000621 if (CE->getNumArgs() < (Num + 1))
622 return 0;
623
Anna Zaks4141e4d2012-11-13 03:18:01 +0000624 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
625 ReleasedAllocated, ReturnsNullOnFailure);
626}
627
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000628/// Checks if the previous call to free on the given symbol failed - if free
629/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000630static bool didPreviousFreeFail(ProgramStateRef State,
631 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000632 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000633 if (Ret) {
634 assert(*Ret && "We should not store the null return symbol");
635 ConstraintManager &CMgr = State->getConstraintManager();
636 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000637 RetStatusSymbol = *Ret;
638 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000639 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000640 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000641}
642
643ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
644 const Expr *ArgExpr,
645 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000646 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000647 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000648 bool &ReleasedAllocated,
649 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000650
Anna Zaks4141e4d2012-11-13 03:18:01 +0000651 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000652 if (!isa<DefinedOrUnknownSVal>(ArgVal))
653 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000654 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
655
656 // Check for null dereferences.
657 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000658 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000659
Anna Zaksb276bd92012-02-14 00:26:13 +0000660 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000661 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000662 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000663 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000664 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000665
Jordy Rose43859f62010-06-07 19:32:37 +0000666 // Unknown values could easily be okay
667 // Undefined values are handled elsewhere
668 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000669 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000670
Jordy Rose43859f62010-06-07 19:32:37 +0000671 const MemRegion *R = ArgVal.getAsRegion();
672
673 // Nonlocs can't be freed, of course.
674 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
675 if (!R) {
676 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000677 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000678 }
679
680 R = R->StripCasts();
681
682 // Blocks might show up as heap data, but should not be free()d
683 if (isa<BlockDataRegion>(R)) {
684 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000685 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000686 }
687
688 const MemSpaceRegion *MS = R->getMemorySpace();
689
690 // Parameters, locals, statics, and globals shouldn't be freed.
691 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
692 // FIXME: at the time this code was written, malloc() regions were
693 // represented by conjured symbols, which are all in UnknownSpaceRegion.
694 // This means that there isn't actually anything from HeapSpaceRegion
695 // that should be freed, even though we allow it here.
696 // Of course, free() can work on memory allocated outside the current
697 // function, so UnknownSpaceRegion is always a possibility.
698 // False negatives are better than false positives.
699
700 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000701 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000702 }
703
704 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
705 // Various cases could lead to non-symbol values here.
706 // For now, ignore them.
707 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000708 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000709
710 SymbolRef Sym = SR->getSymbol();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000711 const RefState *RS = State->get<RegionState>(Sym);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000712 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000713
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000714 // Check double free.
Anna Zaks4141e4d2012-11-13 03:18:01 +0000715 if (RS &&
716 (RS->isReleased() || RS->isRelinquished()) &&
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000717 !didPreviousFreeFail(State, Sym, PreviousRetStatusSymbol)) {
Anna Zaks4141e4d2012-11-13 03:18:01 +0000718
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000719 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000720 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000721 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000722 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000723 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000724 (RS->isReleased() ? "Attempt to free released memory" :
725 "Attempt to free non-owned memory"), N);
Anna Zaksfe571602012-02-16 22:26:07 +0000726 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000727 R->markInteresting(Sym);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000728 if (PreviousRetStatusSymbol)
729 R->markInteresting(PreviousRetStatusSymbol);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000730 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +0000731 C.emitReport(R);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000732 }
Anna Zaksb319e022012-02-08 20:13:28 +0000733 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000734 }
735
Anna Zaks55dd9562012-08-24 02:28:20 +0000736 ReleasedAllocated = (RS != 0);
737
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000738 // Clean out the info on previous call to free return info.
739 State = State->remove<FreeReturnValue>(Sym);
740
Anna Zaks4141e4d2012-11-13 03:18:01 +0000741 // Keep track of the return value. If it is NULL, we will know that free
742 // failed.
743 if (ReturnsNullOnFailure) {
744 SVal RetVal = C.getSVal(ParentExpr);
745 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
746 if (RetStatusSymbol) {
747 C.getSymbolManager().addSymbolDependency(Sym, RetStatusSymbol);
748 State = State->set<FreeReturnValue>(Sym, RetStatusSymbol);
749 }
750 }
751
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000752 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000753 if (Hold)
Anna Zaks4141e4d2012-11-13 03:18:01 +0000754 return State->set<RegionState>(Sym, RefState::getRelinquished(ParentExpr));
755 return State->set<RegionState>(Sym, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000756}
757
Ted Kremenek9c378f72011-08-12 23:37:29 +0000758bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000759 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
760 os << "an integer (" << IntVal->getValue() << ")";
761 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
762 os << "a constant address (" << ConstAddr->getValue() << ")";
763 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000764 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000765 else
766 return false;
767
768 return true;
769}
770
Ted Kremenek9c378f72011-08-12 23:37:29 +0000771bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000772 const MemRegion *MR) {
773 switch (MR->getKind()) {
774 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000775 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +0000776 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000777 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000778 else
779 os << "the address of a function";
780 return true;
781 }
782 case MemRegion::BlockTextRegionKind:
783 os << "block text";
784 return true;
785 case MemRegion::BlockDataRegionKind:
786 // FIXME: where the block came from?
787 os << "a block";
788 return true;
789 default: {
790 const MemSpaceRegion *MS = MR->getMemorySpace();
791
Anna Zakseb31a762012-01-04 23:54:01 +0000792 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000793 const VarRegion *VR = dyn_cast<VarRegion>(MR);
794 const VarDecl *VD;
795 if (VR)
796 VD = VR->getDecl();
797 else
798 VD = NULL;
799
800 if (VD)
801 os << "the address of the local variable '" << VD->getName() << "'";
802 else
803 os << "the address of a local stack variable";
804 return true;
805 }
Anna Zakseb31a762012-01-04 23:54:01 +0000806
807 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000808 const VarRegion *VR = dyn_cast<VarRegion>(MR);
809 const VarDecl *VD;
810 if (VR)
811 VD = VR->getDecl();
812 else
813 VD = NULL;
814
815 if (VD)
816 os << "the address of the parameter '" << VD->getName() << "'";
817 else
818 os << "the address of a parameter";
819 return true;
820 }
Anna Zakseb31a762012-01-04 23:54:01 +0000821
822 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000823 const VarRegion *VR = dyn_cast<VarRegion>(MR);
824 const VarDecl *VD;
825 if (VR)
826 VD = VR->getDecl();
827 else
828 VD = NULL;
829
830 if (VD) {
831 if (VD->isStaticLocal())
832 os << "the address of the static variable '" << VD->getName() << "'";
833 else
834 os << "the address of the global variable '" << VD->getName() << "'";
835 } else
836 os << "the address of a global variable";
837 return true;
838 }
Anna Zakseb31a762012-01-04 23:54:01 +0000839
840 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000841 }
842 }
843}
844
845void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000846 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000847 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000848 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000849 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000850
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000851 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000852 llvm::raw_svector_ostream os(buf);
853
854 const MemRegion *MR = ArgVal.getAsRegion();
855 if (MR) {
856 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
857 MR = ER->getSuperRegion();
858
859 // Special case for alloca()
860 if (isa<AllocaRegion>(MR))
861 os << "Argument to free() was allocated by alloca(), not malloc()";
862 else {
863 os << "Argument to free() is ";
864 if (SummarizeRegion(os, MR))
865 os << ", which is not memory allocated by malloc()";
866 else
867 os << "not memory allocated by malloc()";
868 }
869 } else {
870 os << "Argument to free() is ";
871 if (SummarizeValue(os, ArgVal))
872 os << ", which is not memory allocated by malloc()";
873 else
874 os << "not memory allocated by malloc()";
875 }
876
Anna Zakse172e8b2011-08-17 23:00:25 +0000877 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000878 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000879 R->addRange(range);
Jordan Rose785950e2012-11-02 01:53:40 +0000880 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +0000881 }
882}
883
Anna Zaks87cb5be2012-02-22 19:24:52 +0000884ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
885 const CallExpr *CE,
886 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000887 if (CE->getNumArgs() < 2)
888 return 0;
889
Ted Kremenek8bef8232012-01-26 21:29:00 +0000890 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000891 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000892 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000893 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
894 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000895 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000896 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000897
Ted Kremenek846eabd2010-12-01 21:28:31 +0000898 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000899
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000900 DefinedOrUnknownSVal PtrEQ =
901 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000902
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000903 // Get the size argument. If there is no size arg then give up.
904 const Expr *Arg1 = CE->getArg(1);
905 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000906 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000907
908 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000909 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
910 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000911 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000912 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000913
914 // Compare the size argument to 0.
915 DefinedOrUnknownSVal SizeZero =
916 svalBuilder.evalEQ(state, Arg1Val,
917 svalBuilder.makeIntValWithPtrWidth(0, false));
918
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000919 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
920 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
921 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
922 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
923 // We only assume exceptional states if they are definitely true; if the
924 // state is under-constrained, assume regular realloc behavior.
925 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
926 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
927
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000928 // If the ptr is NULL and the size is not 0, the call is equivalent to
929 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000930 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000931 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000932 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000933 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000934 }
935
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000936 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000937 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000938
Anna Zaks30838b92012-02-13 20:57:07 +0000939 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000940 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000941 SymbolRef FromPtr = arg0Val.getAsSymbol();
942 SVal RetVal = state->getSVal(CE, LCtx);
943 SymbolRef ToPtr = RetVal.getAsSymbol();
944 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000945 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000946
Anna Zaks55dd9562012-08-24 02:28:20 +0000947 bool ReleasedAllocated = false;
948
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000949 // If the size is 0, free the memory.
950 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +0000951 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
952 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000953 // The semantics of the return value are:
954 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +0000955 // to free() is returned. We just free the input pointer and do not add
956 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +0000957 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000958 }
959
960 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +0000961 if (ProgramStateRef stateFree =
962 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
963
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000964 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
965 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000966 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000967 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +0000968
Anna Zaks9dc298b2012-09-12 22:57:34 +0000969 ReallocPairKind Kind = RPToBeFreedAfterFailure;
970 if (FreesOnFail)
971 Kind = RPIsFreeOnFailure;
972 else if (!ReleasedAllocated)
973 Kind = RPDoNotTrackAfterFailure;
974
Anna Zaks55dd9562012-08-24 02:28:20 +0000975 // Record the info about the reallocated symbol so that we could properly
976 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +0000977 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +0000978 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +0000979 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +0000980 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000981 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000982 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000983 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000984}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000985
Anna Zaks87cb5be2012-02-22 19:24:52 +0000986ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +0000987 if (CE->getNumArgs() < 2)
988 return 0;
989
Ted Kremenek8bef8232012-01-26 21:29:00 +0000990 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000991 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000992 const LocationContext *LCtx = C.getLocationContext();
993 SVal count = state->getSVal(CE->getArg(0), LCtx);
994 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000995 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
996 svalBuilder.getContext().getSizeType());
997 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000998
Anna Zaks87cb5be2012-02-22 19:24:52 +0000999 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001000}
1001
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001002LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001003MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1004 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001005 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001006 // Walk the ExplodedGraph backwards and find the first node that referred to
1007 // the tracked symbol.
1008 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001009 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001010
1011 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001012 ProgramStateRef State = N->getState();
1013 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001014 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001015
1016 // Find the most recent expression bound to the symbol in the current
1017 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001018 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001019 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1020 SVal Val = State->getSVal(MR);
1021 if (Val.getAsLocSymbol() == Sym)
1022 ReferenceRegion = MR;
1023 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001024 }
1025
Anna Zaks7752d292012-02-27 23:40:55 +00001026 // Allocation node, is the last node in the current context in which the
1027 // symbol was tracked.
1028 if (N->getLocationContext() == LeakContext)
1029 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001030 N = N->pred_empty() ? NULL : *(N->pred_begin());
1031 }
1032
1033 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001034 const Stmt *AllocationStmt = 0;
Jordan Rose852aa0d2012-07-10 22:07:52 +00001035 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
1036 AllocationStmt = Exit->getCalleeContext()->getCallSite();
1037 else if (StmtPoint *SP = dyn_cast<StmtPoint>(&P))
1038 AllocationStmt = SP->getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +00001039
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001040 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001041}
1042
Anna Zaksda046772012-02-11 21:02:40 +00001043void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1044 CheckerContext &C) const {
1045 assert(N);
1046 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001047 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001048 // Leaks should not be reported if they are post-dominated by a sink:
1049 // (1) Sinks are higher importance bugs.
1050 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1051 // with __noreturn functions such as assert() or exit(). We choose not
1052 // to report leaks on such paths.
1053 BT_Leak->setSuppressOnSink(true);
1054 }
1055
Anna Zaksca8e36e2012-02-23 21:38:21 +00001056 // Most bug reports are cached at the location where they occurred.
1057 // With leaks, we want to unique them by the location where they were
1058 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001059 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001060 const Stmt *AllocStmt = 0;
1061 const MemRegion *Region = 0;
1062 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
1063 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +00001064 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
1065 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001066
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001067 SmallString<200> buf;
1068 llvm::raw_svector_ostream os(buf);
1069 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001070 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001071 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001072 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001073 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001074 }
1075
1076 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001077 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001078 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001079 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001080}
1081
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001082void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1083 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001084{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001085 if (!SymReaper.hasDeadSymbols())
1086 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001087
Ted Kremenek8bef8232012-01-26 21:29:00 +00001088 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001089 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001090 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001091
Anna Zaksf8c17b72012-02-09 06:48:19 +00001092 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001093 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1094 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001095 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001096 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001097 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001098 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001099
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001100 }
1101 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001102
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001103 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001104 ReallocPairsTy RP = state->get<ReallocPairs>();
1105 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001106 if (SymReaper.isDead(I->first) ||
1107 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001108 state = state->remove<ReallocPairs>(I->first);
1109 }
1110 }
1111
Anna Zaks4141e4d2012-11-13 03:18:01 +00001112 // Cleanup the FreeReturnValue Map.
1113 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1114 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1115 if (SymReaper.isDead(I->first) ||
1116 SymReaper.isDead(I->second)) {
1117 state = state->remove<FreeReturnValue>(I->first);
1118 }
1119 }
1120
Anna Zaksca8e36e2012-02-23 21:38:21 +00001121 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001122 ExplodedNode *N = C.getPredecessor();
1123 if (!Errors.empty()) {
1124 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1125 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001126 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001127 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001128 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001129 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001130 }
Anna Zaks54458702012-10-29 22:51:54 +00001131
Anna Zaksca8e36e2012-02-23 21:38:21 +00001132 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001133}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001134
Anna Zaks66c40402012-02-14 21:55:24 +00001135void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001136 // We will check for double free in the post visit.
1137 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001138 return;
1139
1140 // Check use after free, when a freed pointer is passed to a call.
1141 ProgramStateRef State = C.getState();
1142 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1143 E = CE->arg_end(); I != E; ++I) {
1144 const Expr *A = *I;
1145 if (A->getType().getTypePtr()->isAnyPointerType()) {
1146 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1147 if (!Sym)
1148 continue;
1149 if (checkUseAfterFree(Sym, C, A))
1150 return;
1151 }
1152 }
1153}
1154
Anna Zaks91c2a112012-02-08 23:16:56 +00001155void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1156 const Expr *E = S->getRetValue();
1157 if (!E)
1158 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001159
1160 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001161 ProgramStateRef State = C.getState();
1162 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001163 SymbolRef Sym = RetVal.getAsSymbol();
1164 if (!Sym)
1165 // If we are returning a field of the allocated struct or an array element,
1166 // the callee could still free the memory.
1167 // TODO: This logic should be a part of generic symbol escape callback.
1168 if (const MemRegion *MR = RetVal.getAsRegion())
1169 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1170 if (const SymbolicRegion *BMR =
1171 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1172 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001173
Anna Zaks0860cd02012-02-11 21:44:39 +00001174 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001175 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001176 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001177}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001178
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001179// TODO: Blocks should be either inlined or should call invalidate regions
1180// upon invocation. After that's in place, special casing here will not be
1181// needed.
1182void MallocChecker::checkPostStmt(const BlockExpr *BE,
1183 CheckerContext &C) const {
1184
1185 // Scan the BlockDecRefExprs for any object the retain count checker
1186 // may be tracking.
1187 if (!BE->getBlockDecl()->hasCaptures())
1188 return;
1189
1190 ProgramStateRef state = C.getState();
1191 const BlockDataRegion *R =
1192 cast<BlockDataRegion>(state->getSVal(BE,
1193 C.getLocationContext()).getAsRegion());
1194
1195 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1196 E = R->referenced_vars_end();
1197
1198 if (I == E)
1199 return;
1200
1201 SmallVector<const MemRegion*, 10> Regions;
1202 const LocationContext *LC = C.getLocationContext();
1203 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1204
1205 for ( ; I != E; ++I) {
1206 const VarRegion *VR = *I;
1207 if (VR->getSuperRegion() == R) {
1208 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1209 }
1210 Regions.push_back(VR);
1211 }
1212
1213 state =
1214 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1215 Regions.data() + Regions.size()).getState();
1216 C.addTransition(state);
1217}
1218
Anna Zaks14345182012-05-18 01:16:10 +00001219bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001220 assert(Sym);
1221 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001222 return (RS && RS->isReleased());
1223}
1224
1225bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1226 const Stmt *S) const {
1227 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001228 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001229 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001230 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001231
Anna Zaksfebdc322012-02-16 22:26:12 +00001232 BugReport *R = new BugReport(*BT_UseFree,
1233 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001234 if (S)
1235 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001236 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001237 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +00001238 C.emitReport(R);
Anna Zaks91c2a112012-02-08 23:16:56 +00001239 return true;
1240 }
1241 }
1242 return false;
1243}
1244
Zhongxing Xuc8023782010-03-10 04:58:55 +00001245// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001246void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1247 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001248 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001249 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001250 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001251}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001252
Anna Zaks4fb54872012-02-11 21:02:35 +00001253//===----------------------------------------------------------------------===//
1254// Check various ways a symbol can be invalidated.
1255// TODO: This logic (the next 3 functions) is copied/similar to the
1256// RetainRelease checker. We might want to factor this out.
1257//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001258
Anna Zaks4fb54872012-02-11 21:02:35 +00001259// Stop tracking symbols when a value escapes as a result of checkBind.
1260// A value escapes in three possible cases:
1261// (1) we are binding to something that is not a memory region.
1262// (2) we are binding to a memregion that does not have stack storage
1263// (3) we are binding to a memregion with stack storage that the store
1264// does not understand.
1265void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1266 CheckerContext &C) const {
1267 // Are we storing to something that causes the value to "escape"?
1268 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001269 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001270
Anna Zaks4fb54872012-02-11 21:02:35 +00001271 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1272 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001273
Anna Zaks4fb54872012-02-11 21:02:35 +00001274 if (!escapes) {
1275 // To test (3), generate a new state with the binding added. If it is
1276 // the same state, then it escapes (since the store cannot represent
1277 // the binding).
Anna Zaks93c5a242012-05-02 00:05:20 +00001278 // Do this only if we know that the store is not supposed to generate the
1279 // same state.
1280 SVal StoredVal = state->getSVal(regionLoc->getRegion());
1281 if (StoredVal != val)
1282 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001283 }
1284 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001285
1286 // If our store can represent the binding and we aren't storing to something
1287 // that doesn't have local storage then just return and have the simulation
1288 // state continue as is.
1289 if (!escapes)
1290 return;
1291
1292 // Otherwise, find all symbols referenced by 'val' that we are tracking
1293 // and stop tracking them.
1294 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1295 C.addTransition(state);
1296}
1297
1298// If a symbolic region is assumed to NULL (or another constant), stop tracking
1299// it - assuming that allocation failed on this path.
1300ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1301 SVal Cond,
1302 bool Assumption) const {
1303 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001304 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001305 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001306 ConstraintManager &CMgr = state->getConstraintManager();
1307 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1308 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001309 state = state->remove<RegionState>(I.getKey());
1310 }
1311
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001312 // Realloc returns 0 when reallocation fails, which means that we should
1313 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001314 ReallocPairsTy RP = state->get<ReallocPairs>();
1315 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001316 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001317 ConstraintManager &CMgr = state->getConstraintManager();
1318 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001319 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001320 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001321
Anna Zaks9dc298b2012-09-12 22:57:34 +00001322 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1323 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1324 if (RS->isReleased()) {
1325 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001326 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001327 RefState::getAllocated(RS->getStmt()));
1328 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1329 state = state->remove<RegionState>(ReallocSym);
1330 else
1331 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001332 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001333 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001334 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001335 }
1336
Anna Zaks4fb54872012-02-11 21:02:35 +00001337 return state;
1338}
1339
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001340// Check if the function is known to us. So, for example, we could
Jordan Rose740d4902012-07-02 19:27:35 +00001341// conservatively assume it can free/reallocate its pointer arguments.
Anna Zaks66c40402012-02-14 21:55:24 +00001342// (We assume that the pointers cannot escape through calls to system
1343// functions not handled by this checker.)
Jordan Rose740d4902012-07-02 19:27:35 +00001344bool MallocChecker::doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001345 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001346 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001347
1348 // For now, assume that any C++ call can free memory.
1349 // TODO: If we want to be more optimistic here, we'll need to make sure that
1350 // regions escape to C++ containers. They seem to do that even now, but for
1351 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001352 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001353 return false;
1354
Jordan Rose740d4902012-07-02 19:27:35 +00001355 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001356 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001357 // If it's not a framework call, or if it takes a callback, assume it
1358 // can free memory.
1359 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001360 return false;
1361
Jordan Rose740d4902012-07-02 19:27:35 +00001362 Selector S = Msg->getSelector();
Anna Zaks52a04812012-06-20 23:35:57 +00001363
Jordan Rose740d4902012-07-02 19:27:35 +00001364 // Whitelist the ObjC methods which do free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001365 // - Anything containing 'freeWhenDone' param set to 1.
1366 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
Anna Zaks3e4f65d2012-06-22 22:08:09 +00001367 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001368 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1369 if (Call->getArgSVal(i).isConstant(1))
1370 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001371 else
1372 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001373 }
1374 }
1375
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001376 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001377 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001378 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
Jordan Rose740d4902012-07-02 19:27:35 +00001379 StringRef FirstSlot = S.getNameForSlot(0);
1380 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001381 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001382
Anna Zaks5f757682012-06-19 05:10:32 +00001383 // If the first selector starts with addPointer, insertPointer,
1384 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1385 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001386 // that the pointers get freed by following the container itself.
1387 if (FirstSlot.startswith("addPointer") ||
1388 FirstSlot.startswith("insertPointer") ||
1389 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001390 return false;
1391 }
1392
Jordan Rose740d4902012-07-02 19:27:35 +00001393 // Otherwise, assume that the method does not free memory.
1394 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001395 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001396 }
1397
Jordan Rose740d4902012-07-02 19:27:35 +00001398 // At this point the only thing left to handle is straight function calls.
1399 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1400 if (!FD)
1401 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001402
Jordan Rose740d4902012-07-02 19:27:35 +00001403 ASTContext &ASTC = State->getStateManager().getContext();
1404
1405 // If it's one of the allocation functions we can reason about, we model
1406 // its behavior explicitly.
1407 if (isMemFunction(FD, ASTC))
1408 return true;
1409
1410 // If it's not a system call, assume it frees memory.
1411 if (!Call->isInSystemHeader())
1412 return false;
1413
1414 // White list the system functions whose arguments escape.
1415 const IdentifierInfo *II = FD->getIdentifier();
1416 if (!II)
1417 return false;
1418 StringRef FName = II->getName();
1419
Jordan Rose740d4902012-07-02 19:27:35 +00001420 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001421 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001422 if (FName.endswith("NoCopy")) {
1423 // Look for the deallocator argument. We know that the memory ownership
1424 // is not transferred only if the deallocator argument is
1425 // 'kCFAllocatorNull'.
1426 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1427 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1428 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1429 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1430 if (DeallocatorName == "kCFAllocatorNull")
1431 return true;
1432 }
1433 }
1434 return false;
1435 }
1436
Jordan Rose740d4902012-07-02 19:27:35 +00001437 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001438 // 'closefn' is specified (and if that function does free memory),
1439 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001440 // Currently, we do not inspect the 'closefn' function (PR12101).
1441 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001442 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1443 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001444
1445 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1446 // these leaks might be intentional when setting the buffer for stdio.
1447 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1448 if (FName == "setbuf" || FName =="setbuffer" ||
1449 FName == "setlinebuf" || FName == "setvbuf") {
1450 if (Call->getNumArgs() >= 1) {
1451 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1452 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1453 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1454 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1455 return false;
1456 }
1457 }
1458
1459 // A bunch of other functions which either take ownership of a pointer or
1460 // wrap the result up in a struct or object, meaning it can be freed later.
1461 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1462 // but the Malloc checker cannot differentiate between them. The right way
1463 // of doing this would be to implement a pointer escapes callback.
1464 if (FName == "CGBitmapContextCreate" ||
1465 FName == "CGBitmapContextCreateWithData" ||
1466 FName == "CVPixelBufferCreateWithBytes" ||
1467 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1468 FName == "OSAtomicEnqueue") {
1469 return false;
1470 }
1471
Jordan Rose85d7e012012-07-02 19:27:51 +00001472 // Handle cases where we know a buffer's /address/ can escape.
1473 // Note that the above checks handle some special cases where we know that
1474 // even though the address escapes, it's still our responsibility to free the
1475 // buffer.
1476 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001477 return false;
1478
1479 // Otherwise, assume that the function does not free memory.
1480 // Most system calls do not free the memory.
1481 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001482}
1483
Anna Zaks4fb54872012-02-11 21:02:35 +00001484// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1485// escapes, when we are tracking p), do not track the symbol as we cannot reason
1486// about it anymore.
1487ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001488MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001489 const StoreManager::InvalidatedSymbols *invalidated,
1490 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001491 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001492 const CallEvent *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001493 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001494 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001495 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001496
Anna Zaks66c40402012-02-14 21:55:24 +00001497 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001498 // regions (explicit and implicit) escaped.
1499
1500 // Otherwise, whitelist explicit pointers; we still can track them.
1501 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001502 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1503 E = ExplicitRegions.end(); I != E; ++I) {
1504 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1505 WhitelistedSymbols.insert(R->getSymbol());
1506 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001507 }
1508
1509 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1510 E = invalidated->end(); I!=E; ++I) {
1511 SymbolRef sym = *I;
1512 if (WhitelistedSymbols.count(sym))
1513 continue;
Anna Zaks5b7aa342012-06-22 02:04:31 +00001514 // The symbol escaped. Note, we assume that if the symbol is released,
1515 // passing it out will result in a use after free. We also keep tracking
1516 // relinquished symbols.
1517 if (const RefState *RS = State->get<RegionState>(sym)) {
1518 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001519 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001520 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001521 }
Anna Zaks66c40402012-02-14 21:55:24 +00001522 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001523}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001524
Jordy Rose393f98b2012-03-18 07:43:35 +00001525static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1526 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001527 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1528 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001529
Jordan Rose166d5022012-11-02 01:54:06 +00001530 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001531 I != E; ++I) {
1532 SymbolRef sym = I.getKey();
1533 if (!currMap.lookup(sym))
1534 return sym;
1535 }
1536
1537 return NULL;
1538}
1539
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001540PathDiagnosticPiece *
1541MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1542 const ExplodedNode *PrevN,
1543 BugReporterContext &BRC,
1544 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001545 ProgramStateRef state = N->getState();
1546 ProgramStateRef statePrev = PrevN->getState();
1547
1548 const RefState *RS = state->get<RegionState>(Sym);
1549 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001550 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001551 return 0;
1552
Anna Zaksfe571602012-02-16 22:26:07 +00001553 const Stmt *S = 0;
1554 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001555 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001556
1557 // Retrieve the associated statement.
1558 ProgramPoint ProgLoc = N->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +00001559 if (StmtPoint *SP = dyn_cast<StmtPoint>(&ProgLoc))
1560 S = SP->getStmt();
1561 else if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&ProgLoc))
1562 S = Exit->getCalleeContext()->getCallSite();
Anna Zaksfe571602012-02-16 22:26:07 +00001563 // If an assumption was made on a branch, it should be caught
1564 // here by looking at the state transition.
Jordan Rose852aa0d2012-07-10 22:07:52 +00001565 else if (BlockEdge *Edge = dyn_cast<BlockEdge>(&ProgLoc)) {
1566 const CFGBlock *srcBlk = Edge->getSrc();
Anna Zaksfe571602012-02-16 22:26:07 +00001567 S = srcBlk->getTerminator();
1568 }
1569 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001570 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001571
Jordan Rose28038f32012-07-10 22:07:42 +00001572 // FIXME: We will eventually need to handle non-statement-based events
1573 // (__attribute__((cleanup))).
1574
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001575 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001576 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001577 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001578 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001579 StackHint = new StackHintGeneratorForSymbol(Sym,
1580 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001581 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001582 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001583 StackHint = new StackHintGeneratorForSymbol(Sym,
1584 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001585 } else if (isRelinquished(RS, RSPrev, S)) {
1586 Msg = "Memory ownership is transfered";
1587 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001588 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001589 Mode = ReallocationFailed;
1590 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001591 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001592 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001593
Jordy Roseb000fb52012-03-24 03:15:09 +00001594 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1595 // Is it possible to fail two reallocs WITHOUT testing in between?
1596 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1597 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001598 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001599 FailedReallocSymbol = sym;
1600 }
Anna Zaksfe571602012-02-16 22:26:07 +00001601 }
1602
1603 // We are in a special mode if a reallocation failed later in the path.
1604 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001605 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001606
Jordy Roseb000fb52012-03-24 03:15:09 +00001607 // Is this is the first appearance of the reallocated symbol?
1608 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001609 // We're at the reallocation point.
1610 Msg = "Attempt to reallocate memory";
1611 StackHint = new StackHintGeneratorForSymbol(Sym,
1612 "Returned reallocated memory");
1613 FailedReallocSymbol = NULL;
1614 Mode = Normal;
1615 }
Anna Zaksfe571602012-02-16 22:26:07 +00001616 }
1617
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001618 if (!Msg)
1619 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001620 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001621
1622 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001623 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001624 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001625 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001626}
1627
Anna Zaks93c5a242012-05-02 00:05:20 +00001628void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1629 const char *NL, const char *Sep) const {
1630
1631 RegionStateTy RS = State->get<RegionState>();
1632
1633 if (!RS.isEmpty())
1634 Out << "Has Malloc data" << NL;
1635}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001636
Anna Zaks231361a2012-02-08 23:16:52 +00001637#define REGISTER_CHECKER(name) \
1638void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001639 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001640 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001641}
Anna Zaks231361a2012-02-08 23:16:52 +00001642
1643REGISTER_CHECKER(MallocPessimistic)
1644REGISTER_CHECKER(MallocOptimistic)