blob: 3a27d552218712306bb51e7c929c6f52636e4d38 [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 {
Jordan Rosec20c7272012-09-20 01:55:32 +0000445 if (C.wasInlined)
446 return;
447
Anna Zaksb319e022012-02-08 20:13:28 +0000448 const FunctionDecl *FD = C.getCalleeDecl(CE);
449 if (!FD)
450 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000451
Anna Zaks87cb5be2012-02-22 19:24:52 +0000452 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000453 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000454
455 if (FD->getKind() == Decl::Function) {
456 initIdentifierInfo(C.getASTContext());
457 IdentifierInfo *FunI = FD->getIdentifier();
458
459 if (FunI == II_malloc || FunI == II_valloc) {
460 if (CE->getNumArgs() < 1)
461 return;
462 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
463 } else if (FunI == II_realloc) {
464 State = ReallocMem(C, CE, false);
465 } else if (FunI == II_reallocf) {
466 State = ReallocMem(C, CE, true);
467 } else if (FunI == II_calloc) {
468 State = CallocMem(C, CE);
469 } else if (FunI == II_free) {
Anna Zaks55dd9562012-08-24 02:28:20 +0000470 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose5ef6e942012-07-10 23:13:01 +0000471 } else if (FunI == II_strdup) {
472 State = MallocUpdateRefState(C, CE, State);
473 } else if (FunI == II_strndup) {
474 State = MallocUpdateRefState(C, CE, State);
475 }
476 }
477
478 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000479 // Check all the attributes, if there are any.
480 // There can be multiple of these attributes.
481 if (FD->hasAttrs())
482 for (specific_attr_iterator<OwnershipAttr>
483 i = FD->specific_attr_begin<OwnershipAttr>(),
484 e = FD->specific_attr_end<OwnershipAttr>();
485 i != e; ++i) {
486 switch ((*i)->getOwnKind()) {
487 case OwnershipAttr::Returns:
488 State = MallocMemReturnsAttr(C, CE, *i);
489 break;
490 case OwnershipAttr::Takes:
491 case OwnershipAttr::Holds:
492 State = FreeMemAttr(C, CE, *i);
493 break;
494 }
495 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000496 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000497 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000498}
499
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000500static bool isFreeWhenDoneSetToZero(const ObjCMethodCall &Call) {
501 Selector S = Call.getSelector();
Anna Zaks3e4f65d2012-06-22 22:08:09 +0000502 for (unsigned i = 1; i < S.getNumArgs(); ++i)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000503 if (S.getNameForSlot(i).equals("freeWhenDone"))
504 if (Call.getArgSVal(i).isConstant(0))
505 return true;
506
507 return false;
508}
509
Jordan Rosede507ea2012-07-02 19:28:04 +0000510void MallocChecker::checkPreObjCMessage(const ObjCMethodCall &Call,
Jordan Rose740d4902012-07-02 19:27:35 +0000511 CheckerContext &C) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000512 // If the first selector is dataWithBytesNoCopy, assume that the memory will
513 // be released with 'free' by the new object.
514 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
515 // Unless 'freeWhenDone' param set to 0.
516 // TODO: Check that the memory was allocated with malloc.
Anna Zaks55dd9562012-08-24 02:28:20 +0000517 bool ReleasedAllocatedMemory = false;
Jordan Rosede507ea2012-07-02 19:28:04 +0000518 Selector S = Call.getSelector();
Anna Zaks7186dc62012-06-22 22:42:30 +0000519 if ((S.getNameForSlot(0) == "dataWithBytesNoCopy" ||
520 S.getNameForSlot(0) == "initWithBytesNoCopy" ||
521 S.getNameForSlot(0) == "initWithCharactersNoCopy") &&
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000522 !isFreeWhenDoneSetToZero(Call)){
Anna Zaks5b7aa342012-06-22 02:04:31 +0000523 unsigned int argIdx = 0;
Jordan Rose740d4902012-07-02 19:27:35 +0000524 C.addTransition(FreeMemAux(C, Call.getArgExpr(argIdx),
Anna Zaks55dd9562012-08-24 02:28:20 +0000525 Call.getOriginExpr(), C.getState(), true,
526 ReleasedAllocatedMemory));
Anna Zaks5b7aa342012-06-22 02:04:31 +0000527 }
528}
529
Anna Zaks87cb5be2012-02-22 19:24:52 +0000530ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
531 const CallExpr *CE,
532 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000533 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000534 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000535
Sean Huntcf807c42010-08-18 23:23:40 +0000536 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000537 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000538 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000539 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000540 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000541}
542
Anna Zaksb319e022012-02-08 20:13:28 +0000543ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000544 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000545 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000546 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000547
548 // Bind the return value to the symbolic value from the heap region.
549 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
550 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000551 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000552 SValBuilder &svalBuilder = C.getSValBuilder();
553 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
554 DefinedSVal RetVal =
555 cast<DefinedSVal>(svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count));
556 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000557
Anna Zaksb16ce452012-02-15 00:11:22 +0000558 // We expect the malloc functions to return a pointer.
Anna Zakse17fdb22012-06-07 03:57:32 +0000559 if (!isa<Loc>(RetVal))
Anna Zaksb16ce452012-02-15 00:11:22 +0000560 return 0;
561
Jordy Rose32f26562010-07-04 00:00:41 +0000562 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000563 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000564
Jordy Rose32f26562010-07-04 00:00:41 +0000565 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000566 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000567 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000568 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000569 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000570 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000571 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000572 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
573 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
574 DefinedOrUnknownSVal extentMatchesSize =
575 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000576
Anna Zaks60a1fa42012-02-22 03:14:20 +0000577 state = state->assume(extentMatchesSize, true);
578 assert(state);
579 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000580
Anna Zaks87cb5be2012-02-22 19:24:52 +0000581 return MallocUpdateRefState(C, CE, state);
582}
583
584ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
585 const CallExpr *CE,
586 ProgramStateRef state) {
587 // Get the return value.
588 SVal retVal = state->getSVal(CE, C.getLocationContext());
589
590 // We expect the malloc functions to return a pointer.
591 if (!isa<Loc>(retVal))
592 return 0;
593
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000594 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000595 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000596
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000597 // Set the symbol's state to Allocated.
Anna Zaks050cdd72012-06-20 20:57:46 +0000598 return state->set<RegionState>(Sym, RefState::getAllocated(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000599
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000600}
601
Anna Zaks87cb5be2012-02-22 19:24:52 +0000602ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
603 const CallExpr *CE,
604 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000605 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000606 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000607
Anna Zaksb3d72752012-03-01 22:06:06 +0000608 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000609 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000610
Sean Huntcf807c42010-08-18 23:23:40 +0000611 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
612 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000613 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000614 Att->getOwnKind() == OwnershipAttr::Holds,
615 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000616 if (StateI)
617 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000618 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000619 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000620}
621
Ted Kremenek8bef8232012-01-26 21:29:00 +0000622ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000623 const CallExpr *CE,
624 ProgramStateRef state,
625 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000626 bool Hold,
627 bool &ReleasedAllocated) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000628 if (CE->getNumArgs() < (Num + 1))
629 return 0;
630
Anna Zaks55dd9562012-08-24 02:28:20 +0000631 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold, ReleasedAllocated);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000632}
633
634ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
635 const Expr *ArgExpr,
636 const Expr *ParentExpr,
637 ProgramStateRef state,
Anna Zaks55dd9562012-08-24 02:28:20 +0000638 bool Hold,
639 bool &ReleasedAllocated) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000640
Ted Kremenek5eca4822012-01-06 22:09:28 +0000641 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000642 if (!isa<DefinedOrUnknownSVal>(ArgVal))
643 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000644 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
645
646 // Check for null dereferences.
647 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000648 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000649
Anna Zaksb276bd92012-02-14 00:26:13 +0000650 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000651 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000652 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000653 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000654 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000655
Jordy Rose43859f62010-06-07 19:32:37 +0000656 // Unknown values could easily be okay
657 // Undefined values are handled elsewhere
658 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000659 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000660
Jordy Rose43859f62010-06-07 19:32:37 +0000661 const MemRegion *R = ArgVal.getAsRegion();
662
663 // Nonlocs can't be freed, of course.
664 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
665 if (!R) {
666 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000667 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000668 }
669
670 R = R->StripCasts();
671
672 // Blocks might show up as heap data, but should not be free()d
673 if (isa<BlockDataRegion>(R)) {
674 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000675 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000676 }
677
678 const MemSpaceRegion *MS = R->getMemorySpace();
679
680 // Parameters, locals, statics, and globals shouldn't be freed.
681 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
682 // FIXME: at the time this code was written, malloc() regions were
683 // represented by conjured symbols, which are all in UnknownSpaceRegion.
684 // This means that there isn't actually anything from HeapSpaceRegion
685 // that should be freed, even though we allow it here.
686 // Of course, free() can work on memory allocated outside the current
687 // function, so UnknownSpaceRegion is always a possibility.
688 // False negatives are better than false positives.
689
690 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000691 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000692 }
693
694 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
695 // Various cases could lead to non-symbol values here.
696 // For now, ignore them.
697 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000698 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000699
700 SymbolRef Sym = SR->getSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000701 const RefState *RS = state->get<RegionState>(Sym);
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000702
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000703 // Check double free.
Anna Zaksede875b2012-08-03 18:30:18 +0000704 if (RS && (RS->isReleased() || RS->isRelinquished())) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000705 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000706 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000707 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000708 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000709 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000710 (RS->isReleased() ? "Attempt to free released memory" :
711 "Attempt to free non-owned memory"), N);
Anna Zaksfe571602012-02-16 22:26:07 +0000712 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000713 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000714 R->addVisitor(new MallocBugVisitor(Sym));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000715 C.EmitReport(R);
716 }
Anna Zaksb319e022012-02-08 20:13:28 +0000717 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000718 }
719
Anna Zaks55dd9562012-08-24 02:28:20 +0000720 ReleasedAllocated = (RS != 0);
721
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000722 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000723 if (Hold)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000724 return state->set<RegionState>(Sym, RefState::getRelinquished(ParentExpr));
725 return state->set<RegionState>(Sym, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000726}
727
Ted Kremenek9c378f72011-08-12 23:37:29 +0000728bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000729 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
730 os << "an integer (" << IntVal->getValue() << ")";
731 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
732 os << "a constant address (" << ConstAddr->getValue() << ")";
733 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000734 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000735 else
736 return false;
737
738 return true;
739}
740
Ted Kremenek9c378f72011-08-12 23:37:29 +0000741bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000742 const MemRegion *MR) {
743 switch (MR->getKind()) {
744 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000745 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +0000746 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000747 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000748 else
749 os << "the address of a function";
750 return true;
751 }
752 case MemRegion::BlockTextRegionKind:
753 os << "block text";
754 return true;
755 case MemRegion::BlockDataRegionKind:
756 // FIXME: where the block came from?
757 os << "a block";
758 return true;
759 default: {
760 const MemSpaceRegion *MS = MR->getMemorySpace();
761
Anna Zakseb31a762012-01-04 23:54:01 +0000762 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000763 const VarRegion *VR = dyn_cast<VarRegion>(MR);
764 const VarDecl *VD;
765 if (VR)
766 VD = VR->getDecl();
767 else
768 VD = NULL;
769
770 if (VD)
771 os << "the address of the local variable '" << VD->getName() << "'";
772 else
773 os << "the address of a local stack variable";
774 return true;
775 }
Anna Zakseb31a762012-01-04 23:54:01 +0000776
777 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000778 const VarRegion *VR = dyn_cast<VarRegion>(MR);
779 const VarDecl *VD;
780 if (VR)
781 VD = VR->getDecl();
782 else
783 VD = NULL;
784
785 if (VD)
786 os << "the address of the parameter '" << VD->getName() << "'";
787 else
788 os << "the address of a parameter";
789 return true;
790 }
Anna Zakseb31a762012-01-04 23:54:01 +0000791
792 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000793 const VarRegion *VR = dyn_cast<VarRegion>(MR);
794 const VarDecl *VD;
795 if (VR)
796 VD = VR->getDecl();
797 else
798 VD = NULL;
799
800 if (VD) {
801 if (VD->isStaticLocal())
802 os << "the address of the static variable '" << VD->getName() << "'";
803 else
804 os << "the address of the global variable '" << VD->getName() << "'";
805 } else
806 os << "the address of a global variable";
807 return true;
808 }
Anna Zakseb31a762012-01-04 23:54:01 +0000809
810 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000811 }
812 }
813}
814
815void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000816 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000817 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000818 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000819 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000820
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000821 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000822 llvm::raw_svector_ostream os(buf);
823
824 const MemRegion *MR = ArgVal.getAsRegion();
825 if (MR) {
826 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
827 MR = ER->getSuperRegion();
828
829 // Special case for alloca()
830 if (isa<AllocaRegion>(MR))
831 os << "Argument to free() was allocated by alloca(), not malloc()";
832 else {
833 os << "Argument to free() is ";
834 if (SummarizeRegion(os, MR))
835 os << ", which is not memory allocated by malloc()";
836 else
837 os << "not memory allocated by malloc()";
838 }
839 } else {
840 os << "Argument to free() is ";
841 if (SummarizeValue(os, ArgVal))
842 os << ", which is not memory allocated by malloc()";
843 else
844 os << "not memory allocated by malloc()";
845 }
846
Anna Zakse172e8b2011-08-17 23:00:25 +0000847 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000848 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000849 R->addRange(range);
850 C.EmitReport(R);
851 }
852}
853
Anna Zaks87cb5be2012-02-22 19:24:52 +0000854ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
855 const CallExpr *CE,
856 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000857 if (CE->getNumArgs() < 2)
858 return 0;
859
Ted Kremenek8bef8232012-01-26 21:29:00 +0000860 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000861 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000862 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000863 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
864 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000865 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000866 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000867
Ted Kremenek846eabd2010-12-01 21:28:31 +0000868 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000869
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000870 DefinedOrUnknownSVal PtrEQ =
871 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000872
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000873 // Get the size argument. If there is no size arg then give up.
874 const Expr *Arg1 = CE->getArg(1);
875 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000876 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000877
878 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000879 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
880 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000881 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000882 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000883
884 // Compare the size argument to 0.
885 DefinedOrUnknownSVal SizeZero =
886 svalBuilder.evalEQ(state, Arg1Val,
887 svalBuilder.makeIntValWithPtrWidth(0, false));
888
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000889 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
890 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
891 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
892 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
893 // We only assume exceptional states if they are definitely true; if the
894 // state is under-constrained, assume regular realloc behavior.
895 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
896 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
897
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000898 // If the ptr is NULL and the size is not 0, the call is equivalent to
899 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000900 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000901 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000902 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000903 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000904 }
905
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000906 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000907 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000908
Anna Zaks30838b92012-02-13 20:57:07 +0000909 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000910 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000911 SymbolRef FromPtr = arg0Val.getAsSymbol();
912 SVal RetVal = state->getSVal(CE, LCtx);
913 SymbolRef ToPtr = RetVal.getAsSymbol();
914 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000915 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000916
Anna Zaks55dd9562012-08-24 02:28:20 +0000917 bool ReleasedAllocated = false;
918
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000919 // If the size is 0, free the memory.
920 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +0000921 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
922 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000923 // The semantics of the return value are:
924 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +0000925 // to free() is returned. We just free the input pointer and do not add
926 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +0000927 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000928 }
929
930 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +0000931 if (ProgramStateRef stateFree =
932 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
933
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000934 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
935 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000936 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000937 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +0000938
Anna Zaks9dc298b2012-09-12 22:57:34 +0000939 ReallocPairKind Kind = RPToBeFreedAfterFailure;
940 if (FreesOnFail)
941 Kind = RPIsFreeOnFailure;
942 else if (!ReleasedAllocated)
943 Kind = RPDoNotTrackAfterFailure;
944
Anna Zaks55dd9562012-08-24 02:28:20 +0000945 // Record the info about the reallocated symbol so that we could properly
946 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +0000947 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +0000948 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +0000949 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +0000950 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000951 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000952 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000953 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000954}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000955
Anna Zaks87cb5be2012-02-22 19:24:52 +0000956ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +0000957 if (CE->getNumArgs() < 2)
958 return 0;
959
Ted Kremenek8bef8232012-01-26 21:29:00 +0000960 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000961 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000962 const LocationContext *LCtx = C.getLocationContext();
963 SVal count = state->getSVal(CE->getArg(0), LCtx);
964 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000965 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
966 svalBuilder.getContext().getSizeType());
967 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000968
Anna Zaks87cb5be2012-02-22 19:24:52 +0000969 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000970}
971
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000972LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +0000973MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
974 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +0000975 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +0000976 // Walk the ExplodedGraph backwards and find the first node that referred to
977 // the tracked symbol.
978 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000979 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000980
981 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000982 ProgramStateRef State = N->getState();
983 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +0000984 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000985
986 // Find the most recent expression bound to the symbol in the current
987 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000988 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +0000989 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
990 SVal Val = State->getSVal(MR);
991 if (Val.getAsLocSymbol() == Sym)
992 ReferenceRegion = MR;
993 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000994 }
995
Anna Zaks7752d292012-02-27 23:40:55 +0000996 // Allocation node, is the last node in the current context in which the
997 // symbol was tracked.
998 if (N->getLocationContext() == LeakContext)
999 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001000 N = N->pred_empty() ? NULL : *(N->pred_begin());
1001 }
1002
1003 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001004 const Stmt *AllocationStmt = 0;
Jordan Rose852aa0d2012-07-10 22:07:52 +00001005 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
1006 AllocationStmt = Exit->getCalleeContext()->getCallSite();
1007 else if (StmtPoint *SP = dyn_cast<StmtPoint>(&P))
1008 AllocationStmt = SP->getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +00001009
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001010 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001011}
1012
Anna Zaksda046772012-02-11 21:02:40 +00001013void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1014 CheckerContext &C) const {
1015 assert(N);
1016 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001017 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001018 // Leaks should not be reported if they are post-dominated by a sink:
1019 // (1) Sinks are higher importance bugs.
1020 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1021 // with __noreturn functions such as assert() or exit(). We choose not
1022 // to report leaks on such paths.
1023 BT_Leak->setSuppressOnSink(true);
1024 }
1025
Anna Zaksca8e36e2012-02-23 21:38:21 +00001026 // Most bug reports are cached at the location where they occurred.
1027 // With leaks, we want to unique them by the location where they were
1028 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001029 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001030 const Stmt *AllocStmt = 0;
1031 const MemRegion *Region = 0;
1032 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
1033 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +00001034 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
1035 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001036
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001037 SmallString<200> buf;
1038 llvm::raw_svector_ostream os(buf);
1039 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001040 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001041 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001042 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001043 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001044 }
1045
1046 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001047 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001048 R->addVisitor(new MallocBugVisitor(Sym, true));
Anna Zaksda046772012-02-11 21:02:40 +00001049 C.EmitReport(R);
1050}
1051
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001052void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1053 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001054{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001055 if (!SymReaper.hasDeadSymbols())
1056 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001057
Ted Kremenek8bef8232012-01-26 21:29:00 +00001058 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001059 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001060 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001061
Ted Kremenek217470e2011-07-28 23:07:51 +00001062 bool generateReport = false;
Anna Zaksf8c17b72012-02-09 06:48:19 +00001063 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001064 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1065 if (SymReaper.isDead(I->first)) {
Anna Zaksf8c17b72012-02-09 06:48:19 +00001066 if (I->second.isAllocated()) {
Ted Kremenek217470e2011-07-28 23:07:51 +00001067 generateReport = true;
Anna Zaksf8c17b72012-02-09 06:48:19 +00001068 Errors.push_back(I->first);
1069 }
Jordy Rose90760142010-08-18 04:33:47 +00001070 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001071 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001072
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001073 }
1074 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001075
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001076 // Cleanup the Realloc Pairs Map.
Anna Zaks40add292012-02-15 00:11:25 +00001077 ReallocMap RP = state->get<ReallocPairs>();
1078 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
1079 if (SymReaper.isDead(I->first) ||
1080 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001081 state = state->remove<ReallocPairs>(I->first);
1082 }
1083 }
1084
Anna Zaksca8e36e2012-02-23 21:38:21 +00001085 // Generate leak node.
1086 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1087 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Ted Kremenek217470e2011-07-28 23:07:51 +00001088
Anna Zaksca8e36e2012-02-23 21:38:21 +00001089 if (generateReport) {
Anna Zaksf8c17b72012-02-09 06:48:19 +00001090 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaksda046772012-02-11 21:02:40 +00001091 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
1092 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001093 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001094 }
Anna Zaksca8e36e2012-02-23 21:38:21 +00001095 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001096}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001097
Anna Zaksda046772012-02-11 21:02:40 +00001098void MallocChecker::checkEndPath(CheckerContext &C) const {
1099 ProgramStateRef state = C.getState();
Jordy Rose09cef092010-08-18 04:26:59 +00001100 RegionStateTy M = state->get<RegionState>();
Zhongxing Xu243fde92009-11-17 07:54:15 +00001101
Anna Zaksa19581a2012-02-20 22:25:23 +00001102 // If inside inlined call, skip it.
1103 if (C.getLocationContext()->getParent() != 0)
1104 return;
1105
Jordy Rose09cef092010-08-18 04:26:59 +00001106 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) {
Zhongxing Xu243fde92009-11-17 07:54:15 +00001107 RefState RS = I->second;
1108 if (RS.isAllocated()) {
Anna Zaksda046772012-02-11 21:02:40 +00001109 ExplodedNode *N = C.addTransition(state);
1110 if (N)
1111 reportLeak(I->first, N, C);
Zhongxing Xu243fde92009-11-17 07:54:15 +00001112 }
1113 }
1114}
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001115
Anna Zaks66c40402012-02-14 21:55:24 +00001116void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001117 // We will check for double free in the post visit.
1118 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001119 return;
1120
1121 // Check use after free, when a freed pointer is passed to a call.
1122 ProgramStateRef State = C.getState();
1123 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1124 E = CE->arg_end(); I != E; ++I) {
1125 const Expr *A = *I;
1126 if (A->getType().getTypePtr()->isAnyPointerType()) {
1127 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1128 if (!Sym)
1129 continue;
1130 if (checkUseAfterFree(Sym, C, A))
1131 return;
1132 }
1133 }
1134}
1135
Anna Zaks91c2a112012-02-08 23:16:56 +00001136void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1137 const Expr *E = S->getRetValue();
1138 if (!E)
1139 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001140
1141 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001142 ProgramStateRef State = C.getState();
1143 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001144 SymbolRef Sym = RetVal.getAsSymbol();
1145 if (!Sym)
1146 // If we are returning a field of the allocated struct or an array element,
1147 // the callee could still free the memory.
1148 // TODO: This logic should be a part of generic symbol escape callback.
1149 if (const MemRegion *MR = RetVal.getAsRegion())
1150 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1151 if (const SymbolicRegion *BMR =
1152 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1153 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001154
Anna Zaks0860cd02012-02-11 21:44:39 +00001155 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001156 if (Sym)
1157 if (checkUseAfterFree(Sym, C, E))
1158 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001159
Jordan Rose0d53ab42012-08-08 18:23:31 +00001160 // If this function body is not inlined, stop tracking any returned symbols.
1161 if (C.getLocationContext()->getParent() == 0) {
1162 State =
1163 State->scanReachableSymbols<StopTrackingCallback>(RetVal).getState();
1164 C.addTransition(State);
1165 }
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001166}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001167
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001168// TODO: Blocks should be either inlined or should call invalidate regions
1169// upon invocation. After that's in place, special casing here will not be
1170// needed.
1171void MallocChecker::checkPostStmt(const BlockExpr *BE,
1172 CheckerContext &C) const {
1173
1174 // Scan the BlockDecRefExprs for any object the retain count checker
1175 // may be tracking.
1176 if (!BE->getBlockDecl()->hasCaptures())
1177 return;
1178
1179 ProgramStateRef state = C.getState();
1180 const BlockDataRegion *R =
1181 cast<BlockDataRegion>(state->getSVal(BE,
1182 C.getLocationContext()).getAsRegion());
1183
1184 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1185 E = R->referenced_vars_end();
1186
1187 if (I == E)
1188 return;
1189
1190 SmallVector<const MemRegion*, 10> Regions;
1191 const LocationContext *LC = C.getLocationContext();
1192 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1193
1194 for ( ; I != E; ++I) {
1195 const VarRegion *VR = *I;
1196 if (VR->getSuperRegion() == R) {
1197 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1198 }
1199 Regions.push_back(VR);
1200 }
1201
1202 state =
1203 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1204 Regions.data() + Regions.size()).getState();
1205 C.addTransition(state);
1206}
1207
Anna Zaks14345182012-05-18 01:16:10 +00001208bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001209 assert(Sym);
1210 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001211 return (RS && RS->isReleased());
1212}
1213
1214bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1215 const Stmt *S) const {
1216 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001217 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001218 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001219 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001220
Anna Zaksfebdc322012-02-16 22:26:12 +00001221 BugReport *R = new BugReport(*BT_UseFree,
1222 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001223 if (S)
1224 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001225 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001226 R->addVisitor(new MallocBugVisitor(Sym));
Anna Zaks91c2a112012-02-08 23:16:56 +00001227 C.EmitReport(R);
1228 return true;
1229 }
1230 }
1231 return false;
1232}
1233
Zhongxing Xuc8023782010-03-10 04:58:55 +00001234// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001235void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1236 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001237 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001238 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001239 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001240}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001241
Anna Zaks4fb54872012-02-11 21:02:35 +00001242//===----------------------------------------------------------------------===//
1243// Check various ways a symbol can be invalidated.
1244// TODO: This logic (the next 3 functions) is copied/similar to the
1245// RetainRelease checker. We might want to factor this out.
1246//===----------------------------------------------------------------------===//
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001247
Anna Zaks4fb54872012-02-11 21:02:35 +00001248// Stop tracking symbols when a value escapes as a result of checkBind.
1249// A value escapes in three possible cases:
1250// (1) we are binding to something that is not a memory region.
1251// (2) we are binding to a memregion that does not have stack storage
1252// (3) we are binding to a memregion with stack storage that the store
1253// does not understand.
1254void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S,
1255 CheckerContext &C) const {
1256 // Are we storing to something that causes the value to "escape"?
1257 bool escapes = true;
Ted Kremenek8bef8232012-01-26 21:29:00 +00001258 ProgramStateRef state = C.getState();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001259
Anna Zaks4fb54872012-02-11 21:02:35 +00001260 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
1261 escapes = !regionLoc->getRegion()->hasStackStorage();
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001262
Anna Zaks4fb54872012-02-11 21:02:35 +00001263 if (!escapes) {
1264 // To test (3), generate a new state with the binding added. If it is
1265 // the same state, then it escapes (since the store cannot represent
1266 // the binding).
Anna Zaks93c5a242012-05-02 00:05:20 +00001267 // Do this only if we know that the store is not supposed to generate the
1268 // same state.
1269 SVal StoredVal = state->getSVal(regionLoc->getRegion());
1270 if (StoredVal != val)
1271 escapes = (state == (state->bindLoc(*regionLoc, val)));
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001272 }
1273 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001274
1275 // If our store can represent the binding and we aren't storing to something
1276 // that doesn't have local storage then just return and have the simulation
1277 // state continue as is.
1278 if (!escapes)
1279 return;
1280
1281 // Otherwise, find all symbols referenced by 'val' that we are tracking
1282 // and stop tracking them.
1283 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
1284 C.addTransition(state);
1285}
1286
1287// If a symbolic region is assumed to NULL (or another constant), stop tracking
1288// it - assuming that allocation failed on this path.
1289ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1290 SVal Cond,
1291 bool Assumption) const {
1292 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001293 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001294 // If the symbol is assumed to be NULL, remove it from consideration.
1295 if (state->getConstraintManager().isNull(state, I.getKey()).isTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001296 state = state->remove<RegionState>(I.getKey());
1297 }
1298
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001299 // Realloc returns 0 when reallocation fails, which means that we should
1300 // restore the state of the pointer being reallocated.
Anna Zaks40add292012-02-15 00:11:25 +00001301 ReallocMap RP = state->get<ReallocPairs>();
1302 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001303 // If the symbol is assumed to be NULL, remove it from consideration.
Anna Zaks9dc298b2012-09-12 22:57:34 +00001304 if (!state->getConstraintManager().isNull(state, I.getKey()).isTrue())
1305 continue;
1306 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1307 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1308 if (RS->isReleased()) {
1309 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001310 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001311 RefState::getAllocated(RS->getStmt()));
1312 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1313 state = state->remove<RegionState>(ReallocSym);
1314 else
1315 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001316 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001317 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001318 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001319 }
1320
Anna Zaks4fb54872012-02-11 21:02:35 +00001321 return state;
1322}
1323
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001324// Check if the function is known to us. So, for example, we could
Jordan Rose740d4902012-07-02 19:27:35 +00001325// conservatively assume it can free/reallocate its pointer arguments.
Anna Zaks66c40402012-02-14 21:55:24 +00001326// (We assume that the pointers cannot escape through calls to system
1327// functions not handled by this checker.)
Jordan Rose740d4902012-07-02 19:27:35 +00001328bool MallocChecker::doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001329 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001330 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001331
1332 // For now, assume that any C++ call can free memory.
1333 // TODO: If we want to be more optimistic here, we'll need to make sure that
1334 // regions escape to C++ containers. They seem to do that even now, but for
1335 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001336 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001337 return false;
1338
Jordan Rose740d4902012-07-02 19:27:35 +00001339 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001340 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001341 // If it's not a framework call, or if it takes a callback, assume it
1342 // can free memory.
1343 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001344 return false;
1345
Jordan Rose740d4902012-07-02 19:27:35 +00001346 Selector S = Msg->getSelector();
Anna Zaks52a04812012-06-20 23:35:57 +00001347
Jordan Rose740d4902012-07-02 19:27:35 +00001348 // Whitelist the ObjC methods which do free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001349 // - Anything containing 'freeWhenDone' param set to 1.
1350 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
Anna Zaks3e4f65d2012-06-22 22:08:09 +00001351 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001352 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1353 if (Call->getArgSVal(i).isConstant(1))
1354 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001355 else
1356 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001357 }
1358 }
1359
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001360 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001361 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001362 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
Jordan Rose740d4902012-07-02 19:27:35 +00001363 StringRef FirstSlot = S.getNameForSlot(0);
1364 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001365 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001366
Anna Zaks5f757682012-06-19 05:10:32 +00001367 // If the first selector starts with addPointer, insertPointer,
1368 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1369 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001370 // that the pointers get freed by following the container itself.
1371 if (FirstSlot.startswith("addPointer") ||
1372 FirstSlot.startswith("insertPointer") ||
1373 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001374 return false;
1375 }
1376
Jordan Rose740d4902012-07-02 19:27:35 +00001377 // Otherwise, assume that the method does not free memory.
1378 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001379 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001380 }
1381
Jordan Rose740d4902012-07-02 19:27:35 +00001382 // At this point the only thing left to handle is straight function calls.
1383 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1384 if (!FD)
1385 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001386
Jordan Rose740d4902012-07-02 19:27:35 +00001387 ASTContext &ASTC = State->getStateManager().getContext();
1388
1389 // If it's one of the allocation functions we can reason about, we model
1390 // its behavior explicitly.
1391 if (isMemFunction(FD, ASTC))
1392 return true;
1393
1394 // If it's not a system call, assume it frees memory.
1395 if (!Call->isInSystemHeader())
1396 return false;
1397
1398 // White list the system functions whose arguments escape.
1399 const IdentifierInfo *II = FD->getIdentifier();
1400 if (!II)
1401 return false;
1402 StringRef FName = II->getName();
1403
Jordan Rose740d4902012-07-02 19:27:35 +00001404 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001405 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001406 if (FName.endswith("NoCopy")) {
1407 // Look for the deallocator argument. We know that the memory ownership
1408 // is not transferred only if the deallocator argument is
1409 // 'kCFAllocatorNull'.
1410 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1411 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1412 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1413 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1414 if (DeallocatorName == "kCFAllocatorNull")
1415 return true;
1416 }
1417 }
1418 return false;
1419 }
1420
Jordan Rose740d4902012-07-02 19:27:35 +00001421 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001422 // 'closefn' is specified (and if that function does free memory),
1423 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001424 // Currently, we do not inspect the 'closefn' function (PR12101).
1425 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001426 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1427 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001428
1429 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1430 // these leaks might be intentional when setting the buffer for stdio.
1431 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1432 if (FName == "setbuf" || FName =="setbuffer" ||
1433 FName == "setlinebuf" || FName == "setvbuf") {
1434 if (Call->getNumArgs() >= 1) {
1435 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1436 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1437 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1438 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1439 return false;
1440 }
1441 }
1442
1443 // A bunch of other functions which either take ownership of a pointer or
1444 // wrap the result up in a struct or object, meaning it can be freed later.
1445 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1446 // but the Malloc checker cannot differentiate between them. The right way
1447 // of doing this would be to implement a pointer escapes callback.
1448 if (FName == "CGBitmapContextCreate" ||
1449 FName == "CGBitmapContextCreateWithData" ||
1450 FName == "CVPixelBufferCreateWithBytes" ||
1451 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1452 FName == "OSAtomicEnqueue") {
1453 return false;
1454 }
1455
Jordan Rose85d7e012012-07-02 19:27:51 +00001456 // Handle cases where we know a buffer's /address/ can escape.
1457 // Note that the above checks handle some special cases where we know that
1458 // even though the address escapes, it's still our responsibility to free the
1459 // buffer.
1460 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001461 return false;
1462
1463 // Otherwise, assume that the function does not free memory.
1464 // Most system calls do not free the memory.
1465 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001466}
1467
Anna Zaks4fb54872012-02-11 21:02:35 +00001468// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p
1469// escapes, when we are tracking p), do not track the symbol as we cannot reason
1470// about it anymore.
1471ProgramStateRef
Anna Zaks66c40402012-02-14 21:55:24 +00001472MallocChecker::checkRegionChanges(ProgramStateRef State,
Anna Zaks4fb54872012-02-11 21:02:35 +00001473 const StoreManager::InvalidatedSymbols *invalidated,
1474 ArrayRef<const MemRegion *> ExplicitRegions,
Anna Zaks66c40402012-02-14 21:55:24 +00001475 ArrayRef<const MemRegion *> Regions,
Jordan Rose740d4902012-07-02 19:27:35 +00001476 const CallEvent *Call) const {
Anna Zaks0d389b82012-02-23 01:05:27 +00001477 if (!invalidated || invalidated->empty())
Anna Zaks66c40402012-02-14 21:55:24 +00001478 return State;
Anna Zaks4fb54872012-02-11 21:02:35 +00001479 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
Anna Zaks66c40402012-02-14 21:55:24 +00001480
Anna Zaks66c40402012-02-14 21:55:24 +00001481 // If it's a call which might free or reallocate memory, we assume that all
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001482 // regions (explicit and implicit) escaped.
1483
1484 // Otherwise, whitelist explicit pointers; we still can track them.
1485 if (!Call || doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001486 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
1487 E = ExplicitRegions.end(); I != E; ++I) {
1488 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
1489 WhitelistedSymbols.insert(R->getSymbol());
1490 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001491 }
1492
1493 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
1494 E = invalidated->end(); I!=E; ++I) {
1495 SymbolRef sym = *I;
1496 if (WhitelistedSymbols.count(sym))
1497 continue;
Anna Zaks5b7aa342012-06-22 02:04:31 +00001498 // The symbol escaped. Note, we assume that if the symbol is released,
1499 // passing it out will result in a use after free. We also keep tracking
1500 // relinquished symbols.
1501 if (const RefState *RS = State->get<RegionState>(sym)) {
1502 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001503 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001504 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001505 }
Anna Zaks66c40402012-02-14 21:55:24 +00001506 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001507}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001508
Jordy Rose393f98b2012-03-18 07:43:35 +00001509static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1510 ProgramStateRef prevState) {
1511 ReallocMap currMap = currState->get<ReallocPairs>();
1512 ReallocMap prevMap = prevState->get<ReallocPairs>();
1513
1514 for (ReallocMap::iterator I = prevMap.begin(), E = prevMap.end();
1515 I != E; ++I) {
1516 SymbolRef sym = I.getKey();
1517 if (!currMap.lookup(sym))
1518 return sym;
1519 }
1520
1521 return NULL;
1522}
1523
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001524PathDiagnosticPiece *
1525MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1526 const ExplodedNode *PrevN,
1527 BugReporterContext &BRC,
1528 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001529 ProgramStateRef state = N->getState();
1530 ProgramStateRef statePrev = PrevN->getState();
1531
1532 const RefState *RS = state->get<RegionState>(Sym);
1533 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001534 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001535 return 0;
1536
Anna Zaksfe571602012-02-16 22:26:07 +00001537 const Stmt *S = 0;
1538 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001539 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001540
1541 // Retrieve the associated statement.
1542 ProgramPoint ProgLoc = N->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +00001543 if (StmtPoint *SP = dyn_cast<StmtPoint>(&ProgLoc))
1544 S = SP->getStmt();
1545 else if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&ProgLoc))
1546 S = Exit->getCalleeContext()->getCallSite();
Anna Zaksfe571602012-02-16 22:26:07 +00001547 // If an assumption was made on a branch, it should be caught
1548 // here by looking at the state transition.
Jordan Rose852aa0d2012-07-10 22:07:52 +00001549 else if (BlockEdge *Edge = dyn_cast<BlockEdge>(&ProgLoc)) {
1550 const CFGBlock *srcBlk = Edge->getSrc();
Anna Zaksfe571602012-02-16 22:26:07 +00001551 S = srcBlk->getTerminator();
1552 }
1553 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001554 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001555
Jordan Rose28038f32012-07-10 22:07:42 +00001556 // FIXME: We will eventually need to handle non-statement-based events
1557 // (__attribute__((cleanup))).
1558
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001559 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001560 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001561 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001562 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001563 StackHint = new StackHintGeneratorForSymbol(Sym,
1564 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001565 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001566 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001567 StackHint = new StackHintGeneratorForSymbol(Sym,
1568 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001569 } else if (isRelinquished(RS, RSPrev, S)) {
1570 Msg = "Memory ownership is transfered";
1571 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001572 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001573 Mode = ReallocationFailed;
1574 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001575 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001576 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001577
Jordy Roseb000fb52012-03-24 03:15:09 +00001578 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1579 // Is it possible to fail two reallocs WITHOUT testing in between?
1580 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1581 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001582 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001583 FailedReallocSymbol = sym;
1584 }
Anna Zaksfe571602012-02-16 22:26:07 +00001585 }
1586
1587 // We are in a special mode if a reallocation failed later in the path.
1588 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001589 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001590
Jordy Roseb000fb52012-03-24 03:15:09 +00001591 // Is this is the first appearance of the reallocated symbol?
1592 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001593 // We're at the reallocation point.
1594 Msg = "Attempt to reallocate memory";
1595 StackHint = new StackHintGeneratorForSymbol(Sym,
1596 "Returned reallocated memory");
1597 FailedReallocSymbol = NULL;
1598 Mode = Normal;
1599 }
Anna Zaksfe571602012-02-16 22:26:07 +00001600 }
1601
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001602 if (!Msg)
1603 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001604 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001605
1606 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001607 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001608 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001609 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001610}
1611
Anna Zaks93c5a242012-05-02 00:05:20 +00001612void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1613 const char *NL, const char *Sep) const {
1614
1615 RegionStateTy RS = State->get<RegionState>();
1616
1617 if (!RS.isEmpty())
1618 Out << "Has Malloc data" << NL;
1619}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001620
Anna Zaks231361a2012-02-08 23:16:52 +00001621#define REGISTER_CHECKER(name) \
1622void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001623 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001624 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001625}
Anna Zaks231361a2012-02-08 23:16:52 +00001626
1627REGISTER_CHECKER(MallocPessimistic)
1628REGISTER_CHECKER(MallocOptimistic)