blob: 48fdec2d3f9fde3f62d5429569ca03bcf774ae42 [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 {
Anna Zaks050cdd72012-06-20 20:57:46 +000037 enum Kind { // Reference to allocated memory.
38 Allocated,
39 // Reference to released/freed memory.
40 Released,
41 // Reference to escaped memory - no assumptions can be made of
42 // the state after the reference escapes.
43 Escaped,
44 // The responsibility for freeing resources has transfered from
45 // this reference. A relinquished symbol should not be freed.
Ted Kremenekdde201b2010-08-06 21:12:55 +000046 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000047 const Stmt *S;
48
Zhongxing Xu7fb14642009-12-11 00:55:44 +000049public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000050 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
51
Anna Zaks050cdd72012-06-20 20:57:46 +000052 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000053 bool isReleased() const { return K == Released; }
Anna Zaks050cdd72012-06-20 20:57:46 +000054 bool isRelinquished() const { return K == Relinquished; }
Anna Zaksca23eb22012-02-29 18:42:47 +000055
Anna Zaksc8bb3be2012-02-13 18:05:39 +000056 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000057
58 bool operator==(const RefState &X) const {
59 return K == X.K && S == X.S;
60 }
61
Anna Zaks050cdd72012-06-20 20:57:46 +000062 static RefState getAllocated(const Stmt *s) {
63 return RefState(Allocated, s);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000064 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000065 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
66 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000067 static RefState getRelinquished(const Stmt *s) {
68 return RefState(Relinquished, s);
69 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000070
71 void Profile(llvm::FoldingSetNodeID &ID) const {
72 ID.AddInteger(K);
73 ID.AddPointer(S);
74 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000075};
76
Anna Zaks40add292012-02-15 00:11:25 +000077struct ReallocPair {
78 SymbolRef ReallocatedSym;
79 bool IsFreeOnFailure;
80 ReallocPair(SymbolRef S, bool F) : ReallocatedSym(S), IsFreeOnFailure(F) {}
81 void Profile(llvm::FoldingSetNodeID &ID) const {
82 ID.AddInteger(IsFreeOnFailure);
83 ID.AddPointer(ReallocatedSym);
84 }
85 bool operator==(const ReallocPair &X) const {
86 return ReallocatedSym == X.ReallocatedSym &&
87 IsFreeOnFailure == X.IsFreeOnFailure;
88 }
89};
90
Anna Zaks3d7c44e2012-03-21 19:45:08 +000091typedef std::pair<const Stmt*, const MemRegion*> LeakInfo;
92
Anna Zaksb319e022012-02-08 20:13:28 +000093class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +000094 check::EndPath,
95 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +000096 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +000097 check::PostStmt<CallExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +000098 check::PostStmt<BlockExpr>,
Ted Kremeneke3659a72012-01-04 23:48:37 +000099 check::Location,
100 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +0000101 eval::Assume,
102 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000103{
Anna Zaksfebdc322012-02-16 22:26:12 +0000104 mutable OwningPtr<BugType> BT_DoubleFree;
105 mutable OwningPtr<BugType> BT_Leak;
106 mutable OwningPtr<BugType> BT_UseFree;
107 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000108 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000109 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
110
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000111public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000112 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000113 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000114
115 /// In pessimistic mode, the checker assumes that it does not know which
116 /// functions might free the memory.
117 struct ChecksFilter {
118 DefaultBool CMallocPessimistic;
119 DefaultBool CMallocOptimistic;
120 };
121
122 ChecksFilter Filter;
123
Anna Zaks66c40402012-02-14 21:55:24 +0000124 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000125 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000126 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000127 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000128 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000129 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000130 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000131 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000132 void checkLocation(SVal l, bool isLoad, const Stmt *S,
133 CheckerContext &C) const;
134 void checkBind(SVal location, SVal val, const Stmt*S,
135 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000136 ProgramStateRef
137 checkRegionChanges(ProgramStateRef state,
138 const StoreManager::InvalidatedSymbols *invalidated,
139 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000140 ArrayRef<const MemRegion *> Regions,
141 const CallOrObjCMessage *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000142 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
143 return true;
144 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000145
Anna Zaks93c5a242012-05-02 00:05:20 +0000146 void printState(raw_ostream &Out, ProgramStateRef State,
147 const char *NL, const char *Sep) const;
148
Zhongxing Xu7b760962009-11-13 07:25:27 +0000149private:
Anna Zaks66c40402012-02-14 21:55:24 +0000150 void initIdentifierInfo(ASTContext &C) const;
151
152 /// Check if this is one of the functions which can allocate/reallocate memory
153 /// pointed to by one of its arguments.
154 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000155 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
156 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000157
Anna Zaks87cb5be2012-02-22 19:24:52 +0000158 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
159 const CallExpr *CE,
160 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000161 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000162 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000163 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000164 return MallocMemAux(C, CE,
165 state->getSVal(SizeEx, C.getLocationContext()),
166 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000167 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000168
Ted Kremenek8bef8232012-01-26 21:29:00 +0000169 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000170 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000171 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000172
Anna Zaks87cb5be2012-02-22 19:24:52 +0000173 /// Update the RefState to reflect the new memory allocation.
174 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
175 const CallExpr *CE,
176 ProgramStateRef state);
177
178 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
179 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000180 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
181 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000182 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000183
Anna Zaks87cb5be2012-02-22 19:24:52 +0000184 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
185 bool FreesMemOnFailure) const;
186 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000187
Anna Zaks14345182012-05-18 01:16:10 +0000188 ///\brief Check if the memory associated with this symbol was released.
189 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
190
Anna Zaks91c2a112012-02-08 23:16:56 +0000191 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
192 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
193 const Stmt *S = 0) const;
194
Anna Zaks66c40402012-02-14 21:55:24 +0000195 /// Check if the function is not known to us. So, for example, we could
196 /// conservatively assume it can free/reallocate it's pointer arguments.
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000197 bool doesNotFreeMemory(const CallOrObjCMessage *Call,
198 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000199
Ted Kremenek9c378f72011-08-12 23:37:29 +0000200 static bool SummarizeValue(raw_ostream &os, SVal V);
201 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000202 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000203
Anna Zaksca8e36e2012-02-23 21:38:21 +0000204 /// Find the location of the allocation for Sym on the path leading to the
205 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000206 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
207 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000208
Anna Zaksda046772012-02-11 21:02:40 +0000209 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
210
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000211 /// The bug visitor which allows us to print extra diagnostics along the
212 /// BugReport path. For example, showing the allocation site of the leaked
213 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000214 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000215 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000216 enum NotificationMode {
217 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000218 ReallocationFailed
219 };
220
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000221 // The allocated region symbol tracked by the main analysis.
222 SymbolRef Sym;
223
Anna Zaks88feba02012-05-10 01:37:40 +0000224 // The mode we are in, i.e. what kind of diagnostics will be emitted.
225 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000226
Anna Zaks88feba02012-05-10 01:37:40 +0000227 // A symbol from when the primary region should have been reallocated.
228 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000229
Anna Zaks88feba02012-05-10 01:37:40 +0000230 bool IsLeak;
231
232 public:
233 MallocBugVisitor(SymbolRef S, bool isLeak = false)
234 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000235
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000236 virtual ~MallocBugVisitor() {}
237
238 void Profile(llvm::FoldingSetNodeID &ID) const {
239 static int X = 0;
240 ID.AddPointer(&X);
241 ID.AddPointer(Sym);
242 }
243
Anna Zaksfe571602012-02-16 22:26:07 +0000244 inline bool isAllocated(const RefState *S, const RefState *SPrev,
245 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000246 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000247 return (Stmt && isa<CallExpr>(Stmt) &&
248 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000249 }
250
Anna Zaksfe571602012-02-16 22:26:07 +0000251 inline bool isReleased(const RefState *S, const RefState *SPrev,
252 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000253 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000254 return (Stmt && isa<CallExpr>(Stmt) &&
255 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
256 }
257
258 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
259 const Stmt *Stmt) {
260 // If the expression is not a call, and the state change is
261 // released -> allocated, it must be the realloc return value
262 // check. If we have to handle more cases here, it might be cleaner just
263 // to track this extra bit in the state itself.
264 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
265 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000266 }
267
268 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
269 const ExplodedNode *PrevN,
270 BugReporterContext &BRC,
271 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000272
273 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
274 const ExplodedNode *EndPathNode,
275 BugReport &BR) {
276 if (!IsLeak)
277 return 0;
278
279 PathDiagnosticLocation L =
280 PathDiagnosticLocation::createEndOfPath(EndPathNode,
281 BRC.getSourceManager());
282 // Do not add the statement itself as a range in case of leak.
283 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
284 }
285
Anna Zaks56a938f2012-03-16 23:24:20 +0000286 private:
287 class StackHintGeneratorForReallocationFailed
288 : public StackHintGeneratorForSymbol {
289 public:
290 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
291 : StackHintGeneratorForSymbol(S, M) {}
292
293 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
294 SmallString<200> buf;
295 llvm::raw_svector_ostream os(buf);
296
Anna Zaksfbd58742012-03-16 23:44:28 +0000297 os << "Reallocation of ";
Anna Zaks56a938f2012-03-16 23:24:20 +0000298 // Printed parameters start at 1, not 0.
299 printOrdinal(++ArgIndex, os);
300 os << " parameter failed";
301
302 return os.str();
303 }
304
305 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000306 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000307 }
308 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000309 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000310};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000311} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000312
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000313typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000314typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000315class RegionState {};
316class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000317namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000318namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000319 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000320 struct ProgramStateTrait<RegionState>
321 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000322 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000323 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000324
325 template <>
326 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000327 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000328 static void *GDMIndex() { static int x; return &x; }
329 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000330}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000331}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000332
Anna Zaks4fb54872012-02-11 21:02:35 +0000333namespace {
334class StopTrackingCallback : public SymbolVisitor {
335 ProgramStateRef state;
336public:
337 StopTrackingCallback(ProgramStateRef st) : state(st) {}
338 ProgramStateRef getState() const { return state; }
339
340 bool VisitSymbol(SymbolRef sym) {
341 state = state->remove<RegionState>(sym);
342 return true;
343 }
344};
345} // end anonymous namespace
346
Anna Zaks66c40402012-02-14 21:55:24 +0000347void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000348 if (II_malloc)
349 return;
350 II_malloc = &Ctx.Idents.get("malloc");
351 II_free = &Ctx.Idents.get("free");
352 II_realloc = &Ctx.Idents.get("realloc");
353 II_reallocf = &Ctx.Idents.get("reallocf");
354 II_calloc = &Ctx.Idents.get("calloc");
355 II_valloc = &Ctx.Idents.get("valloc");
356 II_strdup = &Ctx.Idents.get("strdup");
357 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000358}
359
Anna Zaks66c40402012-02-14 21:55:24 +0000360bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000361 if (isFreeFunction(FD, C))
362 return true;
363
364 if (isAllocationFunction(FD, C))
365 return true;
366
367 return false;
368}
369
370bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
371 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000372 if (!FD)
373 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000374
Anna Zaks66c40402012-02-14 21:55:24 +0000375 IdentifierInfo *FunI = FD->getIdentifier();
376 if (!FunI)
377 return false;
378
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000379 initIdentifierInfo(C);
380
Anna Zaks14345182012-05-18 01:16:10 +0000381 if (FunI == II_malloc || FunI == II_realloc ||
Anna Zaks60a1fa42012-02-22 03:14:20 +0000382 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
383 FunI == II_strdup || FunI == II_strndup)
Anna Zaks66c40402012-02-14 21:55:24 +0000384 return true;
385
Anna Zaks14345182012-05-18 01:16:10 +0000386 if (Filter.CMallocOptimistic && FD->hasAttrs())
387 for (specific_attr_iterator<OwnershipAttr>
388 i = FD->specific_attr_begin<OwnershipAttr>(),
389 e = FD->specific_attr_end<OwnershipAttr>();
390 i != e; ++i)
391 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
392 return true;
393 return false;
394}
395
396bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
397 if (!FD)
398 return false;
399
400 IdentifierInfo *FunI = FD->getIdentifier();
401 if (!FunI)
402 return false;
403
404 initIdentifierInfo(C);
405
406 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
Anna Zaks66c40402012-02-14 21:55:24 +0000407 return true;
408
Anna Zaks14345182012-05-18 01:16:10 +0000409 if (Filter.CMallocOptimistic && FD->hasAttrs())
410 for (specific_attr_iterator<OwnershipAttr>
411 i = FD->specific_attr_begin<OwnershipAttr>(),
412 e = FD->specific_attr_end<OwnershipAttr>();
413 i != e; ++i)
414 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
415 (*i)->getOwnKind() == OwnershipAttr::Holds)
416 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000417 return false;
418}
419
Anna Zaksb319e022012-02-08 20:13:28 +0000420void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
421 const FunctionDecl *FD = C.getCalleeDecl(CE);
422 if (!FD)
423 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000424
Anna Zaksb16ce452012-02-15 00:11:22 +0000425 initIdentifierInfo(C.getASTContext());
426 IdentifierInfo *FunI = FD->getIdentifier();
427 if (!FunI)
428 return;
429
Anna Zaks87cb5be2012-02-22 19:24:52 +0000430 ProgramStateRef State = C.getState();
Anna Zaksb16ce452012-02-15 00:11:22 +0000431 if (FunI == II_malloc || FunI == II_valloc) {
Anna Zaks259052d2012-04-10 23:41:11 +0000432 if (CE->getNumArgs() < 1)
433 return;
Anna Zaks87cb5be2012-02-22 19:24:52 +0000434 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anna Zaksb16ce452012-02-15 00:11:22 +0000435 } else if (FunI == II_realloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000436 State = ReallocMem(C, CE, false);
Anna Zaks40add292012-02-15 00:11:25 +0000437 } else if (FunI == II_reallocf) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000438 State = ReallocMem(C, CE, true);
Anna Zaksb16ce452012-02-15 00:11:22 +0000439 } else if (FunI == II_calloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000440 State = CallocMem(C, CE);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000441 } else if (FunI == II_free) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000442 State = FreeMemAux(C, CE, C.getState(), 0, false);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000443 } else if (FunI == II_strdup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000444 State = MallocUpdateRefState(C, CE, State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000445 } else if (FunI == II_strndup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000446 State = MallocUpdateRefState(C, CE, State);
447 } else if (Filter.CMallocOptimistic) {
448 // Check all the attributes, if there are any.
449 // There can be multiple of these attributes.
450 if (FD->hasAttrs())
451 for (specific_attr_iterator<OwnershipAttr>
452 i = FD->specific_attr_begin<OwnershipAttr>(),
453 e = FD->specific_attr_end<OwnershipAttr>();
454 i != e; ++i) {
455 switch ((*i)->getOwnKind()) {
456 case OwnershipAttr::Returns:
457 State = MallocMemReturnsAttr(C, CE, *i);
458 break;
459 case OwnershipAttr::Takes:
460 case OwnershipAttr::Holds:
461 State = FreeMemAttr(C, CE, *i);
462 break;
463 }
464 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000465 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000466 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000467}
468
Anna Zaks87cb5be2012-02-22 19:24:52 +0000469ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
470 const CallExpr *CE,
471 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000472 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000473 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000474
Sean Huntcf807c42010-08-18 23:23:40 +0000475 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000476 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000477 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000478 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000479 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000480}
481
Anna Zaksb319e022012-02-08 20:13:28 +0000482ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000483 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000484 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000485 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000486
487 // Bind the return value to the symbolic value from the heap region.
488 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
489 // side effects other than what we model here.
490 unsigned Count = C.getCurrentBlockCount();
491 SValBuilder &svalBuilder = C.getSValBuilder();
492 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
493 DefinedSVal RetVal =
494 cast<DefinedSVal>(svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count));
495 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000496
Anna Zaksb16ce452012-02-15 00:11:22 +0000497 // We expect the malloc functions to return a pointer.
Anna Zakse17fdb22012-06-07 03:57:32 +0000498 if (!isa<Loc>(RetVal))
Anna Zaksb16ce452012-02-15 00:11:22 +0000499 return 0;
500
Jordy Rose32f26562010-07-04 00:00:41 +0000501 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000502 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000503
Jordy Rose32f26562010-07-04 00:00:41 +0000504 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000505 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000506 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000507 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000508 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000509 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000510 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000511 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
512 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
513 DefinedOrUnknownSVal extentMatchesSize =
514 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000515
Anna Zaks60a1fa42012-02-22 03:14:20 +0000516 state = state->assume(extentMatchesSize, true);
517 assert(state);
518 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000519
Anna Zaks87cb5be2012-02-22 19:24:52 +0000520 return MallocUpdateRefState(C, CE, state);
521}
522
523ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
524 const CallExpr *CE,
525 ProgramStateRef state) {
526 // Get the return value.
527 SVal retVal = state->getSVal(CE, C.getLocationContext());
528
529 // We expect the malloc functions to return a pointer.
530 if (!isa<Loc>(retVal))
531 return 0;
532
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000533 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000534 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000535
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000536 // Set the symbol's state to Allocated.
Anna Zaks050cdd72012-06-20 20:57:46 +0000537 return state->set<RegionState>(Sym, RefState::getAllocated(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000538
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000539}
540
Anna Zaks87cb5be2012-02-22 19:24:52 +0000541ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
542 const CallExpr *CE,
543 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000544 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000545 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000546
Anna Zaksb3d72752012-03-01 22:06:06 +0000547 ProgramStateRef State = C.getState();
548
Sean Huntcf807c42010-08-18 23:23:40 +0000549 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
550 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000551 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
552 Att->getOwnKind() == OwnershipAttr::Holds);
553 if (StateI)
554 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000555 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000556 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000557}
558
Ted Kremenek8bef8232012-01-26 21:29:00 +0000559ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000560 const CallExpr *CE,
561 ProgramStateRef state,
562 unsigned Num,
563 bool Hold) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000564 if (CE->getNumArgs() < (Num + 1))
565 return 0;
566
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000567 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000568 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000569 if (!isa<DefinedOrUnknownSVal>(ArgVal))
570 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000571 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
572
573 // Check for null dereferences.
574 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000575 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000576
Anna Zaksb276bd92012-02-14 00:26:13 +0000577 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000578 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000579 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000580 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000581 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000582
Jordy Rose43859f62010-06-07 19:32:37 +0000583 // Unknown values could easily be okay
584 // Undefined values are handled elsewhere
585 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000586 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000587
Jordy Rose43859f62010-06-07 19:32:37 +0000588 const MemRegion *R = ArgVal.getAsRegion();
589
590 // Nonlocs can't be freed, of course.
591 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
592 if (!R) {
593 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000594 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000595 }
596
597 R = R->StripCasts();
598
599 // Blocks might show up as heap data, but should not be free()d
600 if (isa<BlockDataRegion>(R)) {
601 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000602 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000603 }
604
605 const MemSpaceRegion *MS = R->getMemorySpace();
606
607 // Parameters, locals, statics, and globals shouldn't be freed.
608 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
609 // FIXME: at the time this code was written, malloc() regions were
610 // represented by conjured symbols, which are all in UnknownSpaceRegion.
611 // This means that there isn't actually anything from HeapSpaceRegion
612 // that should be freed, even though we allow it here.
613 // Of course, free() can work on memory allocated outside the current
614 // function, so UnknownSpaceRegion is always a possibility.
615 // False negatives are better than false positives.
616
617 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000618 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000619 }
620
621 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
622 // Various cases could lead to non-symbol values here.
623 // For now, ignore them.
624 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000625 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000626
627 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000628 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000629
630 // If the symbol has not been tracked, return. This is possible when free() is
631 // called on a pointer that does not get its pointee directly from malloc().
632 // Full support of this requires inter-procedural analysis.
633 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000634 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000635
636 // Check double free.
Anna Zaks050cdd72012-06-20 20:57:46 +0000637 // TODO: Split the 2 cases for better error messages.
638 if (RS->isReleased() || RS->isRelinquished()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000639 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000640 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000641 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000642 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000643 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaksfebdc322012-02-16 22:26:12 +0000644 "Attempt to free released memory", N);
Anna Zaksfe571602012-02-16 22:26:07 +0000645 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000646 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000647 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000648 C.EmitReport(R);
649 }
Anna Zaksb319e022012-02-08 20:13:28 +0000650 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000651 }
652
653 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000654 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000655 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
656 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000657}
658
Ted Kremenek9c378f72011-08-12 23:37:29 +0000659bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000660 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
661 os << "an integer (" << IntVal->getValue() << ")";
662 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
663 os << "a constant address (" << ConstAddr->getValue() << ")";
664 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000665 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000666 else
667 return false;
668
669 return true;
670}
671
Ted Kremenek9c378f72011-08-12 23:37:29 +0000672bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000673 const MemRegion *MR) {
674 switch (MR->getKind()) {
675 case MemRegion::FunctionTextRegionKind: {
676 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
677 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000678 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000679 else
680 os << "the address of a function";
681 return true;
682 }
683 case MemRegion::BlockTextRegionKind:
684 os << "block text";
685 return true;
686 case MemRegion::BlockDataRegionKind:
687 // FIXME: where the block came from?
688 os << "a block";
689 return true;
690 default: {
691 const MemSpaceRegion *MS = MR->getMemorySpace();
692
Anna Zakseb31a762012-01-04 23:54:01 +0000693 if (isa<StackLocalsSpaceRegion>(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 local variable '" << VD->getName() << "'";
703 else
704 os << "the address of a local stack variable";
705 return true;
706 }
Anna Zakseb31a762012-01-04 23:54:01 +0000707
708 if (isa<StackArgumentsSpaceRegion>(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 os << "the address of the parameter '" << VD->getName() << "'";
718 else
719 os << "the address of a parameter";
720 return true;
721 }
Anna Zakseb31a762012-01-04 23:54:01 +0000722
723 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000724 const VarRegion *VR = dyn_cast<VarRegion>(MR);
725 const VarDecl *VD;
726 if (VR)
727 VD = VR->getDecl();
728 else
729 VD = NULL;
730
731 if (VD) {
732 if (VD->isStaticLocal())
733 os << "the address of the static variable '" << VD->getName() << "'";
734 else
735 os << "the address of the global variable '" << VD->getName() << "'";
736 } else
737 os << "the address of a global variable";
738 return true;
739 }
Anna Zakseb31a762012-01-04 23:54:01 +0000740
741 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000742 }
743 }
744}
745
746void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000747 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000748 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000749 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000750 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000751
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000752 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000753 llvm::raw_svector_ostream os(buf);
754
755 const MemRegion *MR = ArgVal.getAsRegion();
756 if (MR) {
757 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
758 MR = ER->getSuperRegion();
759
760 // Special case for alloca()
761 if (isa<AllocaRegion>(MR))
762 os << "Argument to free() was allocated by alloca(), not malloc()";
763 else {
764 os << "Argument to free() is ";
765 if (SummarizeRegion(os, MR))
766 os << ", which is not memory allocated by malloc()";
767 else
768 os << "not memory allocated by malloc()";
769 }
770 } else {
771 os << "Argument to free() is ";
772 if (SummarizeValue(os, ArgVal))
773 os << ", which is not memory allocated by malloc()";
774 else
775 os << "not memory allocated by malloc()";
776 }
777
Anna Zakse172e8b2011-08-17 23:00:25 +0000778 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000779 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000780 R->addRange(range);
781 C.EmitReport(R);
782 }
783}
784
Anna Zaks87cb5be2012-02-22 19:24:52 +0000785ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
786 const CallExpr *CE,
787 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000788 if (CE->getNumArgs() < 2)
789 return 0;
790
Ted Kremenek8bef8232012-01-26 21:29:00 +0000791 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000792 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000793 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000794 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
795 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000796 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000797 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000798
Ted Kremenek846eabd2010-12-01 21:28:31 +0000799 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000800
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000801 DefinedOrUnknownSVal PtrEQ =
802 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000803
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000804 // Get the size argument. If there is no size arg then give up.
805 const Expr *Arg1 = CE->getArg(1);
806 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000807 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000808
809 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000810 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
811 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000812 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000813 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000814
815 // Compare the size argument to 0.
816 DefinedOrUnknownSVal SizeZero =
817 svalBuilder.evalEQ(state, Arg1Val,
818 svalBuilder.makeIntValWithPtrWidth(0, false));
819
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000820 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
821 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
822 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
823 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
824 // We only assume exceptional states if they are definitely true; if the
825 // state is under-constrained, assume regular realloc behavior.
826 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
827 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
828
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000829 // If the ptr is NULL and the size is not 0, the call is equivalent to
830 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000831 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000832 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000833 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000834 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000835 }
836
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000837 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000838 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000839
Anna Zaks30838b92012-02-13 20:57:07 +0000840 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000841 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000842 SymbolRef FromPtr = arg0Val.getAsSymbol();
843 SVal RetVal = state->getSVal(CE, LCtx);
844 SymbolRef ToPtr = RetVal.getAsSymbol();
845 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000846 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000847
848 // If the size is 0, free the memory.
849 if (SizeIsZero)
850 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000851 // The semantics of the return value are:
852 // If size was equal to 0, either NULL or a pointer suitable to be passed
853 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000854 stateFree = stateFree->set<ReallocPairs>(ToPtr,
855 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000856 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000857 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000858 }
859
860 // Default behavior.
861 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
862 // FIXME: We should copy the content of the original buffer.
863 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
864 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000865 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000866 return 0;
Anna Zaks40add292012-02-15 00:11:25 +0000867 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
868 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000869 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000870 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000871 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000872 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000873}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000874
Anna Zaks87cb5be2012-02-22 19:24:52 +0000875ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +0000876 if (CE->getNumArgs() < 2)
877 return 0;
878
Ted Kremenek8bef8232012-01-26 21:29:00 +0000879 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000880 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000881 const LocationContext *LCtx = C.getLocationContext();
882 SVal count = state->getSVal(CE->getArg(0), LCtx);
883 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000884 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
885 svalBuilder.getContext().getSizeType());
886 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000887
Anna Zaks87cb5be2012-02-22 19:24:52 +0000888 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000889}
890
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000891LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +0000892MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
893 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000894 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000895 // Walk the ExplodedGraph backwards and find the first node that referred to
896 // the tracked symbol.
897 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000898 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000899
900 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000901 ProgramStateRef State = N->getState();
902 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +0000903 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000904
905 // Find the most recent expression bound to the symbol in the current
906 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000907 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +0000908 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
909 SVal Val = State->getSVal(MR);
910 if (Val.getAsLocSymbol() == Sym)
911 ReferenceRegion = MR;
912 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000913 }
914
Anna Zaks7752d292012-02-27 23:40:55 +0000915 // Allocation node, is the last node in the current context in which the
916 // symbol was tracked.
917 if (N->getLocationContext() == LeakContext)
918 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000919 N = N->pred_empty() ? NULL : *(N->pred_begin());
920 }
921
922 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000923 const Stmt *AllocationStmt = 0;
924 if (isa<StmtPoint>(P))
925 AllocationStmt = cast<StmtPoint>(P).getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +0000926
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000927 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +0000928}
929
Anna Zaksda046772012-02-11 21:02:40 +0000930void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
931 CheckerContext &C) const {
932 assert(N);
933 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000934 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000935 // Leaks should not be reported if they are post-dominated by a sink:
936 // (1) Sinks are higher importance bugs.
937 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
938 // with __noreturn functions such as assert() or exit(). We choose not
939 // to report leaks on such paths.
940 BT_Leak->setSuppressOnSink(true);
941 }
942
Anna Zaksca8e36e2012-02-23 21:38:21 +0000943 // Most bug reports are cached at the location where they occurred.
944 // With leaks, we want to unique them by the location where they were
945 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +0000946 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000947 const Stmt *AllocStmt = 0;
948 const MemRegion *Region = 0;
949 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
950 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +0000951 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
952 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +0000953
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000954 SmallString<200> buf;
955 llvm::raw_svector_ostream os(buf);
956 os << "Memory is never released; potential leak";
957 if (Region) {
958 os << " of memory pointed to by '";
959 Region->dumpPretty(os);
960 os <<'\'';
961 }
962
963 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000964 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +0000965 R->addVisitor(new MallocBugVisitor(Sym, true));
Anna Zaksda046772012-02-11 21:02:40 +0000966 C.EmitReport(R);
967}
968
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000969void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
970 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000971{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000972 if (!SymReaper.hasDeadSymbols())
973 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000974
Ted Kremenek8bef8232012-01-26 21:29:00 +0000975 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000976 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000977 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000978
Ted Kremenek217470e2011-07-28 23:07:51 +0000979 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000980 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000981 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
982 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000983 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000984 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000985 Errors.push_back(I->first);
986 }
Jordy Rose90760142010-08-18 04:33:47 +0000987 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000988 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000989
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000990 }
991 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000992
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000993 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000994 ReallocMap RP = state->get<ReallocPairs>();
995 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
996 if (SymReaper.isDead(I->first) ||
997 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000998 state = state->remove<ReallocPairs>(I->first);
999 }
1000 }
1001
Anna Zaksca8e36e2012-02-23 21:38:21 +00001002 // Generate leak node.
1003 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1004 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +00001005
Anna Zaksca8e36e2012-02-23 21:38:21 +00001006 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +00001007 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +00001008 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
1009 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001010 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001011 }
Anna Zaksca8e36e2012-02-23 21:38:21 +00001012 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001013}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001014
Anna Zaksda046772012-02-11 21:02:40 +00001015void MallocChecker::checkEndPath(CheckerContext &C) const {
1016 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +00001017 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +00001018
Anna Zaksa19581a2012-02-20 22:25:23 +00001019 // If inside inlined call, skip it.
1020 if (C.getLocationContext()->getParent() != 0)
1021 return;
1022
Jordy Rose09cef092010-08-18 04:26:59 +00001023 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +00001024 RefState RS = I->second;
1025 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +00001026 ExplodedNode *N = C.addTransition(state);
1027 if (N)
1028 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +00001029 }
1030 }
1031}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001032
Anna Zaks91c2a112012-02-08 23:16:56 +00001033bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
1034 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +00001035 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +00001036 const RefState *RS = state->get<RegionState>(Sym);
1037 if (!RS)
1038 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001039
Anna Zaks91c2a112012-02-08 23:16:56 +00001040 if (RS->isAllocated()) {
1041 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
1042 C.addTransition(state);
1043 return true;
1044 }
1045 return false;
1046}
1047
Anna Zaks66c40402012-02-14 21:55:24 +00001048void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001049 // We will check for double free in the post visit.
1050 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001051 return;
1052
1053 // Check use after free, when a freed pointer is passed to a call.
1054 ProgramStateRef State = C.getState();
1055 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1056 E = CE->arg_end(); I != E; ++I) {
1057 const Expr *A = *I;
1058 if (A->getType().getTypePtr()->isAnyPointerType()) {
1059 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1060 if (!Sym)
1061 continue;
1062 if (checkUseAfterFree(Sym, C, A))
1063 return;
1064 }
1065 }
1066}
1067
Anna Zaks91c2a112012-02-08 23:16:56 +00001068void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1069 const Expr *E = S->getRetValue();
1070 if (!E)
1071 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001072
1073 // Check if we are returning a symbol.
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001074 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
1075 SymbolRef Sym = RetVal.getAsSymbol();
1076 if (!Sym)
1077 // If we are returning a field of the allocated struct or an array element,
1078 // the callee could still free the memory.
1079 // TODO: This logic should be a part of generic symbol escape callback.
1080 if (const MemRegion *MR = RetVal.getAsRegion())
1081 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1082 if (const SymbolicRegion *BMR =
1083 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1084 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001085 if (!Sym)
1086 return;
1087
Anna Zaks0860cd02012-02-11 21:44:39 +00001088 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +00001089 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +00001090 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001091
Anna Zaksa19581a2012-02-20 22:25:23 +00001092 // If this function body is not inlined, check if the symbol is escaping.
1093 if (C.getLocationContext()->getParent() == 0)
1094 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001095}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001096
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001097// TODO: Blocks should be either inlined or should call invalidate regions
1098// upon invocation. After that's in place, special casing here will not be
1099// needed.
1100void MallocChecker::checkPostStmt(const BlockExpr *BE,
1101 CheckerContext &C) const {
1102
1103 // Scan the BlockDecRefExprs for any object the retain count checker
1104 // may be tracking.
1105 if (!BE->getBlockDecl()->hasCaptures())
1106 return;
1107
1108 ProgramStateRef state = C.getState();
1109 const BlockDataRegion *R =
1110 cast<BlockDataRegion>(state->getSVal(BE,
1111 C.getLocationContext()).getAsRegion());
1112
1113 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1114 E = R->referenced_vars_end();
1115
1116 if (I == E)
1117 return;
1118
1119 SmallVector<const MemRegion*, 10> Regions;
1120 const LocationContext *LC = C.getLocationContext();
1121 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1122
1123 for ( ; I != E; ++I) {
1124 const VarRegion *VR = *I;
1125 if (VR->getSuperRegion() == R) {
1126 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1127 }
1128 Regions.push_back(VR);
1129 }
1130
1131 state =
1132 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1133 Regions.data() + Regions.size()).getState();
1134 C.addTransition(state);
1135}
1136
Anna Zaks14345182012-05-18 01:16:10 +00001137bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001138 assert(Sym);
1139 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001140 return (RS && RS->isReleased());
1141}
1142
1143bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1144 const Stmt *S) const {
1145 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001146 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001147 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001148 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001149
Anna Zaksfebdc322012-02-16 22:26:12 +00001150 BugReport *R = new BugReport(*BT_UseFree,
1151 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001152 if (S)
1153 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001154 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001155 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +00001156 C.EmitReport(R);
1157 return true;
1158 }
1159 }
1160 return false;
1161}
1162
Zhongxing Xuc8023782010-03-10 04:58:55 +00001163// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001164void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1165 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001166 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001167 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001168 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001169}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001170
Anna Zaks4fb54872012-02-11 21:02:35 +00001171//===----------------------------------------------------------------------===//
1172// Check various ways a symbol can be invalidated.
1173// TODO: This logic (the next 3 functions) is copied/similar to the
1174// RetainRelease checker. We might want to factor this out.
1175//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001176
Anna Zaks4fb54872012-02-11 21:02:35 +00001177// Stop tracking symbols when a value escapes as a result of checkBind.
1178// A value escapes in three possible cases:
1179// (1) we are binding to something that is not a memory region.
1180// (2) we are binding to a memregion that does not have stack storage
1181// (3) we are binding to a memregion with stack storage that the store
1182// does not understand.
1183void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1184 CheckerContext &C) const {
1185 // Are we storing to something that causes the value to "escape"?
1186 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001187 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001188
Anna Zaks4fb54872012-02-11 21:02:35 +00001189 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1190 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001191
Anna Zaks4fb54872012-02-11 21:02:35 +00001192 if (!escapes) {
1193 // To test (3), generate a new state with the binding added. If it is
1194 // the same state, then it escapes (since the store cannot represent
1195 // the binding).
Anna Zaks93c5a242012-05-02 00:05:20 +00001196 // Do this only if we know that the store is not supposed to generate the
1197 // same state.
1198 SVal StoredVal = state->getSVal(regionLoc->getRegion());
1199 if (StoredVal != val)
1200 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001201 }
Anna Zaksac593002012-02-16 03:40:57 +00001202 if (!escapes) {
1203 // Case 4: We do not currently model what happens when a symbol is
1204 // assigned to a struct field, so be conservative here and let the symbol
1205 // go. TODO: This could definitely be improved upon.
1206 escapes = !isa<VarRegion>(regionLoc->getRegion());
1207 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001208 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001209
1210 // If our store can represent the binding and we aren't storing to something
1211 // that doesn't have local storage then just return and have the simulation
1212 // state continue as is.
1213 if (!escapes)
1214 return;
1215
1216 // Otherwise, find all symbols referenced by 'val' that we are tracking
1217 // and stop tracking them.
1218 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1219 C.addTransition(state);
1220}
1221
1222// If a symbolic region is assumed to NULL (or another constant), stop tracking
1223// it - assuming that allocation failed on this path.
1224ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1225 SVal Cond,
1226 bool Assumption) const {
1227 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001228 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1229 // If the symbol is assumed to NULL or another constant, this will
1230 // return an APSInt*.
1231 if (state->getSymVal(I.getKey()))
1232 state = state->remove<RegionState>(I.getKey());
1233 }
1234
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001235 // Realloc returns 0 when reallocation fails, which means that we should
1236 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001237 ReallocMap RP = state->get<ReallocPairs>();
1238 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001239 // If the symbol is assumed to NULL or another constant, this will
1240 // return an APSInt*.
1241 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001242 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1243 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001244 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001245 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1246 state = state->set<RegionState>(ReallocSym,
Anna Zaks050cdd72012-06-20 20:57:46 +00001247 RefState::getAllocated(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001248 }
1249 state = state->remove<ReallocPairs>(I.getKey());
1250 }
1251 }
1252
Anna Zaks4fb54872012-02-11 21:02:35 +00001253 return state;
1254}
1255
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001256// Check if the function is known to us. So, for example, we could
Anna Zaks66c40402012-02-14 21:55:24 +00001257// conservatively assume it can free/reallocate it's pointer arguments.
1258// (We assume that the pointers cannot escape through calls to system
1259// functions not handled by this checker.)
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001260bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call,
1261 ProgramStateRef State) const {
1262 if (!Call)
1263 return false;
1264
1265 // For now, assume that any C++ call can free memory.
1266 // TODO: If we want to be more optimistic here, we'll need to make sure that
1267 // regions escape to C++ containers. They seem to do that even now, but for
1268 // mysterious reasons.
1269 if (Call->isCXXCall())
1270 return false;
1271
1272 const Decl *D = Call->getDecl();
1273 if (!D)
1274 return false;
1275
Anna Zaks66c40402012-02-14 21:55:24 +00001276 ASTContext &ASTC = State->getStateManager().getContext();
1277
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001278 // If it's one of the allocation functions we can reason about, we model
Jordy Rose257c60f2012-03-06 00:28:20 +00001279 // its behavior explicitly.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001280 if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) {
1281 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001282 }
1283
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001284 // If it's not a system call, assume it frees memory.
Anna Zaks66c40402012-02-14 21:55:24 +00001285 SourceManager &SM = ASTC.getSourceManager();
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001286 if (!SM.isInSystemHeader(D->getLocation()))
1287 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001288
Anna Zaks07d39a42012-02-28 01:54:22 +00001289 // Process C/ObjC functions.
Jordy Rose257c60f2012-03-06 00:28:20 +00001290 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Anna Zaks0d389b82012-02-23 01:05:27 +00001291 // White list the system functions whose arguments escape.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001292 const IdentifierInfo *II = FD->getIdentifier();
Anna Zaks07d39a42012-02-28 01:54:22 +00001293 if (!II)
1294 return true;
1295 StringRef FName = II->getName();
1296
1297 // White list thread local storage.
1298 if (FName.equals("pthread_setspecific"))
1299 return false;
1300
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001301 // White list the 'XXXNoCopy' ObjC functions.
Anna Zaks07d39a42012-02-28 01:54:22 +00001302 if (FName.endswith("NoCopy")) {
1303 // Look for the deallocator argument. We know that the memory ownership
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001304 // is not transferred only if the deallocator argument is
Anna Zaks07d39a42012-02-28 01:54:22 +00001305 // 'kCFAllocatorNull'.
1306 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1307 const Expr *ArgE = Call->getArg(i)->IgnoreParenCasts();
1308 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1309 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1310 if (DeallocatorName == "kCFAllocatorNull")
1311 return true;
1312 }
1313 }
1314 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001315 }
1316
Anna Zaksca23eb22012-02-29 18:42:47 +00001317 // PR12101
1318 // Many CoreFoundation and CoreGraphics might allow a tracked object
1319 // to escape.
1320 if (Call->isCFCGAllowingEscape(FName))
1321 return false;
1322
1323 // Associating streams with malloced buffers. The pointer can escape if
1324 // 'closefn' is specified (and if that function does free memory).
1325 // Currently, we do not inspect the 'closefn' function (PR12101).
1326 if (FName == "funopen")
1327 if (Call->getNumArgs() >= 4 && !Call->getArgSVal(4).isConstant(0))
1328 return false;
1329
1330 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1331 // these leaks might be intentional when setting the buffer for stdio.
1332 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1333 if (FName == "setbuf" || FName =="setbuffer" ||
1334 FName == "setlinebuf" || FName == "setvbuf") {
1335 if (Call->getNumArgs() >= 1)
1336 if (const DeclRefExpr *Arg =
1337 dyn_cast<DeclRefExpr>(Call->getArg(0)->IgnoreParenCasts()))
1338 if (const VarDecl *D = dyn_cast<VarDecl>(Arg->getDecl()))
1339 if (D->getCanonicalDecl()->getName().find("std")
1340 != StringRef::npos)
1341 return false;
1342 }
1343
Jordan Rose1bf908d2012-06-16 00:09:20 +00001344 // A bunch of other functions which either take ownership of a pointer or
1345 // wrap the result up in a struct or object, meaning it can be freed later.
1346 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1347 // but the Malloc checker cannot differentiate between them. The right way
1348 // of doing this would be to implement a pointer escapes callback.
1349 if (FName == "CGBitmapContextCreate" ||
Anna Zaksca23eb22012-02-29 18:42:47 +00001350 FName == "CGBitmapContextCreateWithData" ||
Jordan Rose1bf908d2012-06-16 00:09:20 +00001351 FName == "CVPixelBufferCreateWithBytes" ||
Anna Zaks4cd7edf2012-03-26 18:18:39 +00001352 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1353 FName == "OSAtomicEnqueue") {
Anna Zaksca23eb22012-02-29 18:42:47 +00001354 return false;
1355 }
1356
Anna Zaks62a5c342012-03-30 05:48:16 +00001357 // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1358 // be deallocated by NSMapRemove.
1359 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
1360 return false;
1361
Anna Zaksaca0ac52012-05-03 23:50:28 +00001362 // If the call has a callback as an argument, assume the memory
1363 // can be freed.
1364 if (Call->hasNonZeroCallbackArg())
1365 return false;
1366
Anna Zaks0d389b82012-02-23 01:05:27 +00001367 // Otherwise, assume that the function does not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001368 // Most system calls, do not free the memory.
1369 return true;
1370
1371 // Process ObjC functions.
1372 } else if (const ObjCMethodDecl * ObjCD = dyn_cast<ObjCMethodDecl>(D)) {
1373 Selector S = ObjCD->getSelector();
1374
1375 // White list the ObjC functions which do free memory.
1376 // - Anything containing 'freeWhenDone' param set to 1.
1377 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
1378 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
1379 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1380 if (Call->getArgSVal(i).isConstant(1))
1381 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001382 else
1383 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001384 }
1385 }
1386
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001387 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001388 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001389 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1390 if (S.getNameForSlot(0).endswith("NoCopy")) {
1391 return false;
1392 }
1393
Anna Zaks5f757682012-06-19 05:10:32 +00001394 // If the first selector starts with addPointer, insertPointer,
1395 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1396 // This is similar to C++ containers (vector); we still might want to check
1397 // that the pointers get freed, by following the container itself.
1398 if (S.getNameForSlot(0).startswith("addPointer") ||
1399 S.getNameForSlot(0).startswith("insertPointer") ||
1400 S.getNameForSlot(0).startswith("replacePointer")) {
1401 return false;
1402 }
1403
Anna Zaksaca0ac52012-05-03 23:50:28 +00001404 // If the call has a callback as an argument, assume the memory
1405 // can be freed.
1406 if (Call->hasNonZeroCallbackArg())
1407 return false;
1408
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001409 // Otherwise, assume that the function does not free memory.
1410 // Most system calls, do not free the memory.
1411 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001412 }
1413
1414 // Otherwise, assume that the function can free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001415 return false;
1416
Anna Zaks66c40402012-02-14 21:55:24 +00001417}
1418
Anna Zaks4fb54872012-02-11 21:02:35 +00001419// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1420// escapes, when we are tracking p), do not track the symbol as we cannot reason
1421// about it anymore.
1422ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001423MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001424 const StoreManager::InvalidatedSymbols *invalidated,
1425 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001426 ArrayRef<const MemRegion *> Regions,
1427 const CallOrObjCMessage *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001428 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001429 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001430 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001431
Anna Zaks66c40402012-02-14 21:55:24 +00001432 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001433 // regions (explicit and implicit) escaped.
1434
1435 // Otherwise, whitelist explicit pointers; we still can track them.
1436 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001437 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1438 E = ExplicitRegions.end(); I != E; ++I) {
1439 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1440 WhitelistedSymbols.insert(R->getSymbol());
1441 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001442 }
1443
1444 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1445 E = invalidated->end(); I!=E; ++I) {
1446 SymbolRef sym = *I;
1447 if (WhitelistedSymbols.count(sym))
1448 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001449 // The symbol escaped.
1450 if (const RefState *RS = State->get<RegionState>(sym))
1451 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001452 }
Anna Zaks66c40402012-02-14 21:55:24 +00001453 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001454}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001455
Jordy Rose393f98b2012-03-18 07:43:35 +00001456static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1457 ProgramStateRef prevState) {
1458 ReallocMap currMap = currState->get<ReallocPairs>();
1459 ReallocMap prevMap = prevState->get<ReallocPairs>();
1460
1461 for (ReallocMap::iterator I = prevMap.begin(), E = prevMap.end();
1462 I != E; ++I) {
1463 SymbolRef sym = I.getKey();
1464 if (!currMap.lookup(sym))
1465 return sym;
1466 }
1467
1468 return NULL;
1469}
1470
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001471PathDiagnosticPiece *
1472MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1473 const ExplodedNode *PrevN,
1474 BugReporterContext &BRC,
1475 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001476 ProgramStateRef state = N->getState();
1477 ProgramStateRef statePrev = PrevN->getState();
1478
1479 const RefState *RS = state->get<RegionState>(Sym);
1480 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001481 if (!RS && !RSPrev)
1482 return 0;
1483
Anna Zaksfe571602012-02-16 22:26:07 +00001484 const Stmt *S = 0;
1485 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001486 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001487
1488 // Retrieve the associated statement.
1489 ProgramPoint ProgLoc = N->getLocation();
1490 if (isa<StmtPoint>(ProgLoc))
1491 S = cast<StmtPoint>(ProgLoc).getStmt();
1492 // If an assumption was made on a branch, it should be caught
1493 // here by looking at the state transition.
1494 if (isa<BlockEdge>(ProgLoc)) {
1495 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1496 S = srcBlk->getTerminator();
1497 }
1498 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001499 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001500
1501 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001502 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001503 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001504 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001505 StackHint = new StackHintGeneratorForSymbol(Sym,
1506 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001507 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001508 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001509 StackHint = new StackHintGeneratorForSymbol(Sym,
1510 "Returned released memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001511 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001512 Mode = ReallocationFailed;
1513 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001514 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001515 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001516
Jordy Roseb000fb52012-03-24 03:15:09 +00001517 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1518 // Is it possible to fail two reallocs WITHOUT testing in between?
1519 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1520 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001521 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001522 FailedReallocSymbol = sym;
1523 }
Anna Zaksfe571602012-02-16 22:26:07 +00001524 }
1525
1526 // We are in a special mode if a reallocation failed later in the path.
1527 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001528 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001529
Jordy Roseb000fb52012-03-24 03:15:09 +00001530 // Is this is the first appearance of the reallocated symbol?
1531 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
1532 // If we ever hit this assert, that means BugReporter has decided to skip
1533 // node pairs or visit them out of order.
1534 assert(state->get<RegionState>(FailedReallocSymbol) &&
1535 "Missed the reallocation point");
1536
1537 // We're at the reallocation point.
1538 Msg = "Attempt to reallocate memory";
1539 StackHint = new StackHintGeneratorForSymbol(Sym,
1540 "Returned reallocated memory");
1541 FailedReallocSymbol = NULL;
1542 Mode = Normal;
1543 }
Anna Zaksfe571602012-02-16 22:26:07 +00001544 }
1545
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001546 if (!Msg)
1547 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001548 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001549
1550 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001551 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001552 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001553 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001554}
1555
Anna Zaks93c5a242012-05-02 00:05:20 +00001556void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1557 const char *NL, const char *Sep) const {
1558
1559 RegionStateTy RS = State->get<RegionState>();
1560
1561 if (!RS.isEmpty())
1562 Out << "Has Malloc data" << NL;
1563}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001564
Anna Zaks231361a2012-02-08 23:16:52 +00001565#define REGISTER_CHECKER(name) \
1566void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001567 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001568 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001569}
Anna Zaks231361a2012-02-08 23:16:52 +00001570
1571REGISTER_CHECKER(MallocPessimistic)
1572REGISTER_CHECKER(MallocOptimistic)