blob: 1adcca03fdcf91b8873258a8050f89c7fcf2789e [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"
Anna Zaks66c40402012-02-14 21:55:24 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.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 {
Ted Kremenekdde201b2010-08-06 21:12:55 +000037 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped,
38 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000039 const Stmt *S;
40
Zhongxing Xu7fb14642009-12-11 00:55:44 +000041public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000042 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
43
Zhongxing Xub94b81a2009-12-31 06:13:07 +000044 bool isAllocated() const { return K == AllocateUnchecked; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000045 bool isReleased() const { return K == Released; }
Anna Zaksca23eb22012-02-29 18:42:47 +000046
Anna Zaksc8bb3be2012-02-13 18:05:39 +000047 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000048
49 bool operator==(const RefState &X) const {
50 return K == X.K && S == X.S;
51 }
52
Zhongxing Xub94b81a2009-12-31 06:13:07 +000053 static RefState getAllocateUnchecked(const Stmt *s) {
54 return RefState(AllocateUnchecked, s);
55 }
56 static RefState getAllocateFailed() {
57 return RefState(AllocateFailed, 0);
58 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000059 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
60 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000061 static RefState getRelinquished(const Stmt *s) {
62 return RefState(Relinquished, s);
63 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000064
65 void Profile(llvm::FoldingSetNodeID &ID) const {
66 ID.AddInteger(K);
67 ID.AddPointer(S);
68 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000069};
70
Anna Zaks40add292012-02-15 00:11:25 +000071struct ReallocPair {
72 SymbolRef ReallocatedSym;
73 bool IsFreeOnFailure;
74 ReallocPair(SymbolRef S, bool F) : ReallocatedSym(S), IsFreeOnFailure(F) {}
75 void Profile(llvm::FoldingSetNodeID &ID) const {
76 ID.AddInteger(IsFreeOnFailure);
77 ID.AddPointer(ReallocatedSym);
78 }
79 bool operator==(const ReallocPair &X) const {
80 return ReallocatedSym == X.ReallocatedSym &&
81 IsFreeOnFailure == X.IsFreeOnFailure;
82 }
83};
84
Anna Zaks3d7c44e2012-03-21 19:45:08 +000085typedef std::pair<const Stmt*, const MemRegion*> LeakInfo;
86
Anna Zaksb319e022012-02-08 20:13:28 +000087class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000088 check::EndPath,
89 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +000090 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +000091 check::PostStmt<CallExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +000092 check::PostStmt<BlockExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000093 check::Location,
94 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +000095 eval::Assume,
96 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +000097{
Anna Zaksfebdc322012-02-16 22:26:12 +000098 mutable OwningPtr<BugType> BT_DoubleFree;
99 mutable OwningPtr<BugType> BT_Leak;
100 mutable OwningPtr<BugType> BT_UseFree;
101 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000102 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000103 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
104
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000105public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000106 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000107 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000108
109 /// In pessimistic mode, the checker assumes that it does not know which
110 /// functions might free the memory.
111 struct ChecksFilter {
112 DefaultBool CMallocPessimistic;
113 DefaultBool CMallocOptimistic;
114 };
115
116 ChecksFilter Filter;
117
Anna Zaks66c40402012-02-14 21:55:24 +0000118 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000119 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000120 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000121 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000122 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000123 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000124 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000125 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000126 void checkLocation(SVal l, bool isLoad, const Stmt *S,
127 CheckerContext &C) const;
128 void checkBind(SVal location, SVal val, const Stmt*S,
129 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000130 ProgramStateRef
131 checkRegionChanges(ProgramStateRef state,
132 const StoreManager::InvalidatedSymbols *invalidated,
133 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000134 ArrayRef<const MemRegion *> Regions,
135 const CallOrObjCMessage *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000136 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
137 return true;
138 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000139
Anna Zaks93c5a242012-05-02 00:05:20 +0000140 void printState(raw_ostream &Out, ProgramStateRef State,
141 const char *NL, const char *Sep) const;
142
Zhongxing Xu7b760962009-11-13 07:25:27 +0000143private:
Anna Zaks66c40402012-02-14 21:55:24 +0000144 void initIdentifierInfo(ASTContext &C) const;
145
146 /// Check if this is one of the functions which can allocate/reallocate memory
147 /// pointed to by one of its arguments.
148 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000149 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
150 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000151
Anna Zaks87cb5be2012-02-22 19:24:52 +0000152 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
153 const CallExpr *CE,
154 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000155 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000156 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000157 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000158 return MallocMemAux(C, CE,
159 state->getSVal(SizeEx, C.getLocationContext()),
160 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000161 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000162
Ted Kremenek8bef8232012-01-26 21:29:00 +0000163 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000164 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000165 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000166
Anna Zaks87cb5be2012-02-22 19:24:52 +0000167 /// Update the RefState to reflect the new memory allocation.
168 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
169 const CallExpr *CE,
170 ProgramStateRef state);
171
172 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
173 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000174 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
175 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000176 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000177
Anna Zaks87cb5be2012-02-22 19:24:52 +0000178 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
179 bool FreesMemOnFailure) const;
180 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000181
Anna Zaks14345182012-05-18 01:16:10 +0000182 ///\brief Check if the memory associated with this symbol was released.
183 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
184
Anna Zaks91c2a112012-02-08 23:16:56 +0000185 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
186 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
187 const Stmt *S = 0) const;
188
Anna Zaks66c40402012-02-14 21:55:24 +0000189 /// Check if the function is not known to us. So, for example, we could
190 /// conservatively assume it can free/reallocate it's pointer arguments.
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000191 bool doesNotFreeMemory(const CallOrObjCMessage *Call,
192 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000193
Ted Kremenek9c378f72011-08-12 23:37:29 +0000194 static bool SummarizeValue(raw_ostream &os, SVal V);
195 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000196 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000197
Anna Zaksca8e36e2012-02-23 21:38:21 +0000198 /// Find the location of the allocation for Sym on the path leading to the
199 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000200 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
201 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000202
Anna Zaksda046772012-02-11 21:02:40 +0000203 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
204
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000205 /// The bug visitor which allows us to print extra diagnostics along the
206 /// BugReport path. For example, showing the allocation site of the leaked
207 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000208 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000209 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000210 enum NotificationMode {
211 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000212 ReallocationFailed
213 };
214
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000215 // The allocated region symbol tracked by the main analysis.
216 SymbolRef Sym;
217
Anna Zaks88feba02012-05-10 01:37:40 +0000218 // The mode we are in, i.e. what kind of diagnostics will be emitted.
219 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000220
Anna Zaks88feba02012-05-10 01:37:40 +0000221 // A symbol from when the primary region should have been reallocated.
222 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000223
Anna Zaks88feba02012-05-10 01:37:40 +0000224 bool IsLeak;
225
226 public:
227 MallocBugVisitor(SymbolRef S, bool isLeak = false)
228 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000229
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000230 virtual ~MallocBugVisitor() {}
231
232 void Profile(llvm::FoldingSetNodeID &ID) const {
233 static int X = 0;
234 ID.AddPointer(&X);
235 ID.AddPointer(Sym);
236 }
237
Anna Zaksfe571602012-02-16 22:26:07 +0000238 inline bool isAllocated(const RefState *S, const RefState *SPrev,
239 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000240 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000241 return (Stmt && isa<CallExpr>(Stmt) &&
242 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000243 }
244
Anna Zaksfe571602012-02-16 22:26:07 +0000245 inline bool isReleased(const RefState *S, const RefState *SPrev,
246 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000247 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000248 return (Stmt && isa<CallExpr>(Stmt) &&
249 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
250 }
251
252 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
253 const Stmt *Stmt) {
254 // If the expression is not a call, and the state change is
255 // released -> allocated, it must be the realloc return value
256 // check. If we have to handle more cases here, it might be cleaner just
257 // to track this extra bit in the state itself.
258 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
259 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000260 }
261
262 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
263 const ExplodedNode *PrevN,
264 BugReporterContext &BRC,
265 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000266
267 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
268 const ExplodedNode *EndPathNode,
269 BugReport &BR) {
270 if (!IsLeak)
271 return 0;
272
273 PathDiagnosticLocation L =
274 PathDiagnosticLocation::createEndOfPath(EndPathNode,
275 BRC.getSourceManager());
276 // Do not add the statement itself as a range in case of leak.
277 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
278 }
279
Anna Zaks56a938f2012-03-16 23:24:20 +0000280 private:
281 class StackHintGeneratorForReallocationFailed
282 : public StackHintGeneratorForSymbol {
283 public:
284 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
285 : StackHintGeneratorForSymbol(S, M) {}
286
287 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
288 SmallString<200> buf;
289 llvm::raw_svector_ostream os(buf);
290
Anna Zaksfbd58742012-03-16 23:44:28 +0000291 os << "Reallocation of ";
Anna Zaks56a938f2012-03-16 23:24:20 +0000292 // Printed parameters start at 1, not 0.
293 printOrdinal(++ArgIndex, os);
294 os << " parameter failed";
295
296 return os.str();
297 }
298
299 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000300 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000301 }
302 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000303 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000304};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000305} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000306
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000307typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000308typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000309class RegionState {};
310class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000311namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000312namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000313 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000314 struct ProgramStateTrait<RegionState>
315 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000316 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000317 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000318
319 template <>
320 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000321 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000322 static void *GDMIndex() { static int x; return &x; }
323 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000324}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000325}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000326
Anna Zaks4fb54872012-02-11 21:02:35 +0000327namespace {
328class StopTrackingCallback : public SymbolVisitor {
329 ProgramStateRef state;
330public:
331 StopTrackingCallback(ProgramStateRef st) : state(st) {}
332 ProgramStateRef getState() const { return state; }
333
334 bool VisitSymbol(SymbolRef sym) {
335 state = state->remove<RegionState>(sym);
336 return true;
337 }
338};
339} // end anonymous namespace
340
Anna Zaks66c40402012-02-14 21:55:24 +0000341void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000342 if (II_malloc)
343 return;
344 II_malloc = &Ctx.Idents.get("malloc");
345 II_free = &Ctx.Idents.get("free");
346 II_realloc = &Ctx.Idents.get("realloc");
347 II_reallocf = &Ctx.Idents.get("reallocf");
348 II_calloc = &Ctx.Idents.get("calloc");
349 II_valloc = &Ctx.Idents.get("valloc");
350 II_strdup = &Ctx.Idents.get("strdup");
351 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000352}
353
Anna Zaks66c40402012-02-14 21:55:24 +0000354bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000355 if (isFreeFunction(FD, C))
356 return true;
357
358 if (isAllocationFunction(FD, C))
359 return true;
360
361 return false;
362}
363
364bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
365 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000366 if (!FD)
367 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000368
Anna Zaks66c40402012-02-14 21:55:24 +0000369 IdentifierInfo *FunI = FD->getIdentifier();
370 if (!FunI)
371 return false;
372
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000373 initIdentifierInfo(C);
374
Anna Zaks14345182012-05-18 01:16:10 +0000375 if (FunI == II_malloc || FunI == II_realloc ||
Anna Zaks60a1fa42012-02-22 03:14:20 +0000376 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
377 FunI == II_strdup || FunI == II_strndup)
Anna Zaks66c40402012-02-14 21:55:24 +0000378 return true;
379
Anna Zaks14345182012-05-18 01:16:10 +0000380 if (Filter.CMallocOptimistic && FD->hasAttrs())
381 for (specific_attr_iterator<OwnershipAttr>
382 i = FD->specific_attr_begin<OwnershipAttr>(),
383 e = FD->specific_attr_end<OwnershipAttr>();
384 i != e; ++i)
385 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
386 return true;
387 return false;
388}
389
390bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
391 if (!FD)
392 return false;
393
394 IdentifierInfo *FunI = FD->getIdentifier();
395 if (!FunI)
396 return false;
397
398 initIdentifierInfo(C);
399
400 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
Anna Zaks66c40402012-02-14 21:55:24 +0000401 return true;
402
Anna Zaks14345182012-05-18 01:16:10 +0000403 if (Filter.CMallocOptimistic && FD->hasAttrs())
404 for (specific_attr_iterator<OwnershipAttr>
405 i = FD->specific_attr_begin<OwnershipAttr>(),
406 e = FD->specific_attr_end<OwnershipAttr>();
407 i != e; ++i)
408 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
409 (*i)->getOwnKind() == OwnershipAttr::Holds)
410 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000411 return false;
412}
413
Anna Zaksb319e022012-02-08 20:13:28 +0000414void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
415 const FunctionDecl *FD = C.getCalleeDecl(CE);
416 if (!FD)
417 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000418
Anna Zaksb16ce452012-02-15 00:11:22 +0000419 initIdentifierInfo(C.getASTContext());
420 IdentifierInfo *FunI = FD->getIdentifier();
421 if (!FunI)
422 return;
423
Anna Zaks87cb5be2012-02-22 19:24:52 +0000424 ProgramStateRef State = C.getState();
Anna Zaksb16ce452012-02-15 00:11:22 +0000425 if (FunI == II_malloc || FunI == II_valloc) {
Anna Zaks259052d2012-04-10 23:41:11 +0000426 if (CE->getNumArgs() < 1)
427 return;
Anna Zaks87cb5be2012-02-22 19:24:52 +0000428 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anna Zaksb16ce452012-02-15 00:11:22 +0000429 } else if (FunI == II_realloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000430 State = ReallocMem(C, CE, false);
Anna Zaks40add292012-02-15 00:11:25 +0000431 } else if (FunI == II_reallocf) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000432 State = ReallocMem(C, CE, true);
Anna Zaksb16ce452012-02-15 00:11:22 +0000433 } else if (FunI == II_calloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000434 State = CallocMem(C, CE);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000435 } else if (FunI == II_free) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000436 State = FreeMemAux(C, CE, C.getState(), 0, false);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000437 } else if (FunI == II_strdup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000438 State = MallocUpdateRefState(C, CE, State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000439 } else if (FunI == II_strndup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000440 State = MallocUpdateRefState(C, CE, State);
441 } else if (Filter.CMallocOptimistic) {
442 // Check all the attributes, if there are any.
443 // There can be multiple of these attributes.
444 if (FD->hasAttrs())
445 for (specific_attr_iterator<OwnershipAttr>
446 i = FD->specific_attr_begin<OwnershipAttr>(),
447 e = FD->specific_attr_end<OwnershipAttr>();
448 i != e; ++i) {
449 switch ((*i)->getOwnKind()) {
450 case OwnershipAttr::Returns:
451 State = MallocMemReturnsAttr(C, CE, *i);
452 break;
453 case OwnershipAttr::Takes:
454 case OwnershipAttr::Holds:
455 State = FreeMemAttr(C, CE, *i);
456 break;
457 }
458 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000459 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000460 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000461}
462
Anna Zaks87cb5be2012-02-22 19:24:52 +0000463ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
464 const CallExpr *CE,
465 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000466 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000467 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000468
Sean Huntcf807c42010-08-18 23:23:40 +0000469 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000470 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000471 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000472 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000473 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000474}
475
Anna Zaksb319e022012-02-08 20:13:28 +0000476ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000477 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000478 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000479 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000480
481 // Bind the return value to the symbolic value from the heap region.
482 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
483 // side effects other than what we model here.
484 unsigned Count = C.getCurrentBlockCount();
485 SValBuilder &svalBuilder = C.getSValBuilder();
486 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
487 DefinedSVal RetVal =
488 cast<DefinedSVal>(svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count));
489 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000490
Anna Zaksb16ce452012-02-15 00:11:22 +0000491 // We expect the malloc functions to return a pointer.
Anna Zakse17fdb22012-06-07 03:57:32 +0000492 if (!isa<Loc>(RetVal))
Anna Zaksb16ce452012-02-15 00:11:22 +0000493 return 0;
494
Jordy Rose32f26562010-07-04 00:00:41 +0000495 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000496 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000497
Jordy Rose32f26562010-07-04 00:00:41 +0000498 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000499 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000500 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000501 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000502 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000503 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000504 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000505 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
506 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
507 DefinedOrUnknownSVal extentMatchesSize =
508 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000509
Anna Zaks60a1fa42012-02-22 03:14:20 +0000510 state = state->assume(extentMatchesSize, true);
511 assert(state);
512 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000513
Anna Zaks87cb5be2012-02-22 19:24:52 +0000514 return MallocUpdateRefState(C, CE, state);
515}
516
517ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
518 const CallExpr *CE,
519 ProgramStateRef state) {
520 // Get the return value.
521 SVal retVal = state->getSVal(CE, C.getLocationContext());
522
523 // We expect the malloc functions to return a pointer.
524 if (!isa<Loc>(retVal))
525 return 0;
526
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000527 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000528 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000529
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000530 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000531 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000532
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000533}
534
Anna Zaks87cb5be2012-02-22 19:24:52 +0000535ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
536 const CallExpr *CE,
537 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000538 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000539 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000540
Anna Zaksb3d72752012-03-01 22:06:06 +0000541 ProgramStateRef State = C.getState();
542
Sean Huntcf807c42010-08-18 23:23:40 +0000543 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
544 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000545 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
546 Att->getOwnKind() == OwnershipAttr::Holds);
547 if (StateI)
548 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000549 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000550 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000551}
552
Ted Kremenek8bef8232012-01-26 21:29:00 +0000553ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000554 const CallExpr *CE,
555 ProgramStateRef state,
556 unsigned Num,
557 bool Hold) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000558 if (CE->getNumArgs() < (Num + 1))
559 return 0;
560
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000561 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000562 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000563 if (!isa<DefinedOrUnknownSVal>(ArgVal))
564 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000565 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
566
567 // Check for null dereferences.
568 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000569 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000570
Anna Zaksb276bd92012-02-14 00:26:13 +0000571 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000572 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000573 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000574 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000575 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000576
Jordy Rose43859f62010-06-07 19:32:37 +0000577 // Unknown values could easily be okay
578 // Undefined values are handled elsewhere
579 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000580 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000581
Jordy Rose43859f62010-06-07 19:32:37 +0000582 const MemRegion *R = ArgVal.getAsRegion();
583
584 // Nonlocs can't be freed, of course.
585 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
586 if (!R) {
587 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000588 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000589 }
590
591 R = R->StripCasts();
592
593 // Blocks might show up as heap data, but should not be free()d
594 if (isa<BlockDataRegion>(R)) {
595 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000596 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000597 }
598
599 const MemSpaceRegion *MS = R->getMemorySpace();
600
601 // Parameters, locals, statics, and globals shouldn't be freed.
602 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
603 // FIXME: at the time this code was written, malloc() regions were
604 // represented by conjured symbols, which are all in UnknownSpaceRegion.
605 // This means that there isn't actually anything from HeapSpaceRegion
606 // that should be freed, even though we allow it here.
607 // Of course, free() can work on memory allocated outside the current
608 // function, so UnknownSpaceRegion is always a possibility.
609 // False negatives are better than false positives.
610
611 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000612 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000613 }
614
615 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
616 // Various cases could lead to non-symbol values here.
617 // For now, ignore them.
618 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000619 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000620
621 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000622 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000623
624 // If the symbol has not been tracked, return. This is possible when free() is
625 // called on a pointer that does not get its pointee directly from malloc().
626 // Full support of this requires inter-procedural analysis.
627 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000628 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000629
630 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000631 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000632 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000633 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000634 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000635 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000636 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaksfebdc322012-02-16 22:26:12 +0000637 "Attempt to free released memory", N);
Anna Zaksfe571602012-02-16 22:26:07 +0000638 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000639 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000640 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000641 C.EmitReport(R);
642 }
Anna Zaksb319e022012-02-08 20:13:28 +0000643 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000644 }
645
646 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000647 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000648 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
649 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000650}
651
Ted Kremenek9c378f72011-08-12 23:37:29 +0000652bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000653 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
654 os << "an integer (" << IntVal->getValue() << ")";
655 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
656 os << "a constant address (" << ConstAddr->getValue() << ")";
657 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000658 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000659 else
660 return false;
661
662 return true;
663}
664
Ted Kremenek9c378f72011-08-12 23:37:29 +0000665bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000666 const MemRegion *MR) {
667 switch (MR->getKind()) {
668 case MemRegion::FunctionTextRegionKind: {
669 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
670 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000671 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000672 else
673 os << "the address of a function";
674 return true;
675 }
676 case MemRegion::BlockTextRegionKind:
677 os << "block text";
678 return true;
679 case MemRegion::BlockDataRegionKind:
680 // FIXME: where the block came from?
681 os << "a block";
682 return true;
683 default: {
684 const MemSpaceRegion *MS = MR->getMemorySpace();
685
Anna Zakseb31a762012-01-04 23:54:01 +0000686 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000687 const VarRegion *VR = dyn_cast<VarRegion>(MR);
688 const VarDecl *VD;
689 if (VR)
690 VD = VR->getDecl();
691 else
692 VD = NULL;
693
694 if (VD)
695 os << "the address of the local variable '" << VD->getName() << "'";
696 else
697 os << "the address of a local stack variable";
698 return true;
699 }
Anna Zakseb31a762012-01-04 23:54:01 +0000700
701 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000702 const VarRegion *VR = dyn_cast<VarRegion>(MR);
703 const VarDecl *VD;
704 if (VR)
705 VD = VR->getDecl();
706 else
707 VD = NULL;
708
709 if (VD)
710 os << "the address of the parameter '" << VD->getName() << "'";
711 else
712 os << "the address of a parameter";
713 return true;
714 }
Anna Zakseb31a762012-01-04 23:54:01 +0000715
716 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000717 const VarRegion *VR = dyn_cast<VarRegion>(MR);
718 const VarDecl *VD;
719 if (VR)
720 VD = VR->getDecl();
721 else
722 VD = NULL;
723
724 if (VD) {
725 if (VD->isStaticLocal())
726 os << "the address of the static variable '" << VD->getName() << "'";
727 else
728 os << "the address of the global variable '" << VD->getName() << "'";
729 } else
730 os << "the address of a global variable";
731 return true;
732 }
Anna Zakseb31a762012-01-04 23:54:01 +0000733
734 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000735 }
736 }
737}
738
739void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000740 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000741 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000742 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000743 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000744
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000745 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000746 llvm::raw_svector_ostream os(buf);
747
748 const MemRegion *MR = ArgVal.getAsRegion();
749 if (MR) {
750 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
751 MR = ER->getSuperRegion();
752
753 // Special case for alloca()
754 if (isa<AllocaRegion>(MR))
755 os << "Argument to free() was allocated by alloca(), not malloc()";
756 else {
757 os << "Argument to free() is ";
758 if (SummarizeRegion(os, MR))
759 os << ", which is not memory allocated by malloc()";
760 else
761 os << "not memory allocated by malloc()";
762 }
763 } else {
764 os << "Argument to free() is ";
765 if (SummarizeValue(os, ArgVal))
766 os << ", which is not memory allocated by malloc()";
767 else
768 os << "not memory allocated by malloc()";
769 }
770
Anna Zakse172e8b2011-08-17 23:00:25 +0000771 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000772 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000773 R->addRange(range);
774 C.EmitReport(R);
775 }
776}
777
Anna Zaks87cb5be2012-02-22 19:24:52 +0000778ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
779 const CallExpr *CE,
780 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000781 if (CE->getNumArgs() < 2)
782 return 0;
783
Ted Kremenek8bef8232012-01-26 21:29:00 +0000784 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000785 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000786 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000787 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
788 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000789 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000790 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000791
Ted Kremenek846eabd2010-12-01 21:28:31 +0000792 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000793
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000794 DefinedOrUnknownSVal PtrEQ =
795 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000796
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000797 // Get the size argument. If there is no size arg then give up.
798 const Expr *Arg1 = CE->getArg(1);
799 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000800 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000801
802 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000803 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
804 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000805 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000806 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000807
808 // Compare the size argument to 0.
809 DefinedOrUnknownSVal SizeZero =
810 svalBuilder.evalEQ(state, Arg1Val,
811 svalBuilder.makeIntValWithPtrWidth(0, false));
812
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000813 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
814 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
815 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
816 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
817 // We only assume exceptional states if they are definitely true; if the
818 // state is under-constrained, assume regular realloc behavior.
819 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
820 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
821
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000822 // If the ptr is NULL and the size is not 0, the call is equivalent to
823 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000824 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000825 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000826 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000827 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000828 }
829
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000830 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000831 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000832
Anna Zaks30838b92012-02-13 20:57:07 +0000833 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000834 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000835 SymbolRef FromPtr = arg0Val.getAsSymbol();
836 SVal RetVal = state->getSVal(CE, LCtx);
837 SymbolRef ToPtr = RetVal.getAsSymbol();
838 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000839 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000840
841 // If the size is 0, free the memory.
842 if (SizeIsZero)
843 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000844 // The semantics of the return value are:
845 // If size was equal to 0, either NULL or a pointer suitable to be passed
846 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000847 stateFree = stateFree->set<ReallocPairs>(ToPtr,
848 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000849 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000850 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000851 }
852
853 // Default behavior.
854 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
855 // FIXME: We should copy the content of the original buffer.
856 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
857 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000858 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000859 return 0;
Anna Zaks40add292012-02-15 00:11:25 +0000860 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
861 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000862 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000863 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000864 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000865 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000866}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000867
Anna Zaks87cb5be2012-02-22 19:24:52 +0000868ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +0000869 if (CE->getNumArgs() < 2)
870 return 0;
871
Ted Kremenek8bef8232012-01-26 21:29:00 +0000872 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000873 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000874 const LocationContext *LCtx = C.getLocationContext();
875 SVal count = state->getSVal(CE->getArg(0), LCtx);
876 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000877 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
878 svalBuilder.getContext().getSizeType());
879 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000880
Anna Zaks87cb5be2012-02-22 19:24:52 +0000881 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000882}
883
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000884LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +0000885MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
886 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000887 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000888 // Walk the ExplodedGraph backwards and find the first node that referred to
889 // the tracked symbol.
890 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000891 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000892
893 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000894 ProgramStateRef State = N->getState();
895 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +0000896 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000897
898 // Find the most recent expression bound to the symbol in the current
899 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000900 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +0000901 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
902 SVal Val = State->getSVal(MR);
903 if (Val.getAsLocSymbol() == Sym)
904 ReferenceRegion = MR;
905 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000906 }
907
Anna Zaks7752d292012-02-27 23:40:55 +0000908 // Allocation node, is the last node in the current context in which the
909 // symbol was tracked.
910 if (N->getLocationContext() == LeakContext)
911 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000912 N = N->pred_empty() ? NULL : *(N->pred_begin());
913 }
914
915 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000916 const Stmt *AllocationStmt = 0;
917 if (isa<StmtPoint>(P))
918 AllocationStmt = cast<StmtPoint>(P).getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +0000919
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000920 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +0000921}
922
Anna Zaksda046772012-02-11 21:02:40 +0000923void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
924 CheckerContext &C) const {
925 assert(N);
926 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000927 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000928 // Leaks should not be reported if they are post-dominated by a sink:
929 // (1) Sinks are higher importance bugs.
930 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
931 // with __noreturn functions such as assert() or exit(). We choose not
932 // to report leaks on such paths.
933 BT_Leak->setSuppressOnSink(true);
934 }
935
Anna Zaksca8e36e2012-02-23 21:38:21 +0000936 // Most bug reports are cached at the location where they occurred.
937 // With leaks, we want to unique them by the location where they were
938 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +0000939 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000940 const Stmt *AllocStmt = 0;
941 const MemRegion *Region = 0;
942 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
943 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +0000944 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
945 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +0000946
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000947 SmallString<200> buf;
948 llvm::raw_svector_ostream os(buf);
949 os << "Memory is never released; potential leak";
950 if (Region) {
951 os << " of memory pointed to by '";
952 Region->dumpPretty(os);
953 os <<'\'';
954 }
955
956 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000957 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +0000958 R->addVisitor(new MallocBugVisitor(Sym, true));
Anna Zaksda046772012-02-11 21:02:40 +0000959 C.EmitReport(R);
960}
961
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000962void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
963 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000964{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000965 if (!SymReaper.hasDeadSymbols())
966 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000967
Ted Kremenek8bef8232012-01-26 21:29:00 +0000968 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000969 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000970 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000971
Ted Kremenek217470e2011-07-28 23:07:51 +0000972 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000973 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000974 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
975 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000976 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000977 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000978 Errors.push_back(I->first);
979 }
Jordy Rose90760142010-08-18 04:33:47 +0000980 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000981 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000982
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000983 }
984 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000985
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000986 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000987 ReallocMap RP = state->get<ReallocPairs>();
988 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
989 if (SymReaper.isDead(I->first) ||
990 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000991 state = state->remove<ReallocPairs>(I->first);
992 }
993 }
994
Anna Zaksca8e36e2012-02-23 21:38:21 +0000995 // Generate leak node.
996 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
997 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +0000998
Anna Zaksca8e36e2012-02-23 21:38:21 +0000999 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +00001000 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +00001001 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
1002 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001003 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001004 }
Anna Zaksca8e36e2012-02-23 21:38:21 +00001005 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001006}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001007
Anna Zaksda046772012-02-11 21:02:40 +00001008void MallocChecker::checkEndPath(CheckerContext &C) const {
1009 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +00001010 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +00001011
Anna Zaksa19581a2012-02-20 22:25:23 +00001012 // If inside inlined call, skip it.
1013 if (C.getLocationContext()->getParent() != 0)
1014 return;
1015
Jordy Rose09cef092010-08-18 04:26:59 +00001016 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +00001017 RefState RS = I->second;
1018 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +00001019 ExplodedNode *N = C.addTransition(state);
1020 if (N)
1021 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +00001022 }
1023 }
1024}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001025
Anna Zaks91c2a112012-02-08 23:16:56 +00001026bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
1027 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001028 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +00001029 const RefState *RS = state->get<RegionState>(Sym);
1030 if (!RS)
1031 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001032
Anna Zaks91c2a112012-02-08 23:16:56 +00001033 if (RS->isAllocated()) {
1034 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
1035 C.addTransition(state);
1036 return true;
1037 }
1038 return false;
1039}
1040
Anna Zaks66c40402012-02-14 21:55:24 +00001041void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001042 // We will check for double free in the post visit.
1043 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001044 return;
1045
1046 // Check use after free, when a freed pointer is passed to a call.
1047 ProgramStateRef State = C.getState();
1048 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1049 E = CE->arg_end(); I != E; ++I) {
1050 const Expr *A = *I;
1051 if (A->getType().getTypePtr()->isAnyPointerType()) {
1052 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1053 if (!Sym)
1054 continue;
1055 if (checkUseAfterFree(Sym, C, A))
1056 return;
1057 }
1058 }
1059}
1060
Anna Zaks91c2a112012-02-08 23:16:56 +00001061void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1062 const Expr *E = S->getRetValue();
1063 if (!E)
1064 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001065
1066 // Check if we are returning a symbol.
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001067 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
1068 SymbolRef Sym = RetVal.getAsSymbol();
1069 if (!Sym)
1070 // If we are returning a field of the allocated struct or an array element,
1071 // the callee could still free the memory.
1072 // TODO: This logic should be a part of generic symbol escape callback.
1073 if (const MemRegion *MR = RetVal.getAsRegion())
1074 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1075 if (const SymbolicRegion *BMR =
1076 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1077 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001078 if (!Sym)
1079 return;
1080
Anna Zaks0860cd02012-02-11 21:44:39 +00001081 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +00001082 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +00001083 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001084
Anna Zaksa19581a2012-02-20 22:25:23 +00001085 // If this function body is not inlined, check if the symbol is escaping.
1086 if (C.getLocationContext()->getParent() == 0)
1087 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001088}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001089
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001090// TODO: Blocks should be either inlined or should call invalidate regions
1091// upon invocation. After that's in place, special casing here will not be
1092// needed.
1093void MallocChecker::checkPostStmt(const BlockExpr *BE,
1094 CheckerContext &C) const {
1095
1096 // Scan the BlockDecRefExprs for any object the retain count checker
1097 // may be tracking.
1098 if (!BE->getBlockDecl()->hasCaptures())
1099 return;
1100
1101 ProgramStateRef state = C.getState();
1102 const BlockDataRegion *R =
1103 cast<BlockDataRegion>(state->getSVal(BE,
1104 C.getLocationContext()).getAsRegion());
1105
1106 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1107 E = R->referenced_vars_end();
1108
1109 if (I == E)
1110 return;
1111
1112 SmallVector<const MemRegion*, 10> Regions;
1113 const LocationContext *LC = C.getLocationContext();
1114 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1115
1116 for ( ; I != E; ++I) {
1117 const VarRegion *VR = *I;
1118 if (VR->getSuperRegion() == R) {
1119 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1120 }
1121 Regions.push_back(VR);
1122 }
1123
1124 state =
1125 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1126 Regions.data() + Regions.size()).getState();
1127 C.addTransition(state);
1128}
1129
Anna Zaks14345182012-05-18 01:16:10 +00001130bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001131 assert(Sym);
1132 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001133 return (RS && RS->isReleased());
1134}
1135
1136bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1137 const Stmt *S) const {
1138 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001139 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001140 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001141 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001142
Anna Zaksfebdc322012-02-16 22:26:12 +00001143 BugReport *R = new BugReport(*BT_UseFree,
1144 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001145 if (S)
1146 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001147 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001148 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +00001149 C.EmitReport(R);
1150 return true;
1151 }
1152 }
1153 return false;
1154}
1155
Zhongxing Xuc8023782010-03-10 04:58:55 +00001156// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001157void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1158 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001159 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001160 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001161 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001162}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001163
Anna Zaks4fb54872012-02-11 21:02:35 +00001164//===----------------------------------------------------------------------===//
1165// Check various ways a symbol can be invalidated.
1166// TODO: This logic (the next 3 functions) is copied/similar to the
1167// RetainRelease checker. We might want to factor this out.
1168//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001169
Anna Zaks4fb54872012-02-11 21:02:35 +00001170// Stop tracking symbols when a value escapes as a result of checkBind.
1171// A value escapes in three possible cases:
1172// (1) we are binding to something that is not a memory region.
1173// (2) we are binding to a memregion that does not have stack storage
1174// (3) we are binding to a memregion with stack storage that the store
1175// does not understand.
1176void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1177 CheckerContext &C) const {
1178 // Are we storing to something that causes the value to "escape"?
1179 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001180 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001181
Anna Zaks4fb54872012-02-11 21:02:35 +00001182 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1183 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001184
Anna Zaks4fb54872012-02-11 21:02:35 +00001185 if (!escapes) {
1186 // To test (3), generate a new state with the binding added. If it is
1187 // the same state, then it escapes (since the store cannot represent
1188 // the binding).
Anna Zaks93c5a242012-05-02 00:05:20 +00001189 // Do this only if we know that the store is not supposed to generate the
1190 // same state.
1191 SVal StoredVal = state->getSVal(regionLoc->getRegion());
1192 if (StoredVal != val)
1193 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001194 }
Anna Zaksac593002012-02-16 03:40:57 +00001195 if (!escapes) {
1196 // Case 4: We do not currently model what happens when a symbol is
1197 // assigned to a struct field, so be conservative here and let the symbol
1198 // go. TODO: This could definitely be improved upon.
1199 escapes = !isa<VarRegion>(regionLoc->getRegion());
1200 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001201 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001202
1203 // If our store can represent the binding and we aren't storing to something
1204 // that doesn't have local storage then just return and have the simulation
1205 // state continue as is.
1206 if (!escapes)
1207 return;
1208
1209 // Otherwise, find all symbols referenced by 'val' that we are tracking
1210 // and stop tracking them.
1211 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1212 C.addTransition(state);
1213}
1214
1215// If a symbolic region is assumed to NULL (or another constant), stop tracking
1216// it - assuming that allocation failed on this path.
1217ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1218 SVal Cond,
1219 bool Assumption) const {
1220 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001221 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1222 // If the symbol is assumed to NULL or another constant, this will
1223 // return an APSInt*.
1224 if (state->getSymVal(I.getKey()))
1225 state = state->remove<RegionState>(I.getKey());
1226 }
1227
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001228 // Realloc returns 0 when reallocation fails, which means that we should
1229 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001230 ReallocMap RP = state->get<ReallocPairs>();
1231 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001232 // If the symbol is assumed to NULL or another constant, this will
1233 // return an APSInt*.
1234 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001235 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1236 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001237 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001238 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1239 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001240 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001241 }
1242 state = state->remove<ReallocPairs>(I.getKey());
1243 }
1244 }
1245
Anna Zaks4fb54872012-02-11 21:02:35 +00001246 return state;
1247}
1248
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001249// Check if the function is known to us. So, for example, we could
Anna Zaks66c40402012-02-14 21:55:24 +00001250// conservatively assume it can free/reallocate it's pointer arguments.
1251// (We assume that the pointers cannot escape through calls to system
1252// functions not handled by this checker.)
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001253bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call,
1254 ProgramStateRef State) const {
1255 if (!Call)
1256 return false;
1257
1258 // For now, assume that any C++ call can free memory.
1259 // TODO: If we want to be more optimistic here, we'll need to make sure that
1260 // regions escape to C++ containers. They seem to do that even now, but for
1261 // mysterious reasons.
1262 if (Call->isCXXCall())
1263 return false;
1264
1265 const Decl *D = Call->getDecl();
1266 if (!D)
1267 return false;
1268
Anna Zaks66c40402012-02-14 21:55:24 +00001269 ASTContext &ASTC = State->getStateManager().getContext();
1270
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001271 // If it's one of the allocation functions we can reason about, we model
Jordy Rose257c60f2012-03-06 00:28:20 +00001272 // its behavior explicitly.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001273 if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) {
1274 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001275 }
1276
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001277 // If it's not a system call, assume it frees memory.
Anna Zaks66c40402012-02-14 21:55:24 +00001278 SourceManager &SM = ASTC.getSourceManager();
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001279 if (!SM.isInSystemHeader(D->getLocation()))
1280 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001281
Anna Zaks07d39a42012-02-28 01:54:22 +00001282 // Process C/ObjC functions.
Jordy Rose257c60f2012-03-06 00:28:20 +00001283 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Anna Zaks0d389b82012-02-23 01:05:27 +00001284 // White list the system functions whose arguments escape.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001285 const IdentifierInfo *II = FD->getIdentifier();
Anna Zaks07d39a42012-02-28 01:54:22 +00001286 if (!II)
1287 return true;
1288 StringRef FName = II->getName();
1289
1290 // White list thread local storage.
1291 if (FName.equals("pthread_setspecific"))
1292 return false;
1293
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001294 // White list the 'XXXNoCopy' ObjC functions.
Anna Zaks07d39a42012-02-28 01:54:22 +00001295 if (FName.endswith("NoCopy")) {
1296 // Look for the deallocator argument. We know that the memory ownership
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001297 // is not transferred only if the deallocator argument is
Anna Zaks07d39a42012-02-28 01:54:22 +00001298 // 'kCFAllocatorNull'.
1299 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1300 const Expr *ArgE = Call->getArg(i)->IgnoreParenCasts();
1301 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1302 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1303 if (DeallocatorName == "kCFAllocatorNull")
1304 return true;
1305 }
1306 }
1307 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001308 }
1309
Anna Zaksca23eb22012-02-29 18:42:47 +00001310 // PR12101
1311 // Many CoreFoundation and CoreGraphics might allow a tracked object
1312 // to escape.
1313 if (Call->isCFCGAllowingEscape(FName))
1314 return false;
1315
1316 // Associating streams with malloced buffers. The pointer can escape if
1317 // 'closefn' is specified (and if that function does free memory).
1318 // Currently, we do not inspect the 'closefn' function (PR12101).
1319 if (FName == "funopen")
1320 if (Call->getNumArgs() >= 4 && !Call->getArgSVal(4).isConstant(0))
1321 return false;
1322
1323 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1324 // these leaks might be intentional when setting the buffer for stdio.
1325 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1326 if (FName == "setbuf" || FName =="setbuffer" ||
1327 FName == "setlinebuf" || FName == "setvbuf") {
1328 if (Call->getNumArgs() >= 1)
1329 if (const DeclRefExpr *Arg =
1330 dyn_cast<DeclRefExpr>(Call->getArg(0)->IgnoreParenCasts()))
1331 if (const VarDecl *D = dyn_cast<VarDecl>(Arg->getDecl()))
1332 if (D->getCanonicalDecl()->getName().find("std")
1333 != StringRef::npos)
1334 return false;
1335 }
1336
Jordan Rose1bf908d2012-06-16 00:09:20 +00001337 // A bunch of other functions which either take ownership of a pointer or
1338 // wrap the result up in a struct or object, meaning it can be freed later.
1339 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1340 // but the Malloc checker cannot differentiate between them. The right way
1341 // of doing this would be to implement a pointer escapes callback.
1342 if (FName == "CGBitmapContextCreate" ||
Anna Zaksca23eb22012-02-29 18:42:47 +00001343 FName == "CGBitmapContextCreateWithData" ||
Jordan Rose1bf908d2012-06-16 00:09:20 +00001344 FName == "CVPixelBufferCreateWithBytes" ||
Anna Zaks4cd7edf2012-03-26 18:18:39 +00001345 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1346 FName == "OSAtomicEnqueue") {
Anna Zaksca23eb22012-02-29 18:42:47 +00001347 return false;
1348 }
1349
Anna Zaks62a5c342012-03-30 05:48:16 +00001350 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1351 // be deallocated by NSMapRemove.
1352 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
1353 return false;
1354
Anna Zaksaca0ac52012-05-03 23:50:28 +00001355 // If the call has a callback as an argument, assume the memory
1356 // can be freed.
1357 if (Call->hasNonZeroCallbackArg())
1358 return false;
1359
Anna Zaks0d389b82012-02-23 01:05:27 +00001360 // Otherwise, assume that the function does not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001361 // Most system calls, do not free the memory.
1362 return true;
1363
1364 // Process ObjC functions.
1365 } else if (const ObjCMethodDecl * ObjCD = dyn_cast<ObjCMethodDecl>(D)) {
1366 Selector S = ObjCD->getSelector();
1367
1368 // White list the ObjC functions which do free memory.
1369 // - Anything containing 'freeWhenDone' param set to 1.
1370 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
1371 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
1372 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1373 if (Call->getArgSVal(i).isConstant(1))
1374 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001375 else
1376 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001377 }
1378 }
1379
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001380 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001381 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001382 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1383 if (S.getNameForSlot(0).endswith("NoCopy")) {
1384 return false;
1385 }
1386
Anna Zaksaca0ac52012-05-03 23:50:28 +00001387 // If the call has a callback as an argument, assume the memory
1388 // can be freed.
1389 if (Call->hasNonZeroCallbackArg())
1390 return false;
1391
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001392 // Otherwise, assume that the function does not free memory.
1393 // Most system calls, do not free the memory.
1394 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001395 }
1396
1397 // Otherwise, assume that the function can free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001398 return false;
1399
Anna Zaks66c40402012-02-14 21:55:24 +00001400}
1401
Anna Zaks4fb54872012-02-11 21:02:35 +00001402// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1403// escapes, when we are tracking p), do not track the symbol as we cannot reason
1404// about it anymore.
1405ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001406MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001407 const StoreManager::InvalidatedSymbols *invalidated,
1408 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001409 ArrayRef<const MemRegion *> Regions,
1410 const CallOrObjCMessage *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001411 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001412 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001413 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001414
Anna Zaks66c40402012-02-14 21:55:24 +00001415 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001416 // regions (explicit and implicit) escaped.
1417
1418 // Otherwise, whitelist explicit pointers; we still can track them.
1419 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001420 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1421 E = ExplicitRegions.end(); I != E; ++I) {
1422 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1423 WhitelistedSymbols.insert(R->getSymbol());
1424 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001425 }
1426
1427 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1428 E = invalidated->end(); I!=E; ++I) {
1429 SymbolRef sym = *I;
1430 if (WhitelistedSymbols.count(sym))
1431 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001432 // The symbol escaped.
1433 if (const RefState *RS = State->get<RegionState>(sym))
1434 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001435 }
Anna Zaks66c40402012-02-14 21:55:24 +00001436 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001437}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001438
Jordy Rose393f98b2012-03-18 07:43:35 +00001439static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1440 ProgramStateRef prevState) {
1441 ReallocMap currMap = currState->get<ReallocPairs>();
1442 ReallocMap prevMap = prevState->get<ReallocPairs>();
1443
1444 for (ReallocMap::iterator I = prevMap.begin(), E = prevMap.end();
1445 I != E; ++I) {
1446 SymbolRef sym = I.getKey();
1447 if (!currMap.lookup(sym))
1448 return sym;
1449 }
1450
1451 return NULL;
1452}
1453
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001454PathDiagnosticPiece *
1455MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1456 const ExplodedNode *PrevN,
1457 BugReporterContext &BRC,
1458 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001459 ProgramStateRef state = N->getState();
1460 ProgramStateRef statePrev = PrevN->getState();
1461
1462 const RefState *RS = state->get<RegionState>(Sym);
1463 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001464 if (!RS && !RSPrev)
1465 return 0;
1466
Anna Zaksfe571602012-02-16 22:26:07 +00001467 const Stmt *S = 0;
1468 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001469 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001470
1471 // Retrieve the associated statement.
1472 ProgramPoint ProgLoc = N->getLocation();
1473 if (isa<StmtPoint>(ProgLoc))
1474 S = cast<StmtPoint>(ProgLoc).getStmt();
1475 // If an assumption was made on a branch, it should be caught
1476 // here by looking at the state transition.
1477 if (isa<BlockEdge>(ProgLoc)) {
1478 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1479 S = srcBlk->getTerminator();
1480 }
1481 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001482 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001483
1484 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001485 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001486 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001487 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001488 StackHint = new StackHintGeneratorForSymbol(Sym,
1489 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001490 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001491 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001492 StackHint = new StackHintGeneratorForSymbol(Sym,
1493 "Returned released memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001494 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001495 Mode = ReallocationFailed;
1496 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001497 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001498 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001499
Jordy Roseb000fb52012-03-24 03:15:09 +00001500 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1501 // Is it possible to fail two reallocs WITHOUT testing in between?
1502 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1503 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001504 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001505 FailedReallocSymbol = sym;
1506 }
Anna Zaksfe571602012-02-16 22:26:07 +00001507 }
1508
1509 // We are in a special mode if a reallocation failed later in the path.
1510 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001511 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001512
Jordy Roseb000fb52012-03-24 03:15:09 +00001513 // Is this is the first appearance of the reallocated symbol?
1514 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
1515 // If we ever hit this assert, that means BugReporter has decided to skip
1516 // node pairs or visit them out of order.
1517 assert(state->get<RegionState>(FailedReallocSymbol) &&
1518 "Missed the reallocation point");
1519
1520 // We're at the reallocation point.
1521 Msg = "Attempt to reallocate memory";
1522 StackHint = new StackHintGeneratorForSymbol(Sym,
1523 "Returned reallocated memory");
1524 FailedReallocSymbol = NULL;
1525 Mode = Normal;
1526 }
Anna Zaksfe571602012-02-16 22:26:07 +00001527 }
1528
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001529 if (!Msg)
1530 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001531 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001532
1533 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001534 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001535 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001536 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001537}
1538
Anna Zaks93c5a242012-05-02 00:05:20 +00001539void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1540 const char *NL, const char *Sep) const {
1541
1542 RegionStateTy RS = State->get<RegionState>();
1543
1544 if (!RS.isEmpty())
1545 Out << "Has Malloc data" << NL;
1546}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001547
Anna Zaks231361a2012-02-08 23:16:52 +00001548#define REGISTER_CHECKER(name) \
1549void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001550 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001551 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001552}
Anna Zaks231361a2012-02-08 23:16:52 +00001553
1554REGISTER_CHECKER(MallocPessimistic)
1555REGISTER_CHECKER(MallocOptimistic)