blob: f5218746befc4429eb48996f2ddb6b3356821028 [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
Zhongxing Xu7b760962009-11-13 07:25:27 +0000140private:
Anna Zaks66c40402012-02-14 21:55:24 +0000141 void initIdentifierInfo(ASTContext &C) const;
142
143 /// Check if this is one of the functions which can allocate/reallocate memory
144 /// pointed to by one of its arguments.
145 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
146
Anna Zaks87cb5be2012-02-22 19:24:52 +0000147 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
148 const CallExpr *CE,
149 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000150 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000151 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000152 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000153 return MallocMemAux(C, CE,
154 state->getSVal(SizeEx, C.getLocationContext()),
155 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000156 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000157
Ted Kremenek8bef8232012-01-26 21:29:00 +0000158 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000159 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000160 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000161
Anna Zaks87cb5be2012-02-22 19:24:52 +0000162 /// Update the RefState to reflect the new memory allocation.
163 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
164 const CallExpr *CE,
165 ProgramStateRef state);
166
167 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
168 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000169 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
170 ProgramStateRef state, unsigned Num,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000171 bool Hold) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000172
Anna Zaks87cb5be2012-02-22 19:24:52 +0000173 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
174 bool FreesMemOnFailure) const;
175 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000176
Anna Zaks91c2a112012-02-08 23:16:56 +0000177 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const;
178 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
179 const Stmt *S = 0) const;
180
Anna Zaks66c40402012-02-14 21:55:24 +0000181 /// Check if the function is not known to us. So, for example, we could
182 /// conservatively assume it can free/reallocate it's pointer arguments.
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000183 bool doesNotFreeMemory(const CallOrObjCMessage *Call,
184 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000185
Ted Kremenek9c378f72011-08-12 23:37:29 +0000186 static bool SummarizeValue(raw_ostream &os, SVal V);
187 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000188 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000189
Anna Zaksca8e36e2012-02-23 21:38:21 +0000190 /// Find the location of the allocation for Sym on the path leading to the
191 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000192 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
193 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000194
Anna Zaksda046772012-02-11 21:02:40 +0000195 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
196
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000197 /// The bug visitor which allows us to print extra diagnostics along the
198 /// BugReport path. For example, showing the allocation site of the leaked
199 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000200 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000201 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000202 enum NotificationMode {
203 Normal,
204 Complete,
205 ReallocationFailed
206 };
207
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000208 // The allocated region symbol tracked by the main analysis.
209 SymbolRef Sym;
Anna Zaksfe571602012-02-16 22:26:07 +0000210 NotificationMode Mode;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000211
212 public:
Anna Zaksfe571602012-02-16 22:26:07 +0000213 MallocBugVisitor(SymbolRef S) : Sym(S), Mode(Normal) {}
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000214 virtual ~MallocBugVisitor() {}
215
216 void Profile(llvm::FoldingSetNodeID &ID) const {
217 static int X = 0;
218 ID.AddPointer(&X);
219 ID.AddPointer(Sym);
220 }
221
Anna Zaksfe571602012-02-16 22:26:07 +0000222 inline bool isAllocated(const RefState *S, const RefState *SPrev,
223 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000224 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000225 return (Stmt && isa<CallExpr>(Stmt) &&
226 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000227 }
228
Anna Zaksfe571602012-02-16 22:26:07 +0000229 inline bool isReleased(const RefState *S, const RefState *SPrev,
230 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000231 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000232 return (Stmt && isa<CallExpr>(Stmt) &&
233 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
234 }
235
236 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
237 const Stmt *Stmt) {
238 // If the expression is not a call, and the state change is
239 // released -> allocated, it must be the realloc return value
240 // check. If we have to handle more cases here, it might be cleaner just
241 // to track this extra bit in the state itself.
242 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
243 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000244 }
245
246 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
247 const ExplodedNode *PrevN,
248 BugReporterContext &BRC,
249 BugReport &BR);
Anna Zaks56a938f2012-03-16 23:24:20 +0000250 private:
251 class StackHintGeneratorForReallocationFailed
252 : public StackHintGeneratorForSymbol {
253 public:
254 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
255 : StackHintGeneratorForSymbol(S, M) {}
256
257 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
258 SmallString<200> buf;
259 llvm::raw_svector_ostream os(buf);
260
Anna Zaksfbd58742012-03-16 23:44:28 +0000261 os << "Reallocation of ";
Anna Zaks56a938f2012-03-16 23:24:20 +0000262 // Printed parameters start at 1, not 0.
263 printOrdinal(++ArgIndex, os);
264 os << " parameter failed";
265
266 return os.str();
267 }
268
269 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000270 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000271 }
272 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000273 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000274};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000275} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000276
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000277typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000278typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000279class RegionState {};
280class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000281namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000282namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000283 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000284 struct ProgramStateTrait<RegionState>
285 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000286 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000287 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000288
289 template <>
290 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000291 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000292 static void *GDMIndex() { static int x; return &x; }
293 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000294}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000295}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000296
Anna Zaks4fb54872012-02-11 21:02:35 +0000297namespace {
298class StopTrackingCallback : public SymbolVisitor {
299 ProgramStateRef state;
300public:
301 StopTrackingCallback(ProgramStateRef st) : state(st) {}
302 ProgramStateRef getState() const { return state; }
303
304 bool VisitSymbol(SymbolRef sym) {
305 state = state->remove<RegionState>(sym);
306 return true;
307 }
308};
309} // end anonymous namespace
310
Anna Zaks66c40402012-02-14 21:55:24 +0000311void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000312 if (!II_malloc)
313 II_malloc = &Ctx.Idents.get("malloc");
314 if (!II_free)
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000315 II_free = &Ctx.Idents.get("free");
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000316 if (!II_realloc)
317 II_realloc = &Ctx.Idents.get("realloc");
Anna Zaks40add292012-02-15 00:11:25 +0000318 if (!II_reallocf)
319 II_reallocf = &Ctx.Idents.get("reallocf");
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000320 if (!II_calloc)
321 II_calloc = &Ctx.Idents.get("calloc");
Anna Zaksb16ce452012-02-15 00:11:22 +0000322 if (!II_valloc)
323 II_valloc = &Ctx.Idents.get("valloc");
Anna Zaks60a1fa42012-02-22 03:14:20 +0000324 if (!II_strdup)
325 II_strdup = &Ctx.Idents.get("strdup");
326 if (!II_strndup)
327 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000328}
329
Anna Zaks66c40402012-02-14 21:55:24 +0000330bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000331 if (!FD)
332 return false;
Anna Zaks66c40402012-02-14 21:55:24 +0000333 IdentifierInfo *FunI = FD->getIdentifier();
334 if (!FunI)
335 return false;
336
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000337 initIdentifierInfo(C);
338
Anna Zaks40add292012-02-15 00:11:25 +0000339 if (FunI == II_malloc || FunI == II_free || FunI == II_realloc ||
Anna Zaks60a1fa42012-02-22 03:14:20 +0000340 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
341 FunI == II_strdup || FunI == II_strndup)
Anna Zaks66c40402012-02-14 21:55:24 +0000342 return true;
343
344 if (Filter.CMallocOptimistic && FD->hasAttrs() &&
345 FD->specific_attr_begin<OwnershipAttr>() !=
346 FD->specific_attr_end<OwnershipAttr>())
347 return true;
348
349
350 return false;
351}
352
Anna Zaksb319e022012-02-08 20:13:28 +0000353void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
354 const FunctionDecl *FD = C.getCalleeDecl(CE);
355 if (!FD)
356 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000357
Anna Zaksb16ce452012-02-15 00:11:22 +0000358 initIdentifierInfo(C.getASTContext());
359 IdentifierInfo *FunI = FD->getIdentifier();
360 if (!FunI)
361 return;
362
Anna Zaks87cb5be2012-02-22 19:24:52 +0000363 ProgramStateRef State = C.getState();
Anna Zaksb16ce452012-02-15 00:11:22 +0000364 if (FunI == II_malloc || FunI == II_valloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000365 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
Anna Zaksb16ce452012-02-15 00:11:22 +0000366 } else if (FunI == II_realloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000367 State = ReallocMem(C, CE, false);
Anna Zaks40add292012-02-15 00:11:25 +0000368 } else if (FunI == II_reallocf) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000369 State = ReallocMem(C, CE, true);
Anna Zaksb16ce452012-02-15 00:11:22 +0000370 } else if (FunI == II_calloc) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000371 State = CallocMem(C, CE);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000372 } else if (FunI == II_free) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000373 State = FreeMemAux(C, CE, C.getState(), 0, false);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000374 } else if (FunI == II_strdup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000375 State = MallocUpdateRefState(C, CE, State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000376 } else if (FunI == II_strndup) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000377 State = MallocUpdateRefState(C, CE, State);
378 } else if (Filter.CMallocOptimistic) {
379 // Check all the attributes, if there are any.
380 // There can be multiple of these attributes.
381 if (FD->hasAttrs())
382 for (specific_attr_iterator<OwnershipAttr>
383 i = FD->specific_attr_begin<OwnershipAttr>(),
384 e = FD->specific_attr_end<OwnershipAttr>();
385 i != e; ++i) {
386 switch ((*i)->getOwnKind()) {
387 case OwnershipAttr::Returns:
388 State = MallocMemReturnsAttr(C, CE, *i);
389 break;
390 case OwnershipAttr::Takes:
391 case OwnershipAttr::Holds:
392 State = FreeMemAttr(C, CE, *i);
393 break;
394 }
395 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000396 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000397 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000398}
399
Anna Zaks87cb5be2012-02-22 19:24:52 +0000400ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
401 const CallExpr *CE,
402 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000403 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000404 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000405
Sean Huntcf807c42010-08-18 23:23:40 +0000406 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000407 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000408 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000409 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000410 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000411}
412
Anna Zaksb319e022012-02-08 20:13:28 +0000413ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000414 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000415 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000416 ProgramStateRef state) {
Anna Zaksb319e022012-02-08 20:13:28 +0000417 // Get the return value.
418 SVal retVal = state->getSVal(CE, C.getLocationContext());
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000419
Anna Zaksb16ce452012-02-15 00:11:22 +0000420 // We expect the malloc functions to return a pointer.
421 if (!isa<Loc>(retVal))
422 return 0;
423
Jordy Rose32f26562010-07-04 00:00:41 +0000424 // Fill the region with the initialization value.
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000425 state = state->bindDefault(retVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000426
Jordy Rose32f26562010-07-04 00:00:41 +0000427 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000428 const SymbolicRegion *R =
429 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000430 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000431 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000432 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000433 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000434 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
435 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
436 DefinedOrUnknownSVal extentMatchesSize =
437 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000438
Anna Zaks60a1fa42012-02-22 03:14:20 +0000439 state = state->assume(extentMatchesSize, true);
440 assert(state);
441 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000442
Anna Zaks87cb5be2012-02-22 19:24:52 +0000443 return MallocUpdateRefState(C, CE, state);
444}
445
446ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
447 const CallExpr *CE,
448 ProgramStateRef state) {
449 // Get the return value.
450 SVal retVal = state->getSVal(CE, C.getLocationContext());
451
452 // We expect the malloc functions to return a pointer.
453 if (!isa<Loc>(retVal))
454 return 0;
455
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000456 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000457 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000458
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000459 // Set the symbol's state to Allocated.
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000460 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000461
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000462}
463
Anna Zaks87cb5be2012-02-22 19:24:52 +0000464ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
465 const CallExpr *CE,
466 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000467 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000468 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000469
Anna Zaksb3d72752012-03-01 22:06:06 +0000470 ProgramStateRef State = C.getState();
471
Sean Huntcf807c42010-08-18 23:23:40 +0000472 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
473 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000474 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
475 Att->getOwnKind() == OwnershipAttr::Holds);
476 if (StateI)
477 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000478 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000479 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000480}
481
Ted Kremenek8bef8232012-01-26 21:29:00 +0000482ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000483 const CallExpr *CE,
484 ProgramStateRef state,
485 unsigned Num,
486 bool Hold) const {
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000487 const Expr *ArgExpr = CE->getArg(Num);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000488 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000489 if (!isa<DefinedOrUnknownSVal>(ArgVal))
490 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000491 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
492
493 // Check for null dereferences.
494 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000495 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000496
Anna Zaksb276bd92012-02-14 00:26:13 +0000497 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000498 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000499 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000500 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000501 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000502
Jordy Rose43859f62010-06-07 19:32:37 +0000503 // Unknown values could easily be okay
504 // Undefined values are handled elsewhere
505 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000506 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000507
Jordy Rose43859f62010-06-07 19:32:37 +0000508 const MemRegion *R = ArgVal.getAsRegion();
509
510 // Nonlocs can't be freed, of course.
511 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
512 if (!R) {
513 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000514 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000515 }
516
517 R = R->StripCasts();
518
519 // Blocks might show up as heap data, but should not be free()d
520 if (isa<BlockDataRegion>(R)) {
521 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000522 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000523 }
524
525 const MemSpaceRegion *MS = R->getMemorySpace();
526
527 // Parameters, locals, statics, and globals shouldn't be freed.
528 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
529 // FIXME: at the time this code was written, malloc() regions were
530 // represented by conjured symbols, which are all in UnknownSpaceRegion.
531 // This means that there isn't actually anything from HeapSpaceRegion
532 // that should be freed, even though we allow it here.
533 // Of course, free() can work on memory allocated outside the current
534 // function, so UnknownSpaceRegion is always a possibility.
535 // False negatives are better than false positives.
536
537 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000538 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000539 }
540
541 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
542 // Various cases could lead to non-symbol values here.
543 // For now, ignore them.
544 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000545 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000546
547 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000548 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000549
550 // If the symbol has not been tracked, return. This is possible when free() is
551 // called on a pointer that does not get its pointee directly from malloc().
552 // Full support of this requires inter-procedural analysis.
553 if (!RS)
Anna Zaksb319e022012-02-08 20:13:28 +0000554 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000555
556 // Check double free.
Zhongxing Xu243fde92009-11-17 07:54:15 +0000557 if (RS->isReleased()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000558 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000559 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000560 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000561 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000562 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaksfebdc322012-02-16 22:26:12 +0000563 "Attempt to free released memory", N);
Anna Zaksfe571602012-02-16 22:26:07 +0000564 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000565 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000566 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000567 C.EmitReport(R);
568 }
Anna Zaksb319e022012-02-08 20:13:28 +0000569 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000570 }
571
572 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000573 if (Hold)
Anna Zaksb276bd92012-02-14 00:26:13 +0000574 return state->set<RegionState>(Sym, RefState::getRelinquished(CE));
575 return state->set<RegionState>(Sym, RefState::getReleased(CE));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000576}
577
Ted Kremenek9c378f72011-08-12 23:37:29 +0000578bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000579 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
580 os << "an integer (" << IntVal->getValue() << ")";
581 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
582 os << "a constant address (" << ConstAddr->getValue() << ")";
583 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000584 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000585 else
586 return false;
587
588 return true;
589}
590
Ted Kremenek9c378f72011-08-12 23:37:29 +0000591bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000592 const MemRegion *MR) {
593 switch (MR->getKind()) {
594 case MemRegion::FunctionTextRegionKind: {
595 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
596 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000597 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000598 else
599 os << "the address of a function";
600 return true;
601 }
602 case MemRegion::BlockTextRegionKind:
603 os << "block text";
604 return true;
605 case MemRegion::BlockDataRegionKind:
606 // FIXME: where the block came from?
607 os << "a block";
608 return true;
609 default: {
610 const MemSpaceRegion *MS = MR->getMemorySpace();
611
Anna Zakseb31a762012-01-04 23:54:01 +0000612 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000613 const VarRegion *VR = dyn_cast<VarRegion>(MR);
614 const VarDecl *VD;
615 if (VR)
616 VD = VR->getDecl();
617 else
618 VD = NULL;
619
620 if (VD)
621 os << "the address of the local variable '" << VD->getName() << "'";
622 else
623 os << "the address of a local stack variable";
624 return true;
625 }
Anna Zakseb31a762012-01-04 23:54:01 +0000626
627 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000628 const VarRegion *VR = dyn_cast<VarRegion>(MR);
629 const VarDecl *VD;
630 if (VR)
631 VD = VR->getDecl();
632 else
633 VD = NULL;
634
635 if (VD)
636 os << "the address of the parameter '" << VD->getName() << "'";
637 else
638 os << "the address of a parameter";
639 return true;
640 }
Anna Zakseb31a762012-01-04 23:54:01 +0000641
642 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000643 const VarRegion *VR = dyn_cast<VarRegion>(MR);
644 const VarDecl *VD;
645 if (VR)
646 VD = VR->getDecl();
647 else
648 VD = NULL;
649
650 if (VD) {
651 if (VD->isStaticLocal())
652 os << "the address of the static variable '" << VD->getName() << "'";
653 else
654 os << "the address of the global variable '" << VD->getName() << "'";
655 } else
656 os << "the address of a global variable";
657 return true;
658 }
Anna Zakseb31a762012-01-04 23:54:01 +0000659
660 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000661 }
662 }
663}
664
665void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000666 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000667 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000668 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000669 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000670
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000671 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000672 llvm::raw_svector_ostream os(buf);
673
674 const MemRegion *MR = ArgVal.getAsRegion();
675 if (MR) {
676 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
677 MR = ER->getSuperRegion();
678
679 // Special case for alloca()
680 if (isa<AllocaRegion>(MR))
681 os << "Argument to free() was allocated by alloca(), not malloc()";
682 else {
683 os << "Argument to free() is ";
684 if (SummarizeRegion(os, MR))
685 os << ", which is not memory allocated by malloc()";
686 else
687 os << "not memory allocated by malloc()";
688 }
689 } else {
690 os << "Argument to free() is ";
691 if (SummarizeValue(os, ArgVal))
692 os << ", which is not memory allocated by malloc()";
693 else
694 os << "not memory allocated by malloc()";
695 }
696
Anna Zakse172e8b2011-08-17 23:00:25 +0000697 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000698 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000699 R->addRange(range);
700 C.EmitReport(R);
701 }
702}
703
Anna Zaks87cb5be2012-02-22 19:24:52 +0000704ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
705 const CallExpr *CE,
706 bool FreesOnFail) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000707 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000708 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000709 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000710 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
711 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000712 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000713 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000714
Ted Kremenek846eabd2010-12-01 21:28:31 +0000715 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000716
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000717 DefinedOrUnknownSVal PtrEQ =
718 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000719
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000720 // Get the size argument. If there is no size arg then give up.
721 const Expr *Arg1 = CE->getArg(1);
722 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000723 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000724
725 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000726 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
727 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000728 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000729 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000730
731 // Compare the size argument to 0.
732 DefinedOrUnknownSVal SizeZero =
733 svalBuilder.evalEQ(state, Arg1Val,
734 svalBuilder.makeIntValWithPtrWidth(0, false));
735
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000736 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
737 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
738 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
739 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
740 // We only assume exceptional states if they are definitely true; if the
741 // state is under-constrained, assume regular realloc behavior.
742 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
743 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
744
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000745 // If the ptr is NULL and the size is not 0, the call is equivalent to
746 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000747 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000748 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000749 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000750 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000751 }
752
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000753 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000754 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000755
Anna Zaks30838b92012-02-13 20:57:07 +0000756 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000757 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000758 SymbolRef FromPtr = arg0Val.getAsSymbol();
759 SVal RetVal = state->getSVal(CE, LCtx);
760 SymbolRef ToPtr = RetVal.getAsSymbol();
761 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000762 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000763
764 // If the size is 0, free the memory.
765 if (SizeIsZero)
766 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000767 // The semantics of the return value are:
768 // If size was equal to 0, either NULL or a pointer suitable to be passed
769 // to free() is returned.
Anna Zaks40add292012-02-15 00:11:25 +0000770 stateFree = stateFree->set<ReallocPairs>(ToPtr,
771 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000772 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000773 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000774 }
775
776 // Default behavior.
777 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) {
778 // FIXME: We should copy the content of the original buffer.
779 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
780 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000781 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000782 return 0;
Anna Zaks40add292012-02-15 00:11:25 +0000783 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
784 ReallocPair(FromPtr, FreesOnFail));
Anna Zaksb276bd92012-02-14 00:26:13 +0000785 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000786 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000787 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000788 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000789}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000790
Anna Zaks87cb5be2012-02-22 19:24:52 +0000791ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Ted Kremenek8bef8232012-01-26 21:29:00 +0000792 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000793 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000794 const LocationContext *LCtx = C.getLocationContext();
795 SVal count = state->getSVal(CE->getArg(0), LCtx);
796 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000797 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
798 svalBuilder.getContext().getSizeType());
799 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000800
Anna Zaks87cb5be2012-02-22 19:24:52 +0000801 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000802}
803
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000804LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +0000805MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
806 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000807 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000808 // Walk the ExplodedGraph backwards and find the first node that referred to
809 // the tracked symbol.
810 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000811 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000812
813 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000814 ProgramStateRef State = N->getState();
815 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +0000816 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000817
818 // Find the most recent expression bound to the symbol in the current
819 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000820 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +0000821 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
822 SVal Val = State->getSVal(MR);
823 if (Val.getAsLocSymbol() == Sym)
824 ReferenceRegion = MR;
825 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000826 }
827
Anna Zaks7752d292012-02-27 23:40:55 +0000828 // Allocation node, is the last node in the current context in which the
829 // symbol was tracked.
830 if (N->getLocationContext() == LeakContext)
831 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000832 N = N->pred_empty() ? NULL : *(N->pred_begin());
833 }
834
835 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000836 const Stmt *AllocationStmt = 0;
837 if (isa<StmtPoint>(P))
838 AllocationStmt = cast<StmtPoint>(P).getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +0000839
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000840 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +0000841}
842
Anna Zaksda046772012-02-11 21:02:40 +0000843void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
844 CheckerContext &C) const {
845 assert(N);
846 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +0000847 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +0000848 // Leaks should not be reported if they are post-dominated by a sink:
849 // (1) Sinks are higher importance bugs.
850 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
851 // with __noreturn functions such as assert() or exit(). We choose not
852 // to report leaks on such paths.
853 BT_Leak->setSuppressOnSink(true);
854 }
855
Anna Zaksca8e36e2012-02-23 21:38:21 +0000856 // Most bug reports are cached at the location where they occurred.
857 // With leaks, we want to unique them by the location where they were
858 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +0000859 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000860 const Stmt *AllocStmt = 0;
861 const MemRegion *Region = 0;
862 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
863 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +0000864 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
865 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +0000866
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000867 SmallString<200> buf;
868 llvm::raw_svector_ostream os(buf);
869 os << "Memory is never released; potential leak";
870 if (Region) {
871 os << " of memory pointed to by '";
872 Region->dumpPretty(os);
873 os <<'\'';
874 }
875
876 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000877 R->markInteresting(Sym);
Anna Zaksda046772012-02-11 21:02:40 +0000878 R->addVisitor(new MallocBugVisitor(Sym));
879 C.EmitReport(R);
880}
881
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000882void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
883 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000884{
Zhongxing Xu173ff562010-08-15 08:19:57 +0000885 if (!SymReaper.hasDeadSymbols())
886 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000887
Ted Kremenek8bef8232012-01-26 21:29:00 +0000888 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000889 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +0000890 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +0000891
Ted Kremenek217470e2011-07-28 23:07:51 +0000892 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000893 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +0000894 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
895 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000896 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +0000897 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +0000898 Errors.push_back(I->first);
899 }
Jordy Rose90760142010-08-18 04:33:47 +0000900 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +0000901 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +0000902
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +0000903 }
904 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000905
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000906 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +0000907 ReallocMap RP = state->get<ReallocPairs>();
908 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
909 if (SymReaper.isDead(I->first) ||
910 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000911 state = state->remove<ReallocPairs>(I->first);
912 }
913 }
914
Anna Zaksca8e36e2012-02-23 21:38:21 +0000915 // Generate leak node.
916 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
917 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +0000918
Anna Zaksca8e36e2012-02-23 21:38:21 +0000919 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +0000920 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +0000921 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
922 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +0000923 }
Ted Kremenek217470e2011-07-28 23:07:51 +0000924 }
Anna Zaksca8e36e2012-02-23 21:38:21 +0000925 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +0000926}
Zhongxing Xu243fde92009-11-17 07:54:15 +0000927
Anna Zaksda046772012-02-11 21:02:40 +0000928void MallocChecker::checkEndPath(CheckerContext &C) const {
929 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +0000930 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +0000931
Anna Zaksa19581a2012-02-20 22:25:23 +0000932 // If inside inlined call, skip it.
933 if (C.getLocationContext()->getParent() != 0)
934 return;
935
Jordy Rose09cef092010-08-18 04:26:59 +0000936 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000937 RefState RS = I->second;
938 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +0000939 ExplodedNode *N = C.addTransition(state);
940 if (N)
941 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +0000942 }
943 }
944}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000945
Anna Zaks91c2a112012-02-08 23:16:56 +0000946bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S,
947 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000948 ProgramStateRef state = C.getState();
Anna Zaks91c2a112012-02-08 23:16:56 +0000949 const RefState *RS = state->get<RegionState>(Sym);
950 if (!RS)
951 return false;
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000952
Anna Zaks91c2a112012-02-08 23:16:56 +0000953 if (RS->isAllocated()) {
954 state = state->set<RegionState>(Sym, RefState::getEscaped(S));
955 C.addTransition(state);
956 return true;
957 }
958 return false;
959}
960
Anna Zaks66c40402012-02-14 21:55:24 +0000961void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
962 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext()))
963 return;
964
965 // Check use after free, when a freed pointer is passed to a call.
966 ProgramStateRef State = C.getState();
967 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
968 E = CE->arg_end(); I != E; ++I) {
969 const Expr *A = *I;
970 if (A->getType().getTypePtr()->isAnyPointerType()) {
971 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
972 if (!Sym)
973 continue;
974 if (checkUseAfterFree(Sym, C, A))
975 return;
976 }
977 }
978}
979
Anna Zaks91c2a112012-02-08 23:16:56 +0000980void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
981 const Expr *E = S->getRetValue();
982 if (!E)
983 return;
Anna Zaks0860cd02012-02-11 21:44:39 +0000984
985 // Check if we are returning a symbol.
Anna Zaksd9ab7bb2012-02-22 02:36:01 +0000986 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext());
987 SymbolRef Sym = RetVal.getAsSymbol();
988 if (!Sym)
989 // If we are returning a field of the allocated struct or an array element,
990 // the callee could still free the memory.
991 // TODO: This logic should be a part of generic symbol escape callback.
992 if (const MemRegion *MR = RetVal.getAsRegion())
993 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
994 if (const SymbolicRegion *BMR =
995 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
996 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +0000997 if (!Sym)
998 return;
999
Anna Zaks0860cd02012-02-11 21:44:39 +00001000 // Check if we are returning freed memory.
Anna Zaksfe571602012-02-16 22:26:07 +00001001 if (checkUseAfterFree(Sym, C, E))
Anna Zaks15d0ae12012-02-11 23:46:36 +00001002 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001003
Anna Zaksa19581a2012-02-20 22:25:23 +00001004 // If this function body is not inlined, check if the symbol is escaping.
1005 if (C.getLocationContext()->getParent() == 0)
1006 checkEscape(Sym, E, C);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001007}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001008
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001009// TODO: Blocks should be either inlined or should call invalidate regions
1010// upon invocation. After that's in place, special casing here will not be
1011// needed.
1012void MallocChecker::checkPostStmt(const BlockExpr *BE,
1013 CheckerContext &C) const {
1014
1015 // Scan the BlockDecRefExprs for any object the retain count checker
1016 // may be tracking.
1017 if (!BE->getBlockDecl()->hasCaptures())
1018 return;
1019
1020 ProgramStateRef state = C.getState();
1021 const BlockDataRegion *R =
1022 cast<BlockDataRegion>(state->getSVal(BE,
1023 C.getLocationContext()).getAsRegion());
1024
1025 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1026 E = R->referenced_vars_end();
1027
1028 if (I == E)
1029 return;
1030
1031 SmallVector<const MemRegion*, 10> Regions;
1032 const LocationContext *LC = C.getLocationContext();
1033 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1034
1035 for ( ; I != E; ++I) {
1036 const VarRegion *VR = *I;
1037 if (VR->getSuperRegion() == R) {
1038 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1039 }
1040 Regions.push_back(VR);
1041 }
1042
1043 state =
1044 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1045 Regions.data() + Regions.size()).getState();
1046 C.addTransition(state);
1047}
1048
Anna Zaks91c2a112012-02-08 23:16:56 +00001049bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1050 const Stmt *S) const {
1051 assert(Sym);
1052 const RefState *RS = C.getState()->get<RegionState>(Sym);
1053 if (RS && RS->isReleased()) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001054 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001055 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001056 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001057
Anna Zaksfebdc322012-02-16 22:26:12 +00001058 BugReport *R = new BugReport(*BT_UseFree,
1059 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001060 if (S)
1061 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001062 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001063 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +00001064 C.EmitReport(R);
1065 return true;
1066 }
1067 }
1068 return false;
1069}
1070
Zhongxing Xuc8023782010-03-10 04:58:55 +00001071// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001072void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1073 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001074 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001075 if (Sym)
1076 checkUseAfterFree(Sym, C);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001077}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001078
Anna Zaks4fb54872012-02-11 21:02:35 +00001079//===----------------------------------------------------------------------===//
1080// Check various ways a symbol can be invalidated.
1081// TODO: This logic (the next 3 functions) is copied/similar to the
1082// RetainRelease checker. We might want to factor this out.
1083//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001084
Anna Zaks4fb54872012-02-11 21:02:35 +00001085// Stop tracking symbols when a value escapes as a result of checkBind.
1086// A value escapes in three possible cases:
1087// (1) we are binding to something that is not a memory region.
1088// (2) we are binding to a memregion that does not have stack storage
1089// (3) we are binding to a memregion with stack storage that the store
1090// does not understand.
1091void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1092 CheckerContext &C) const {
1093 // Are we storing to something that causes the value to "escape"?
1094 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001095 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001096
Anna Zaks4fb54872012-02-11 21:02:35 +00001097 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1098 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001099
Anna Zaks4fb54872012-02-11 21:02:35 +00001100 if (!escapes) {
1101 // To test (3), generate a new state with the binding added. If it is
1102 // the same state, then it escapes (since the store cannot represent
1103 // the binding).
1104 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001105 }
Anna Zaksac593002012-02-16 03:40:57 +00001106 if (!escapes) {
1107 // Case 4: We do not currently model what happens when a symbol is
1108 // assigned to a struct field, so be conservative here and let the symbol
1109 // go. TODO: This could definitely be improved upon.
1110 escapes = !isa<VarRegion>(regionLoc->getRegion());
1111 }
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001112 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001113
1114 // If our store can represent the binding and we aren't storing to something
1115 // that doesn't have local storage then just return and have the simulation
1116 // state continue as is.
1117 if (!escapes)
1118 return;
1119
1120 // Otherwise, find all symbols referenced by 'val' that we are tracking
1121 // and stop tracking them.
1122 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1123 C.addTransition(state);
1124}
1125
1126// If a symbolic region is assumed to NULL (or another constant), stop tracking
1127// it - assuming that allocation failed on this path.
1128ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1129 SVal Cond,
1130 bool Assumption) const {
1131 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001132 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1133 // If the symbol is assumed to NULL or another constant, this will
1134 // return an APSInt*.
1135 if (state->getSymVal(I.getKey()))
1136 state = state->remove<RegionState>(I.getKey());
1137 }
1138
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001139 // Realloc returns 0 when reallocation fails, which means that we should
1140 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001141 ReallocMap RP = state->get<ReallocPairs>();
1142 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001143 // If the symbol is assumed to NULL or another constant, this will
1144 // return an APSInt*.
1145 if (state->getSymVal(I.getKey())) {
Anna Zaks40add292012-02-15 00:11:25 +00001146 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1147 const RefState *RS = state->get<RegionState>(ReallocSym);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001148 if (RS) {
Anna Zaks40add292012-02-15 00:11:25 +00001149 if (RS->isReleased() && ! I.getData().IsFreeOnFailure)
1150 state = state->set<RegionState>(ReallocSym,
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001151 RefState::getAllocateUnchecked(RS->getStmt()));
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001152 }
1153 state = state->remove<ReallocPairs>(I.getKey());
1154 }
1155 }
1156
Anna Zaks4fb54872012-02-11 21:02:35 +00001157 return state;
1158}
1159
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001160// Check if the function is known to us. So, for example, we could
Anna Zaks66c40402012-02-14 21:55:24 +00001161// conservatively assume it can free/reallocate it's pointer arguments.
1162// (We assume that the pointers cannot escape through calls to system
1163// functions not handled by this checker.)
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001164bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call,
1165 ProgramStateRef State) const {
1166 if (!Call)
1167 return false;
1168
1169 // For now, assume that any C++ call can free memory.
1170 // TODO: If we want to be more optimistic here, we'll need to make sure that
1171 // regions escape to C++ containers. They seem to do that even now, but for
1172 // mysterious reasons.
1173 if (Call->isCXXCall())
1174 return false;
1175
1176 const Decl *D = Call->getDecl();
1177 if (!D)
1178 return false;
1179
Anna Zaks66c40402012-02-14 21:55:24 +00001180 ASTContext &ASTC = State->getStateManager().getContext();
1181
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001182 // If it's one of the allocation functions we can reason about, we model
Jordy Rose257c60f2012-03-06 00:28:20 +00001183 // its behavior explicitly.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001184 if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) {
1185 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001186 }
1187
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001188 // If it's not a system call, assume it frees memory.
Anna Zaks66c40402012-02-14 21:55:24 +00001189 SourceManager &SM = ASTC.getSourceManager();
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001190 if (!SM.isInSystemHeader(D->getLocation()))
1191 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001192
Anna Zaks07d39a42012-02-28 01:54:22 +00001193 // Process C/ObjC functions.
Jordy Rose257c60f2012-03-06 00:28:20 +00001194 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Anna Zaks0d389b82012-02-23 01:05:27 +00001195 // White list the system functions whose arguments escape.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001196 const IdentifierInfo *II = FD->getIdentifier();
Anna Zaks07d39a42012-02-28 01:54:22 +00001197 if (!II)
1198 return true;
1199 StringRef FName = II->getName();
1200
1201 // White list thread local storage.
1202 if (FName.equals("pthread_setspecific"))
1203 return false;
1204
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001205 // White list the 'XXXNoCopy' ObjC functions.
Anna Zaks07d39a42012-02-28 01:54:22 +00001206 if (FName.endswith("NoCopy")) {
1207 // Look for the deallocator argument. We know that the memory ownership
1208 // is not transfered only if the deallocator argument is
1209 // 'kCFAllocatorNull'.
1210 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1211 const Expr *ArgE = Call->getArg(i)->IgnoreParenCasts();
1212 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1213 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1214 if (DeallocatorName == "kCFAllocatorNull")
1215 return true;
1216 }
1217 }
1218 return false;
Anna Zaks0d389b82012-02-23 01:05:27 +00001219 }
1220
Anna Zaksca23eb22012-02-29 18:42:47 +00001221 // PR12101
1222 // Many CoreFoundation and CoreGraphics might allow a tracked object
1223 // to escape.
1224 if (Call->isCFCGAllowingEscape(FName))
1225 return false;
1226
1227 // Associating streams with malloced buffers. The pointer can escape if
1228 // 'closefn' is specified (and if that function does free memory).
1229 // Currently, we do not inspect the 'closefn' function (PR12101).
1230 if (FName == "funopen")
1231 if (Call->getNumArgs() >= 4 && !Call->getArgSVal(4).isConstant(0))
1232 return false;
1233
1234 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1235 // these leaks might be intentional when setting the buffer for stdio.
1236 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1237 if (FName == "setbuf" || FName =="setbuffer" ||
1238 FName == "setlinebuf" || FName == "setvbuf") {
1239 if (Call->getNumArgs() >= 1)
1240 if (const DeclRefExpr *Arg =
1241 dyn_cast<DeclRefExpr>(Call->getArg(0)->IgnoreParenCasts()))
1242 if (const VarDecl *D = dyn_cast<VarDecl>(Arg->getDecl()))
1243 if (D->getCanonicalDecl()->getName().find("std")
1244 != StringRef::npos)
1245 return false;
1246 }
1247
1248 // A bunch of other functions, which take ownership of a pointer (See retain
1249 // release checker). Not all the parameters here are invalidated, but the
1250 // Malloc checker cannot differentiate between them. The right way of doing
1251 // this would be to implement a pointer escapes callback.
1252 if (FName == "CVPixelBufferCreateWithBytes" ||
1253 FName == "CGBitmapContextCreateWithData" ||
1254 FName == "CVPixelBufferCreateWithPlanarBytes") {
1255 return false;
1256 }
1257
Anna Zaks0d389b82012-02-23 01:05:27 +00001258 // Otherwise, assume that the function does not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001259 // Most system calls, do not free the memory.
1260 return true;
1261
1262 // Process ObjC functions.
1263 } else if (const ObjCMethodDecl * ObjCD = dyn_cast<ObjCMethodDecl>(D)) {
1264 Selector S = ObjCD->getSelector();
1265
1266 // White list the ObjC functions which do free memory.
1267 // - Anything containing 'freeWhenDone' param set to 1.
1268 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
1269 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
1270 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1271 if (Call->getArgSVal(i).isConstant(1))
1272 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001273 else
1274 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001275 }
1276 }
1277
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001278 // If the first selector ends with NoCopy, assume that the ownership is
1279 // transfered as well.
1280 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1281 if (S.getNameForSlot(0).endswith("NoCopy")) {
1282 return false;
1283 }
1284
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001285 // Otherwise, assume that the function does not free memory.
1286 // Most system calls, do not free the memory.
1287 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001288 }
1289
1290 // Otherwise, assume that the function can free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001291 return false;
1292
Anna Zaks66c40402012-02-14 21:55:24 +00001293}
1294
Anna Zaks4fb54872012-02-11 21:02:35 +00001295// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1296// escapes, when we are tracking p), do not track the symbol as we cannot reason
1297// about it anymore.
1298ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001299MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001300 const StoreManager::InvalidatedSymbols *invalidated,
1301 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001302 ArrayRef<const MemRegion *> Regions,
1303 const CallOrObjCMessage *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001304 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001305 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001306 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001307
Anna Zaks66c40402012-02-14 21:55:24 +00001308 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001309 // regions (explicit and implicit) escaped.
1310
1311 // Otherwise, whitelist explicit pointers; we still can track them.
1312 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001313 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1314 E = ExplicitRegions.end(); I != E; ++I) {
1315 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1316 WhitelistedSymbols.insert(R->getSymbol());
1317 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001318 }
1319
1320 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1321 E = invalidated->end(); I!=E; ++I) {
1322 SymbolRef sym = *I;
1323 if (WhitelistedSymbols.count(sym))
1324 continue;
Anna Zaks66c40402012-02-14 21:55:24 +00001325 // The symbol escaped.
1326 if (const RefState *RS = State->get<RegionState>(sym))
1327 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt()));
Anna Zaks4fb54872012-02-11 21:02:35 +00001328 }
Anna Zaks66c40402012-02-14 21:55:24 +00001329 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001330}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001331
Jordy Rose393f98b2012-03-18 07:43:35 +00001332static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1333 ProgramStateRef prevState) {
1334 ReallocMap currMap = currState->get<ReallocPairs>();
1335 ReallocMap prevMap = prevState->get<ReallocPairs>();
1336
1337 for (ReallocMap::iterator I = prevMap.begin(), E = prevMap.end();
1338 I != E; ++I) {
1339 SymbolRef sym = I.getKey();
1340 if (!currMap.lookup(sym))
1341 return sym;
1342 }
1343
1344 return NULL;
1345}
1346
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001347PathDiagnosticPiece *
1348MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1349 const ExplodedNode *PrevN,
1350 BugReporterContext &BRC,
1351 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001352 ProgramStateRef state = N->getState();
1353 ProgramStateRef statePrev = PrevN->getState();
1354
1355 const RefState *RS = state->get<RegionState>(Sym);
1356 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001357 if (!RS && !RSPrev)
1358 return 0;
1359
Anna Zaksfe571602012-02-16 22:26:07 +00001360 const Stmt *S = 0;
1361 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001362 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001363
1364 // Retrieve the associated statement.
1365 ProgramPoint ProgLoc = N->getLocation();
1366 if (isa<StmtPoint>(ProgLoc))
1367 S = cast<StmtPoint>(ProgLoc).getStmt();
1368 // If an assumption was made on a branch, it should be caught
1369 // here by looking at the state transition.
1370 if (isa<BlockEdge>(ProgLoc)) {
1371 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc();
1372 S = srcBlk->getTerminator();
1373 }
1374 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001375 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001376
1377 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001378 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001379 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001380 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001381 StackHint = new StackHintGeneratorForSymbol(Sym,
1382 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001383 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001384 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001385 StackHint = new StackHintGeneratorForSymbol(Sym,
1386 "Returned released memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001387 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001388 Mode = ReallocationFailed;
1389 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001390 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001391 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001392
1393 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev))
1394 BR.markInteresting(sym);
Anna Zaksfe571602012-02-16 22:26:07 +00001395 }
1396
1397 // We are in a special mode if a reallocation failed later in the path.
1398 } else if (Mode == ReallocationFailed) {
1399 // Generate a special diagnostic for the first realloc we find.
1400 if (!isAllocated(RS, RSPrev, S) && !isReleased(RS, RSPrev, S))
1401 return 0;
1402
1403 // Check that the name of the function is realloc.
1404 const CallExpr *CE = dyn_cast<CallExpr>(S);
1405 if (!CE)
1406 return 0;
1407 const FunctionDecl *funDecl = CE->getDirectCallee();
1408 if (!funDecl)
1409 return 0;
1410 StringRef FunName = funDecl->getName();
1411 if (!(FunName.equals("realloc") || FunName.equals("reallocf")))
1412 return 0;
1413 Msg = "Attempt to reallocate memory";
Anna Zaksfbd58742012-03-16 23:44:28 +00001414 StackHint = new StackHintGeneratorForSymbol(Sym,
1415 "Returned reallocated memory");
Anna Zaksfe571602012-02-16 22:26:07 +00001416 Mode = Normal;
1417 }
1418
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001419 if (!Msg)
1420 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001421 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001422
1423 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001424 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001425 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001426 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001427}
1428
1429
Anna Zaks231361a2012-02-08 23:16:52 +00001430#define REGISTER_CHECKER(name) \
1431void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001432 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001433 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001434}
Anna Zaks231361a2012-02-08 23:16:52 +00001435
1436REGISTER_CHECKER(MallocPessimistic)
1437REGISTER_CHECKER(MallocOptimistic)