blob: dfcedf6408218285d300c22dde2bbb0750727183 [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"
Anna Zaks60a1fa42012-02-22 03:14:20 +000029#include <climits>
30
Zhongxing Xu589c0f22009-11-12 08:38:56 +000031using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000032using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000033
34namespace {
35
Zhongxing Xu7fb14642009-12-11 00:55:44 +000036class RefState {
Anna Zaks050cdd72012-06-20 20:57:46 +000037 enum Kind { // Reference to allocated memory.
38 Allocated,
39 // Reference to released/freed memory.
40 Released,
Anna Zaks050cdd72012-06-20 20:57:46 +000041 // The responsibility for freeing resources has transfered from
42 // this reference. A relinquished symbol should not be freed.
Ted Kremenekdde201b2010-08-06 21:12:55 +000043 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000044 const Stmt *S;
45
Zhongxing Xu7fb14642009-12-11 00:55:44 +000046public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000047 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
48
Anna Zaks050cdd72012-06-20 20:57:46 +000049 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000050 bool isReleased() const { return K == Released; }
Anna Zaks050cdd72012-06-20 20:57:46 +000051 bool isRelinquished() const { return K == Relinquished; }
Anna Zaksca23eb22012-02-29 18:42:47 +000052
Anna Zaksc8bb3be2012-02-13 18:05:39 +000053 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000054
55 bool operator==(const RefState &X) const {
56 return K == X.K && S == X.S;
57 }
58
Anna Zaks050cdd72012-06-20 20:57:46 +000059 static RefState getAllocated(const Stmt *s) {
60 return RefState(Allocated, s);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000061 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000062 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000063 static RefState getRelinquished(const Stmt *s) {
64 return RefState(Relinquished, s);
65 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000066
67 void Profile(llvm::FoldingSetNodeID &ID) const {
68 ID.AddInteger(K);
69 ID.AddPointer(S);
70 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000071};
72
Anna Zaks40add292012-02-15 00:11:25 +000073struct ReallocPair {
74 SymbolRef ReallocatedSym;
75 bool IsFreeOnFailure;
76 ReallocPair(SymbolRef S, bool F) : ReallocatedSym(S), IsFreeOnFailure(F) {}
77 void Profile(llvm::FoldingSetNodeID &ID) const {
78 ID.AddInteger(IsFreeOnFailure);
79 ID.AddPointer(ReallocatedSym);
80 }
81 bool operator==(const ReallocPair &X) const {
82 return ReallocatedSym == X.ReallocatedSym &&
83 IsFreeOnFailure == X.IsFreeOnFailure;
84 }
85};
86
Anna Zaks3d7c44e2012-03-21 19:45:08 +000087typedef std::pair<const Stmt*, const MemRegion*> LeakInfo;
88
Anna Zaksb319e022012-02-08 20:13:28 +000089class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000090 check::EndPath,
91 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +000092 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +000093 check::PostStmt<CallExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +000094 check::PostStmt<BlockExpr>,
Anna Zaks5b7aa342012-06-22 02:04:31 +000095 check::PreObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +000096 check::Location,
97 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000098 eval::Assume,
99 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000100{
Anna Zaksfebdc322012-02-16 22:26:12 +0000101 mutable OwningPtr<BugType> BT_DoubleFree;
102 mutable OwningPtr<BugType> BT_Leak;
103 mutable OwningPtr<BugType> BT_UseFree;
104 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000105 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000106 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
107
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000108public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000109 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000110 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000111
112 /// In pessimistic mode, the checker assumes that it does not know which
113 /// functions might free the memory.
114 struct ChecksFilter {
115 DefaultBool CMallocPessimistic;
116 DefaultBool CMallocOptimistic;
117 };
118
119 ChecksFilter Filter;
120
Anna Zaks66c40402012-02-14 21:55:24 +0000121 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000122 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Jordan Rosede507ea2012-07-02 19:28:04 +0000123 void checkPreObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000124 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000125 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000126 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000127 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000128 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000129 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000130 void checkLocation(SVal l, bool isLoad, const Stmt *S,
131 CheckerContext &C) const;
132 void checkBind(SVal location, SVal val, const Stmt*S,
133 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000134 ProgramStateRef
135 checkRegionChanges(ProgramStateRef state,
136 const StoreManager::InvalidatedSymbols *invalidated,
137 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000138 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +0000139 const CallEvent *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000140 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
141 return true;
142 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000143
Anna Zaks93c5a242012-05-02 00:05:20 +0000144 void printState(raw_ostream &Out, ProgramStateRef State,
145 const char *NL, const char *Sep) const;
146
Zhongxing Xu7b760962009-11-13 07:25:27 +0000147private:
Anna Zaks66c40402012-02-14 21:55:24 +0000148 void initIdentifierInfo(ASTContext &C) const;
149
150 /// Check if this is one of the functions which can allocate/reallocate memory
151 /// pointed to by one of its arguments.
152 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000153 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
154 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000155
Anna Zaks87cb5be2012-02-22 19:24:52 +0000156 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
157 const CallExpr *CE,
158 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000159 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000160 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000161 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000162 return MallocMemAux(C, CE,
163 state->getSVal(SizeEx, C.getLocationContext()),
164 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000165 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000166
Ted Kremenek8bef8232012-01-26 21:29:00 +0000167 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000168 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000169 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000170
Anna Zaks87cb5be2012-02-22 19:24:52 +0000171 /// Update the RefState to reflect the new memory allocation.
172 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
173 const CallExpr *CE,
174 ProgramStateRef state);
175
176 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
177 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000178 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000179 ProgramStateRef state, unsigned Num,
180 bool Hold) const;
181 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
182 const Expr *ParentExpr,
183 ProgramStateRef state,
184 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000185
Anna Zaks87cb5be2012-02-22 19:24:52 +0000186 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
187 bool FreesMemOnFailure) const;
188 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000189
Anna Zaks14345182012-05-18 01:16:10 +0000190 ///\brief Check if the memory associated with this symbol was released.
191 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
192
Anna Zaks91c2a112012-02-08 23:16:56 +0000193 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
194 const Stmt *S = 0) const;
195
Anna Zaks66c40402012-02-14 21:55:24 +0000196 /// Check if the function is not known to us. So, for example, we could
197 /// conservatively assume it can free/reallocate it's pointer arguments.
Jordan Rose740d4902012-07-02 19:27:35 +0000198 bool doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000199 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000200
Ted Kremenek9c378f72011-08-12 23:37:29 +0000201 static bool SummarizeValue(raw_ostream &os, SVal V);
202 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000203 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000204
Anna Zaksca8e36e2012-02-23 21:38:21 +0000205 /// Find the location of the allocation for Sym on the path leading to the
206 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000207 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
208 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000209
Anna Zaksda046772012-02-11 21:02:40 +0000210 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
211
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000212 /// The bug visitor which allows us to print extra diagnostics along the
213 /// BugReport path. For example, showing the allocation site of the leaked
214 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000215 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000216 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000217 enum NotificationMode {
218 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000219 ReallocationFailed
220 };
221
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000222 // The allocated region symbol tracked by the main analysis.
223 SymbolRef Sym;
224
Anna Zaks88feba02012-05-10 01:37:40 +0000225 // The mode we are in, i.e. what kind of diagnostics will be emitted.
226 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000227
Anna Zaks88feba02012-05-10 01:37:40 +0000228 // A symbol from when the primary region should have been reallocated.
229 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000230
Anna Zaks88feba02012-05-10 01:37:40 +0000231 bool IsLeak;
232
233 public:
234 MallocBugVisitor(SymbolRef S, bool isLeak = false)
235 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000236
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000237 virtual ~MallocBugVisitor() {}
238
239 void Profile(llvm::FoldingSetNodeID &ID) const {
240 static int X = 0;
241 ID.AddPointer(&X);
242 ID.AddPointer(Sym);
243 }
244
Anna Zaksfe571602012-02-16 22:26:07 +0000245 inline bool isAllocated(const RefState *S, const RefState *SPrev,
246 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000247 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000248 return (Stmt && isa<CallExpr>(Stmt) &&
249 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000250 }
251
Anna Zaksfe571602012-02-16 22:26:07 +0000252 inline bool isReleased(const RefState *S, const RefState *SPrev,
253 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000254 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000255 return (Stmt && isa<CallExpr>(Stmt) &&
256 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
257 }
258
Anna Zaks5b7aa342012-06-22 02:04:31 +0000259 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
260 const Stmt *Stmt) {
261 // Did not track -> relinquished. Other state (allocated) -> relinquished.
262 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
263 isa<ObjCPropertyRefExpr>(Stmt)) &&
264 (S && S->isRelinquished()) &&
265 (!SPrev || !SPrev->isRelinquished()));
266 }
267
Anna Zaksfe571602012-02-16 22:26:07 +0000268 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
269 const Stmt *Stmt) {
270 // If the expression is not a call, and the state change is
271 // released -> allocated, it must be the realloc return value
272 // check. If we have to handle more cases here, it might be cleaner just
273 // to track this extra bit in the state itself.
274 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
275 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000276 }
277
278 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
279 const ExplodedNode *PrevN,
280 BugReporterContext &BRC,
281 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000282
283 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
284 const ExplodedNode *EndPathNode,
285 BugReport &BR) {
286 if (!IsLeak)
287 return 0;
288
289 PathDiagnosticLocation L =
290 PathDiagnosticLocation::createEndOfPath(EndPathNode,
291 BRC.getSourceManager());
292 // Do not add the statement itself as a range in case of leak.
293 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
294 }
295
Anna Zaks56a938f2012-03-16 23:24:20 +0000296 private:
297 class StackHintGeneratorForReallocationFailed
298 : public StackHintGeneratorForSymbol {
299 public:
300 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
301 : StackHintGeneratorForSymbol(S, M) {}
302
303 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
304 SmallString<200> buf;
305 llvm::raw_svector_ostream os(buf);
306
Anna Zaksfbd58742012-03-16 23:44:28 +0000307 os << "Reallocation of ";
Anna Zaks56a938f2012-03-16 23:24:20 +0000308 // Printed parameters start at 1, not 0.
309 printOrdinal(++ArgIndex, os);
310 os << " parameter failed";
311
312 return os.str();
313 }
314
315 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000316 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000317 }
318 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000319 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000320};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000321} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000322
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000323typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000324typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000325class RegionState {};
326class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000327namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000328namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000329 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000330 struct ProgramStateTrait<RegionState>
331 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000332 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000333 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000334
335 template <>
336 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000337 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000338 static void *GDMIndex() { static int x; return &x; }
339 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000340}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000341}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000342
Anna Zaks4fb54872012-02-11 21:02:35 +0000343namespace {
344class StopTrackingCallback : public SymbolVisitor {
345 ProgramStateRef state;
346public:
347 StopTrackingCallback(ProgramStateRef st) : state(st) {}
348 ProgramStateRef getState() const { return state; }
349
350 bool VisitSymbol(SymbolRef sym) {
351 state = state->remove<RegionState>(sym);
352 return true;
353 }
354};
355} // end anonymous namespace
356
Anna Zaks66c40402012-02-14 21:55:24 +0000357void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000358 if (II_malloc)
359 return;
360 II_malloc = &Ctx.Idents.get("malloc");
361 II_free = &Ctx.Idents.get("free");
362 II_realloc = &Ctx.Idents.get("realloc");
363 II_reallocf = &Ctx.Idents.get("reallocf");
364 II_calloc = &Ctx.Idents.get("calloc");
365 II_valloc = &Ctx.Idents.get("valloc");
366 II_strdup = &Ctx.Idents.get("strdup");
367 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000368}
369
Anna Zaks66c40402012-02-14 21:55:24 +0000370bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000371 if (isFreeFunction(FD, C))
372 return true;
373
374 if (isAllocationFunction(FD, C))
375 return true;
376
377 return false;
378}
379
380bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
381 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000382 if (!FD)
383 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000384
Jordan Rose5ef6e942012-07-10 23:13:01 +0000385 if (FD->getKind() == Decl::Function) {
386 IdentifierInfo *FunI = FD->getIdentifier();
387 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000388
Jordan Rose5ef6e942012-07-10 23:13:01 +0000389 if (FunI == II_malloc || FunI == II_realloc ||
390 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
391 FunI == II_strdup || FunI == II_strndup)
392 return true;
393 }
Anna Zaks66c40402012-02-14 21:55:24 +0000394
Anna Zaks14345182012-05-18 01:16:10 +0000395 if (Filter.CMallocOptimistic && FD->hasAttrs())
396 for (specific_attr_iterator<OwnershipAttr>
397 i = FD->specific_attr_begin<OwnershipAttr>(),
398 e = FD->specific_attr_end<OwnershipAttr>();
399 i != e; ++i)
400 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
401 return true;
402 return false;
403}
404
405bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
406 if (!FD)
407 return false;
408
Jordan Rose5ef6e942012-07-10 23:13:01 +0000409 if (FD->getKind() == Decl::Function) {
410 IdentifierInfo *FunI = FD->getIdentifier();
411 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000412
Jordan Rose5ef6e942012-07-10 23:13:01 +0000413 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
414 return true;
415 }
Anna Zaks66c40402012-02-14 21:55:24 +0000416
Anna Zaks14345182012-05-18 01:16:10 +0000417 if (Filter.CMallocOptimistic && FD->hasAttrs())
418 for (specific_attr_iterator<OwnershipAttr>
419 i = FD->specific_attr_begin<OwnershipAttr>(),
420 e = FD->specific_attr_end<OwnershipAttr>();
421 i != e; ++i)
422 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
423 (*i)->getOwnKind() == OwnershipAttr::Holds)
424 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000425 return false;
426}
427
Anna Zaksb319e022012-02-08 20:13:28 +0000428void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
429 const FunctionDecl *FD = C.getCalleeDecl(CE);
430 if (!FD)
431 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000432
Anna Zaks87cb5be2012-02-22 19:24:52 +0000433 ProgramStateRef State = C.getState();
Jordan Rose5ef6e942012-07-10 23:13:01 +0000434
435 if (FD->getKind() == Decl::Function) {
436 initIdentifierInfo(C.getASTContext());
437 IdentifierInfo *FunI = FD->getIdentifier();
438
439 if (FunI == II_malloc || FunI == II_valloc) {
440 if (CE->getNumArgs() < 1)
441 return;
442 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
443 } else if (FunI == II_realloc) {
444 State = ReallocMem(C, CE, false);
445 } else if (FunI == II_reallocf) {
446 State = ReallocMem(C, CE, true);
447 } else if (FunI == II_calloc) {
448 State = CallocMem(C, CE);
449 } else if (FunI == II_free) {
450 State = FreeMemAux(C, CE, State, 0, false);
451 } else if (FunI == II_strdup) {
452 State = MallocUpdateRefState(C, CE, State);
453 } else if (FunI == II_strndup) {
454 State = MallocUpdateRefState(C, CE, State);
455 }
456 }
457
458 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000459 // Check all the attributes, if there are any.
460 // There can be multiple of these attributes.
461 if (FD->hasAttrs())
462 for (specific_attr_iterator<OwnershipAttr>
463 i = FD->specific_attr_begin<OwnershipAttr>(),
464 e = FD->specific_attr_end<OwnershipAttr>();
465 i != e; ++i) {
466 switch ((*i)->getOwnKind()) {
467 case OwnershipAttr::Returns:
468 State = MallocMemReturnsAttr(C, CE, *i);
469 break;
470 case OwnershipAttr::Takes:
471 case OwnershipAttr::Holds:
472 State = FreeMemAttr(C, CE, *i);
473 break;
474 }
475 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000476 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000477 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000478}
479
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000480static bool isFreeWhenDoneSetToZero(const ObjCMethodCall &Call) {
481 Selector S = Call.getSelector();
Anna Zaks3e4f65d2012-06-22 22:08:09 +0000482 for (unsigned i = 1; i < S.getNumArgs(); ++i)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000483 if (S.getNameForSlot(i).equals("freeWhenDone"))
484 if (Call.getArgSVal(i).isConstant(0))
485 return true;
486
487 return false;
488}
489
Jordan Rosede507ea2012-07-02 19:28:04 +0000490void MallocChecker::checkPreObjCMessage(const ObjCMethodCall &Call,
Jordan Rose740d4902012-07-02 19:27:35 +0000491 CheckerContext &C) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000492 // If the first selector is dataWithBytesNoCopy, assume that the memory will
493 // be released with 'free' by the new object.
494 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
495 // Unless 'freeWhenDone' param set to 0.
496 // TODO: Check that the memory was allocated with malloc.
Jordan Rosede507ea2012-07-02 19:28:04 +0000497 Selector S = Call.getSelector();
Anna Zaks7186dc62012-06-22 22:42:30 +0000498 if ((S.getNameForSlot(0) == "dataWithBytesNoCopy" ||
499 S.getNameForSlot(0) == "initWithBytesNoCopy" ||
500 S.getNameForSlot(0) == "initWithCharactersNoCopy") &&
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000501 !isFreeWhenDoneSetToZero(Call)){
Anna Zaks5b7aa342012-06-22 02:04:31 +0000502 unsigned int argIdx = 0;
Jordan Rose740d4902012-07-02 19:27:35 +0000503 C.addTransition(FreeMemAux(C, Call.getArgExpr(argIdx),
Jordan Rosede507ea2012-07-02 19:28:04 +0000504 Call.getOriginExpr(), C.getState(), true));
Anna Zaks5b7aa342012-06-22 02:04:31 +0000505 }
506}
507
Anna Zaks87cb5be2012-02-22 19:24:52 +0000508ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
509 const CallExpr *CE,
510 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000511 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000512 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000513
Sean Huntcf807c42010-08-18 23:23:40 +0000514 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000515 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000516 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000517 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000518 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000519}
520
Anna Zaksb319e022012-02-08 20:13:28 +0000521ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000522 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000523 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000524 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000525
526 // Bind the return value to the symbolic value from the heap region.
527 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
528 // side effects other than what we model here.
529 unsigned Count = C.getCurrentBlockCount();
530 SValBuilder &svalBuilder = C.getSValBuilder();
531 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
532 DefinedSVal RetVal =
533 cast<DefinedSVal>(svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count));
534 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000535
Anna Zaksb16ce452012-02-15 00:11:22 +0000536 // We expect the malloc functions to return a pointer.
Anna Zakse17fdb22012-06-07 03:57:32 +0000537 if (!isa<Loc>(RetVal))
Anna Zaksb16ce452012-02-15 00:11:22 +0000538 return 0;
539
Jordy Rose32f26562010-07-04 00:00:41 +0000540 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000541 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000542
Jordy Rose32f26562010-07-04 00:00:41 +0000543 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000544 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000545 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000546 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000547 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000548 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000549 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000550 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
551 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
552 DefinedOrUnknownSVal extentMatchesSize =
553 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000554
Anna Zaks60a1fa42012-02-22 03:14:20 +0000555 state = state->assume(extentMatchesSize, true);
556 assert(state);
557 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000558
Anna Zaks87cb5be2012-02-22 19:24:52 +0000559 return MallocUpdateRefState(C, CE, state);
560}
561
562ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
563 const CallExpr *CE,
564 ProgramStateRef state) {
565 // Get the return value.
566 SVal retVal = state->getSVal(CE, C.getLocationContext());
567
568 // We expect the malloc functions to return a pointer.
569 if (!isa<Loc>(retVal))
570 return 0;
571
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000572 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000573 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000574
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000575 // Set the symbol's state to Allocated.
Anna Zaks050cdd72012-06-20 20:57:46 +0000576 return state->set<RegionState>(Sym, RefState::getAllocated(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000577
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000578}
579
Anna Zaks87cb5be2012-02-22 19:24:52 +0000580ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
581 const CallExpr *CE,
582 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000583 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000584 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000585
Anna Zaksb3d72752012-03-01 22:06:06 +0000586 ProgramStateRef State = C.getState();
587
Sean Huntcf807c42010-08-18 23:23:40 +0000588 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
589 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000590 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
591 Att->getOwnKind() == OwnershipAttr::Holds);
592 if (StateI)
593 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000594 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000595 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000596}
597
Ted Kremenek8bef8232012-01-26 21:29:00 +0000598ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000599 const CallExpr *CE,
600 ProgramStateRef state,
601 unsigned Num,
602 bool Hold) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000603 if (CE->getNumArgs() < (Num + 1))
604 return 0;
605
Anna Zaks5b7aa342012-06-22 02:04:31 +0000606 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold);
607}
608
609ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
610 const Expr *ArgExpr,
611 const Expr *ParentExpr,
612 ProgramStateRef state,
613 bool Hold) const {
614
Ted Kremenek5eca4822012-01-06 22:09:28 +0000615 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000616 if (!isa<DefinedOrUnknownSVal>(ArgVal))
617 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000618 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
619
620 // Check for null dereferences.
621 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000622 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000623
Anna Zaksb276bd92012-02-14 00:26:13 +0000624 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000625 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000626 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000627 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000628 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000629
Jordy Rose43859f62010-06-07 19:32:37 +0000630 // Unknown values could easily be okay
631 // Undefined values are handled elsewhere
632 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000633 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000634
Jordy Rose43859f62010-06-07 19:32:37 +0000635 const MemRegion *R = ArgVal.getAsRegion();
636
637 // Nonlocs can't be freed, of course.
638 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
639 if (!R) {
640 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000641 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000642 }
643
644 R = R->StripCasts();
645
646 // Blocks might show up as heap data, but should not be free()d
647 if (isa<BlockDataRegion>(R)) {
648 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000649 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000650 }
651
652 const MemSpaceRegion *MS = R->getMemorySpace();
653
654 // Parameters, locals, statics, and globals shouldn't be freed.
655 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
656 // FIXME: at the time this code was written, malloc() regions were
657 // represented by conjured symbols, which are all in UnknownSpaceRegion.
658 // This means that there isn't actually anything from HeapSpaceRegion
659 // that should be freed, even though we allow it here.
660 // Of course, free() can work on memory allocated outside the current
661 // function, so UnknownSpaceRegion is always a possibility.
662 // False negatives are better than false positives.
663
664 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000665 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000666 }
667
668 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
669 // Various cases could lead to non-symbol values here.
670 // For now, ignore them.
671 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000672 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000673
674 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000675 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000676
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000677 // Check double free.
Anna Zaksede875b2012-08-03 18:30:18 +0000678 if (RS && (RS->isReleased() || RS->isRelinquished())) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000679 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000680 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000681 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000682 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000683 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000684 (RS->isReleased() ? "Attempt to free released memory" :
685 "Attempt to free non-owned memory"), N);
Anna Zaksfe571602012-02-16 22:26:07 +0000686 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000687 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000688 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000689 C.EmitReport(R);
690 }
Anna Zaksb319e022012-02-08 20:13:28 +0000691 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000692 }
693
694 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000695 if (Hold)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000696 return state->set<RegionState>(Sym, RefState::getRelinquished(ParentExpr));
697 return state->set<RegionState>(Sym, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000698}
699
Ted Kremenek9c378f72011-08-12 23:37:29 +0000700bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000701 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
702 os << "an integer (" << IntVal->getValue() << ")";
703 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
704 os << "a constant address (" << ConstAddr->getValue() << ")";
705 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000706 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000707 else
708 return false;
709
710 return true;
711}
712
Ted Kremenek9c378f72011-08-12 23:37:29 +0000713bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000714 const MemRegion *MR) {
715 switch (MR->getKind()) {
716 case MemRegion::FunctionTextRegionKind: {
717 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
718 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000719 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000720 else
721 os << "the address of a function";
722 return true;
723 }
724 case MemRegion::BlockTextRegionKind:
725 os << "block text";
726 return true;
727 case MemRegion::BlockDataRegionKind:
728 // FIXME: where the block came from?
729 os << "a block";
730 return true;
731 default: {
732 const MemSpaceRegion *MS = MR->getMemorySpace();
733
Anna Zakseb31a762012-01-04 23:54:01 +0000734 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000735 const VarRegion *VR = dyn_cast<VarRegion>(MR);
736 const VarDecl *VD;
737 if (VR)
738 VD = VR->getDecl();
739 else
740 VD = NULL;
741
742 if (VD)
743 os << "the address of the local variable '" << VD->getName() << "'";
744 else
745 os << "the address of a local stack variable";
746 return true;
747 }
Anna Zakseb31a762012-01-04 23:54:01 +0000748
749 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000750 const VarRegion *VR = dyn_cast<VarRegion>(MR);
751 const VarDecl *VD;
752 if (VR)
753 VD = VR->getDecl();
754 else
755 VD = NULL;
756
757 if (VD)
758 os << "the address of the parameter '" << VD->getName() << "'";
759 else
760 os << "the address of a parameter";
761 return true;
762 }
Anna Zakseb31a762012-01-04 23:54:01 +0000763
764 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000765 const VarRegion *VR = dyn_cast<VarRegion>(MR);
766 const VarDecl *VD;
767 if (VR)
768 VD = VR->getDecl();
769 else
770 VD = NULL;
771
772 if (VD) {
773 if (VD->isStaticLocal())
774 os << "the address of the static variable '" << VD->getName() << "'";
775 else
776 os << "the address of the global variable '" << VD->getName() << "'";
777 } else
778 os << "the address of a global variable";
779 return true;
780 }
Anna Zakseb31a762012-01-04 23:54:01 +0000781
782 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000783 }
784 }
785}
786
787void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000788 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000789 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000790 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000791 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000792
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000793 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000794 llvm::raw_svector_ostream os(buf);
795
796 const MemRegion *MR = ArgVal.getAsRegion();
797 if (MR) {
798 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
799 MR = ER->getSuperRegion();
800
801 // Special case for alloca()
802 if (isa<AllocaRegion>(MR))
803 os << "Argument to free() was allocated by alloca(), not malloc()";
804 else {
805 os << "Argument to free() is ";
806 if (SummarizeRegion(os, MR))
807 os << ", which is not memory allocated by malloc()";
808 else
809 os << "not memory allocated by malloc()";
810 }
811 } else {
812 os << "Argument to free() is ";
813 if (SummarizeValue(os, ArgVal))
814 os << ", which is not memory allocated by malloc()";
815 else
816 os << "not memory allocated by malloc()";
817 }
818
Anna Zakse172e8b2011-08-17 23:00:25 +0000819 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000820 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000821 R->addRange(range);
822 C.EmitReport(R);
823 }
824}
825
Anna Zaks87cb5be2012-02-22 19:24:52 +0000826ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
827 const CallExpr *CE,
828 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000829 if (CE->getNumArgs() < 2)
830 return 0;
831
Ted Kremenek8bef8232012-01-26 21:29:00 +0000832 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000833 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000834 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000835 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
836 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000837 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000838 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000839
Ted Kremenek846eabd2010-12-01 21:28:31 +0000840 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000841
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000842 DefinedOrUnknownSVal PtrEQ =
843 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000844
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000845 // Get the size argument. If there is no size arg then give up.
846 const Expr *Arg1 = CE->getArg(1);
847 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000848 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000849
850 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000851 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
852 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000853 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000854 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000855
856 // Compare the size argument to 0.
857 DefinedOrUnknownSVal SizeZero =
858 svalBuilder.evalEQ(state, Arg1Val,
859 svalBuilder.makeIntValWithPtrWidth(0, false));
860
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000861 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
862 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
863 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
864 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
865 // We only assume exceptional states if they are definitely true; if the
866 // state is under-constrained, assume regular realloc behavior.
867 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
868 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
869
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000870 // If the ptr is NULL and the size is not 0, the call is equivalent to
871 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000872 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000873 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000874 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000875 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000876 }
877
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000878 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000879 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000880
Anna Zaks30838b92012-02-13 20:57:07 +0000881 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000882 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000883 SymbolRef FromPtr = arg0Val.getAsSymbol();
884 SVal RetVal = state->getSVal(CE, LCtx);
885 SymbolRef ToPtr = RetVal.getAsSymbol();
886 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000887 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000888
889 // If the size is 0, free the memory.
890 if (SizeIsZero)
891 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000892 // The semantics of the return value are:
893 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +0000894 // to free() is returned. We just free the input pointer and do not add
895 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +0000896 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000897 }
898
899 // Default behavior.
900 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
901 // FIXME: We should copy the content of the original buffer.
902 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
903 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000904 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000905 return 0;
Anna Zaks40add292012-02-15 00:11:25 +0000906 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
907 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000908 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000909 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000910 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000911 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000912}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000913
Anna Zaks87cb5be2012-02-22 19:24:52 +0000914ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +0000915 if (CE->getNumArgs() < 2)
916 return 0;
917
Ted Kremenek8bef8232012-01-26 21:29:00 +0000918 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000919 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000920 const LocationContext *LCtx = C.getLocationContext();
921 SVal count = state->getSVal(CE->getArg(0), LCtx);
922 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000923 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
924 svalBuilder.getContext().getSizeType());
925 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000926
Anna Zaks87cb5be2012-02-22 19:24:52 +0000927 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000928}
929
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000930LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +0000931MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
932 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000933 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000934 // Walk the ExplodedGraph backwards and find the first node that referred to
935 // the tracked symbol.
936 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000937 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000938
939 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000940 ProgramStateRef State = N->getState();
941 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +0000942 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000943
944 // Find the most recent expression bound to the symbol in the current
945 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000946 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +0000947 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
948 SVal Val = State->getSVal(MR);
949 if (Val.getAsLocSymbol() == Sym)
950 ReferenceRegion = MR;
951 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000952 }
953
Anna Zaks7752d292012-02-27 23:40:55 +0000954 // Allocation node, is the last node in the current context in which the
955 // symbol was tracked.
956 if (N->getLocationContext() == LeakContext)
957 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000958 N = N->pred_empty() ? NULL : *(N->pred_begin());
959 }
960
961 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000962 const Stmt *AllocationStmt = 0;
Jordan Rose852aa0d2012-07-10 22:07:52 +0000963 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
964 AllocationStmt = Exit->getCalleeContext()->getCallSite();
965 else if (StmtPoint *SP = dyn_cast<StmtPoint>(&P))
966 AllocationStmt = SP->getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +0000967
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000968 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +0000969}
970
Anna Zaksda046772012-02-11 21:02:40 +0000971void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
972 CheckerContext &C) const {
973 assert(N);
974 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000975 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000976 // Leaks should not be reported if they are post-dominated by a sink:
977 // (1) Sinks are higher importance bugs.
978 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
979 // with __noreturn functions such as assert() or exit(). We choose not
980 // to report leaks on such paths.
981 BT_Leak->setSuppressOnSink(true);
982 }
983
Anna Zaksca8e36e2012-02-23 21:38:21 +0000984 // Most bug reports are cached at the location where they occurred.
985 // With leaks, we want to unique them by the location where they were
986 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +0000987 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000988 const Stmt *AllocStmt = 0;
989 const MemRegion *Region = 0;
990 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
991 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +0000992 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
993 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +0000994
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000995 SmallString<200> buf;
996 llvm::raw_svector_ostream os(buf);
997 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +0000998 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000999 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001000 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001001 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001002 }
1003
1004 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001005 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001006 R->addVisitor(new MallocBugVisitor(Sym, true));
Anna Zaksda046772012-02-11 21:02:40 +00001007 C.EmitReport(R);
1008}
1009
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001010void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1011 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001012{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001013 if (!SymReaper.hasDeadSymbols())
1014 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001015
Ted Kremenek8bef8232012-01-26 21:29:00 +00001016 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001017 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001018 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001019
Ted Kremenek217470e2011-07-28 23:07:51 +00001020 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +00001021 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001022 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1023 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +00001024 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +00001025 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +00001026 Errors.push_back(I->first);
1027 }
Jordy Rose90760142010-08-18 04:33:47 +00001028 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001029 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001030
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001031 }
1032 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001033
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001034 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +00001035 ReallocMap RP = state->get<ReallocPairs>();
1036 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
1037 if (SymReaper.isDead(I->first) ||
1038 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001039 state = state->remove<ReallocPairs>(I->first);
1040 }
1041 }
1042
Anna Zaksca8e36e2012-02-23 21:38:21 +00001043 // Generate leak node.
1044 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1045 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +00001046
Anna Zaksca8e36e2012-02-23 21:38:21 +00001047 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +00001048 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +00001049 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
1050 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001051 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001052 }
Anna Zaksca8e36e2012-02-23 21:38:21 +00001053 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001054}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001055
Anna Zaksda046772012-02-11 21:02:40 +00001056void MallocChecker::checkEndPath(CheckerContext &C) const {
1057 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +00001058 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +00001059
Anna Zaksa19581a2012-02-20 22:25:23 +00001060 // If inside inlined call, skip it.
1061 if (C.getLocationContext()->getParent() != 0)
1062 return;
1063
Jordy Rose09cef092010-08-18 04:26:59 +00001064 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +00001065 RefState RS = I->second;
1066 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +00001067 ExplodedNode *N = C.addTransition(state);
1068 if (N)
1069 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +00001070 }
1071 }
1072}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001073
Anna Zaks66c40402012-02-14 21:55:24 +00001074void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001075 // We will check for double free in the post visit.
1076 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001077 return;
1078
1079 // Check use after free, when a freed pointer is passed to a call.
1080 ProgramStateRef State = C.getState();
1081 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1082 E = CE->arg_end(); I != E; ++I) {
1083 const Expr *A = *I;
1084 if (A->getType().getTypePtr()->isAnyPointerType()) {
1085 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1086 if (!Sym)
1087 continue;
1088 if (checkUseAfterFree(Sym, C, A))
1089 return;
1090 }
1091 }
1092}
1093
Anna Zaks91c2a112012-02-08 23:16:56 +00001094void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1095 const Expr *E = S->getRetValue();
1096 if (!E)
1097 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001098
1099 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001100 ProgramStateRef State = C.getState();
1101 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001102 SymbolRef Sym = RetVal.getAsSymbol();
1103 if (!Sym)
1104 // If we are returning a field of the allocated struct or an array element,
1105 // the callee could still free the memory.
1106 // TODO: This logic should be a part of generic symbol escape callback.
1107 if (const MemRegion *MR = RetVal.getAsRegion())
1108 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1109 if (const SymbolicRegion *BMR =
1110 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1111 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001112
Anna Zaks0860cd02012-02-11 21:44:39 +00001113 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001114 if (Sym)
1115 if (checkUseAfterFree(Sym, C, E))
1116 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001117
Jordan Rose0d53ab42012-08-08 18:23:31 +00001118 // If this function body is not inlined, stop tracking any returned symbols.
1119 if (C.getLocationContext()->getParent() == 0) {
1120 State =
1121 State->scanReachableSymbols<StopTrackingCallback>(RetVal).getState();
1122 C.addTransition(State);
1123 }
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001124}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001125
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001126// TODO: Blocks should be either inlined or should call invalidate regions
1127// upon invocation. After that's in place, special casing here will not be
1128// needed.
1129void MallocChecker::checkPostStmt(const BlockExpr *BE,
1130 CheckerContext &C) const {
1131
1132 // Scan the BlockDecRefExprs for any object the retain count checker
1133 // may be tracking.
1134 if (!BE->getBlockDecl()->hasCaptures())
1135 return;
1136
1137 ProgramStateRef state = C.getState();
1138 const BlockDataRegion *R =
1139 cast<BlockDataRegion>(state->getSVal(BE,
1140 C.getLocationContext()).getAsRegion());
1141
1142 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1143 E = R->referenced_vars_end();
1144
1145 if (I == E)
1146 return;
1147
1148 SmallVector<const MemRegion*, 10> Regions;
1149 const LocationContext *LC = C.getLocationContext();
1150 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1151
1152 for ( ; I != E; ++I) {
1153 const VarRegion *VR = *I;
1154 if (VR->getSuperRegion() == R) {
1155 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1156 }
1157 Regions.push_back(VR);
1158 }
1159
1160 state =
1161 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1162 Regions.data() + Regions.size()).getState();
1163 C.addTransition(state);
1164}
1165
Anna Zaks14345182012-05-18 01:16:10 +00001166bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001167 assert(Sym);
1168 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001169 return (RS && RS->isReleased());
1170}
1171
1172bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1173 const Stmt *S) const {
1174 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001175 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001176 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001177 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001178
Anna Zaksfebdc322012-02-16 22:26:12 +00001179 BugReport *R = new BugReport(*BT_UseFree,
1180 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001181 if (S)
1182 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001183 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001184 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +00001185 C.EmitReport(R);
1186 return true;
1187 }
1188 }
1189 return false;
1190}
1191
Zhongxing Xuc8023782010-03-10 04:58:55 +00001192// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001193void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1194 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001195 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001196 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001197 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001198}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001199
Anna Zaks4fb54872012-02-11 21:02:35 +00001200//===----------------------------------------------------------------------===//
1201// Check various ways a symbol can be invalidated.
1202// TODO: This logic (the next 3 functions) is copied/similar to the
1203// RetainRelease checker. We might want to factor this out.
1204//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001205
Anna Zaks4fb54872012-02-11 21:02:35 +00001206// Stop tracking symbols when a value escapes as a result of checkBind.
1207// A value escapes in three possible cases:
1208// (1) we are binding to something that is not a memory region.
1209// (2) we are binding to a memregion that does not have stack storage
1210// (3) we are binding to a memregion with stack storage that the store
1211// does not understand.
1212void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1213 CheckerContext &C) const {
1214 // Are we storing to something that causes the value to "escape"?
1215 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001216 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001217
Anna Zaks4fb54872012-02-11 21:02:35 +00001218 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1219 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001220
Anna Zaks4fb54872012-02-11 21:02:35 +00001221 if (!escapes) {
1222 // To test (3), generate a new state with the binding added. If it is
1223 // the same state, then it escapes (since the store cannot represent
1224 // the binding).
Anna Zaks93c5a242012-05-02 00:05:20 +00001225 // Do this only if we know that the store is not supposed to generate the
1226 // same state.
1227 SVal StoredVal = state->getSVal(regionLoc->getRegion());
1228 if (StoredVal != val)
1229 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001230 }
1231 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001232
1233 // If our store can represent the binding and we aren't storing to something
1234 // that doesn't have local storage then just return and have the simulation
1235 // state continue as is.
1236 if (!escapes)
1237 return;
1238
1239 // Otherwise, find all symbols referenced by 'val' that we are tracking
1240 // and stop tracking them.
1241 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1242 C.addTransition(state);
1243}
1244
1245// If a symbolic region is assumed to NULL (or another constant), stop tracking
1246// it - assuming that allocation failed on this path.
1247ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1248 SVal Cond,
1249 bool Assumption) const {
1250 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001251 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1252 // If the symbol is assumed to NULL or another constant, this will
1253 // return an APSInt*.
1254 if (state->getSymVal(I.getKey()))
1255 state = state->remove<RegionState>(I.getKey());
1256 }
1257
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001258 // Realloc returns 0 when reallocation fails, which means that we should
1259 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001260 ReallocMap RP = state->get<ReallocPairs>();
1261 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001262 // If the symbol is assumed to NULL or another constant, this will
1263 // return an APSInt*.
1264 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001265 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1266 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001267 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001268 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1269 state = state->set<RegionState>(ReallocSym,
Anna Zaks050cdd72012-06-20 20:57:46 +00001270 RefState::getAllocated(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001271 }
1272 state = state->remove<ReallocPairs>(I.getKey());
1273 }
1274 }
1275
Anna Zaks4fb54872012-02-11 21:02:35 +00001276 return state;
1277}
1278
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001279// Check if the function is known to us. So, for example, we could
Jordan Rose740d4902012-07-02 19:27:35 +00001280// conservatively assume it can free/reallocate its pointer arguments.
Anna Zaks66c40402012-02-14 21:55:24 +00001281// (We assume that the pointers cannot escape through calls to system
1282// functions not handled by this checker.)
Jordan Rose740d4902012-07-02 19:27:35 +00001283bool MallocChecker::doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001284 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001285 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001286
1287 // For now, assume that any C++ call can free memory.
1288 // TODO: If we want to be more optimistic here, we'll need to make sure that
1289 // regions escape to C++ containers. They seem to do that even now, but for
1290 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001291 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001292 return false;
1293
Jordan Rose740d4902012-07-02 19:27:35 +00001294 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001295 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001296 // If it's not a framework call, or if it takes a callback, assume it
1297 // can free memory.
1298 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001299 return false;
1300
Jordan Rose740d4902012-07-02 19:27:35 +00001301 Selector S = Msg->getSelector();
Anna Zaks52a04812012-06-20 23:35:57 +00001302
Jordan Rose740d4902012-07-02 19:27:35 +00001303 // Whitelist the ObjC methods which do free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001304 // - Anything containing 'freeWhenDone' param set to 1.
1305 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
Anna Zaks3e4f65d2012-06-22 22:08:09 +00001306 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001307 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1308 if (Call->getArgSVal(i).isConstant(1))
1309 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001310 else
1311 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001312 }
1313 }
1314
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001315 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001316 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001317 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
Jordan Rose740d4902012-07-02 19:27:35 +00001318 StringRef FirstSlot = S.getNameForSlot(0);
1319 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001320 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001321
Anna Zaks5f757682012-06-19 05:10:32 +00001322 // If the first selector starts with addPointer, insertPointer,
1323 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1324 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001325 // that the pointers get freed by following the container itself.
1326 if (FirstSlot.startswith("addPointer") ||
1327 FirstSlot.startswith("insertPointer") ||
1328 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001329 return false;
1330 }
1331
Jordan Rose740d4902012-07-02 19:27:35 +00001332 // Otherwise, assume that the method does not free memory.
1333 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001334 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001335 }
1336
Jordan Rose740d4902012-07-02 19:27:35 +00001337 // At this point the only thing left to handle is straight function calls.
1338 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1339 if (!FD)
1340 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001341
Jordan Rose740d4902012-07-02 19:27:35 +00001342 ASTContext &ASTC = State->getStateManager().getContext();
1343
1344 // If it's one of the allocation functions we can reason about, we model
1345 // its behavior explicitly.
1346 if (isMemFunction(FD, ASTC))
1347 return true;
1348
1349 // If it's not a system call, assume it frees memory.
1350 if (!Call->isInSystemHeader())
1351 return false;
1352
1353 // White list the system functions whose arguments escape.
1354 const IdentifierInfo *II = FD->getIdentifier();
1355 if (!II)
1356 return false;
1357 StringRef FName = II->getName();
1358
Jordan Rose740d4902012-07-02 19:27:35 +00001359 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001360 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001361 if (FName.endswith("NoCopy")) {
1362 // Look for the deallocator argument. We know that the memory ownership
1363 // is not transferred only if the deallocator argument is
1364 // 'kCFAllocatorNull'.
1365 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1366 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1367 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1368 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1369 if (DeallocatorName == "kCFAllocatorNull")
1370 return true;
1371 }
1372 }
1373 return false;
1374 }
1375
Jordan Rose740d4902012-07-02 19:27:35 +00001376 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001377 // 'closefn' is specified (and if that function does free memory),
1378 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001379 // Currently, we do not inspect the 'closefn' function (PR12101).
1380 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001381 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1382 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001383
1384 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1385 // these leaks might be intentional when setting the buffer for stdio.
1386 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1387 if (FName == "setbuf" || FName =="setbuffer" ||
1388 FName == "setlinebuf" || FName == "setvbuf") {
1389 if (Call->getNumArgs() >= 1) {
1390 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1391 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1392 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1393 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1394 return false;
1395 }
1396 }
1397
1398 // A bunch of other functions which either take ownership of a pointer or
1399 // wrap the result up in a struct or object, meaning it can be freed later.
1400 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1401 // but the Malloc checker cannot differentiate between them. The right way
1402 // of doing this would be to implement a pointer escapes callback.
1403 if (FName == "CGBitmapContextCreate" ||
1404 FName == "CGBitmapContextCreateWithData" ||
1405 FName == "CVPixelBufferCreateWithBytes" ||
1406 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1407 FName == "OSAtomicEnqueue") {
1408 return false;
1409 }
1410
Jordan Rose85d7e012012-07-02 19:27:51 +00001411 // Handle cases where we know a buffer's /address/ can escape.
1412 // Note that the above checks handle some special cases where we know that
1413 // even though the address escapes, it's still our responsibility to free the
1414 // buffer.
1415 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001416 return false;
1417
1418 // Otherwise, assume that the function does not free memory.
1419 // Most system calls do not free the memory.
1420 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001421}
1422
Anna Zaks4fb54872012-02-11 21:02:35 +00001423// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1424// escapes, when we are tracking p), do not track the symbol as we cannot reason
1425// about it anymore.
1426ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001427MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001428 const StoreManager::InvalidatedSymbols *invalidated,
1429 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001430 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001431 const CallEvent *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001432 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001433 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001434 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001435
Anna Zaks66c40402012-02-14 21:55:24 +00001436 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001437 // regions (explicit and implicit) escaped.
1438
1439 // Otherwise, whitelist explicit pointers; we still can track them.
1440 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001441 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1442 E = ExplicitRegions.end(); I != E; ++I) {
1443 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1444 WhitelistedSymbols.insert(R->getSymbol());
1445 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001446 }
1447
1448 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1449 E = invalidated->end(); I!=E; ++I) {
1450 SymbolRef sym = *I;
1451 if (WhitelistedSymbols.count(sym))
1452 continue;
Anna Zaks5b7aa342012-06-22 02:04:31 +00001453 // The symbol escaped. Note, we assume that if the symbol is released,
1454 // passing it out will result in a use after free. We also keep tracking
1455 // relinquished symbols.
1456 if (const RefState *RS = State->get<RegionState>(sym)) {
1457 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001458 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001459 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001460 }
Anna Zaks66c40402012-02-14 21:55:24 +00001461 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001462}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001463
Jordy Rose393f98b2012-03-18 07:43:35 +00001464static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1465 ProgramStateRef prevState) {
1466 ReallocMap currMap = currState->get<ReallocPairs>();
1467 ReallocMap prevMap = prevState->get<ReallocPairs>();
1468
1469 for (ReallocMap::iterator I = prevMap.begin(), E = prevMap.end();
1470 I != E; ++I) {
1471 SymbolRef sym = I.getKey();
1472 if (!currMap.lookup(sym))
1473 return sym;
1474 }
1475
1476 return NULL;
1477}
1478
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001479PathDiagnosticPiece *
1480MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1481 const ExplodedNode *PrevN,
1482 BugReporterContext &BRC,
1483 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001484 ProgramStateRef state = N->getState();
1485 ProgramStateRef statePrev = PrevN->getState();
1486
1487 const RefState *RS = state->get<RegionState>(Sym);
1488 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001489 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001490 return 0;
1491
Anna Zaksfe571602012-02-16 22:26:07 +00001492 const Stmt *S = 0;
1493 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001494 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001495
1496 // Retrieve the associated statement.
1497 ProgramPoint ProgLoc = N->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +00001498 if (StmtPoint *SP = dyn_cast<StmtPoint>(&ProgLoc))
1499 S = SP->getStmt();
1500 else if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&ProgLoc))
1501 S = Exit->getCalleeContext()->getCallSite();
Anna Zaksfe571602012-02-16 22:26:07 +00001502 // If an assumption was made on a branch, it should be caught
1503 // here by looking at the state transition.
Jordan Rose852aa0d2012-07-10 22:07:52 +00001504 else if (BlockEdge *Edge = dyn_cast<BlockEdge>(&ProgLoc)) {
1505 const CFGBlock *srcBlk = Edge->getSrc();
Anna Zaksfe571602012-02-16 22:26:07 +00001506 S = srcBlk->getTerminator();
1507 }
1508 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001509 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001510
Jordan Rose28038f32012-07-10 22:07:42 +00001511 // FIXME: We will eventually need to handle non-statement-based events
1512 // (__attribute__((cleanup))).
1513
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001514 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001515 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001516 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001517 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001518 StackHint = new StackHintGeneratorForSymbol(Sym,
1519 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001520 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001521 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001522 StackHint = new StackHintGeneratorForSymbol(Sym,
1523 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001524 } else if (isRelinquished(RS, RSPrev, S)) {
1525 Msg = "Memory ownership is transfered";
1526 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001527 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001528 Mode = ReallocationFailed;
1529 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001530 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001531 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001532
Jordy Roseb000fb52012-03-24 03:15:09 +00001533 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1534 // Is it possible to fail two reallocs WITHOUT testing in between?
1535 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1536 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001537 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001538 FailedReallocSymbol = sym;
1539 }
Anna Zaksfe571602012-02-16 22:26:07 +00001540 }
1541
1542 // We are in a special mode if a reallocation failed later in the path.
1543 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001544 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001545
Jordy Roseb000fb52012-03-24 03:15:09 +00001546 // Is this is the first appearance of the reallocated symbol?
1547 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001548 // We're at the reallocation point.
1549 Msg = "Attempt to reallocate memory";
1550 StackHint = new StackHintGeneratorForSymbol(Sym,
1551 "Returned reallocated memory");
1552 FailedReallocSymbol = NULL;
1553 Mode = Normal;
1554 }
Anna Zaksfe571602012-02-16 22:26:07 +00001555 }
1556
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001557 if (!Msg)
1558 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001559 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001560
1561 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001562 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001563 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001564 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001565}
1566
Anna Zaks93c5a242012-05-02 00:05:20 +00001567void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1568 const char *NL, const char *Sep) const {
1569
1570 RegionStateTy RS = State->get<RegionState>();
1571
1572 if (!RS.isEmpty())
1573 Out << "Has Malloc data" << NL;
1574}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001575
Anna Zaks231361a2012-02-08 23:16:52 +00001576#define REGISTER_CHECKER(name) \
1577void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001578 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001579 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001580}
Anna Zaks231361a2012-02-08 23:16:52 +00001581
1582REGISTER_CHECKER(MallocPessimistic)
1583REGISTER_CHECKER(MallocOptimistic)