blob: 3b9712fd9bf0fc45dc2bcfb6a366e325d0d91122 [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 Zaksb319e022012-02-08 20:13:28 +0000480 // Get the return value.
481 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000482
Anna Zaksb16ce452012-02-15 00:11:22 +0000483 // We expect the malloc functions to return a pointer.
484 if (!isa<Loc>(retVal))
485 return 0;
486
Jordy Rose32f26562010-07-04 00:00:41 +0000487 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000488 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000489
Jordy Rose32f26562010-07-04 00:00:41 +0000490 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000491 const SymbolicRegion *R =
492 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000493 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000494 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000495 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000496 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000497 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
498 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
499 DefinedOrUnknownSVal extentMatchesSize =
500 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000501
Anna Zaks60a1fa42012-02-22 03:14:20 +0000502 state = state->assume(extentMatchesSize, true);
503 assert(state);
504 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000505
Anna Zaks87cb5be2012-02-22 19:24:52 +0000506 return MallocUpdateRefState(C, CE, state);
507}
508
509ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
510 const CallExpr *CE,
511 ProgramStateRef state) {
512 // Get the return value.
513 SVal retVal = state->getSVal(CE, C.getLocationContext());
514
515 // We expect the malloc functions to return a pointer.
516 if (!isa<Loc>(retVal))
517 return 0;
518
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000519 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000520 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000521
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000522 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000523 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000524
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000525}
526
Anna Zaks87cb5be2012-02-22 19:24:52 +0000527ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
528 const CallExpr *CE,
529 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000530 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000531 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000532
Anna Zaksb3d72752012-03-01 22:06:06 +0000533 ProgramStateRef State = C.getState();
534
Sean Huntcf807c42010-08-18 23:23:40 +0000535 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
536 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000537 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
538 Att->getOwnKind() == OwnershipAttr::Holds);
539 if (StateI)
540 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000541 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000542 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000543}
544
Ted Kremenek8bef8232012-01-26 21:29:00 +0000545ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000546 const CallExpr *CE,
547 ProgramStateRef state,
548 unsigned Num,
549 bool Hold) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000550 if (CE->getNumArgs() < (Num + 1))
551 return 0;
552
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000553 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000554 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000555 if (!isa<DefinedOrUnknownSVal>(ArgVal))
556 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000557 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
558
559 // Check for null dereferences.
560 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000561 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000562
Anna Zaksb276bd92012-02-14 00:26:13 +0000563 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000564 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000565 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000566 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000567 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000568
Jordy Rose43859f62010-06-07 19:32:37 +0000569 // Unknown values could easily be okay
570 // Undefined values are handled elsewhere
571 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000572 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000573
Jordy Rose43859f62010-06-07 19:32:37 +0000574 const MemRegion *R = ArgVal.getAsRegion();
575
576 // Nonlocs can't be freed, of course.
577 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
578 if (!R) {
579 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000580 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000581 }
582
583 R = R->StripCasts();
584
585 // Blocks might show up as heap data, but should not be free()d
586 if (isa<BlockDataRegion>(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 const MemSpaceRegion *MS = R->getMemorySpace();
592
593 // Parameters, locals, statics, and globals shouldn't be freed.
594 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
595 // FIXME: at the time this code was written, malloc() regions were
596 // represented by conjured symbols, which are all in UnknownSpaceRegion.
597 // This means that there isn't actually anything from HeapSpaceRegion
598 // that should be freed, even though we allow it here.
599 // Of course, free() can work on memory allocated outside the current
600 // function, so UnknownSpaceRegion is always a possibility.
601 // False negatives are better than false positives.
602
603 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000604 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000605 }
606
607 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
608 // Various cases could lead to non-symbol values here.
609 // For now, ignore them.
610 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000611 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000612
613 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000614 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000615
616 // If the symbol has not been tracked, return. This is possible when free() is
617 // called on a pointer that does not get its pointee directly from malloc().
618 // Full support of this requires inter-procedural analysis.
619 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000620 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000621
622 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000623 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000624 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000625 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000626 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000627 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000628 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaksfebdc322012-02-16 22:26:12 +0000629 "Attempt to free released memory", N);
Anna Zaksfe571602012-02-16 22:26:07 +0000630 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000631 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000632 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000633 C.EmitReport(R);
634 }
Anna Zaksb319e022012-02-08 20:13:28 +0000635 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000636 }
637
638 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000639 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000640 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
641 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000642}
643
Ted Kremenek9c378f72011-08-12 23:37:29 +0000644bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000645 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
646 os << "an integer (" << IntVal->getValue() << ")";
647 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
648 os << "a constant address (" << ConstAddr->getValue() << ")";
649 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000650 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000651 else
652 return false;
653
654 return true;
655}
656
Ted Kremenek9c378f72011-08-12 23:37:29 +0000657bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000658 const MemRegion *MR) {
659 switch (MR->getKind()) {
660 case MemRegion::FunctionTextRegionKind: {
661 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
662 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000663 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000664 else
665 os << "the address of a function";
666 return true;
667 }
668 case MemRegion::BlockTextRegionKind:
669 os << "block text";
670 return true;
671 case MemRegion::BlockDataRegionKind:
672 // FIXME: where the block came from?
673 os << "a block";
674 return true;
675 default: {
676 const MemSpaceRegion *MS = MR->getMemorySpace();
677
Anna Zakseb31a762012-01-04 23:54:01 +0000678 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000679 const VarRegion *VR = dyn_cast<VarRegion>(MR);
680 const VarDecl *VD;
681 if (VR)
682 VD = VR->getDecl();
683 else
684 VD = NULL;
685
686 if (VD)
687 os << "the address of the local variable '" << VD->getName() << "'";
688 else
689 os << "the address of a local stack variable";
690 return true;
691 }
Anna Zakseb31a762012-01-04 23:54:01 +0000692
693 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000694 const VarRegion *VR = dyn_cast<VarRegion>(MR);
695 const VarDecl *VD;
696 if (VR)
697 VD = VR->getDecl();
698 else
699 VD = NULL;
700
701 if (VD)
702 os << "the address of the parameter '" << VD->getName() << "'";
703 else
704 os << "the address of a parameter";
705 return true;
706 }
Anna Zakseb31a762012-01-04 23:54:01 +0000707
708 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000709 const VarRegion *VR = dyn_cast<VarRegion>(MR);
710 const VarDecl *VD;
711 if (VR)
712 VD = VR->getDecl();
713 else
714 VD = NULL;
715
716 if (VD) {
717 if (VD->isStaticLocal())
718 os << "the address of the static variable '" << VD->getName() << "'";
719 else
720 os << "the address of the global variable '" << VD->getName() << "'";
721 } else
722 os << "the address of a global variable";
723 return true;
724 }
Anna Zakseb31a762012-01-04 23:54:01 +0000725
726 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000727 }
728 }
729}
730
731void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000732 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000733 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000734 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000735 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000736
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000737 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000738 llvm::raw_svector_ostream os(buf);
739
740 const MemRegion *MR = ArgVal.getAsRegion();
741 if (MR) {
742 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
743 MR = ER->getSuperRegion();
744
745 // Special case for alloca()
746 if (isa<AllocaRegion>(MR))
747 os << "Argument to free() was allocated by alloca(), not malloc()";
748 else {
749 os << "Argument to free() is ";
750 if (SummarizeRegion(os, MR))
751 os << ", which is not memory allocated by malloc()";
752 else
753 os << "not memory allocated by malloc()";
754 }
755 } else {
756 os << "Argument to free() is ";
757 if (SummarizeValue(os, ArgVal))
758 os << ", which is not memory allocated by malloc()";
759 else
760 os << "not memory allocated by malloc()";
761 }
762
Anna Zakse172e8b2011-08-17 23:00:25 +0000763 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000764 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000765 R->addRange(range);
766 C.EmitReport(R);
767 }
768}
769
Anna Zaks87cb5be2012-02-22 19:24:52 +0000770ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
771 const CallExpr *CE,
772 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000773 if (CE->getNumArgs() < 2)
774 return 0;
775
Ted Kremenek8bef8232012-01-26 21:29:00 +0000776 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000777 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000778 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000779 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
780 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000781 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000782 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000783
Ted Kremenek846eabd2010-12-01 21:28:31 +0000784 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000785
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000786 DefinedOrUnknownSVal PtrEQ =
787 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000788
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000789 // Get the size argument. If there is no size arg then give up.
790 const Expr *Arg1 = CE->getArg(1);
791 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000792 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000793
794 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000795 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
796 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000797 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000798 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000799
800 // Compare the size argument to 0.
801 DefinedOrUnknownSVal SizeZero =
802 svalBuilder.evalEQ(state, Arg1Val,
803 svalBuilder.makeIntValWithPtrWidth(0, false));
804
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000805 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
806 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
807 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
808 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
809 // We only assume exceptional states if they are definitely true; if the
810 // state is under-constrained, assume regular realloc behavior.
811 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
812 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
813
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000814 // If the ptr is NULL and the size is not 0, the call is equivalent to
815 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000816 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000817 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000818 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000819 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000820 }
821
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000822 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000823 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000824
Anna Zaks30838b92012-02-13 20:57:07 +0000825 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000826 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000827 SymbolRef FromPtr = arg0Val.getAsSymbol();
828 SVal RetVal = state->getSVal(CE, LCtx);
829 SymbolRef ToPtr = RetVal.getAsSymbol();
830 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000831 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000832
833 // If the size is 0, free the memory.
834 if (SizeIsZero)
835 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000836 // The semantics of the return value are:
837 // If size was equal to 0, either NULL or a pointer suitable to be passed
838 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000839 stateFree = stateFree->set<ReallocPairs>(ToPtr,
840 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000841 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000842 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000843 }
844
845 // Default behavior.
846 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
847 // FIXME: We should copy the content of the original buffer.
848 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
849 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000850 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000851 return 0;
Anna Zaks40add292012-02-15 00:11:25 +0000852 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
853 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000854 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000855 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000856 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000857 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000858}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000859
Anna Zaks87cb5be2012-02-22 19:24:52 +0000860ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +0000861 if (CE->getNumArgs() < 2)
862 return 0;
863
Ted Kremenek8bef8232012-01-26 21:29:00 +0000864 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000865 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000866 const LocationContext *LCtx = C.getLocationContext();
867 SVal count = state->getSVal(CE->getArg(0), LCtx);
868 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000869 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
870 svalBuilder.getContext().getSizeType());
871 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000872
Anna Zaks87cb5be2012-02-22 19:24:52 +0000873 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000874}
875
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000876LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +0000877MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
878 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000879 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000880 // Walk the ExplodedGraph backwards and find the first node that referred to
881 // the tracked symbol.
882 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000883 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000884
885 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000886 ProgramStateRef State = N->getState();
887 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +0000888 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000889
890 // Find the most recent expression bound to the symbol in the current
891 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000892 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +0000893 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
894 SVal Val = State->getSVal(MR);
895 if (Val.getAsLocSymbol() == Sym)
896 ReferenceRegion = MR;
897 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000898 }
899
Anna Zaks7752d292012-02-27 23:40:55 +0000900 // Allocation node, is the last node in the current context in which the
901 // symbol was tracked.
902 if (N->getLocationContext() == LeakContext)
903 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000904 N = N->pred_empty() ? NULL : *(N->pred_begin());
905 }
906
907 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000908 const Stmt *AllocationStmt = 0;
909 if (isa<StmtPoint>(P))
910 AllocationStmt = cast<StmtPoint>(P).getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +0000911
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000912 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +0000913}
914
Anna Zaksda046772012-02-11 21:02:40 +0000915void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
916 CheckerContext &C) const {
917 assert(N);
918 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000919 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000920 // Leaks should not be reported if they are post-dominated by a sink:
921 // (1) Sinks are higher importance bugs.
922 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
923 // with __noreturn functions such as assert() or exit(). We choose not
924 // to report leaks on such paths.
925 BT_Leak->setSuppressOnSink(true);
926 }
927
Anna Zaksca8e36e2012-02-23 21:38:21 +0000928 // Most bug reports are cached at the location where they occurred.
929 // With leaks, we want to unique them by the location where they were
930 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +0000931 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000932 const Stmt *AllocStmt = 0;
933 const MemRegion *Region = 0;
934 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
935 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +0000936 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
937 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +0000938
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000939 SmallString<200> buf;
940 llvm::raw_svector_ostream os(buf);
941 os << "Memory is never released; potential leak";
942 if (Region) {
943 os << " of memory pointed to by '";
944 Region->dumpPretty(os);
945 os <<'\'';
946 }
947
948 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000949 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +0000950 R->addVisitor(new MallocBugVisitor(Sym, true));
Anna Zaksda046772012-02-11 21:02:40 +0000951 C.EmitReport(R);
952}
953
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000954void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
955 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000956{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000957 if (!SymReaper.hasDeadSymbols())
958 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000959
Ted Kremenek8bef8232012-01-26 21:29:00 +0000960 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000961 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000962 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000963
Ted Kremenek217470e2011-07-28 23:07:51 +0000964 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000965 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000966 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
967 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000968 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000969 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000970 Errors.push_back(I->first);
971 }
Jordy Rose90760142010-08-18 04:33:47 +0000972 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000973 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000974
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000975 }
976 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000977
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000978 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000979 ReallocMap RP = state->get<ReallocPairs>();
980 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
981 if (SymReaper.isDead(I->first) ||
982 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000983 state = state->remove<ReallocPairs>(I->first);
984 }
985 }
986
Anna Zaksca8e36e2012-02-23 21:38:21 +0000987 // Generate leak node.
988 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
989 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +0000990
Anna Zaksca8e36e2012-02-23 21:38:21 +0000991 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000992 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000993 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
994 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000995 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000996 }
Anna Zaksca8e36e2012-02-23 21:38:21 +0000997 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +0000998}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000999
Anna Zaksda046772012-02-11 21:02:40 +00001000void MallocChecker::checkEndPath(CheckerContext &C) const {
1001 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +00001002 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +00001003
Anna Zaksa19581a2012-02-20 22:25:23 +00001004 // If inside inlined call, skip it.
1005 if (C.getLocationContext()->getParent() != 0)
1006 return;
1007
Jordy Rose09cef092010-08-18 04:26:59 +00001008 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +00001009 RefState RS = I->second;
1010 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +00001011 ExplodedNode *N = C.addTransition(state);
1012 if (N)
1013 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +00001014 }
1015 }
1016}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001017
Anna Zaks91c2a112012-02-08 23:16:56 +00001018bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
1019 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001020 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +00001021 const RefState *RS = state->get<RegionState>(Sym);
1022 if (!RS)
1023 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001024
Anna Zaks91c2a112012-02-08 23:16:56 +00001025 if (RS->isAllocated()) {
1026 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
1027 C.addTransition(state);
1028 return true;
1029 }
1030 return false;
1031}
1032
Anna Zaks66c40402012-02-14 21:55:24 +00001033void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001034 // We will check for double free in the post visit.
1035 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001036 return;
1037
1038 // Check use after free, when a freed pointer is passed to a call.
1039 ProgramStateRef State = C.getState();
1040 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1041 E = CE->arg_end(); I != E; ++I) {
1042 const Expr *A = *I;
1043 if (A->getType().getTypePtr()->isAnyPointerType()) {
1044 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1045 if (!Sym)
1046 continue;
1047 if (checkUseAfterFree(Sym, C, A))
1048 return;
1049 }
1050 }
1051}
1052
Anna Zaks91c2a112012-02-08 23:16:56 +00001053void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1054 const Expr *E = S->getRetValue();
1055 if (!E)
1056 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001057
1058 // Check if we are returning a symbol.
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001059 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
1060 SymbolRef Sym = RetVal.getAsSymbol();
1061 if (!Sym)
1062 // If we are returning a field of the allocated struct or an array element,
1063 // the callee could still free the memory.
1064 // TODO: This logic should be a part of generic symbol escape callback.
1065 if (const MemRegion *MR = RetVal.getAsRegion())
1066 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1067 if (const SymbolicRegion *BMR =
1068 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1069 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001070 if (!Sym)
1071 return;
1072
Anna Zaks0860cd02012-02-11 21:44:39 +00001073 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +00001074 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +00001075 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001076
Anna Zaksa19581a2012-02-20 22:25:23 +00001077 // If this function body is not inlined, check if the symbol is escaping.
1078 if (C.getLocationContext()->getParent() == 0)
1079 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001080}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001081
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001082// TODO: Blocks should be either inlined or should call invalidate regions
1083// upon invocation. After that's in place, special casing here will not be
1084// needed.
1085void MallocChecker::checkPostStmt(const BlockExpr *BE,
1086 CheckerContext &C) const {
1087
1088 // Scan the BlockDecRefExprs for any object the retain count checker
1089 // may be tracking.
1090 if (!BE->getBlockDecl()->hasCaptures())
1091 return;
1092
1093 ProgramStateRef state = C.getState();
1094 const BlockDataRegion *R =
1095 cast<BlockDataRegion>(state->getSVal(BE,
1096 C.getLocationContext()).getAsRegion());
1097
1098 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1099 E = R->referenced_vars_end();
1100
1101 if (I == E)
1102 return;
1103
1104 SmallVector<const MemRegion*, 10> Regions;
1105 const LocationContext *LC = C.getLocationContext();
1106 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1107
1108 for ( ; I != E; ++I) {
1109 const VarRegion *VR = *I;
1110 if (VR->getSuperRegion() == R) {
1111 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1112 }
1113 Regions.push_back(VR);
1114 }
1115
1116 state =
1117 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1118 Regions.data() + Regions.size()).getState();
1119 C.addTransition(state);
1120}
1121
Anna Zaks14345182012-05-18 01:16:10 +00001122bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001123 assert(Sym);
1124 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001125 return (RS && RS->isReleased());
1126}
1127
1128bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1129 const Stmt *S) const {
1130 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001131 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001132 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001133 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001134
Anna Zaksfebdc322012-02-16 22:26:12 +00001135 BugReport *R = new BugReport(*BT_UseFree,
1136 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001137 if (S)
1138 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001139 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001140 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +00001141 C.EmitReport(R);
1142 return true;
1143 }
1144 }
1145 return false;
1146}
1147
Zhongxing Xuc8023782010-03-10 04:58:55 +00001148// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001149void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1150 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001151 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001152 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001153 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001154}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001155
Anna Zaks4fb54872012-02-11 21:02:35 +00001156//===----------------------------------------------------------------------===//
1157// Check various ways a symbol can be invalidated.
1158// TODO: This logic (the next 3 functions) is copied/similar to the
1159// RetainRelease checker. We might want to factor this out.
1160//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001161
Anna Zaks4fb54872012-02-11 21:02:35 +00001162// Stop tracking symbols when a value escapes as a result of checkBind.
1163// A value escapes in three possible cases:
1164// (1) we are binding to something that is not a memory region.
1165// (2) we are binding to a memregion that does not have stack storage
1166// (3) we are binding to a memregion with stack storage that the store
1167// does not understand.
1168void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1169 CheckerContext &C) const {
1170 // Are we storing to something that causes the value to "escape"?
1171 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001172 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001173
Anna Zaks4fb54872012-02-11 21:02:35 +00001174 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1175 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001176
Anna Zaks4fb54872012-02-11 21:02:35 +00001177 if (!escapes) {
1178 // To test (3), generate a new state with the binding added. If it is
1179 // the same state, then it escapes (since the store cannot represent
1180 // the binding).
Anna Zaks93c5a242012-05-02 00:05:20 +00001181 // Do this only if we know that the store is not supposed to generate the
1182 // same state.
1183 SVal StoredVal = state->getSVal(regionLoc->getRegion());
1184 if (StoredVal != val)
1185 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001186 }
Anna Zaksac593002012-02-16 03:40:57 +00001187 if (!escapes) {
1188 // Case 4: We do not currently model what happens when a symbol is
1189 // assigned to a struct field, so be conservative here and let the symbol
1190 // go. TODO: This could definitely be improved upon.
1191 escapes = !isa<VarRegion>(regionLoc->getRegion());
1192 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001193 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001194
1195 // If our store can represent the binding and we aren't storing to something
1196 // that doesn't have local storage then just return and have the simulation
1197 // state continue as is.
1198 if (!escapes)
1199 return;
1200
1201 // Otherwise, find all symbols referenced by 'val' that we are tracking
1202 // and stop tracking them.
1203 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1204 C.addTransition(state);
1205}
1206
1207// If a symbolic region is assumed to NULL (or another constant), stop tracking
1208// it - assuming that allocation failed on this path.
1209ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1210 SVal Cond,
1211 bool Assumption) const {
1212 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001213 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1214 // If the symbol is assumed to NULL or another constant, this will
1215 // return an APSInt*.
1216 if (state->getSymVal(I.getKey()))
1217 state = state->remove<RegionState>(I.getKey());
1218 }
1219
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001220 // Realloc returns 0 when reallocation fails, which means that we should
1221 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001222 ReallocMap RP = state->get<ReallocPairs>();
1223 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001224 // If the symbol is assumed to NULL or another constant, this will
1225 // return an APSInt*.
1226 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001227 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1228 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001229 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001230 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1231 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001232 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001233 }
1234 state = state->remove<ReallocPairs>(I.getKey());
1235 }
1236 }
1237
Anna Zaks4fb54872012-02-11 21:02:35 +00001238 return state;
1239}
1240
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001241// Check if the function is known to us. So, for example, we could
Anna Zaks66c40402012-02-14 21:55:24 +00001242// conservatively assume it can free/reallocate it's pointer arguments.
1243// (We assume that the pointers cannot escape through calls to system
1244// functions not handled by this checker.)
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001245bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call,
1246 ProgramStateRef State) const {
1247 if (!Call)
1248 return false;
1249
1250 // For now, assume that any C++ call can free memory.
1251 // TODO: If we want to be more optimistic here, we'll need to make sure that
1252 // regions escape to C++ containers. They seem to do that even now, but for
1253 // mysterious reasons.
1254 if (Call->isCXXCall())
1255 return false;
1256
1257 const Decl *D = Call->getDecl();
1258 if (!D)
1259 return false;
1260
Anna Zaks66c40402012-02-14 21:55:24 +00001261 ASTContext &ASTC = State->getStateManager().getContext();
1262
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001263 // If it's one of the allocation functions we can reason about, we model
Jordy Rose257c60f2012-03-06 00:28:20 +00001264 // its behavior explicitly.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001265 if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) {
1266 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001267 }
1268
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001269 // If it's not a system call, assume it frees memory.
Anna Zaks66c40402012-02-14 21:55:24 +00001270 SourceManager &SM = ASTC.getSourceManager();
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001271 if (!SM.isInSystemHeader(D->getLocation()))
1272 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001273
Anna Zaks07d39a42012-02-28 01:54:22 +00001274 // Process C/ObjC functions.
Jordy Rose257c60f2012-03-06 00:28:20 +00001275 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Anna Zaks0d389b82012-02-23 01:05:27 +00001276 // White list the system functions whose arguments escape.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001277 const IdentifierInfo *II = FD->getIdentifier();
Anna Zaks07d39a42012-02-28 01:54:22 +00001278 if (!II)
1279 return true;
1280 StringRef FName = II->getName();
1281
1282 // White list thread local storage.
1283 if (FName.equals("pthread_setspecific"))
1284 return false;
1285
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001286 // White list the 'XXXNoCopy' ObjC functions.
Anna Zaks07d39a42012-02-28 01:54:22 +00001287 if (FName.endswith("NoCopy")) {
1288 // Look for the deallocator argument. We know that the memory ownership
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001289 // is not transferred only if the deallocator argument is
Anna Zaks07d39a42012-02-28 01:54:22 +00001290 // 'kCFAllocatorNull'.
1291 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1292 const Expr *ArgE = Call->getArg(i)->IgnoreParenCasts();
1293 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1294 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1295 if (DeallocatorName == "kCFAllocatorNull")
1296 return true;
1297 }
1298 }
1299 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001300 }
1301
Anna Zaksca23eb22012-02-29 18:42:47 +00001302 // PR12101
1303 // Many CoreFoundation and CoreGraphics might allow a tracked object
1304 // to escape.
1305 if (Call->isCFCGAllowingEscape(FName))
1306 return false;
1307
1308 // Associating streams with malloced buffers. The pointer can escape if
1309 // 'closefn' is specified (and if that function does free memory).
1310 // Currently, we do not inspect the 'closefn' function (PR12101).
1311 if (FName == "funopen")
1312 if (Call->getNumArgs() >= 4 && !Call->getArgSVal(4).isConstant(0))
1313 return false;
1314
1315 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1316 // these leaks might be intentional when setting the buffer for stdio.
1317 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1318 if (FName == "setbuf" || FName =="setbuffer" ||
1319 FName == "setlinebuf" || FName == "setvbuf") {
1320 if (Call->getNumArgs() >= 1)
1321 if (const DeclRefExpr *Arg =
1322 dyn_cast<DeclRefExpr>(Call->getArg(0)->IgnoreParenCasts()))
1323 if (const VarDecl *D = dyn_cast<VarDecl>(Arg->getDecl()))
1324 if (D->getCanonicalDecl()->getName().find("std")
1325 != StringRef::npos)
1326 return false;
1327 }
1328
1329 // A bunch of other functions, which take ownership of a pointer (See retain
1330 // release checker). Not all the parameters here are invalidated, but the
1331 // Malloc checker cannot differentiate between them. The right way of doing
1332 // this would be to implement a pointer escapes callback.
1333 if (FName == "CVPixelBufferCreateWithBytes" ||
1334 FName == "CGBitmapContextCreateWithData" ||
Anna Zaks4cd7edf2012-03-26 18:18:39 +00001335 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1336 FName == "OSAtomicEnqueue") {
Anna Zaksca23eb22012-02-29 18:42:47 +00001337 return false;
1338 }
1339
Anna Zaks62a5c342012-03-30 05:48:16 +00001340 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1341 // be deallocated by NSMapRemove.
1342 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
1343 return false;
1344
Anna Zaksaca0ac52012-05-03 23:50:28 +00001345 // If the call has a callback as an argument, assume the memory
1346 // can be freed.
1347 if (Call->hasNonZeroCallbackArg())
1348 return false;
1349
Anna Zaks0d389b82012-02-23 01:05:27 +00001350 // Otherwise, assume that the function does not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001351 // Most system calls, do not free the memory.
1352 return true;
1353
1354 // Process ObjC functions.
1355 } else if (const ObjCMethodDecl * ObjCD = dyn_cast<ObjCMethodDecl>(D)) {
1356 Selector S = ObjCD->getSelector();
1357
1358 // White list the ObjC functions which do free memory.
1359 // - Anything containing 'freeWhenDone' param set to 1.
1360 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
1361 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
1362 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1363 if (Call->getArgSVal(i).isConstant(1))
1364 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001365 else
1366 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001367 }
1368 }
1369
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001370 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001371 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001372 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1373 if (S.getNameForSlot(0).endswith("NoCopy")) {
1374 return false;
1375 }
1376
Anna Zaksaca0ac52012-05-03 23:50:28 +00001377 // If the call has a callback as an argument, assume the memory
1378 // can be freed.
1379 if (Call->hasNonZeroCallbackArg())
1380 return false;
1381
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001382 // Otherwise, assume that the function does not free memory.
1383 // Most system calls, do not free the memory.
1384 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001385 }
1386
1387 // Otherwise, assume that the function can free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001388 return false;
1389
Anna Zaks66c40402012-02-14 21:55:24 +00001390}
1391
Anna Zaks4fb54872012-02-11 21:02:35 +00001392// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1393// escapes, when we are tracking p), do not track the symbol as we cannot reason
1394// about it anymore.
1395ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001396MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001397 const StoreManager::InvalidatedSymbols *invalidated,
1398 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001399 ArrayRef<const MemRegion *> Regions,
1400 const CallOrObjCMessage *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001401 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001402 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001403 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001404
Anna Zaks66c40402012-02-14 21:55:24 +00001405 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001406 // regions (explicit and implicit) escaped.
1407
1408 // Otherwise, whitelist explicit pointers; we still can track them.
1409 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001410 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1411 E = ExplicitRegions.end(); I != E; ++I) {
1412 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1413 WhitelistedSymbols.insert(R->getSymbol());
1414 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001415 }
1416
1417 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1418 E = invalidated->end(); I!=E; ++I) {
1419 SymbolRef sym = *I;
1420 if (WhitelistedSymbols.count(sym))
1421 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001422 // The symbol escaped.
1423 if (const RefState *RS = State->get<RegionState>(sym))
1424 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001425 }
Anna Zaks66c40402012-02-14 21:55:24 +00001426 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001427}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001428
Jordy Rose393f98b2012-03-18 07:43:35 +00001429static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1430 ProgramStateRef prevState) {
1431 ReallocMap currMap = currState->get<ReallocPairs>();
1432 ReallocMap prevMap = prevState->get<ReallocPairs>();
1433
1434 for (ReallocMap::iterator I = prevMap.begin(), E = prevMap.end();
1435 I != E; ++I) {
1436 SymbolRef sym = I.getKey();
1437 if (!currMap.lookup(sym))
1438 return sym;
1439 }
1440
1441 return NULL;
1442}
1443
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001444PathDiagnosticPiece *
1445MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1446 const ExplodedNode *PrevN,
1447 BugReporterContext &BRC,
1448 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001449 ProgramStateRef state = N->getState();
1450 ProgramStateRef statePrev = PrevN->getState();
1451
1452 const RefState *RS = state->get<RegionState>(Sym);
1453 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001454 if (!RS && !RSPrev)
1455 return 0;
1456
Anna Zaksfe571602012-02-16 22:26:07 +00001457 const Stmt *S = 0;
1458 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001459 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001460
1461 // Retrieve the associated statement.
1462 ProgramPoint ProgLoc = N->getLocation();
1463 if (isa<StmtPoint>(ProgLoc))
1464 S = cast<StmtPoint>(ProgLoc).getStmt();
1465 // If an assumption was made on a branch, it should be caught
1466 // here by looking at the state transition.
1467 if (isa<BlockEdge>(ProgLoc)) {
1468 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1469 S = srcBlk->getTerminator();
1470 }
1471 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001472 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001473
1474 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001475 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001476 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001477 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001478 StackHint = new StackHintGeneratorForSymbol(Sym,
1479 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001480 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001481 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001482 StackHint = new StackHintGeneratorForSymbol(Sym,
1483 "Returned released memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001484 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001485 Mode = ReallocationFailed;
1486 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001487 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001488 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001489
Jordy Roseb000fb52012-03-24 03:15:09 +00001490 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1491 // Is it possible to fail two reallocs WITHOUT testing in between?
1492 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1493 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001494 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001495 FailedReallocSymbol = sym;
1496 }
Anna Zaksfe571602012-02-16 22:26:07 +00001497 }
1498
1499 // We are in a special mode if a reallocation failed later in the path.
1500 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001501 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001502
Jordy Roseb000fb52012-03-24 03:15:09 +00001503 // Is this is the first appearance of the reallocated symbol?
1504 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
1505 // If we ever hit this assert, that means BugReporter has decided to skip
1506 // node pairs or visit them out of order.
1507 assert(state->get<RegionState>(FailedReallocSymbol) &&
1508 "Missed the reallocation point");
1509
1510 // We're at the reallocation point.
1511 Msg = "Attempt to reallocate memory";
1512 StackHint = new StackHintGeneratorForSymbol(Sym,
1513 "Returned reallocated memory");
1514 FailedReallocSymbol = NULL;
1515 Mode = Normal;
1516 }
Anna Zaksfe571602012-02-16 22:26:07 +00001517 }
1518
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001519 if (!Msg)
1520 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001521 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001522
1523 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001524 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001525 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001526 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001527}
1528
Anna Zaks93c5a242012-05-02 00:05:20 +00001529void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1530 const char *NL, const char *Sep) const {
1531
1532 RegionStateTy RS = State->get<RegionState>();
1533
1534 if (!RS.isEmpty())
1535 Out << "Has Malloc data" << NL;
1536}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001537
Anna Zaks231361a2012-02-08 23:16:52 +00001538#define REGISTER_CHECKER(name) \
1539void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001540 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001541 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001542}
Anna Zaks231361a2012-02-08 23:16:52 +00001543
1544REGISTER_CHECKER(MallocPessimistic)
1545REGISTER_CHECKER(MallocOptimistic)