blob: c036d739dd4dd7baa05cc734d2bff7179873c9d7 [file] [log] [blame]
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001//=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines malloc/free checker, which checks for potential memory
11// leaks, double free, and use-after-free problems.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000015#include "ClangSACheckers.h"
Anna Zaksf0dfc9c2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000017#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000018#include "clang/StaticAnalyzer/Core/CheckerManager.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000020#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Jordan Rosef540c542012-07-26 21:39:41 +000021#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
23#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Anna Zaks15d0ae12012-02-11 23:46:36 +000025#include "clang/Basic/SourceManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000026#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000027#include "llvm/ADT/SmallString.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000028#include "llvm/ADT/STLExtras.h"
Anna Zaks60a1fa42012-02-22 03:14:20 +000029#include <climits>
30
Zhongxing Xu589c0f22009-11-12 08:38:56 +000031using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000032using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000033
34namespace {
35
Zhongxing Xu7fb14642009-12-11 00:55:44 +000036class RefState {
Anna Zaks050cdd72012-06-20 20:57:46 +000037 enum Kind { // Reference to allocated memory.
38 Allocated,
39 // Reference to released/freed memory.
40 Released,
Anna Zaks050cdd72012-06-20 20:57:46 +000041 // The responsibility for freeing resources has transfered from
42 // this reference. A relinquished symbol should not be freed.
Ted Kremenekdde201b2010-08-06 21:12:55 +000043 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000044 const Stmt *S;
45
Zhongxing Xu7fb14642009-12-11 00:55:44 +000046public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000047 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
48
Anna Zaks050cdd72012-06-20 20:57:46 +000049 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000050 bool isReleased() const { return K == Released; }
Anna Zaks050cdd72012-06-20 20:57:46 +000051 bool isRelinquished() const { return K == Relinquished; }
Anna Zaksca23eb22012-02-29 18:42:47 +000052
Anna Zaksc8bb3be2012-02-13 18:05:39 +000053 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000054
55 bool operator==(const RefState &X) const {
56 return K == X.K && S == X.S;
57 }
58
Anna Zaks050cdd72012-06-20 20:57:46 +000059 static RefState getAllocated(const Stmt *s) {
60 return RefState(Allocated, s);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000061 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000062 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000063 static RefState getRelinquished(const Stmt *s) {
64 return RefState(Relinquished, s);
65 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000066
67 void Profile(llvm::FoldingSetNodeID &ID) const {
68 ID.AddInteger(K);
69 ID.AddPointer(S);
70 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000071};
72
Anna Zaks9dc298b2012-09-12 22:57:34 +000073enum ReallocPairKind {
74 RPToBeFreedAfterFailure,
75 // The symbol has been freed when reallocation failed.
76 RPIsFreeOnFailure,
77 // The symbol does not need to be freed after reallocation fails.
78 RPDoNotTrackAfterFailure
79};
80
Anna Zaks55dd9562012-08-24 02:28:20 +000081/// \class ReallocPair
82/// \brief Stores information about the symbol being reallocated by a call to
83/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaks40add292012-02-15 00:11:25 +000084struct ReallocPair {
Anna Zaks55dd9562012-08-24 02:28:20 +000085 // \brief The symbol which realloc reallocated.
Anna Zaks40add292012-02-15 00:11:25 +000086 SymbolRef ReallocatedSym;
Anna Zaks9dc298b2012-09-12 22:57:34 +000087 ReallocPairKind Kind;
Anna Zaks55dd9562012-08-24 02:28:20 +000088
Anna Zaks9dc298b2012-09-12 22:57:34 +000089 ReallocPair(SymbolRef S, ReallocPairKind K) :
90 ReallocatedSym(S), Kind(K) {}
Anna Zaks40add292012-02-15 00:11:25 +000091 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks9dc298b2012-09-12 22:57:34 +000092 ID.AddInteger(Kind);
Anna Zaks40add292012-02-15 00:11:25 +000093 ID.AddPointer(ReallocatedSym);
94 }
95 bool operator==(const ReallocPair &X) const {
96 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks9dc298b2012-09-12 22:57:34 +000097 Kind == X.Kind;
Anna Zaks40add292012-02-15 00:11:25 +000098 }
99};
100
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000101typedef std::pair<const Stmt*, const MemRegion*> LeakInfo;
102
Anna Zaksb319e022012-02-08 20:13:28 +0000103class MallocChecker : public Checker<check::DeadSymbols,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000104 check::EndPath,
105 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +0000106 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +0000107 check::PostStmt<CallExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000108 check::PostStmt<BlockExpr>,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000109 check::PreObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000110 check::Location,
111 check::Bind,
Anna Zaks4fb54872012-02-11 21:02:35 +0000112 eval::Assume,
113 check::RegionChanges>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000114{
Anna Zaksfebdc322012-02-16 22:26:12 +0000115 mutable OwningPtr<BugType> BT_DoubleFree;
116 mutable OwningPtr<BugType> BT_Leak;
117 mutable OwningPtr<BugType> BT_UseFree;
118 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000119 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000120 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
121
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000122public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000123 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000124 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000125
126 /// In pessimistic mode, the checker assumes that it does not know which
127 /// functions might free the memory.
128 struct ChecksFilter {
129 DefaultBool CMallocPessimistic;
130 DefaultBool CMallocOptimistic;
131 };
132
133 ChecksFilter Filter;
134
Anna Zaks66c40402012-02-14 21:55:24 +0000135 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000136 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Jordan Rosede507ea2012-07-02 19:28:04 +0000137 void checkPreObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000138 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000139 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Anna Zaksaf498a22011-10-25 19:56:48 +0000140 void checkEndPath(CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000141 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000142 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000143 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000144 void checkLocation(SVal l, bool isLoad, const Stmt *S,
145 CheckerContext &C) const;
146 void checkBind(SVal location, SVal val, const Stmt*S,
147 CheckerContext &C) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000148 ProgramStateRef
149 checkRegionChanges(ProgramStateRef state,
150 const StoreManager::InvalidatedSymbols *invalidated,
151 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +0000152 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +0000153 const CallEvent *Call) const;
Anna Zaks4fb54872012-02-11 21:02:35 +0000154 bool wantsRegionChangeUpdate(ProgramStateRef state) const {
155 return true;
156 }
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000157
Anna Zaks93c5a242012-05-02 00:05:20 +0000158 void printState(raw_ostream &Out, ProgramStateRef State,
159 const char *NL, const char *Sep) const;
160
Zhongxing Xu7b760962009-11-13 07:25:27 +0000161private:
Anna Zaks66c40402012-02-14 21:55:24 +0000162 void initIdentifierInfo(ASTContext &C) const;
163
164 /// Check if this is one of the functions which can allocate/reallocate memory
165 /// pointed to by one of its arguments.
166 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000167 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
168 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000169
Anna Zaks87cb5be2012-02-22 19:24:52 +0000170 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
171 const CallExpr *CE,
172 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000173 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000174 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000175 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000176 return MallocMemAux(C, CE,
177 state->getSVal(SizeEx, C.getLocationContext()),
178 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000179 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000180
Ted Kremenek8bef8232012-01-26 21:29:00 +0000181 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000182 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000183 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000184
Anna Zaks87cb5be2012-02-22 19:24:52 +0000185 /// Update the RefState to reflect the new memory allocation.
186 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
187 const CallExpr *CE,
188 ProgramStateRef state);
189
190 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
191 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000192 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000193 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000194 bool Hold,
195 bool &ReleasedAllocated) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000196 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
197 const Expr *ParentExpr,
198 ProgramStateRef state,
Anna Zaks55dd9562012-08-24 02:28:20 +0000199 bool Hold,
200 bool &ReleasedAllocated) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000201
Anna Zaks87cb5be2012-02-22 19:24:52 +0000202 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
203 bool FreesMemOnFailure) const;
204 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000205
Anna Zaks14345182012-05-18 01:16:10 +0000206 ///\brief Check if the memory associated with this symbol was released.
207 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
208
Anna Zaks91c2a112012-02-08 23:16:56 +0000209 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
210 const Stmt *S = 0) const;
211
Anna Zaks66c40402012-02-14 21:55:24 +0000212 /// Check if the function is not known to us. So, for example, we could
213 /// conservatively assume it can free/reallocate it's pointer arguments.
Jordan Rose740d4902012-07-02 19:27:35 +0000214 bool doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000215 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000216
Ted Kremenek9c378f72011-08-12 23:37:29 +0000217 static bool SummarizeValue(raw_ostream &os, SVal V);
218 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000219 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000220
Anna Zaksca8e36e2012-02-23 21:38:21 +0000221 /// Find the location of the allocation for Sym on the path leading to the
222 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000223 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
224 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000225
Anna Zaksda046772012-02-11 21:02:40 +0000226 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
227
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000228 /// The bug visitor which allows us to print extra diagnostics along the
229 /// BugReport path. For example, showing the allocation site of the leaked
230 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000231 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000232 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000233 enum NotificationMode {
234 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000235 ReallocationFailed
236 };
237
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000238 // The allocated region symbol tracked by the main analysis.
239 SymbolRef Sym;
240
Anna Zaks88feba02012-05-10 01:37:40 +0000241 // The mode we are in, i.e. what kind of diagnostics will be emitted.
242 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000243
Anna Zaks88feba02012-05-10 01:37:40 +0000244 // A symbol from when the primary region should have been reallocated.
245 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000246
Anna Zaks88feba02012-05-10 01:37:40 +0000247 bool IsLeak;
248
249 public:
250 MallocBugVisitor(SymbolRef S, bool isLeak = false)
251 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000252
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000253 virtual ~MallocBugVisitor() {}
254
255 void Profile(llvm::FoldingSetNodeID &ID) const {
256 static int X = 0;
257 ID.AddPointer(&X);
258 ID.AddPointer(Sym);
259 }
260
Anna Zaksfe571602012-02-16 22:26:07 +0000261 inline bool isAllocated(const RefState *S, const RefState *SPrev,
262 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000263 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000264 return (Stmt && isa<CallExpr>(Stmt) &&
265 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000266 }
267
Anna Zaksfe571602012-02-16 22:26:07 +0000268 inline bool isReleased(const RefState *S, const RefState *SPrev,
269 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000270 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000271 return (Stmt && isa<CallExpr>(Stmt) &&
272 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
273 }
274
Anna Zaks5b7aa342012-06-22 02:04:31 +0000275 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
276 const Stmt *Stmt) {
277 // Did not track -> relinquished. Other state (allocated) -> relinquished.
278 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
279 isa<ObjCPropertyRefExpr>(Stmt)) &&
280 (S && S->isRelinquished()) &&
281 (!SPrev || !SPrev->isRelinquished()));
282 }
283
Anna Zaksfe571602012-02-16 22:26:07 +0000284 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
285 const Stmt *Stmt) {
286 // If the expression is not a call, and the state change is
287 // released -> allocated, it must be the realloc return value
288 // check. If we have to handle more cases here, it might be cleaner just
289 // to track this extra bit in the state itself.
290 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
291 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000292 }
293
294 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
295 const ExplodedNode *PrevN,
296 BugReporterContext &BRC,
297 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000298
299 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
300 const ExplodedNode *EndPathNode,
301 BugReport &BR) {
302 if (!IsLeak)
303 return 0;
304
305 PathDiagnosticLocation L =
306 PathDiagnosticLocation::createEndOfPath(EndPathNode,
307 BRC.getSourceManager());
308 // Do not add the statement itself as a range in case of leak.
309 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
310 }
311
Anna Zaks56a938f2012-03-16 23:24:20 +0000312 private:
313 class StackHintGeneratorForReallocationFailed
314 : public StackHintGeneratorForSymbol {
315 public:
316 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
317 : StackHintGeneratorForSymbol(S, M) {}
318
319 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
320 SmallString<200> buf;
321 llvm::raw_svector_ostream os(buf);
322
Anna Zaksfbd58742012-03-16 23:44:28 +0000323 os << "Reallocation of ";
Anna Zaks56a938f2012-03-16 23:24:20 +0000324 // Printed parameters start at 1, not 0.
325 printOrdinal(++ArgIndex, os);
326 os << " parameter failed";
327
328 return os.str();
329 }
330
331 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000332 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000333 }
334 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000335 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000336};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000337} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000338
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000339typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy;
Anna Zaks40add292012-02-15 00:11:25 +0000340typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000341class RegionState {};
342class ReallocPairs {};
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000343namespace clang {
Ted Kremenek9ef65372010-12-23 07:20:52 +0000344namespace ento {
Zhongxing Xu243fde92009-11-17 07:54:15 +0000345 template <>
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000346 struct ProgramStateTrait<RegionState>
347 : public ProgramStatePartialTrait<RegionStateTy> {
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000348 static void *GDMIndex() { static int x; return &x; }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000349 };
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000350
351 template <>
352 struct ProgramStateTrait<ReallocPairs>
Anna Zaks40add292012-02-15 00:11:25 +0000353 : public ProgramStatePartialTrait<ReallocMap> {
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000354 static void *GDMIndex() { static int x; return &x; }
355 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000356}
Argyrios Kyrtzidis5a4f98f2010-12-22 18:53:20 +0000357}
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000358
Anna Zaks4fb54872012-02-11 21:02:35 +0000359namespace {
360class StopTrackingCallback : public SymbolVisitor {
361 ProgramStateRef state;
362public:
363 StopTrackingCallback(ProgramStateRef st) : state(st) {}
364 ProgramStateRef getState() const { return state; }
365
366 bool VisitSymbol(SymbolRef sym) {
367 state = state->remove<RegionState>(sym);
368 return true;
369 }
370};
371} // end anonymous namespace
372
Anna Zaks66c40402012-02-14 21:55:24 +0000373void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000374 if (II_malloc)
375 return;
376 II_malloc = &Ctx.Idents.get("malloc");
377 II_free = &Ctx.Idents.get("free");
378 II_realloc = &Ctx.Idents.get("realloc");
379 II_reallocf = &Ctx.Idents.get("reallocf");
380 II_calloc = &Ctx.Idents.get("calloc");
381 II_valloc = &Ctx.Idents.get("valloc");
382 II_strdup = &Ctx.Idents.get("strdup");
383 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000384}
385
Anna Zaks66c40402012-02-14 21:55:24 +0000386bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000387 if (isFreeFunction(FD, C))
388 return true;
389
390 if (isAllocationFunction(FD, C))
391 return true;
392
393 return false;
394}
395
396bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
397 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000398 if (!FD)
399 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000400
Jordan Rose5ef6e942012-07-10 23:13:01 +0000401 if (FD->getKind() == Decl::Function) {
402 IdentifierInfo *FunI = FD->getIdentifier();
403 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000404
Jordan Rose5ef6e942012-07-10 23:13:01 +0000405 if (FunI == II_malloc || FunI == II_realloc ||
406 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
407 FunI == II_strdup || FunI == II_strndup)
408 return true;
409 }
Anna Zaks66c40402012-02-14 21:55:24 +0000410
Anna Zaks14345182012-05-18 01:16:10 +0000411 if (Filter.CMallocOptimistic && FD->hasAttrs())
412 for (specific_attr_iterator<OwnershipAttr>
413 i = FD->specific_attr_begin<OwnershipAttr>(),
414 e = FD->specific_attr_end<OwnershipAttr>();
415 i != e; ++i)
416 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
417 return true;
418 return false;
419}
420
421bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
422 if (!FD)
423 return false;
424
Jordan Rose5ef6e942012-07-10 23:13:01 +0000425 if (FD->getKind() == Decl::Function) {
426 IdentifierInfo *FunI = FD->getIdentifier();
427 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000428
Jordan Rose5ef6e942012-07-10 23:13:01 +0000429 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
430 return true;
431 }
Anna Zaks66c40402012-02-14 21:55:24 +0000432
Anna Zaks14345182012-05-18 01:16:10 +0000433 if (Filter.CMallocOptimistic && FD->hasAttrs())
434 for (specific_attr_iterator<OwnershipAttr>
435 i = FD->specific_attr_begin<OwnershipAttr>(),
436 e = FD->specific_attr_end<OwnershipAttr>();
437 i != e; ++i)
438 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
439 (*i)->getOwnKind() == OwnershipAttr::Holds)
440 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000441 return false;
442}
443
Anna Zaksb319e022012-02-08 20:13:28 +0000444void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
445 const FunctionDecl *FD = C.getCalleeDecl(CE);
446 if (!FD)
447 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000448
Anna Zaks87cb5be2012-02-22 19:24:52 +0000449 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000450 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000451
452 if (FD->getKind() == Decl::Function) {
453 initIdentifierInfo(C.getASTContext());
454 IdentifierInfo *FunI = FD->getIdentifier();
455
456 if (FunI == II_malloc || FunI == II_valloc) {
457 if (CE->getNumArgs() < 1)
458 return;
459 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
460 } else if (FunI == II_realloc) {
461 State = ReallocMem(C, CE, false);
462 } else if (FunI == II_reallocf) {
463 State = ReallocMem(C, CE, true);
464 } else if (FunI == II_calloc) {
465 State = CallocMem(C, CE);
466 } else if (FunI == II_free) {
Anna Zaks55dd9562012-08-24 02:28:20 +0000467 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose5ef6e942012-07-10 23:13:01 +0000468 } else if (FunI == II_strdup) {
469 State = MallocUpdateRefState(C, CE, State);
470 } else if (FunI == II_strndup) {
471 State = MallocUpdateRefState(C, CE, State);
472 }
473 }
474
475 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000476 // Check all the attributes, if there are any.
477 // There can be multiple of these attributes.
478 if (FD->hasAttrs())
479 for (specific_attr_iterator<OwnershipAttr>
480 i = FD->specific_attr_begin<OwnershipAttr>(),
481 e = FD->specific_attr_end<OwnershipAttr>();
482 i != e; ++i) {
483 switch ((*i)->getOwnKind()) {
484 case OwnershipAttr::Returns:
485 State = MallocMemReturnsAttr(C, CE, *i);
486 break;
487 case OwnershipAttr::Takes:
488 case OwnershipAttr::Holds:
489 State = FreeMemAttr(C, CE, *i);
490 break;
491 }
492 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000493 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000494 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000495}
496
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000497static bool isFreeWhenDoneSetToZero(const ObjCMethodCall &Call) {
498 Selector S = Call.getSelector();
Anna Zaks3e4f65d2012-06-22 22:08:09 +0000499 for (unsigned i = 1; i < S.getNumArgs(); ++i)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000500 if (S.getNameForSlot(i).equals("freeWhenDone"))
501 if (Call.getArgSVal(i).isConstant(0))
502 return true;
503
504 return false;
505}
506
Jordan Rosede507ea2012-07-02 19:28:04 +0000507void MallocChecker::checkPreObjCMessage(const ObjCMethodCall &Call,
Jordan Rose740d4902012-07-02 19:27:35 +0000508 CheckerContext &C) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000509 // If the first selector is dataWithBytesNoCopy, assume that the memory will
510 // be released with 'free' by the new object.
511 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
512 // Unless 'freeWhenDone' param set to 0.
513 // TODO: Check that the memory was allocated with malloc.
Anna Zaks55dd9562012-08-24 02:28:20 +0000514 bool ReleasedAllocatedMemory = false;
Jordan Rosede507ea2012-07-02 19:28:04 +0000515 Selector S = Call.getSelector();
Anna Zaks7186dc62012-06-22 22:42:30 +0000516 if ((S.getNameForSlot(0) == "dataWithBytesNoCopy" ||
517 S.getNameForSlot(0) == "initWithBytesNoCopy" ||
518 S.getNameForSlot(0) == "initWithCharactersNoCopy") &&
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000519 !isFreeWhenDoneSetToZero(Call)){
Anna Zaks5b7aa342012-06-22 02:04:31 +0000520 unsigned int argIdx = 0;
Jordan Rose740d4902012-07-02 19:27:35 +0000521 C.addTransition(FreeMemAux(C, Call.getArgExpr(argIdx),
Anna Zaks55dd9562012-08-24 02:28:20 +0000522 Call.getOriginExpr(), C.getState(), true,
523 ReleasedAllocatedMemory));
Anna Zaks5b7aa342012-06-22 02:04:31 +0000524 }
525}
526
Anna Zaks87cb5be2012-02-22 19:24:52 +0000527ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
528 const CallExpr *CE,
529 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000530 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000531 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000532
Sean Huntcf807c42010-08-18 23:23:40 +0000533 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000534 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000535 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000536 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000537 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000538}
539
Anna Zaksb319e022012-02-08 20:13:28 +0000540ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000541 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000542 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000543 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000544
545 // Bind the return value to the symbolic value from the heap region.
546 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
547 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000548 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000549 SValBuilder &svalBuilder = C.getSValBuilder();
550 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
551 DefinedSVal RetVal =
552 cast<DefinedSVal>(svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count));
553 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000554
Anna Zaksb16ce452012-02-15 00:11:22 +0000555 // We expect the malloc functions to return a pointer.
Anna Zakse17fdb22012-06-07 03:57:32 +0000556 if (!isa<Loc>(RetVal))
Anna Zaksb16ce452012-02-15 00:11:22 +0000557 return 0;
558
Jordy Rose32f26562010-07-04 00:00:41 +0000559 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000560 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000561
Jordy Rose32f26562010-07-04 00:00:41 +0000562 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000563 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000564 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000565 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000566 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000567 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000568 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000569 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
570 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
571 DefinedOrUnknownSVal extentMatchesSize =
572 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000573
Anna Zaks60a1fa42012-02-22 03:14:20 +0000574 state = state->assume(extentMatchesSize, true);
575 assert(state);
576 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000577
Anna Zaks87cb5be2012-02-22 19:24:52 +0000578 return MallocUpdateRefState(C, CE, state);
579}
580
581ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
582 const CallExpr *CE,
583 ProgramStateRef state) {
584 // Get the return value.
585 SVal retVal = state->getSVal(CE, C.getLocationContext());
586
587 // We expect the malloc functions to return a pointer.
588 if (!isa<Loc>(retVal))
589 return 0;
590
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000591 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000592 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000593
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000594 // Set the symbol's state to Allocated.
Anna Zaks050cdd72012-06-20 20:57:46 +0000595 return state->set<RegionState>(Sym, RefState::getAllocated(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000596
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000597}
598
Anna Zaks87cb5be2012-02-22 19:24:52 +0000599ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
600 const CallExpr *CE,
601 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000602 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000603 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000604
Anna Zaksb3d72752012-03-01 22:06:06 +0000605 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000606 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000607
Sean Huntcf807c42010-08-18 23:23:40 +0000608 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
609 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000610 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000611 Att->getOwnKind() == OwnershipAttr::Holds,
612 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000613 if (StateI)
614 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000615 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000616 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000617}
618
Ted Kremenek8bef8232012-01-26 21:29:00 +0000619ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000620 const CallExpr *CE,
621 ProgramStateRef state,
622 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000623 bool Hold,
624 bool &ReleasedAllocated) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000625 if (CE->getNumArgs() < (Num + 1))
626 return 0;
627
Anna Zaks55dd9562012-08-24 02:28:20 +0000628 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold, ReleasedAllocated);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000629}
630
631ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
632 const Expr *ArgExpr,
633 const Expr *ParentExpr,
634 ProgramStateRef state,
Anna Zaks55dd9562012-08-24 02:28:20 +0000635 bool Hold,
636 bool &ReleasedAllocated) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000637
Ted Kremenek5eca4822012-01-06 22:09:28 +0000638 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000639 if (!isa<DefinedOrUnknownSVal>(ArgVal))
640 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000641 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
642
643 // Check for null dereferences.
644 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000645 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000646
Anna Zaksb276bd92012-02-14 00:26:13 +0000647 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000648 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000649 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000650 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000651 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000652
Jordy Rose43859f62010-06-07 19:32:37 +0000653 // Unknown values could easily be okay
654 // Undefined values are handled elsewhere
655 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000656 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000657
Jordy Rose43859f62010-06-07 19:32:37 +0000658 const MemRegion *R = ArgVal.getAsRegion();
659
660 // Nonlocs can't be freed, of course.
661 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
662 if (!R) {
663 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000664 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000665 }
666
667 R = R->StripCasts();
668
669 // Blocks might show up as heap data, but should not be free()d
670 if (isa<BlockDataRegion>(R)) {
671 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000672 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000673 }
674
675 const MemSpaceRegion *MS = R->getMemorySpace();
676
677 // Parameters, locals, statics, and globals shouldn't be freed.
678 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
679 // FIXME: at the time this code was written, malloc() regions were
680 // represented by conjured symbols, which are all in UnknownSpaceRegion.
681 // This means that there isn't actually anything from HeapSpaceRegion
682 // that should be freed, even though we allow it here.
683 // Of course, free() can work on memory allocated outside the current
684 // function, so UnknownSpaceRegion is always a possibility.
685 // False negatives are better than false positives.
686
687 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000688 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000689 }
690
691 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
692 // Various cases could lead to non-symbol values here.
693 // For now, ignore them.
694 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000695 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000696
697 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000698 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000699
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000700 // Check double free.
Anna Zaksede875b2012-08-03 18:30:18 +0000701 if (RS && (RS->isReleased() || RS->isRelinquished())) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000702 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000703 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000704 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000705 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000706 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000707 (RS->isReleased() ? "Attempt to free released memory" :
708 "Attempt to free non-owned memory"), N);
Anna Zaksfe571602012-02-16 22:26:07 +0000709 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000710 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000711 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000712 C.EmitReport(R);
713 }
Anna Zaksb319e022012-02-08 20:13:28 +0000714 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000715 }
716
Anna Zaks55dd9562012-08-24 02:28:20 +0000717 ReleasedAllocated = (RS != 0);
718
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000719 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000720 if (Hold)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000721 return state->set<RegionState>(Sym, RefState::getRelinquished(ParentExpr));
722 return state->set<RegionState>(Sym, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000723}
724
Ted Kremenek9c378f72011-08-12 23:37:29 +0000725bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000726 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
727 os << "an integer (" << IntVal->getValue() << ")";
728 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
729 os << "a constant address (" << ConstAddr->getValue() << ")";
730 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000731 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000732 else
733 return false;
734
735 return true;
736}
737
Ted Kremenek9c378f72011-08-12 23:37:29 +0000738bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000739 const MemRegion *MR) {
740 switch (MR->getKind()) {
741 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000742 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +0000743 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000744 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000745 else
746 os << "the address of a function";
747 return true;
748 }
749 case MemRegion::BlockTextRegionKind:
750 os << "block text";
751 return true;
752 case MemRegion::BlockDataRegionKind:
753 // FIXME: where the block came from?
754 os << "a block";
755 return true;
756 default: {
757 const MemSpaceRegion *MS = MR->getMemorySpace();
758
Anna Zakseb31a762012-01-04 23:54:01 +0000759 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000760 const VarRegion *VR = dyn_cast<VarRegion>(MR);
761 const VarDecl *VD;
762 if (VR)
763 VD = VR->getDecl();
764 else
765 VD = NULL;
766
767 if (VD)
768 os << "the address of the local variable '" << VD->getName() << "'";
769 else
770 os << "the address of a local stack variable";
771 return true;
772 }
Anna Zakseb31a762012-01-04 23:54:01 +0000773
774 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000775 const VarRegion *VR = dyn_cast<VarRegion>(MR);
776 const VarDecl *VD;
777 if (VR)
778 VD = VR->getDecl();
779 else
780 VD = NULL;
781
782 if (VD)
783 os << "the address of the parameter '" << VD->getName() << "'";
784 else
785 os << "the address of a parameter";
786 return true;
787 }
Anna Zakseb31a762012-01-04 23:54:01 +0000788
789 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000790 const VarRegion *VR = dyn_cast<VarRegion>(MR);
791 const VarDecl *VD;
792 if (VR)
793 VD = VR->getDecl();
794 else
795 VD = NULL;
796
797 if (VD) {
798 if (VD->isStaticLocal())
799 os << "the address of the static variable '" << VD->getName() << "'";
800 else
801 os << "the address of the global variable '" << VD->getName() << "'";
802 } else
803 os << "the address of a global variable";
804 return true;
805 }
Anna Zakseb31a762012-01-04 23:54:01 +0000806
807 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000808 }
809 }
810}
811
812void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000813 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000814 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000815 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000816 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000817
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000818 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000819 llvm::raw_svector_ostream os(buf);
820
821 const MemRegion *MR = ArgVal.getAsRegion();
822 if (MR) {
823 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
824 MR = ER->getSuperRegion();
825
826 // Special case for alloca()
827 if (isa<AllocaRegion>(MR))
828 os << "Argument to free() was allocated by alloca(), not malloc()";
829 else {
830 os << "Argument to free() is ";
831 if (SummarizeRegion(os, MR))
832 os << ", which is not memory allocated by malloc()";
833 else
834 os << "not memory allocated by malloc()";
835 }
836 } else {
837 os << "Argument to free() is ";
838 if (SummarizeValue(os, ArgVal))
839 os << ", which is not memory allocated by malloc()";
840 else
841 os << "not memory allocated by malloc()";
842 }
843
Anna Zakse172e8b2011-08-17 23:00:25 +0000844 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000845 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000846 R->addRange(range);
847 C.EmitReport(R);
848 }
849}
850
Anna Zaks87cb5be2012-02-22 19:24:52 +0000851ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
852 const CallExpr *CE,
853 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000854 if (CE->getNumArgs() < 2)
855 return 0;
856
Ted Kremenek8bef8232012-01-26 21:29:00 +0000857 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000858 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000859 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000860 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
861 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000862 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000863 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000864
Ted Kremenek846eabd2010-12-01 21:28:31 +0000865 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000866
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000867 DefinedOrUnknownSVal PtrEQ =
868 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000869
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000870 // Get the size argument. If there is no size arg then give up.
871 const Expr *Arg1 = CE->getArg(1);
872 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000873 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000874
875 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000876 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
877 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000878 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000879 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000880
881 // Compare the size argument to 0.
882 DefinedOrUnknownSVal SizeZero =
883 svalBuilder.evalEQ(state, Arg1Val,
884 svalBuilder.makeIntValWithPtrWidth(0, false));
885
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000886 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
887 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
888 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
889 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
890 // We only assume exceptional states if they are definitely true; if the
891 // state is under-constrained, assume regular realloc behavior.
892 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
893 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
894
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000895 // If the ptr is NULL and the size is not 0, the call is equivalent to
896 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000897 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000898 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000899 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000900 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000901 }
902
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000903 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000904 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000905
Anna Zaks30838b92012-02-13 20:57:07 +0000906 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000907 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000908 SymbolRef FromPtr = arg0Val.getAsSymbol();
909 SVal RetVal = state->getSVal(CE, LCtx);
910 SymbolRef ToPtr = RetVal.getAsSymbol();
911 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000912 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000913
Anna Zaks55dd9562012-08-24 02:28:20 +0000914 bool ReleasedAllocated = false;
915
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000916 // If the size is 0, free the memory.
917 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +0000918 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
919 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000920 // The semantics of the return value are:
921 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +0000922 // to free() is returned. We just free the input pointer and do not add
923 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +0000924 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000925 }
926
927 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +0000928 if (ProgramStateRef stateFree =
929 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
930
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000931 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
932 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000933 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000934 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +0000935
Anna Zaks9dc298b2012-09-12 22:57:34 +0000936 ReallocPairKind Kind = RPToBeFreedAfterFailure;
937 if (FreesOnFail)
938 Kind = RPIsFreeOnFailure;
939 else if (!ReleasedAllocated)
940 Kind = RPDoNotTrackAfterFailure;
941
Anna Zaks55dd9562012-08-24 02:28:20 +0000942 // Record the info about the reallocated symbol so that we could properly
943 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +0000944 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +0000945 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +0000946 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +0000947 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000948 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000949 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000950 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000951}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000952
Anna Zaks87cb5be2012-02-22 19:24:52 +0000953ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +0000954 if (CE->getNumArgs() < 2)
955 return 0;
956
Ted Kremenek8bef8232012-01-26 21:29:00 +0000957 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000958 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000959 const LocationContext *LCtx = C.getLocationContext();
960 SVal count = state->getSVal(CE->getArg(0), LCtx);
961 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000962 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
963 svalBuilder.getContext().getSizeType());
964 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000965
Anna Zaks87cb5be2012-02-22 19:24:52 +0000966 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000967}
968
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000969LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +0000970MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
971 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000972 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000973 // Walk the ExplodedGraph backwards and find the first node that referred to
974 // the tracked symbol.
975 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000976 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000977
978 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000979 ProgramStateRef State = N->getState();
980 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +0000981 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000982
983 // Find the most recent expression bound to the symbol in the current
984 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000985 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +0000986 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
987 SVal Val = State->getSVal(MR);
988 if (Val.getAsLocSymbol() == Sym)
989 ReferenceRegion = MR;
990 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000991 }
992
Anna Zaks7752d292012-02-27 23:40:55 +0000993 // Allocation node, is the last node in the current context in which the
994 // symbol was tracked.
995 if (N->getLocationContext() == LeakContext)
996 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000997 N = N->pred_empty() ? NULL : *(N->pred_begin());
998 }
999
1000 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001001 const Stmt *AllocationStmt = 0;
Jordan Rose852aa0d2012-07-10 22:07:52 +00001002 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
1003 AllocationStmt = Exit->getCalleeContext()->getCallSite();
1004 else if (StmtPoint *SP = dyn_cast<StmtPoint>(&P))
1005 AllocationStmt = SP->getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +00001006
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001007 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001008}
1009
Anna Zaksda046772012-02-11 21:02:40 +00001010void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1011 CheckerContext &C) const {
1012 assert(N);
1013 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001014 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001015 // Leaks should not be reported if they are post-dominated by a sink:
1016 // (1) Sinks are higher importance bugs.
1017 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1018 // with __noreturn functions such as assert() or exit(). We choose not
1019 // to report leaks on such paths.
1020 BT_Leak->setSuppressOnSink(true);
1021 }
1022
Anna Zaksca8e36e2012-02-23 21:38:21 +00001023 // Most bug reports are cached at the location where they occurred.
1024 // With leaks, we want to unique them by the location where they were
1025 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001026 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001027 const Stmt *AllocStmt = 0;
1028 const MemRegion *Region = 0;
1029 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
1030 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +00001031 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
1032 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001033
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001034 SmallString<200> buf;
1035 llvm::raw_svector_ostream os(buf);
1036 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001037 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001038 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001039 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001040 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001041 }
1042
1043 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001044 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001045 R->addVisitor(new MallocBugVisitor(Sym, true));
Anna Zaksda046772012-02-11 21:02:40 +00001046 C.EmitReport(R);
1047}
1048
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001049void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1050 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001051{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001052 if (!SymReaper.hasDeadSymbols())
1053 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001054
Ted Kremenek8bef8232012-01-26 21:29:00 +00001055 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001056 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001057 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001058
Ted Kremenek217470e2011-07-28 23:07:51 +00001059 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +00001060 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001061 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1062 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +00001063 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +00001064 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +00001065 Errors.push_back(I->first);
1066 }
Jordy Rose90760142010-08-18 04:33:47 +00001067 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001068 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001069
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001070 }
1071 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001072
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001073 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +00001074 ReallocMap RP = state->get<ReallocPairs>();
1075 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
1076 if (SymReaper.isDead(I->first) ||
1077 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001078 state = state->remove<ReallocPairs>(I->first);
1079 }
1080 }
1081
Anna Zaksca8e36e2012-02-23 21:38:21 +00001082 // Generate leak node.
1083 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1084 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +00001085
Anna Zaksca8e36e2012-02-23 21:38:21 +00001086 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +00001087 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +00001088 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
1089 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001090 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001091 }
Anna Zaksca8e36e2012-02-23 21:38:21 +00001092 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001093}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001094
Anna Zaksda046772012-02-11 21:02:40 +00001095void MallocChecker::checkEndPath(CheckerContext &C) const {
1096 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +00001097 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +00001098
Anna Zaksa19581a2012-02-20 22:25:23 +00001099 // If inside inlined call, skip it.
1100 if (C.getLocationContext()->getParent() != 0)
1101 return;
1102
Jordy Rose09cef092010-08-18 04:26:59 +00001103 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +00001104 RefState RS = I->second;
1105 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +00001106 ExplodedNode *N = C.addTransition(state);
1107 if (N)
1108 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +00001109 }
1110 }
1111}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001112
Anna Zaks66c40402012-02-14 21:55:24 +00001113void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001114 // We will check for double free in the post visit.
1115 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001116 return;
1117
1118 // Check use after free, when a freed pointer is passed to a call.
1119 ProgramStateRef State = C.getState();
1120 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1121 E = CE->arg_end(); I != E; ++I) {
1122 const Expr *A = *I;
1123 if (A->getType().getTypePtr()->isAnyPointerType()) {
1124 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1125 if (!Sym)
1126 continue;
1127 if (checkUseAfterFree(Sym, C, A))
1128 return;
1129 }
1130 }
1131}
1132
Anna Zaks91c2a112012-02-08 23:16:56 +00001133void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1134 const Expr *E = S->getRetValue();
1135 if (!E)
1136 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001137
1138 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001139 ProgramStateRef State = C.getState();
1140 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001141 SymbolRef Sym = RetVal.getAsSymbol();
1142 if (!Sym)
1143 // If we are returning a field of the allocated struct or an array element,
1144 // the callee could still free the memory.
1145 // TODO: This logic should be a part of generic symbol escape callback.
1146 if (const MemRegion *MR = RetVal.getAsRegion())
1147 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1148 if (const SymbolicRegion *BMR =
1149 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1150 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001151
Anna Zaks0860cd02012-02-11 21:44:39 +00001152 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001153 if (Sym)
1154 if (checkUseAfterFree(Sym, C, E))
1155 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001156
Jordan Rose0d53ab42012-08-08 18:23:31 +00001157 // If this function body is not inlined, stop tracking any returned symbols.
1158 if (C.getLocationContext()->getParent() == 0) {
1159 State =
1160 State->scanReachableSymbols<StopTrackingCallback>(RetVal).getState();
1161 C.addTransition(State);
1162 }
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001163}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001164
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001165// TODO: Blocks should be either inlined or should call invalidate regions
1166// upon invocation. After that's in place, special casing here will not be
1167// needed.
1168void MallocChecker::checkPostStmt(const BlockExpr *BE,
1169 CheckerContext &C) const {
1170
1171 // Scan the BlockDecRefExprs for any object the retain count checker
1172 // may be tracking.
1173 if (!BE->getBlockDecl()->hasCaptures())
1174 return;
1175
1176 ProgramStateRef state = C.getState();
1177 const BlockDataRegion *R =
1178 cast<BlockDataRegion>(state->getSVal(BE,
1179 C.getLocationContext()).getAsRegion());
1180
1181 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1182 E = R->referenced_vars_end();
1183
1184 if (I == E)
1185 return;
1186
1187 SmallVector<const MemRegion*, 10> Regions;
1188 const LocationContext *LC = C.getLocationContext();
1189 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1190
1191 for ( ; I != E; ++I) {
1192 const VarRegion *VR = *I;
1193 if (VR->getSuperRegion() == R) {
1194 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1195 }
1196 Regions.push_back(VR);
1197 }
1198
1199 state =
1200 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1201 Regions.data() + Regions.size()).getState();
1202 C.addTransition(state);
1203}
1204
Anna Zaks14345182012-05-18 01:16:10 +00001205bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001206 assert(Sym);
1207 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001208 return (RS && RS->isReleased());
1209}
1210
1211bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1212 const Stmt *S) const {
1213 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001214 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001215 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001216 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001217
Anna Zaksfebdc322012-02-16 22:26:12 +00001218 BugReport *R = new BugReport(*BT_UseFree,
1219 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001220 if (S)
1221 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001222 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001223 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +00001224 C.EmitReport(R);
1225 return true;
1226 }
1227 }
1228 return false;
1229}
1230
Zhongxing Xuc8023782010-03-10 04:58:55 +00001231// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001232void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1233 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001234 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001235 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001236 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001237}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001238
Anna Zaks4fb54872012-02-11 21:02:35 +00001239//===----------------------------------------------------------------------===//
1240// Check various ways a symbol can be invalidated.
1241// TODO: This logic (the next 3 functions) is copied/similar to the
1242// RetainRelease checker. We might want to factor this out.
1243//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001244
Anna Zaks4fb54872012-02-11 21:02:35 +00001245// Stop tracking symbols when a value escapes as a result of checkBind.
1246// A value escapes in three possible cases:
1247// (1) we are binding to something that is not a memory region.
1248// (2) we are binding to a memregion that does not have stack storage
1249// (3) we are binding to a memregion with stack storage that the store
1250// does not understand.
1251void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1252 CheckerContext &C) const {
1253 // Are we storing to something that causes the value to "escape"?
1254 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001255 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001256
Anna Zaks4fb54872012-02-11 21:02:35 +00001257 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1258 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001259
Anna Zaks4fb54872012-02-11 21:02:35 +00001260 if (!escapes) {
1261 // To test (3), generate a new state with the binding added. If it is
1262 // the same state, then it escapes (since the store cannot represent
1263 // the binding).
Anna Zaks93c5a242012-05-02 00:05:20 +00001264 // Do this only if we know that the store is not supposed to generate the
1265 // same state.
1266 SVal StoredVal = state->getSVal(regionLoc->getRegion());
1267 if (StoredVal != val)
1268 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001269 }
1270 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001271
1272 // If our store can represent the binding and we aren't storing to something
1273 // that doesn't have local storage then just return and have the simulation
1274 // state continue as is.
1275 if (!escapes)
1276 return;
1277
1278 // Otherwise, find all symbols referenced by 'val' that we are tracking
1279 // and stop tracking them.
1280 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1281 C.addTransition(state);
1282}
1283
1284// If a symbolic region is assumed to NULL (or another constant), stop tracking
1285// it - assuming that allocation failed on this path.
1286ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1287 SVal Cond,
1288 bool Assumption) const {
1289 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001290 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001291 // If the symbol is assumed to be NULL, remove it from consideration.
1292 if (state->getConstraintManager().isNull(state, I.getKey()).isTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001293 state = state->remove<RegionState>(I.getKey());
1294 }
1295
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001296 // Realloc returns 0 when reallocation fails, which means that we should
1297 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001298 ReallocMap RP = state->get<ReallocPairs>();
1299 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001300 // If the symbol is assumed to be NULL, remove it from consideration.
Anna Zaks9dc298b2012-09-12 22:57:34 +00001301 if (!state->getConstraintManager().isNull(state, I.getKey()).isTrue())
1302 continue;
1303 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1304 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1305 if (RS->isReleased()) {
1306 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001307 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001308 RefState::getAllocated(RS->getStmt()));
1309 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1310 state = state->remove<RegionState>(ReallocSym);
1311 else
1312 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001313 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001314 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001315 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001316 }
1317
Anna Zaks4fb54872012-02-11 21:02:35 +00001318 return state;
1319}
1320
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001321// Check if the function is known to us. So, for example, we could
Jordan Rose740d4902012-07-02 19:27:35 +00001322// conservatively assume it can free/reallocate its pointer arguments.
Anna Zaks66c40402012-02-14 21:55:24 +00001323// (We assume that the pointers cannot escape through calls to system
1324// functions not handled by this checker.)
Jordan Rose740d4902012-07-02 19:27:35 +00001325bool MallocChecker::doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001326 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001327 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001328
1329 // For now, assume that any C++ call can free memory.
1330 // TODO: If we want to be more optimistic here, we'll need to make sure that
1331 // regions escape to C++ containers. They seem to do that even now, but for
1332 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001333 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001334 return false;
1335
Jordan Rose740d4902012-07-02 19:27:35 +00001336 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001337 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001338 // If it's not a framework call, or if it takes a callback, assume it
1339 // can free memory.
1340 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001341 return false;
1342
Jordan Rose740d4902012-07-02 19:27:35 +00001343 Selector S = Msg->getSelector();
Anna Zaks52a04812012-06-20 23:35:57 +00001344
Jordan Rose740d4902012-07-02 19:27:35 +00001345 // Whitelist the ObjC methods which do free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001346 // - Anything containing 'freeWhenDone' param set to 1.
1347 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
Anna Zaks3e4f65d2012-06-22 22:08:09 +00001348 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001349 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1350 if (Call->getArgSVal(i).isConstant(1))
1351 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001352 else
1353 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001354 }
1355 }
1356
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001357 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001358 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001359 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
Jordan Rose740d4902012-07-02 19:27:35 +00001360 StringRef FirstSlot = S.getNameForSlot(0);
1361 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001362 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001363
Anna Zaks5f757682012-06-19 05:10:32 +00001364 // If the first selector starts with addPointer, insertPointer,
1365 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1366 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001367 // that the pointers get freed by following the container itself.
1368 if (FirstSlot.startswith("addPointer") ||
1369 FirstSlot.startswith("insertPointer") ||
1370 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001371 return false;
1372 }
1373
Jordan Rose740d4902012-07-02 19:27:35 +00001374 // Otherwise, assume that the method does not free memory.
1375 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001376 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001377 }
1378
Jordan Rose740d4902012-07-02 19:27:35 +00001379 // At this point the only thing left to handle is straight function calls.
1380 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1381 if (!FD)
1382 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001383
Jordan Rose740d4902012-07-02 19:27:35 +00001384 ASTContext &ASTC = State->getStateManager().getContext();
1385
1386 // If it's one of the allocation functions we can reason about, we model
1387 // its behavior explicitly.
1388 if (isMemFunction(FD, ASTC))
1389 return true;
1390
1391 // If it's not a system call, assume it frees memory.
1392 if (!Call->isInSystemHeader())
1393 return false;
1394
1395 // White list the system functions whose arguments escape.
1396 const IdentifierInfo *II = FD->getIdentifier();
1397 if (!II)
1398 return false;
1399 StringRef FName = II->getName();
1400
Jordan Rose740d4902012-07-02 19:27:35 +00001401 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001402 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001403 if (FName.endswith("NoCopy")) {
1404 // Look for the deallocator argument. We know that the memory ownership
1405 // is not transferred only if the deallocator argument is
1406 // 'kCFAllocatorNull'.
1407 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1408 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1409 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1410 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1411 if (DeallocatorName == "kCFAllocatorNull")
1412 return true;
1413 }
1414 }
1415 return false;
1416 }
1417
Jordan Rose740d4902012-07-02 19:27:35 +00001418 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001419 // 'closefn' is specified (and if that function does free memory),
1420 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001421 // Currently, we do not inspect the 'closefn' function (PR12101).
1422 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001423 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1424 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001425
1426 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1427 // these leaks might be intentional when setting the buffer for stdio.
1428 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1429 if (FName == "setbuf" || FName =="setbuffer" ||
1430 FName == "setlinebuf" || FName == "setvbuf") {
1431 if (Call->getNumArgs() >= 1) {
1432 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1433 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1434 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1435 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1436 return false;
1437 }
1438 }
1439
1440 // A bunch of other functions which either take ownership of a pointer or
1441 // wrap the result up in a struct or object, meaning it can be freed later.
1442 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1443 // but the Malloc checker cannot differentiate between them. The right way
1444 // of doing this would be to implement a pointer escapes callback.
1445 if (FName == "CGBitmapContextCreate" ||
1446 FName == "CGBitmapContextCreateWithData" ||
1447 FName == "CVPixelBufferCreateWithBytes" ||
1448 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1449 FName == "OSAtomicEnqueue") {
1450 return false;
1451 }
1452
Jordan Rose85d7e012012-07-02 19:27:51 +00001453 // Handle cases where we know a buffer's /address/ can escape.
1454 // Note that the above checks handle some special cases where we know that
1455 // even though the address escapes, it's still our responsibility to free the
1456 // buffer.
1457 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001458 return false;
1459
1460 // Otherwise, assume that the function does not free memory.
1461 // Most system calls do not free the memory.
1462 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001463}
1464
Anna Zaks4fb54872012-02-11 21:02:35 +00001465// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1466// escapes, when we are tracking p), do not track the symbol as we cannot reason
1467// about it anymore.
1468ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001469MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001470 const StoreManager::InvalidatedSymbols *invalidated,
1471 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001472 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001473 const CallEvent *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001474 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001475 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001476 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001477
Anna Zaks66c40402012-02-14 21:55:24 +00001478 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001479 // regions (explicit and implicit) escaped.
1480
1481 // Otherwise, whitelist explicit pointers; we still can track them.
1482 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001483 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1484 E = ExplicitRegions.end(); I != E; ++I) {
1485 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1486 WhitelistedSymbols.insert(R->getSymbol());
1487 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001488 }
1489
1490 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1491 E = invalidated->end(); I!=E; ++I) {
1492 SymbolRef sym = *I;
1493 if (WhitelistedSymbols.count(sym))
1494 continue;
Anna Zaks5b7aa342012-06-22 02:04:31 +00001495 // The symbol escaped. Note, we assume that if the symbol is released,
1496 // passing it out will result in a use after free. We also keep tracking
1497 // relinquished symbols.
1498 if (const RefState *RS = State->get<RegionState>(sym)) {
1499 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001500 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001501 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001502 }
Anna Zaks66c40402012-02-14 21:55:24 +00001503 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001504}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001505
Jordy Rose393f98b2012-03-18 07:43:35 +00001506static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1507 ProgramStateRef prevState) {
1508 ReallocMap currMap = currState->get<ReallocPairs>();
1509 ReallocMap prevMap = prevState->get<ReallocPairs>();
1510
1511 for (ReallocMap::iterator I = prevMap.begin(), E = prevMap.end();
1512 I != E; ++I) {
1513 SymbolRef sym = I.getKey();
1514 if (!currMap.lookup(sym))
1515 return sym;
1516 }
1517
1518 return NULL;
1519}
1520
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001521PathDiagnosticPiece *
1522MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1523 const ExplodedNode *PrevN,
1524 BugReporterContext &BRC,
1525 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001526 ProgramStateRef state = N->getState();
1527 ProgramStateRef statePrev = PrevN->getState();
1528
1529 const RefState *RS = state->get<RegionState>(Sym);
1530 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001531 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001532 return 0;
1533
Anna Zaksfe571602012-02-16 22:26:07 +00001534 const Stmt *S = 0;
1535 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001536 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001537
1538 // Retrieve the associated statement.
1539 ProgramPoint ProgLoc = N->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +00001540 if (StmtPoint *SP = dyn_cast<StmtPoint>(&ProgLoc))
1541 S = SP->getStmt();
1542 else if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&ProgLoc))
1543 S = Exit->getCalleeContext()->getCallSite();
Anna Zaksfe571602012-02-16 22:26:07 +00001544 // If an assumption was made on a branch, it should be caught
1545 // here by looking at the state transition.
Jordan Rose852aa0d2012-07-10 22:07:52 +00001546 else if (BlockEdge *Edge = dyn_cast<BlockEdge>(&ProgLoc)) {
1547 const CFGBlock *srcBlk = Edge->getSrc();
Anna Zaksfe571602012-02-16 22:26:07 +00001548 S = srcBlk->getTerminator();
1549 }
1550 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001551 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001552
Jordan Rose28038f32012-07-10 22:07:42 +00001553 // FIXME: We will eventually need to handle non-statement-based events
1554 // (__attribute__((cleanup))).
1555
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001556 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001557 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001558 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001559 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001560 StackHint = new StackHintGeneratorForSymbol(Sym,
1561 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001562 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001563 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001564 StackHint = new StackHintGeneratorForSymbol(Sym,
1565 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001566 } else if (isRelinquished(RS, RSPrev, S)) {
1567 Msg = "Memory ownership is transfered";
1568 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001569 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001570 Mode = ReallocationFailed;
1571 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001572 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001573 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001574
Jordy Roseb000fb52012-03-24 03:15:09 +00001575 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1576 // Is it possible to fail two reallocs WITHOUT testing in between?
1577 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1578 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001579 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001580 FailedReallocSymbol = sym;
1581 }
Anna Zaksfe571602012-02-16 22:26:07 +00001582 }
1583
1584 // We are in a special mode if a reallocation failed later in the path.
1585 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001586 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001587
Jordy Roseb000fb52012-03-24 03:15:09 +00001588 // Is this is the first appearance of the reallocated symbol?
1589 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001590 // We're at the reallocation point.
1591 Msg = "Attempt to reallocate memory";
1592 StackHint = new StackHintGeneratorForSymbol(Sym,
1593 "Returned reallocated memory");
1594 FailedReallocSymbol = NULL;
1595 Mode = Normal;
1596 }
Anna Zaksfe571602012-02-16 22:26:07 +00001597 }
1598
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001599 if (!Msg)
1600 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001601 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001602
1603 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001604 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001605 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001606 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001607}
1608
Anna Zaks93c5a242012-05-02 00:05:20 +00001609void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1610 const char *NL, const char *Sep) const {
1611
1612 RegionStateTy RS = State->get<RegionState>();
1613
1614 if (!RS.isEmpty())
1615 Out << "Has Malloc data" << NL;
1616}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001617
Anna Zaks231361a2012-02-08 23:16:52 +00001618#define REGISTER_CHECKER(name) \
1619void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001620 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001621 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001622}
Anna Zaks231361a2012-02-08 23:16:52 +00001623
1624REGISTER_CHECKER(MallocPessimistic)
1625REGISTER_CHECKER(MallocOptimistic)