blob: 4f19c2ee079eeb518f56bc6c85a8e27c88407955 [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,
41 // Reference to escaped memory - no assumptions can be made of
42 // the state after the reference escapes.
43 Escaped,
44 // The responsibility for freeing resources has transfered from
45 // this reference. A relinquished symbol should not be freed.
Ted Kremenekdde201b2010-08-06 21:12:55 +000046 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000047 const Stmt *S;
48
Zhongxing Xu7fb14642009-12-11 00:55:44 +000049public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000050 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
51
Anna Zaks050cdd72012-06-20 20:57:46 +000052 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000053 bool isReleased() const { return K == Released; }
Anna Zaks050cdd72012-06-20 20:57:46 +000054 bool isRelinquished() const { return K == Relinquished; }
Anna Zaksca23eb22012-02-29 18:42:47 +000055
Anna Zaksc8bb3be2012-02-13 18:05:39 +000056 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000057
58 bool operator==(const RefState &X) const {
59 return K == X.K && S == X.S;
60 }
61
Anna Zaks050cdd72012-06-20 20:57:46 +000062 static RefState getAllocated(const Stmt *s) {
63 return RefState(Allocated, s);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000064 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000065 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
66 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000067 static RefState getRelinquished(const Stmt *s) {
68 return RefState(Relinquished, s);
69 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000070
71 void Profile(llvm::FoldingSetNodeID &ID) const {
72 ID.AddInteger(K);
73 ID.AddPointer(S);
74 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000075};
76
Anna Zaks40add292012-02-15 00:11:25 +000077struct ReallocPair {
78 SymbolRef ReallocatedSym;
79 bool IsFreeOnFailure;
80 ReallocPair(SymbolRef S, bool F) : ReallocatedSym(S), IsFreeOnFailure(F) {}
81 void Profile(llvm::FoldingSetNodeID &ID) const {
82 ID.AddInteger(IsFreeOnFailure);
83 ID.AddPointer(ReallocatedSym);
84 }
85 bool operator==(const ReallocPair &X) const {
86 return ReallocatedSym == X.ReallocatedSym &&
87 IsFreeOnFailure == X.IsFreeOnFailure;
88 }
89};
90
Anna Zaks3d7c44e2012-03-21 19:45:08 +000091typedef std::pair<const Stmt*, const MemRegion*> LeakInfo;
92
Anna Zaksb319e022012-02-08 20:13:28 +000093class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000094 check::EndPath,
95 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +000096 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +000097 check::PostStmt<CallExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +000098 check::PostStmt<BlockExpr>,
Anna Zaks5b7aa342012-06-22 02:04:31 +000099 check::PreObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000100 check::Location,
101 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +0000102 eval::Assume,
103 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000104{
Anna Zaksfebdc322012-02-16 22:26:12 +0000105 mutable OwningPtr<BugType> BT_DoubleFree;
106 mutable OwningPtr<BugType> BT_Leak;
107 mutable OwningPtr<BugType> BT_UseFree;
108 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000109 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000110 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
111
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000112public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000113 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000114 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000115
116 /// In pessimistic mode, the checker assumes that it does not know which
117 /// functions might free the memory.
118 struct ChecksFilter {
119 DefaultBool CMallocPessimistic;
120 DefaultBool CMallocOptimistic;
121 };
122
123 ChecksFilter Filter;
124
Anna Zaks66c40402012-02-14 21:55:24 +0000125 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000126 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Jordan Rosede507ea2012-07-02 19:28:04 +0000127 void checkPreObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000128 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000129 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000130 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000131 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000132 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000133 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000134 void checkLocation(SVal l, bool isLoad, const Stmt *S,
135 CheckerContext &C) const;
136 void checkBind(SVal location, SVal val, const Stmt*S,
137 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000138 ProgramStateRef
139 checkRegionChanges(ProgramStateRef state,
140 const StoreManager::InvalidatedSymbols *invalidated,
141 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000142 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +0000143 const CallEvent *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000144 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
145 return true;
146 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000147
Anna Zaks93c5a242012-05-02 00:05:20 +0000148 void printState(raw_ostream &Out, ProgramStateRef State,
149 const char *NL, const char *Sep) const;
150
Zhongxing Xu7b760962009-11-13 07:25:27 +0000151private:
Anna Zaks66c40402012-02-14 21:55:24 +0000152 void initIdentifierInfo(ASTContext &C) const;
153
154 /// Check if this is one of the functions which can allocate/reallocate memory
155 /// pointed to by one of its arguments.
156 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000157 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
158 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000159
Anna Zaks87cb5be2012-02-22 19:24:52 +0000160 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
161 const CallExpr *CE,
162 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000163 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000164 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000165 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000166 return MallocMemAux(C, CE,
167 state->getSVal(SizeEx, C.getLocationContext()),
168 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000169 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000170
Ted Kremenek8bef8232012-01-26 21:29:00 +0000171 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000172 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000173 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000174
Anna Zaks87cb5be2012-02-22 19:24:52 +0000175 /// Update the RefState to reflect the new memory allocation.
176 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
177 const CallExpr *CE,
178 ProgramStateRef state);
179
180 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
181 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000182 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000183 ProgramStateRef state, unsigned Num,
184 bool Hold) const;
185 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
186 const Expr *ParentExpr,
187 ProgramStateRef state,
188 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000189
Anna Zaks87cb5be2012-02-22 19:24:52 +0000190 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
191 bool FreesMemOnFailure) const;
192 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000193
Anna Zaks14345182012-05-18 01:16:10 +0000194 ///\brief Check if the memory associated with this symbol was released.
195 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
196
Anna Zaks91c2a112012-02-08 23:16:56 +0000197 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
198 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
199 const Stmt *S = 0) const;
200
Anna Zaks66c40402012-02-14 21:55:24 +0000201 /// Check if the function is not known to us. So, for example, we could
202 /// conservatively assume it can free/reallocate it's pointer arguments.
Jordan Rose740d4902012-07-02 19:27:35 +0000203 bool doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000204 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000205
Ted Kremenek9c378f72011-08-12 23:37:29 +0000206 static bool SummarizeValue(raw_ostream &os, SVal V);
207 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000208 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000209
Anna Zaksca8e36e2012-02-23 21:38:21 +0000210 /// Find the location of the allocation for Sym on the path leading to the
211 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000212 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
213 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000214
Anna Zaksda046772012-02-11 21:02:40 +0000215 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
216
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000217 /// The bug visitor which allows us to print extra diagnostics along the
218 /// BugReport path. For example, showing the allocation site of the leaked
219 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000220 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000221 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000222 enum NotificationMode {
223 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000224 ReallocationFailed
225 };
226
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000227 // The allocated region symbol tracked by the main analysis.
228 SymbolRef Sym;
229
Anna Zaks88feba02012-05-10 01:37:40 +0000230 // The mode we are in, i.e. what kind of diagnostics will be emitted.
231 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000232
Anna Zaks88feba02012-05-10 01:37:40 +0000233 // A symbol from when the primary region should have been reallocated.
234 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000235
Anna Zaks88feba02012-05-10 01:37:40 +0000236 bool IsLeak;
237
238 public:
239 MallocBugVisitor(SymbolRef S, bool isLeak = false)
240 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000241
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000242 virtual ~MallocBugVisitor() {}
243
244 void Profile(llvm::FoldingSetNodeID &ID) const {
245 static int X = 0;
246 ID.AddPointer(&X);
247 ID.AddPointer(Sym);
248 }
249
Anna Zaksfe571602012-02-16 22:26:07 +0000250 inline bool isAllocated(const RefState *S, const RefState *SPrev,
251 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000252 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000253 return (Stmt && isa<CallExpr>(Stmt) &&
254 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000255 }
256
Anna Zaksfe571602012-02-16 22:26:07 +0000257 inline bool isReleased(const RefState *S, const RefState *SPrev,
258 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000259 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000260 return (Stmt && isa<CallExpr>(Stmt) &&
261 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
262 }
263
Anna Zaks5b7aa342012-06-22 02:04:31 +0000264 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
265 const Stmt *Stmt) {
266 // Did not track -> relinquished. Other state (allocated) -> relinquished.
267 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
268 isa<ObjCPropertyRefExpr>(Stmt)) &&
269 (S && S->isRelinquished()) &&
270 (!SPrev || !SPrev->isRelinquished()));
271 }
272
Anna Zaksfe571602012-02-16 22:26:07 +0000273 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
274 const Stmt *Stmt) {
275 // If the expression is not a call, and the state change is
276 // released -> allocated, it must be the realloc return value
277 // check. If we have to handle more cases here, it might be cleaner just
278 // to track this extra bit in the state itself.
279 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
280 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000281 }
282
283 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
284 const ExplodedNode *PrevN,
285 BugReporterContext &BRC,
286 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000287
288 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
289 const ExplodedNode *EndPathNode,
290 BugReport &BR) {
291 if (!IsLeak)
292 return 0;
293
294 PathDiagnosticLocation L =
295 PathDiagnosticLocation::createEndOfPath(EndPathNode,
296 BRC.getSourceManager());
297 // Do not add the statement itself as a range in case of leak.
298 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
299 }
300
Anna Zaks56a938f2012-03-16 23:24:20 +0000301 private:
302 class StackHintGeneratorForReallocationFailed
303 : public StackHintGeneratorForSymbol {
304 public:
305 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
306 : StackHintGeneratorForSymbol(S, M) {}
307
308 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
309 SmallString<200> buf;
310 llvm::raw_svector_ostream os(buf);
311
Anna Zaksfbd58742012-03-16 23:44:28 +0000312 os << "Reallocation of ";
Anna Zaks56a938f2012-03-16 23:24:20 +0000313 // Printed parameters start at 1, not 0.
314 printOrdinal(++ArgIndex, os);
315 os << " parameter failed";
316
317 return os.str();
318 }
319
320 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000321 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000322 }
323 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000324 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000325};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000326} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000327
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000328typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000329typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000330class RegionState {};
331class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000332namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000333namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000334 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000335 struct ProgramStateTrait<RegionState>
336 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000337 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000338 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000339
340 template <>
341 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000342 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000343 static void *GDMIndex() { static int x; return &x; }
344 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000345}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000346}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000347
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 {
434 const FunctionDecl *FD = C.getCalleeDecl(CE);
435 if (!FD)
436 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000437
Anna Zaks87cb5be2012-02-22 19:24:52 +0000438 ProgramStateRef State = C.getState();
Jordan Rose5ef6e942012-07-10 23:13:01 +0000439
440 if (FD->getKind() == Decl::Function) {
441 initIdentifierInfo(C.getASTContext());
442 IdentifierInfo *FunI = FD->getIdentifier();
443
444 if (FunI == II_malloc || FunI == II_valloc) {
445 if (CE->getNumArgs() < 1)
446 return;
447 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
448 } else if (FunI == II_realloc) {
449 State = ReallocMem(C, CE, false);
450 } else if (FunI == II_reallocf) {
451 State = ReallocMem(C, CE, true);
452 } else if (FunI == II_calloc) {
453 State = CallocMem(C, CE);
454 } else if (FunI == II_free) {
455 State = FreeMemAux(C, CE, State, 0, false);
456 } else if (FunI == II_strdup) {
457 State = MallocUpdateRefState(C, CE, State);
458 } else if (FunI == II_strndup) {
459 State = MallocUpdateRefState(C, CE, State);
460 }
461 }
462
463 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000464 // Check all the attributes, if there are any.
465 // There can be multiple of these attributes.
466 if (FD->hasAttrs())
467 for (specific_attr_iterator<OwnershipAttr>
468 i = FD->specific_attr_begin<OwnershipAttr>(),
469 e = FD->specific_attr_end<OwnershipAttr>();
470 i != e; ++i) {
471 switch ((*i)->getOwnKind()) {
472 case OwnershipAttr::Returns:
473 State = MallocMemReturnsAttr(C, CE, *i);
474 break;
475 case OwnershipAttr::Takes:
476 case OwnershipAttr::Holds:
477 State = FreeMemAttr(C, CE, *i);
478 break;
479 }
480 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000481 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000482 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000483}
484
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000485static bool isFreeWhenDoneSetToZero(const ObjCMethodCall &Call) {
486 Selector S = Call.getSelector();
Anna Zaks3e4f65d2012-06-22 22:08:09 +0000487 for (unsigned i = 1; i < S.getNumArgs(); ++i)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000488 if (S.getNameForSlot(i).equals("freeWhenDone"))
489 if (Call.getArgSVal(i).isConstant(0))
490 return true;
491
492 return false;
493}
494
Jordan Rosede507ea2012-07-02 19:28:04 +0000495void MallocChecker::checkPreObjCMessage(const ObjCMethodCall &Call,
Jordan Rose740d4902012-07-02 19:27:35 +0000496 CheckerContext &C) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000497 // If the first selector is dataWithBytesNoCopy, assume that the memory will
498 // be released with 'free' by the new object.
499 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
500 // Unless 'freeWhenDone' param set to 0.
501 // TODO: Check that the memory was allocated with malloc.
Jordan Rosede507ea2012-07-02 19:28:04 +0000502 Selector S = Call.getSelector();
Anna Zaks7186dc62012-06-22 22:42:30 +0000503 if ((S.getNameForSlot(0) == "dataWithBytesNoCopy" ||
504 S.getNameForSlot(0) == "initWithBytesNoCopy" ||
505 S.getNameForSlot(0) == "initWithCharactersNoCopy") &&
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000506 !isFreeWhenDoneSetToZero(Call)){
Anna Zaks5b7aa342012-06-22 02:04:31 +0000507 unsigned int argIdx = 0;
Jordan Rose740d4902012-07-02 19:27:35 +0000508 C.addTransition(FreeMemAux(C, Call.getArgExpr(argIdx),
Jordan Rosede507ea2012-07-02 19:28:04 +0000509 Call.getOriginExpr(), C.getState(), true));
Anna Zaks5b7aa342012-06-22 02:04:31 +0000510 }
511}
512
Anna Zaks87cb5be2012-02-22 19:24:52 +0000513ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
514 const CallExpr *CE,
515 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000516 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000517 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000518
Sean Huntcf807c42010-08-18 23:23:40 +0000519 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000520 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000521 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000522 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000523 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000524}
525
Anna Zaksb319e022012-02-08 20:13:28 +0000526ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000527 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000528 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000529 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000530
531 // Bind the return value to the symbolic value from the heap region.
532 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
533 // side effects other than what we model here.
534 unsigned Count = C.getCurrentBlockCount();
535 SValBuilder &svalBuilder = C.getSValBuilder();
536 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
537 DefinedSVal RetVal =
538 cast<DefinedSVal>(svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count));
539 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000540
Anna Zaksb16ce452012-02-15 00:11:22 +0000541 // We expect the malloc functions to return a pointer.
Anna Zakse17fdb22012-06-07 03:57:32 +0000542 if (!isa<Loc>(RetVal))
Anna Zaksb16ce452012-02-15 00:11:22 +0000543 return 0;
544
Jordy Rose32f26562010-07-04 00:00:41 +0000545 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000546 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000547
Jordy Rose32f26562010-07-04 00:00:41 +0000548 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000549 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000550 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000551 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000552 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000553 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000554 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000555 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
556 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
557 DefinedOrUnknownSVal extentMatchesSize =
558 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000559
Anna Zaks60a1fa42012-02-22 03:14:20 +0000560 state = state->assume(extentMatchesSize, true);
561 assert(state);
562 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000563
Anna Zaks87cb5be2012-02-22 19:24:52 +0000564 return MallocUpdateRefState(C, CE, state);
565}
566
567ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
568 const CallExpr *CE,
569 ProgramStateRef state) {
570 // Get the return value.
571 SVal retVal = state->getSVal(CE, C.getLocationContext());
572
573 // We expect the malloc functions to return a pointer.
574 if (!isa<Loc>(retVal))
575 return 0;
576
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000577 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000578 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000579
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000580 // Set the symbol's state to Allocated.
Anna Zaks050cdd72012-06-20 20:57:46 +0000581 return state->set<RegionState>(Sym, RefState::getAllocated(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000582
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000583}
584
Anna Zaks87cb5be2012-02-22 19:24:52 +0000585ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
586 const CallExpr *CE,
587 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000588 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000589 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000590
Anna Zaksb3d72752012-03-01 22:06:06 +0000591 ProgramStateRef State = C.getState();
592
Sean Huntcf807c42010-08-18 23:23:40 +0000593 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
594 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000595 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
596 Att->getOwnKind() == OwnershipAttr::Holds);
597 if (StateI)
598 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000599 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000600 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000601}
602
Ted Kremenek8bef8232012-01-26 21:29:00 +0000603ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000604 const CallExpr *CE,
605 ProgramStateRef state,
606 unsigned Num,
607 bool Hold) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000608 if (CE->getNumArgs() < (Num + 1))
609 return 0;
610
Anna Zaks5b7aa342012-06-22 02:04:31 +0000611 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold);
612}
613
614ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
615 const Expr *ArgExpr,
616 const Expr *ParentExpr,
617 ProgramStateRef state,
618 bool Hold) const {
619
Ted Kremenek5eca4822012-01-06 22:09:28 +0000620 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000621 if (!isa<DefinedOrUnknownSVal>(ArgVal))
622 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000623 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
624
625 // Check for null dereferences.
626 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000627 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000628
Anna Zaksb276bd92012-02-14 00:26:13 +0000629 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000630 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000631 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000632 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000633 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000634
Jordy Rose43859f62010-06-07 19:32:37 +0000635 // Unknown values could easily be okay
636 // Undefined values are handled elsewhere
637 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000638 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000639
Jordy Rose43859f62010-06-07 19:32:37 +0000640 const MemRegion *R = ArgVal.getAsRegion();
641
642 // Nonlocs can't be freed, of course.
643 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
644 if (!R) {
645 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000646 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000647 }
648
649 R = R->StripCasts();
650
651 // Blocks might show up as heap data, but should not be free()d
652 if (isa<BlockDataRegion>(R)) {
653 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000654 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000655 }
656
657 const MemSpaceRegion *MS = R->getMemorySpace();
658
659 // Parameters, locals, statics, and globals shouldn't be freed.
660 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
661 // FIXME: at the time this code was written, malloc() regions were
662 // represented by conjured symbols, which are all in UnknownSpaceRegion.
663 // This means that there isn't actually anything from HeapSpaceRegion
664 // that should be freed, even though we allow it here.
665 // Of course, free() can work on memory allocated outside the current
666 // function, so UnknownSpaceRegion is always a possibility.
667 // False negatives are better than false positives.
668
669 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000670 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000671 }
672
673 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
674 // Various cases could lead to non-symbol values here.
675 // For now, ignore them.
676 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000677 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000678
679 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000680 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000681
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000682 // Check double free.
Anna Zaksede875b2012-08-03 18:30:18 +0000683 if (RS && (RS->isReleased() || RS->isRelinquished())) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000684 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000685 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000686 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000687 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000688 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000689 (RS->isReleased() ? "Attempt to free released memory" :
690 "Attempt to free non-owned memory"), N);
Anna Zaksfe571602012-02-16 22:26:07 +0000691 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000692 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000693 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000694 C.EmitReport(R);
695 }
Anna Zaksb319e022012-02-08 20:13:28 +0000696 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000697 }
698
699 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000700 if (Hold)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000701 return state->set<RegionState>(Sym, RefState::getRelinquished(ParentExpr));
702 return state->set<RegionState>(Sym, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000703}
704
Ted Kremenek9c378f72011-08-12 23:37:29 +0000705bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000706 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
707 os << "an integer (" << IntVal->getValue() << ")";
708 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
709 os << "a constant address (" << ConstAddr->getValue() << ")";
710 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000711 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000712 else
713 return false;
714
715 return true;
716}
717
Ted Kremenek9c378f72011-08-12 23:37:29 +0000718bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000719 const MemRegion *MR) {
720 switch (MR->getKind()) {
721 case MemRegion::FunctionTextRegionKind: {
722 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
723 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000724 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000725 else
726 os << "the address of a function";
727 return true;
728 }
729 case MemRegion::BlockTextRegionKind:
730 os << "block text";
731 return true;
732 case MemRegion::BlockDataRegionKind:
733 // FIXME: where the block came from?
734 os << "a block";
735 return true;
736 default: {
737 const MemSpaceRegion *MS = MR->getMemorySpace();
738
Anna Zakseb31a762012-01-04 23:54:01 +0000739 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000740 const VarRegion *VR = dyn_cast<VarRegion>(MR);
741 const VarDecl *VD;
742 if (VR)
743 VD = VR->getDecl();
744 else
745 VD = NULL;
746
747 if (VD)
748 os << "the address of the local variable '" << VD->getName() << "'";
749 else
750 os << "the address of a local stack variable";
751 return true;
752 }
Anna Zakseb31a762012-01-04 23:54:01 +0000753
754 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000755 const VarRegion *VR = dyn_cast<VarRegion>(MR);
756 const VarDecl *VD;
757 if (VR)
758 VD = VR->getDecl();
759 else
760 VD = NULL;
761
762 if (VD)
763 os << "the address of the parameter '" << VD->getName() << "'";
764 else
765 os << "the address of a parameter";
766 return true;
767 }
Anna Zakseb31a762012-01-04 23:54:01 +0000768
769 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000770 const VarRegion *VR = dyn_cast<VarRegion>(MR);
771 const VarDecl *VD;
772 if (VR)
773 VD = VR->getDecl();
774 else
775 VD = NULL;
776
777 if (VD) {
778 if (VD->isStaticLocal())
779 os << "the address of the static variable '" << VD->getName() << "'";
780 else
781 os << "the address of the global variable '" << VD->getName() << "'";
782 } else
783 os << "the address of a global variable";
784 return true;
785 }
Anna Zakseb31a762012-01-04 23:54:01 +0000786
787 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000788 }
789 }
790}
791
792void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000793 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000794 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000795 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000796 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000797
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000798 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000799 llvm::raw_svector_ostream os(buf);
800
801 const MemRegion *MR = ArgVal.getAsRegion();
802 if (MR) {
803 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
804 MR = ER->getSuperRegion();
805
806 // Special case for alloca()
807 if (isa<AllocaRegion>(MR))
808 os << "Argument to free() was allocated by alloca(), not malloc()";
809 else {
810 os << "Argument to free() is ";
811 if (SummarizeRegion(os, MR))
812 os << ", which is not memory allocated by malloc()";
813 else
814 os << "not memory allocated by malloc()";
815 }
816 } else {
817 os << "Argument to free() is ";
818 if (SummarizeValue(os, ArgVal))
819 os << ", which is not memory allocated by malloc()";
820 else
821 os << "not memory allocated by malloc()";
822 }
823
Anna Zakse172e8b2011-08-17 23:00:25 +0000824 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000825 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000826 R->addRange(range);
827 C.EmitReport(R);
828 }
829}
830
Anna Zaks87cb5be2012-02-22 19:24:52 +0000831ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
832 const CallExpr *CE,
833 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000834 if (CE->getNumArgs() < 2)
835 return 0;
836
Ted Kremenek8bef8232012-01-26 21:29:00 +0000837 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000838 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000839 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000840 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
841 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000842 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000843 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000844
Ted Kremenek846eabd2010-12-01 21:28:31 +0000845 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000846
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000847 DefinedOrUnknownSVal PtrEQ =
848 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000849
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000850 // Get the size argument. If there is no size arg then give up.
851 const Expr *Arg1 = CE->getArg(1);
852 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000853 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000854
855 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000856 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
857 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000858 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000859 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000860
861 // Compare the size argument to 0.
862 DefinedOrUnknownSVal SizeZero =
863 svalBuilder.evalEQ(state, Arg1Val,
864 svalBuilder.makeIntValWithPtrWidth(0, false));
865
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000866 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
867 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
868 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
869 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
870 // We only assume exceptional states if they are definitely true; if the
871 // state is under-constrained, assume regular realloc behavior.
872 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
873 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
874
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000875 // If the ptr is NULL and the size is not 0, the call is equivalent to
876 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000877 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000878 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000879 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000880 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000881 }
882
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000883 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000884 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000885
Anna Zaks30838b92012-02-13 20:57:07 +0000886 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000887 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000888 SymbolRef FromPtr = arg0Val.getAsSymbol();
889 SVal RetVal = state->getSVal(CE, LCtx);
890 SymbolRef ToPtr = RetVal.getAsSymbol();
891 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000892 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000893
894 // If the size is 0, free the memory.
895 if (SizeIsZero)
896 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000897 // The semantics of the return value are:
898 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +0000899 // to free() is returned. We just free the input pointer and do not add
900 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +0000901 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000902 }
903
904 // Default behavior.
905 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
906 // FIXME: We should copy the content of the original buffer.
907 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
908 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000909 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000910 return 0;
Anna Zaks40add292012-02-15 00:11:25 +0000911 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
912 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000913 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000914 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000915 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000916 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000917}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000918
Anna Zaks87cb5be2012-02-22 19:24:52 +0000919ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +0000920 if (CE->getNumArgs() < 2)
921 return 0;
922
Ted Kremenek8bef8232012-01-26 21:29:00 +0000923 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000924 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000925 const LocationContext *LCtx = C.getLocationContext();
926 SVal count = state->getSVal(CE->getArg(0), LCtx);
927 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000928 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
929 svalBuilder.getContext().getSizeType());
930 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000931
Anna Zaks87cb5be2012-02-22 19:24:52 +0000932 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000933}
934
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000935LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +0000936MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
937 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000938 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000939 // Walk the ExplodedGraph backwards and find the first node that referred to
940 // the tracked symbol.
941 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000942 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000943
944 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000945 ProgramStateRef State = N->getState();
946 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +0000947 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000948
949 // Find the most recent expression bound to the symbol in the current
950 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000951 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +0000952 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
953 SVal Val = State->getSVal(MR);
954 if (Val.getAsLocSymbol() == Sym)
955 ReferenceRegion = MR;
956 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000957 }
958
Anna Zaks7752d292012-02-27 23:40:55 +0000959 // Allocation node, is the last node in the current context in which the
960 // symbol was tracked.
961 if (N->getLocationContext() == LeakContext)
962 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000963 N = N->pred_empty() ? NULL : *(N->pred_begin());
964 }
965
966 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000967 const Stmt *AllocationStmt = 0;
Jordan Rose852aa0d2012-07-10 22:07:52 +0000968 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
969 AllocationStmt = Exit->getCalleeContext()->getCallSite();
970 else if (StmtPoint *SP = dyn_cast<StmtPoint>(&P))
971 AllocationStmt = SP->getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +0000972
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000973 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +0000974}
975
Anna Zaksda046772012-02-11 21:02:40 +0000976void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
977 CheckerContext &C) const {
978 assert(N);
979 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000980 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000981 // Leaks should not be reported if they are post-dominated by a sink:
982 // (1) Sinks are higher importance bugs.
983 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
984 // with __noreturn functions such as assert() or exit(). We choose not
985 // to report leaks on such paths.
986 BT_Leak->setSuppressOnSink(true);
987 }
988
Anna Zaksca8e36e2012-02-23 21:38:21 +0000989 // Most bug reports are cached at the location where they occurred.
990 // With leaks, we want to unique them by the location where they were
991 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +0000992 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000993 const Stmt *AllocStmt = 0;
994 const MemRegion *Region = 0;
995 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
996 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +0000997 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
998 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +0000999
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001000 SmallString<200> buf;
1001 llvm::raw_svector_ostream os(buf);
1002 os << "Memory is never released; potential leak";
1003 if (Region) {
1004 os << " of memory pointed to by '";
1005 Region->dumpPretty(os);
1006 os <<'\'';
1007 }
1008
1009 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001010 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001011 R->addVisitor(new MallocBugVisitor(Sym, true));
Anna Zaksda046772012-02-11 21:02:40 +00001012 C.EmitReport(R);
1013}
1014
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001015void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1016 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001017{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001018 if (!SymReaper.hasDeadSymbols())
1019 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001020
Ted Kremenek8bef8232012-01-26 21:29:00 +00001021 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001022 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001023 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001024
Ted Kremenek217470e2011-07-28 23:07:51 +00001025 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +00001026 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001027 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1028 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +00001029 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +00001030 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +00001031 Errors.push_back(I->first);
1032 }
Jordy Rose90760142010-08-18 04:33:47 +00001033 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001034 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001035
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001036 }
1037 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001038
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001039 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +00001040 ReallocMap RP = state->get<ReallocPairs>();
1041 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
1042 if (SymReaper.isDead(I->first) ||
1043 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001044 state = state->remove<ReallocPairs>(I->first);
1045 }
1046 }
1047
Anna Zaksca8e36e2012-02-23 21:38:21 +00001048 // Generate leak node.
1049 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1050 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +00001051
Anna Zaksca8e36e2012-02-23 21:38:21 +00001052 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +00001053 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +00001054 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
1055 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001056 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001057 }
Anna Zaksca8e36e2012-02-23 21:38:21 +00001058 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001059}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001060
Anna Zaksda046772012-02-11 21:02:40 +00001061void MallocChecker::checkEndPath(CheckerContext &C) const {
1062 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +00001063 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +00001064
Anna Zaksa19581a2012-02-20 22:25:23 +00001065 // If inside inlined call, skip it.
1066 if (C.getLocationContext()->getParent() != 0)
1067 return;
1068
Jordy Rose09cef092010-08-18 04:26:59 +00001069 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +00001070 RefState RS = I->second;
1071 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +00001072 ExplodedNode *N = C.addTransition(state);
1073 if (N)
1074 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +00001075 }
1076 }
1077}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001078
Anna Zaks91c2a112012-02-08 23:16:56 +00001079bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
1080 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001081 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +00001082 const RefState *RS = state->get<RegionState>(Sym);
1083 if (!RS)
1084 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001085
Anna Zaks91c2a112012-02-08 23:16:56 +00001086 if (RS->isAllocated()) {
1087 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
1088 C.addTransition(state);
1089 return true;
1090 }
1091 return false;
1092}
1093
Anna Zaks66c40402012-02-14 21:55:24 +00001094void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001095 // We will check for double free in the post visit.
1096 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001097 return;
1098
1099 // Check use after free, when a freed pointer is passed to a call.
1100 ProgramStateRef State = C.getState();
1101 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1102 E = CE->arg_end(); I != E; ++I) {
1103 const Expr *A = *I;
1104 if (A->getType().getTypePtr()->isAnyPointerType()) {
1105 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1106 if (!Sym)
1107 continue;
1108 if (checkUseAfterFree(Sym, C, A))
1109 return;
1110 }
1111 }
1112}
1113
Anna Zaks91c2a112012-02-08 23:16:56 +00001114void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1115 const Expr *E = S->getRetValue();
1116 if (!E)
1117 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001118
1119 // Check if we are returning a symbol.
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001120 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
1121 SymbolRef Sym = RetVal.getAsSymbol();
1122 if (!Sym)
1123 // If we are returning a field of the allocated struct or an array element,
1124 // the callee could still free the memory.
1125 // TODO: This logic should be a part of generic symbol escape callback.
1126 if (const MemRegion *MR = RetVal.getAsRegion())
1127 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1128 if (const SymbolicRegion *BMR =
1129 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1130 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001131 if (!Sym)
1132 return;
1133
Anna Zaks0860cd02012-02-11 21:44:39 +00001134 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +00001135 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +00001136 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001137
Anna Zaksa19581a2012-02-20 22:25:23 +00001138 // If this function body is not inlined, check if the symbol is escaping.
1139 if (C.getLocationContext()->getParent() == 0)
1140 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001141}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001142
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001143// TODO: Blocks should be either inlined or should call invalidate regions
1144// upon invocation. After that's in place, special casing here will not be
1145// needed.
1146void MallocChecker::checkPostStmt(const BlockExpr *BE,
1147 CheckerContext &C) const {
1148
1149 // Scan the BlockDecRefExprs for any object the retain count checker
1150 // may be tracking.
1151 if (!BE->getBlockDecl()->hasCaptures())
1152 return;
1153
1154 ProgramStateRef state = C.getState();
1155 const BlockDataRegion *R =
1156 cast<BlockDataRegion>(state->getSVal(BE,
1157 C.getLocationContext()).getAsRegion());
1158
1159 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1160 E = R->referenced_vars_end();
1161
1162 if (I == E)
1163 return;
1164
1165 SmallVector<const MemRegion*, 10> Regions;
1166 const LocationContext *LC = C.getLocationContext();
1167 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1168
1169 for ( ; I != E; ++I) {
1170 const VarRegion *VR = *I;
1171 if (VR->getSuperRegion() == R) {
1172 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1173 }
1174 Regions.push_back(VR);
1175 }
1176
1177 state =
1178 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1179 Regions.data() + Regions.size()).getState();
1180 C.addTransition(state);
1181}
1182
Anna Zaks14345182012-05-18 01:16:10 +00001183bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001184 assert(Sym);
1185 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001186 return (RS && RS->isReleased());
1187}
1188
1189bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1190 const Stmt *S) const {
1191 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001192 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001193 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001194 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001195
Anna Zaksfebdc322012-02-16 22:26:12 +00001196 BugReport *R = new BugReport(*BT_UseFree,
1197 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001198 if (S)
1199 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001200 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001201 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +00001202 C.EmitReport(R);
1203 return true;
1204 }
1205 }
1206 return false;
1207}
1208
Zhongxing Xuc8023782010-03-10 04:58:55 +00001209// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001210void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1211 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001212 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001213 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001214 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001215}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001216
Anna Zaks4fb54872012-02-11 21:02:35 +00001217//===----------------------------------------------------------------------===//
1218// Check various ways a symbol can be invalidated.
1219// TODO: This logic (the next 3 functions) is copied/similar to the
1220// RetainRelease checker. We might want to factor this out.
1221//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001222
Anna Zaks4fb54872012-02-11 21:02:35 +00001223// Stop tracking symbols when a value escapes as a result of checkBind.
1224// A value escapes in three possible cases:
1225// (1) we are binding to something that is not a memory region.
1226// (2) we are binding to a memregion that does not have stack storage
1227// (3) we are binding to a memregion with stack storage that the store
1228// does not understand.
1229void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1230 CheckerContext &C) const {
1231 // Are we storing to something that causes the value to "escape"?
1232 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001233 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001234
Anna Zaks4fb54872012-02-11 21:02:35 +00001235 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1236 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001237
Anna Zaks4fb54872012-02-11 21:02:35 +00001238 if (!escapes) {
1239 // To test (3), generate a new state with the binding added. If it is
1240 // the same state, then it escapes (since the store cannot represent
1241 // the binding).
Anna Zaks93c5a242012-05-02 00:05:20 +00001242 // Do this only if we know that the store is not supposed to generate the
1243 // same state.
1244 SVal StoredVal = state->getSVal(regionLoc->getRegion());
1245 if (StoredVal != val)
1246 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001247 }
Anna Zaksac593002012-02-16 03:40:57 +00001248 if (!escapes) {
1249 // Case 4: We do not currently model what happens when a symbol is
1250 // assigned to a struct field, so be conservative here and let the symbol
1251 // go. TODO: This could definitely be improved upon.
1252 escapes = !isa<VarRegion>(regionLoc->getRegion());
1253 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001254 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001255
1256 // If our store can represent the binding and we aren't storing to something
1257 // that doesn't have local storage then just return and have the simulation
1258 // state continue as is.
1259 if (!escapes)
1260 return;
1261
1262 // Otherwise, find all symbols referenced by 'val' that we are tracking
1263 // and stop tracking them.
1264 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1265 C.addTransition(state);
1266}
1267
1268// If a symbolic region is assumed to NULL (or another constant), stop tracking
1269// it - assuming that allocation failed on this path.
1270ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1271 SVal Cond,
1272 bool Assumption) const {
1273 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001274 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1275 // If the symbol is assumed to NULL or another constant, this will
1276 // return an APSInt*.
1277 if (state->getSymVal(I.getKey()))
1278 state = state->remove<RegionState>(I.getKey());
1279 }
1280
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001281 // Realloc returns 0 when reallocation fails, which means that we should
1282 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001283 ReallocMap RP = state->get<ReallocPairs>();
1284 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001285 // If the symbol is assumed to NULL or another constant, this will
1286 // return an APSInt*.
1287 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001288 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1289 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001290 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001291 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1292 state = state->set<RegionState>(ReallocSym,
Anna Zaks050cdd72012-06-20 20:57:46 +00001293 RefState::getAllocated(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001294 }
1295 state = state->remove<ReallocPairs>(I.getKey());
1296 }
1297 }
1298
Anna Zaks4fb54872012-02-11 21:02:35 +00001299 return state;
1300}
1301
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001302// Check if the function is known to us. So, for example, we could
Jordan Rose740d4902012-07-02 19:27:35 +00001303// conservatively assume it can free/reallocate its pointer arguments.
Anna Zaks66c40402012-02-14 21:55:24 +00001304// (We assume that the pointers cannot escape through calls to system
1305// functions not handled by this checker.)
Jordan Rose740d4902012-07-02 19:27:35 +00001306bool MallocChecker::doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001307 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001308 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001309
1310 // For now, assume that any C++ call can free memory.
1311 // TODO: If we want to be more optimistic here, we'll need to make sure that
1312 // regions escape to C++ containers. They seem to do that even now, but for
1313 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001314 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001315 return false;
1316
Jordan Rose740d4902012-07-02 19:27:35 +00001317 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001318 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001319 // If it's not a framework call, or if it takes a callback, assume it
1320 // can free memory.
1321 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001322 return false;
1323
Jordan Rose740d4902012-07-02 19:27:35 +00001324 Selector S = Msg->getSelector();
Anna Zaks52a04812012-06-20 23:35:57 +00001325
Jordan Rose740d4902012-07-02 19:27:35 +00001326 // Whitelist the ObjC methods which do free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001327 // - Anything containing 'freeWhenDone' param set to 1.
1328 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
Anna Zaks3e4f65d2012-06-22 22:08:09 +00001329 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001330 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1331 if (Call->getArgSVal(i).isConstant(1))
1332 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001333 else
1334 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001335 }
1336 }
1337
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001338 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001339 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001340 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
Jordan Rose740d4902012-07-02 19:27:35 +00001341 StringRef FirstSlot = S.getNameForSlot(0);
1342 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001343 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001344
Anna Zaks5f757682012-06-19 05:10:32 +00001345 // If the first selector starts with addPointer, insertPointer,
1346 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1347 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001348 // that the pointers get freed by following the container itself.
1349 if (FirstSlot.startswith("addPointer") ||
1350 FirstSlot.startswith("insertPointer") ||
1351 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001352 return false;
1353 }
1354
Jordan Rose740d4902012-07-02 19:27:35 +00001355 // Otherwise, assume that the method does not free memory.
1356 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001357 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001358 }
1359
Jordan Rose740d4902012-07-02 19:27:35 +00001360 // At this point the only thing left to handle is straight function calls.
1361 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1362 if (!FD)
1363 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001364
Jordan Rose740d4902012-07-02 19:27:35 +00001365 ASTContext &ASTC = State->getStateManager().getContext();
1366
1367 // If it's one of the allocation functions we can reason about, we model
1368 // its behavior explicitly.
1369 if (isMemFunction(FD, ASTC))
1370 return true;
1371
1372 // If it's not a system call, assume it frees memory.
1373 if (!Call->isInSystemHeader())
1374 return false;
1375
1376 // White list the system functions whose arguments escape.
1377 const IdentifierInfo *II = FD->getIdentifier();
1378 if (!II)
1379 return false;
1380 StringRef FName = II->getName();
1381
Jordan Rose740d4902012-07-02 19:27:35 +00001382 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001383 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001384 if (FName.endswith("NoCopy")) {
1385 // Look for the deallocator argument. We know that the memory ownership
1386 // is not transferred only if the deallocator argument is
1387 // 'kCFAllocatorNull'.
1388 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1389 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1390 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1391 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1392 if (DeallocatorName == "kCFAllocatorNull")
1393 return true;
1394 }
1395 }
1396 return false;
1397 }
1398
Jordan Rose740d4902012-07-02 19:27:35 +00001399 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001400 // 'closefn' is specified (and if that function does free memory),
1401 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001402 // Currently, we do not inspect the 'closefn' function (PR12101).
1403 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001404 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1405 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001406
1407 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1408 // these leaks might be intentional when setting the buffer for stdio.
1409 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1410 if (FName == "setbuf" || FName =="setbuffer" ||
1411 FName == "setlinebuf" || FName == "setvbuf") {
1412 if (Call->getNumArgs() >= 1) {
1413 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1414 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1415 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1416 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1417 return false;
1418 }
1419 }
1420
1421 // A bunch of other functions which either take ownership of a pointer or
1422 // wrap the result up in a struct or object, meaning it can be freed later.
1423 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1424 // but the Malloc checker cannot differentiate between them. The right way
1425 // of doing this would be to implement a pointer escapes callback.
1426 if (FName == "CGBitmapContextCreate" ||
1427 FName == "CGBitmapContextCreateWithData" ||
1428 FName == "CVPixelBufferCreateWithBytes" ||
1429 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1430 FName == "OSAtomicEnqueue") {
1431 return false;
1432 }
1433
Jordan Rose85d7e012012-07-02 19:27:51 +00001434 // Handle cases where we know a buffer's /address/ can escape.
1435 // Note that the above checks handle some special cases where we know that
1436 // even though the address escapes, it's still our responsibility to free the
1437 // buffer.
1438 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001439 return false;
1440
1441 // Otherwise, assume that the function does not free memory.
1442 // Most system calls do not free the memory.
1443 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001444}
1445
Anna Zaks4fb54872012-02-11 21:02:35 +00001446// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1447// escapes, when we are tracking p), do not track the symbol as we cannot reason
1448// about it anymore.
1449ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001450MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001451 const StoreManager::InvalidatedSymbols *invalidated,
1452 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001453 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001454 const CallEvent *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001455 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001456 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001457 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001458
Anna Zaks66c40402012-02-14 21:55:24 +00001459 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001460 // regions (explicit and implicit) escaped.
1461
1462 // Otherwise, whitelist explicit pointers; we still can track them.
1463 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001464 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1465 E = ExplicitRegions.end(); I != E; ++I) {
1466 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1467 WhitelistedSymbols.insert(R->getSymbol());
1468 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001469 }
1470
1471 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1472 E = invalidated->end(); I!=E; ++I) {
1473 SymbolRef sym = *I;
1474 if (WhitelistedSymbols.count(sym))
1475 continue;
Anna Zaks5b7aa342012-06-22 02:04:31 +00001476 // The symbol escaped. Note, we assume that if the symbol is released,
1477 // passing it out will result in a use after free. We also keep tracking
1478 // relinquished symbols.
1479 if (const RefState *RS = State->get<RegionState>(sym)) {
1480 if (RS->isAllocated())
1481 State = State->set<RegionState>(sym,
1482 RefState::getEscaped(RS->getStmt()));
1483 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001484 }
Anna Zaks66c40402012-02-14 21:55:24 +00001485 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001486}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001487
Jordy Rose393f98b2012-03-18 07:43:35 +00001488static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1489 ProgramStateRef prevState) {
1490 ReallocMap currMap = currState->get<ReallocPairs>();
1491 ReallocMap prevMap = prevState->get<ReallocPairs>();
1492
1493 for (ReallocMap::iterator I = prevMap.begin(), E = prevMap.end();
1494 I != E; ++I) {
1495 SymbolRef sym = I.getKey();
1496 if (!currMap.lookup(sym))
1497 return sym;
1498 }
1499
1500 return NULL;
1501}
1502
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001503PathDiagnosticPiece *
1504MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1505 const ExplodedNode *PrevN,
1506 BugReporterContext &BRC,
1507 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001508 ProgramStateRef state = N->getState();
1509 ProgramStateRef statePrev = PrevN->getState();
1510
1511 const RefState *RS = state->get<RegionState>(Sym);
1512 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001513 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001514 return 0;
1515
Anna Zaksfe571602012-02-16 22:26:07 +00001516 const Stmt *S = 0;
1517 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001518 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001519
1520 // Retrieve the associated statement.
1521 ProgramPoint ProgLoc = N->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +00001522 if (StmtPoint *SP = dyn_cast<StmtPoint>(&ProgLoc))
1523 S = SP->getStmt();
1524 else if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&ProgLoc))
1525 S = Exit->getCalleeContext()->getCallSite();
Anna Zaksfe571602012-02-16 22:26:07 +00001526 // If an assumption was made on a branch, it should be caught
1527 // here by looking at the state transition.
Jordan Rose852aa0d2012-07-10 22:07:52 +00001528 else if (BlockEdge *Edge = dyn_cast<BlockEdge>(&ProgLoc)) {
1529 const CFGBlock *srcBlk = Edge->getSrc();
Anna Zaksfe571602012-02-16 22:26:07 +00001530 S = srcBlk->getTerminator();
1531 }
1532 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001533 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001534
Jordan Rose28038f32012-07-10 22:07:42 +00001535 // FIXME: We will eventually need to handle non-statement-based events
1536 // (__attribute__((cleanup))).
1537
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001538 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001539 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001540 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001541 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001542 StackHint = new StackHintGeneratorForSymbol(Sym,
1543 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001544 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001545 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001546 StackHint = new StackHintGeneratorForSymbol(Sym,
1547 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001548 } else if (isRelinquished(RS, RSPrev, S)) {
1549 Msg = "Memory ownership is transfered";
1550 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001551 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001552 Mode = ReallocationFailed;
1553 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001554 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001555 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001556
Jordy Roseb000fb52012-03-24 03:15:09 +00001557 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1558 // Is it possible to fail two reallocs WITHOUT testing in between?
1559 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1560 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001561 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001562 FailedReallocSymbol = sym;
1563 }
Anna Zaksfe571602012-02-16 22:26:07 +00001564 }
1565
1566 // We are in a special mode if a reallocation failed later in the path.
1567 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001568 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001569
Jordy Roseb000fb52012-03-24 03:15:09 +00001570 // Is this is the first appearance of the reallocated symbol?
1571 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001572 // We're at the reallocation point.
1573 Msg = "Attempt to reallocate memory";
1574 StackHint = new StackHintGeneratorForSymbol(Sym,
1575 "Returned reallocated memory");
1576 FailedReallocSymbol = NULL;
1577 Mode = Normal;
1578 }
Anna Zaksfe571602012-02-16 22:26:07 +00001579 }
1580
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001581 if (!Msg)
1582 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001583 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001584
1585 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001586 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001587 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001588 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001589}
1590
Anna Zaks93c5a242012-05-02 00:05:20 +00001591void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1592 const char *NL, const char *Sep) const {
1593
1594 RegionStateTy RS = State->get<RegionState>();
1595
1596 if (!RS.isEmpty())
1597 Out << "Has Malloc data" << NL;
1598}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001599
Anna Zaks231361a2012-02-08 23:16:52 +00001600#define REGISTER_CHECKER(name) \
1601void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001602 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001603 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001604}
Anna Zaks231361a2012-02-08 23:16:52 +00001605
1606REGISTER_CHECKER(MallocPessimistic)
1607REGISTER_CHECKER(MallocOptimistic)