blob: af902a009638bf22a97ada463d687b3ad7b0c0bc [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/AST/Attr.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000020#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000021#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rosef540c542012-07-26 21:39:41 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
25#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000027#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000028#include "llvm/ADT/STLExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000029#include "llvm/ADT/SmallString.h"
Jordan Rose615a0922012-09-22 01:24:42 +000030#include "llvm/ADT/StringExtras.h"
Anna Zaks60a1fa42012-02-22 03:14:20 +000031#include <climits>
32
Zhongxing Xu589c0f22009-11-12 08:38:56 +000033using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000034using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000035
36namespace {
37
Zhongxing Xu7fb14642009-12-11 00:55:44 +000038class RefState {
Anna Zaks050cdd72012-06-20 20:57:46 +000039 enum Kind { // Reference to allocated memory.
40 Allocated,
41 // Reference to released/freed memory.
42 Released,
Anna Zaks050cdd72012-06-20 20:57:46 +000043 // The responsibility for freeing resources has transfered from
44 // this reference. A relinquished symbol should not be freed.
Ted Kremenekdde201b2010-08-06 21:12:55 +000045 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000046 const Stmt *S;
47
Zhongxing Xu7fb14642009-12-11 00:55:44 +000048public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000049 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
50
Anna Zaks050cdd72012-06-20 20:57:46 +000051 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000052 bool isReleased() const { return K == Released; }
Anna Zaks050cdd72012-06-20 20:57:46 +000053 bool isRelinquished() const { return K == Relinquished; }
Anna Zaksca23eb22012-02-29 18:42:47 +000054
Anna Zaksc8bb3be2012-02-13 18:05:39 +000055 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000056
57 bool operator==(const RefState &X) const {
58 return K == X.K && S == X.S;
59 }
60
Anna Zaks050cdd72012-06-20 20:57:46 +000061 static RefState getAllocated(const Stmt *s) {
62 return RefState(Allocated, s);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000063 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000064 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000065 static RefState getRelinquished(const Stmt *s) {
66 return RefState(Relinquished, s);
67 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000068
69 void Profile(llvm::FoldingSetNodeID &ID) const {
70 ID.AddInteger(K);
71 ID.AddPointer(S);
72 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000073};
74
Anna Zaks9dc298b2012-09-12 22:57:34 +000075enum ReallocPairKind {
76 RPToBeFreedAfterFailure,
77 // The symbol has been freed when reallocation failed.
78 RPIsFreeOnFailure,
79 // The symbol does not need to be freed after reallocation fails.
80 RPDoNotTrackAfterFailure
81};
82
Anna Zaks55dd9562012-08-24 02:28:20 +000083/// \class ReallocPair
84/// \brief Stores information about the symbol being reallocated by a call to
85/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaks40add292012-02-15 00:11:25 +000086struct ReallocPair {
Anna Zaks55dd9562012-08-24 02:28:20 +000087 // \brief The symbol which realloc reallocated.
Anna Zaks40add292012-02-15 00:11:25 +000088 SymbolRef ReallocatedSym;
Anna Zaks9dc298b2012-09-12 22:57:34 +000089 ReallocPairKind Kind;
Anna Zaks55dd9562012-08-24 02:28:20 +000090
Anna Zaks9dc298b2012-09-12 22:57:34 +000091 ReallocPair(SymbolRef S, ReallocPairKind K) :
92 ReallocatedSym(S), Kind(K) {}
Anna Zaks40add292012-02-15 00:11:25 +000093 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks9dc298b2012-09-12 22:57:34 +000094 ID.AddInteger(Kind);
Anna Zaks40add292012-02-15 00:11:25 +000095 ID.AddPointer(ReallocatedSym);
96 }
97 bool operator==(const ReallocPair &X) const {
98 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks9dc298b2012-09-12 22:57:34 +000099 Kind == X.Kind;
Anna Zaks40add292012-02-15 00:11:25 +0000100 }
101};
102
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000103typedef std::pair<const Stmt*, const MemRegion*> LeakInfo;
104
Anna Zaksb319e022012-02-08 20:13:28 +0000105class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000106 check::PointerEscape,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000107 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +0000108 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +0000109 check::PostStmt<CallExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000110 check::PostStmt<BlockExpr>,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000111 check::PostObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000112 check::Location,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000113 eval::Assume>
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;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000137 void checkPostObjCMessage(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;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000140 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000141 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000142 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000143 void checkLocation(SVal l, bool isLoad, const Stmt *S,
144 CheckerContext &C) const;
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000145
146 ProgramStateRef checkPointerEscape(ProgramStateRef State,
147 const InvalidatedSymbols &Escaped,
148 const CallEvent *Call) const;
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000149
Anna Zaks93c5a242012-05-02 00:05:20 +0000150 void printState(raw_ostream &Out, ProgramStateRef State,
151 const char *NL, const char *Sep) const;
152
Zhongxing Xu7b760962009-11-13 07:25:27 +0000153private:
Anna Zaks66c40402012-02-14 21:55:24 +0000154 void initIdentifierInfo(ASTContext &C) const;
155
156 /// Check if this is one of the functions which can allocate/reallocate memory
157 /// pointed to by one of its arguments.
158 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000159 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
160 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000161
Anna Zaks87cb5be2012-02-22 19:24:52 +0000162 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
163 const CallExpr *CE,
164 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000165 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000166 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000167 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000168 return MallocMemAux(C, CE,
169 state->getSVal(SizeEx, C.getLocationContext()),
170 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000171 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000172
Ted Kremenek8bef8232012-01-26 21:29:00 +0000173 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000174 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000175 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000176
Anna Zaks87cb5be2012-02-22 19:24:52 +0000177 /// Update the RefState to reflect the new memory allocation.
178 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
179 const CallExpr *CE,
180 ProgramStateRef state);
181
182 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
183 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000184 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000185 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000186 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000187 bool &ReleasedAllocated,
188 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000189 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
190 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000191 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000192 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000193 bool &ReleasedAllocated,
194 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000195
Anna Zaks87cb5be2012-02-22 19:24:52 +0000196 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
197 bool FreesMemOnFailure) const;
198 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000199
Anna Zaks14345182012-05-18 01:16:10 +0000200 ///\brief Check if the memory associated with this symbol was released.
201 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
202
Anna Zaks91c2a112012-02-08 23:16:56 +0000203 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
204 const Stmt *S = 0) const;
205
Anna Zaks66c40402012-02-14 21:55:24 +0000206 /// Check if the function is not known to us. So, for example, we could
207 /// conservatively assume it can free/reallocate it's pointer arguments.
Jordan Rose740d4902012-07-02 19:27:35 +0000208 bool doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000209 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000210
Ted Kremenek9c378f72011-08-12 23:37:29 +0000211 static bool SummarizeValue(raw_ostream &os, SVal V);
212 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000213 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000214
Anna Zaksca8e36e2012-02-23 21:38:21 +0000215 /// Find the location of the allocation for Sym on the path leading to the
216 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000217 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
218 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000219
Anna Zaksda046772012-02-11 21:02:40 +0000220 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
221
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000222 /// The bug visitor which allows us to print extra diagnostics along the
223 /// BugReport path. For example, showing the allocation site of the leaked
224 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000225 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000226 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000227 enum NotificationMode {
228 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000229 ReallocationFailed
230 };
231
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000232 // The allocated region symbol tracked by the main analysis.
233 SymbolRef Sym;
234
Anna Zaks88feba02012-05-10 01:37:40 +0000235 // The mode we are in, i.e. what kind of diagnostics will be emitted.
236 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000237
Anna Zaks88feba02012-05-10 01:37:40 +0000238 // A symbol from when the primary region should have been reallocated.
239 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000240
Anna Zaks88feba02012-05-10 01:37:40 +0000241 bool IsLeak;
242
243 public:
244 MallocBugVisitor(SymbolRef S, bool isLeak = false)
245 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000246
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000247 virtual ~MallocBugVisitor() {}
248
249 void Profile(llvm::FoldingSetNodeID &ID) const {
250 static int X = 0;
251 ID.AddPointer(&X);
252 ID.AddPointer(Sym);
253 }
254
Anna Zaksfe571602012-02-16 22:26:07 +0000255 inline bool isAllocated(const RefState *S, const RefState *SPrev,
256 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000257 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000258 return (Stmt && isa<CallExpr>(Stmt) &&
259 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000260 }
261
Anna Zaksfe571602012-02-16 22:26:07 +0000262 inline bool isReleased(const RefState *S, const RefState *SPrev,
263 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000264 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000265 return (Stmt && isa<CallExpr>(Stmt) &&
266 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
267 }
268
Anna Zaks5b7aa342012-06-22 02:04:31 +0000269 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
270 const Stmt *Stmt) {
271 // Did not track -> relinquished. Other state (allocated) -> relinquished.
272 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
273 isa<ObjCPropertyRefExpr>(Stmt)) &&
274 (S && S->isRelinquished()) &&
275 (!SPrev || !SPrev->isRelinquished()));
276 }
277
Anna Zaksfe571602012-02-16 22:26:07 +0000278 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
279 const Stmt *Stmt) {
280 // If the expression is not a call, and the state change is
281 // released -> allocated, it must be the realloc return value
282 // check. If we have to handle more cases here, it might be cleaner just
283 // to track this extra bit in the state itself.
284 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
285 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000286 }
287
288 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
289 const ExplodedNode *PrevN,
290 BugReporterContext &BRC,
291 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000292
293 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
294 const ExplodedNode *EndPathNode,
295 BugReport &BR) {
296 if (!IsLeak)
297 return 0;
298
299 PathDiagnosticLocation L =
300 PathDiagnosticLocation::createEndOfPath(EndPathNode,
301 BRC.getSourceManager());
302 // Do not add the statement itself as a range in case of leak.
303 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
304 }
305
Anna Zaks56a938f2012-03-16 23:24:20 +0000306 private:
307 class StackHintGeneratorForReallocationFailed
308 : public StackHintGeneratorForSymbol {
309 public:
310 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
311 : StackHintGeneratorForSymbol(S, M) {}
312
313 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000314 // Printed parameters start at 1, not 0.
315 ++ArgIndex;
316
Anna Zaks56a938f2012-03-16 23:24:20 +0000317 SmallString<200> buf;
318 llvm::raw_svector_ostream os(buf);
319
Jordan Rose615a0922012-09-22 01:24:42 +0000320 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
321 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000322
323 return os.str();
324 }
325
326 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000327 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000328 }
329 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000330 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000331};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000332} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000333
Jordan Rose166d5022012-11-02 01:54:06 +0000334REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
335REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000336
Anna Zaks4141e4d2012-11-13 03:18:01 +0000337// A map from the freed symbol to the symbol representing the return value of
338// the free function.
339REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
340
Anna Zaks4fb54872012-02-11 21:02:35 +0000341namespace {
342class StopTrackingCallback : public SymbolVisitor {
343 ProgramStateRef state;
344public:
345 StopTrackingCallback(ProgramStateRef st) : state(st) {}
346 ProgramStateRef getState() const { return state; }
347
348 bool VisitSymbol(SymbolRef sym) {
349 state = state->remove<RegionState>(sym);
350 return true;
351 }
352};
353} // end anonymous namespace
354
Anna Zaks66c40402012-02-14 21:55:24 +0000355void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000356 if (II_malloc)
357 return;
358 II_malloc = &Ctx.Idents.get("malloc");
359 II_free = &Ctx.Idents.get("free");
360 II_realloc = &Ctx.Idents.get("realloc");
361 II_reallocf = &Ctx.Idents.get("reallocf");
362 II_calloc = &Ctx.Idents.get("calloc");
363 II_valloc = &Ctx.Idents.get("valloc");
364 II_strdup = &Ctx.Idents.get("strdup");
365 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000366}
367
Anna Zaks66c40402012-02-14 21:55:24 +0000368bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000369 if (isFreeFunction(FD, C))
370 return true;
371
372 if (isAllocationFunction(FD, C))
373 return true;
374
375 return false;
376}
377
378bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
379 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000380 if (!FD)
381 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000382
Jordan Rose5ef6e942012-07-10 23:13:01 +0000383 if (FD->getKind() == Decl::Function) {
384 IdentifierInfo *FunI = FD->getIdentifier();
385 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000386
Jordan Rose5ef6e942012-07-10 23:13:01 +0000387 if (FunI == II_malloc || FunI == II_realloc ||
388 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
389 FunI == II_strdup || FunI == II_strndup)
390 return true;
391 }
Anna Zaks66c40402012-02-14 21:55:24 +0000392
Anna Zaks14345182012-05-18 01:16:10 +0000393 if (Filter.CMallocOptimistic && FD->hasAttrs())
394 for (specific_attr_iterator<OwnershipAttr>
395 i = FD->specific_attr_begin<OwnershipAttr>(),
396 e = FD->specific_attr_end<OwnershipAttr>();
397 i != e; ++i)
398 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
399 return true;
400 return false;
401}
402
403bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
404 if (!FD)
405 return false;
406
Jordan Rose5ef6e942012-07-10 23:13:01 +0000407 if (FD->getKind() == Decl::Function) {
408 IdentifierInfo *FunI = FD->getIdentifier();
409 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000410
Jordan Rose5ef6e942012-07-10 23:13:01 +0000411 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
412 return true;
413 }
Anna Zaks66c40402012-02-14 21:55:24 +0000414
Anna Zaks14345182012-05-18 01:16:10 +0000415 if (Filter.CMallocOptimistic && FD->hasAttrs())
416 for (specific_attr_iterator<OwnershipAttr>
417 i = FD->specific_attr_begin<OwnershipAttr>(),
418 e = FD->specific_attr_end<OwnershipAttr>();
419 i != e; ++i)
420 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
421 (*i)->getOwnKind() == OwnershipAttr::Holds)
422 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000423 return false;
424}
425
Anna Zaksb319e022012-02-08 20:13:28 +0000426void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000427 if (C.wasInlined)
428 return;
429
Anna Zaksb319e022012-02-08 20:13:28 +0000430 const FunctionDecl *FD = C.getCalleeDecl(CE);
431 if (!FD)
432 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000433
Anna Zaks87cb5be2012-02-22 19:24:52 +0000434 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000435 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000436
437 if (FD->getKind() == Decl::Function) {
438 initIdentifierInfo(C.getASTContext());
439 IdentifierInfo *FunI = FD->getIdentifier();
440
441 if (FunI == II_malloc || FunI == II_valloc) {
442 if (CE->getNumArgs() < 1)
443 return;
444 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
445 } else if (FunI == II_realloc) {
446 State = ReallocMem(C, CE, false);
447 } else if (FunI == II_reallocf) {
448 State = ReallocMem(C, CE, true);
449 } else if (FunI == II_calloc) {
450 State = CallocMem(C, CE);
451 } else if (FunI == II_free) {
Anna Zaks55dd9562012-08-24 02:28:20 +0000452 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose5ef6e942012-07-10 23:13:01 +0000453 } else if (FunI == II_strdup) {
454 State = MallocUpdateRefState(C, CE, State);
455 } else if (FunI == II_strndup) {
456 State = MallocUpdateRefState(C, CE, State);
457 }
458 }
459
460 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000461 // Check all the attributes, if there are any.
462 // There can be multiple of these attributes.
463 if (FD->hasAttrs())
464 for (specific_attr_iterator<OwnershipAttr>
465 i = FD->specific_attr_begin<OwnershipAttr>(),
466 e = FD->specific_attr_end<OwnershipAttr>();
467 i != e; ++i) {
468 switch ((*i)->getOwnKind()) {
469 case OwnershipAttr::Returns:
470 State = MallocMemReturnsAttr(C, CE, *i);
471 break;
472 case OwnershipAttr::Takes:
473 case OwnershipAttr::Holds:
474 State = FreeMemAttr(C, CE, *i);
475 break;
476 }
477 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000478 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000479 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000480}
481
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000482static bool isFreeWhenDoneSetToZero(const ObjCMethodCall &Call) {
483 Selector S = Call.getSelector();
Anna Zaks3e4f65d2012-06-22 22:08:09 +0000484 for (unsigned i = 1; i < S.getNumArgs(); ++i)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000485 if (S.getNameForSlot(i).equals("freeWhenDone"))
486 if (Call.getArgSVal(i).isConstant(0))
487 return true;
488
489 return false;
490}
491
Anna Zaks4141e4d2012-11-13 03:18:01 +0000492void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
493 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000494 if (C.wasInlined)
495 return;
496
Anna Zaks5b7aa342012-06-22 02:04:31 +0000497 // If the first selector is dataWithBytesNoCopy, assume that the memory will
498 // be released with 'free' by the new object.
499 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
500 // Unless 'freeWhenDone' param set to 0.
501 // TODO: Check that the memory was allocated with malloc.
Anna Zaks55dd9562012-08-24 02:28:20 +0000502 bool ReleasedAllocatedMemory = false;
Jordan Rosede507ea2012-07-02 19:28:04 +0000503 Selector S = Call.getSelector();
Anna Zaks7186dc62012-06-22 22:42:30 +0000504 if ((S.getNameForSlot(0) == "dataWithBytesNoCopy" ||
505 S.getNameForSlot(0) == "initWithBytesNoCopy" ||
506 S.getNameForSlot(0) == "initWithCharactersNoCopy") &&
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000507 !isFreeWhenDoneSetToZero(Call)){
Anna Zaks5b7aa342012-06-22 02:04:31 +0000508 unsigned int argIdx = 0;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000509 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(argIdx),
510 Call.getOriginExpr(), C.getState(), true,
511 ReleasedAllocatedMemory,
512 /* RetNullOnFailure*/ true);
513
514 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000515 }
516}
517
Anna Zaks87cb5be2012-02-22 19:24:52 +0000518ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
519 const CallExpr *CE,
520 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000521 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000522 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000523
Sean Huntcf807c42010-08-18 23:23:40 +0000524 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000525 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000526 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000527 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000528 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000529}
530
Anna Zaksb319e022012-02-08 20:13:28 +0000531ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000532 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000533 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000534 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000535
536 // Bind the return value to the symbolic value from the heap region.
537 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
538 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000539 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000540 SValBuilder &svalBuilder = C.getSValBuilder();
541 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
542 DefinedSVal RetVal =
543 cast<DefinedSVal>(svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count));
544 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000545
Anna Zaksb16ce452012-02-15 00:11:22 +0000546 // We expect the malloc functions to return a pointer.
Anna Zakse17fdb22012-06-07 03:57:32 +0000547 if (!isa<Loc>(RetVal))
Anna Zaksb16ce452012-02-15 00:11:22 +0000548 return 0;
549
Jordy Rose32f26562010-07-04 00:00:41 +0000550 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000551 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000552
Jordy Rose32f26562010-07-04 00:00:41 +0000553 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000554 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000555 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000556 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000557 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000558 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000559 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000560 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
561 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
562 DefinedOrUnknownSVal extentMatchesSize =
563 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000564
Anna Zaks60a1fa42012-02-22 03:14:20 +0000565 state = state->assume(extentMatchesSize, true);
566 assert(state);
567 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000568
Anna Zaks87cb5be2012-02-22 19:24:52 +0000569 return MallocUpdateRefState(C, CE, state);
570}
571
572ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
573 const CallExpr *CE,
574 ProgramStateRef state) {
575 // Get the return value.
576 SVal retVal = state->getSVal(CE, C.getLocationContext());
577
578 // We expect the malloc functions to return a pointer.
579 if (!isa<Loc>(retVal))
580 return 0;
581
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000582 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000583 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000584
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000585 // Set the symbol's state to Allocated.
Anna Zaks050cdd72012-06-20 20:57:46 +0000586 return state->set<RegionState>(Sym, RefState::getAllocated(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000587
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000588}
589
Anna Zaks87cb5be2012-02-22 19:24:52 +0000590ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
591 const CallExpr *CE,
592 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000593 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000594 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000595
Anna Zaksb3d72752012-03-01 22:06:06 +0000596 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000597 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000598
Sean Huntcf807c42010-08-18 23:23:40 +0000599 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
600 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000601 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000602 Att->getOwnKind() == OwnershipAttr::Holds,
603 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000604 if (StateI)
605 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000606 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000607 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000608}
609
Ted Kremenek8bef8232012-01-26 21:29:00 +0000610ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000611 const CallExpr *CE,
612 ProgramStateRef state,
613 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000614 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000615 bool &ReleasedAllocated,
616 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000617 if (CE->getNumArgs() < (Num + 1))
618 return 0;
619
Anna Zaks4141e4d2012-11-13 03:18:01 +0000620 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
621 ReleasedAllocated, ReturnsNullOnFailure);
622}
623
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000624/// Checks if the previous call to free on the given symbol failed - if free
625/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000626static bool didPreviousFreeFail(ProgramStateRef State,
627 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000628 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000629 if (Ret) {
630 assert(*Ret && "We should not store the null return symbol");
631 ConstraintManager &CMgr = State->getConstraintManager();
632 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000633 RetStatusSymbol = *Ret;
634 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000635 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000636 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000637}
638
639ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
640 const Expr *ArgExpr,
641 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000642 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000643 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000644 bool &ReleasedAllocated,
645 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000646
Anna Zaks4141e4d2012-11-13 03:18:01 +0000647 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000648 if (!isa<DefinedOrUnknownSVal>(ArgVal))
649 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000650 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
651
652 // Check for null dereferences.
653 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000654 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000655
Anna Zaksb276bd92012-02-14 00:26:13 +0000656 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000657 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000658 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000659 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000660 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000661
Jordy Rose43859f62010-06-07 19:32:37 +0000662 // Unknown values could easily be okay
663 // Undefined values are handled elsewhere
664 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000665 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000666
Jordy Rose43859f62010-06-07 19:32:37 +0000667 const MemRegion *R = ArgVal.getAsRegion();
668
669 // Nonlocs can't be freed, of course.
670 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
671 if (!R) {
672 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000673 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000674 }
675
676 R = R->StripCasts();
677
678 // Blocks might show up as heap data, but should not be free()d
679 if (isa<BlockDataRegion>(R)) {
680 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000681 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000682 }
683
684 const MemSpaceRegion *MS = R->getMemorySpace();
685
686 // Parameters, locals, statics, and globals shouldn't be freed.
687 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
688 // FIXME: at the time this code was written, malloc() regions were
689 // represented by conjured symbols, which are all in UnknownSpaceRegion.
690 // This means that there isn't actually anything from HeapSpaceRegion
691 // that should be freed, even though we allow it here.
692 // Of course, free() can work on memory allocated outside the current
693 // function, so UnknownSpaceRegion is always a possibility.
694 // False negatives are better than false positives.
695
696 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000697 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000698 }
699
700 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
701 // Various cases could lead to non-symbol values here.
702 // For now, ignore them.
703 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000704 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000705
706 SymbolRef Sym = SR->getSymbol();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000707 const RefState *RS = State->get<RegionState>(Sym);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000708 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000709
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000710 // Check double free.
Anna Zaks4141e4d2012-11-13 03:18:01 +0000711 if (RS &&
712 (RS->isReleased() || RS->isRelinquished()) &&
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000713 !didPreviousFreeFail(State, Sym, PreviousRetStatusSymbol)) {
Anna Zaks4141e4d2012-11-13 03:18:01 +0000714
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000715 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000716 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000717 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000718 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000719 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000720 (RS->isReleased() ? "Attempt to free released memory" :
721 "Attempt to free non-owned memory"), N);
Anna Zaksfe571602012-02-16 22:26:07 +0000722 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000723 R->markInteresting(Sym);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000724 if (PreviousRetStatusSymbol)
725 R->markInteresting(PreviousRetStatusSymbol);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000726 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +0000727 C.emitReport(R);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000728 }
Anna Zaksb319e022012-02-08 20:13:28 +0000729 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000730 }
731
Anna Zaks55dd9562012-08-24 02:28:20 +0000732 ReleasedAllocated = (RS != 0);
733
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000734 // Clean out the info on previous call to free return info.
735 State = State->remove<FreeReturnValue>(Sym);
736
Anna Zaks4141e4d2012-11-13 03:18:01 +0000737 // Keep track of the return value. If it is NULL, we will know that free
738 // failed.
739 if (ReturnsNullOnFailure) {
740 SVal RetVal = C.getSVal(ParentExpr);
741 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
742 if (RetStatusSymbol) {
743 C.getSymbolManager().addSymbolDependency(Sym, RetStatusSymbol);
744 State = State->set<FreeReturnValue>(Sym, RetStatusSymbol);
745 }
746 }
747
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000748 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000749 if (Hold)
Anna Zaks4141e4d2012-11-13 03:18:01 +0000750 return State->set<RegionState>(Sym, RefState::getRelinquished(ParentExpr));
751 return State->set<RegionState>(Sym, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000752}
753
Ted Kremenek9c378f72011-08-12 23:37:29 +0000754bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000755 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
756 os << "an integer (" << IntVal->getValue() << ")";
757 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
758 os << "a constant address (" << ConstAddr->getValue() << ")";
759 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000760 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000761 else
762 return false;
763
764 return true;
765}
766
Ted Kremenek9c378f72011-08-12 23:37:29 +0000767bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000768 const MemRegion *MR) {
769 switch (MR->getKind()) {
770 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000771 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +0000772 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000773 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000774 else
775 os << "the address of a function";
776 return true;
777 }
778 case MemRegion::BlockTextRegionKind:
779 os << "block text";
780 return true;
781 case MemRegion::BlockDataRegionKind:
782 // FIXME: where the block came from?
783 os << "a block";
784 return true;
785 default: {
786 const MemSpaceRegion *MS = MR->getMemorySpace();
787
Anna Zakseb31a762012-01-04 23:54:01 +0000788 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000789 const VarRegion *VR = dyn_cast<VarRegion>(MR);
790 const VarDecl *VD;
791 if (VR)
792 VD = VR->getDecl();
793 else
794 VD = NULL;
795
796 if (VD)
797 os << "the address of the local variable '" << VD->getName() << "'";
798 else
799 os << "the address of a local stack variable";
800 return true;
801 }
Anna Zakseb31a762012-01-04 23:54:01 +0000802
803 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000804 const VarRegion *VR = dyn_cast<VarRegion>(MR);
805 const VarDecl *VD;
806 if (VR)
807 VD = VR->getDecl();
808 else
809 VD = NULL;
810
811 if (VD)
812 os << "the address of the parameter '" << VD->getName() << "'";
813 else
814 os << "the address of a parameter";
815 return true;
816 }
Anna Zakseb31a762012-01-04 23:54:01 +0000817
818 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000819 const VarRegion *VR = dyn_cast<VarRegion>(MR);
820 const VarDecl *VD;
821 if (VR)
822 VD = VR->getDecl();
823 else
824 VD = NULL;
825
826 if (VD) {
827 if (VD->isStaticLocal())
828 os << "the address of the static variable '" << VD->getName() << "'";
829 else
830 os << "the address of the global variable '" << VD->getName() << "'";
831 } else
832 os << "the address of a global variable";
833 return true;
834 }
Anna Zakseb31a762012-01-04 23:54:01 +0000835
836 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000837 }
838 }
839}
840
841void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000842 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000843 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000844 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000845 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000846
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000847 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000848 llvm::raw_svector_ostream os(buf);
849
850 const MemRegion *MR = ArgVal.getAsRegion();
851 if (MR) {
852 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
853 MR = ER->getSuperRegion();
854
855 // Special case for alloca()
856 if (isa<AllocaRegion>(MR))
857 os << "Argument to free() was allocated by alloca(), not malloc()";
858 else {
859 os << "Argument to free() is ";
860 if (SummarizeRegion(os, MR))
861 os << ", which is not memory allocated by malloc()";
862 else
863 os << "not memory allocated by malloc()";
864 }
865 } else {
866 os << "Argument to free() is ";
867 if (SummarizeValue(os, ArgVal))
868 os << ", which is not memory allocated by malloc()";
869 else
870 os << "not memory allocated by malloc()";
871 }
872
Anna Zakse172e8b2011-08-17 23:00:25 +0000873 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000874 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000875 R->addRange(range);
Jordan Rose785950e2012-11-02 01:53:40 +0000876 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +0000877 }
878}
879
Anna Zaks87cb5be2012-02-22 19:24:52 +0000880ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
881 const CallExpr *CE,
882 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000883 if (CE->getNumArgs() < 2)
884 return 0;
885
Ted Kremenek8bef8232012-01-26 21:29:00 +0000886 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000887 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000888 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000889 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
890 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000891 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000892 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000893
Ted Kremenek846eabd2010-12-01 21:28:31 +0000894 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000895
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000896 DefinedOrUnknownSVal PtrEQ =
897 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000898
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000899 // Get the size argument. If there is no size arg then give up.
900 const Expr *Arg1 = CE->getArg(1);
901 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000902 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000903
904 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000905 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
906 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000907 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000908 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000909
910 // Compare the size argument to 0.
911 DefinedOrUnknownSVal SizeZero =
912 svalBuilder.evalEQ(state, Arg1Val,
913 svalBuilder.makeIntValWithPtrWidth(0, false));
914
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000915 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
916 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
917 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
918 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
919 // We only assume exceptional states if they are definitely true; if the
920 // state is under-constrained, assume regular realloc behavior.
921 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
922 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
923
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000924 // If the ptr is NULL and the size is not 0, the call is equivalent to
925 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000926 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000927 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000928 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000929 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000930 }
931
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000932 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000933 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000934
Anna Zaks30838b92012-02-13 20:57:07 +0000935 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000936 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000937 SymbolRef FromPtr = arg0Val.getAsSymbol();
938 SVal RetVal = state->getSVal(CE, LCtx);
939 SymbolRef ToPtr = RetVal.getAsSymbol();
940 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000941 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000942
Anna Zaks55dd9562012-08-24 02:28:20 +0000943 bool ReleasedAllocated = false;
944
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000945 // If the size is 0, free the memory.
946 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +0000947 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
948 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000949 // The semantics of the return value are:
950 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +0000951 // to free() is returned. We just free the input pointer and do not add
952 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +0000953 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000954 }
955
956 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +0000957 if (ProgramStateRef stateFree =
958 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
959
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000960 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
961 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000962 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000963 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +0000964
Anna Zaks9dc298b2012-09-12 22:57:34 +0000965 ReallocPairKind Kind = RPToBeFreedAfterFailure;
966 if (FreesOnFail)
967 Kind = RPIsFreeOnFailure;
968 else if (!ReleasedAllocated)
969 Kind = RPDoNotTrackAfterFailure;
970
Anna Zaks55dd9562012-08-24 02:28:20 +0000971 // Record the info about the reallocated symbol so that we could properly
972 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +0000973 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +0000974 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +0000975 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +0000976 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000977 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000978 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000979 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000980}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000981
Anna Zaks87cb5be2012-02-22 19:24:52 +0000982ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +0000983 if (CE->getNumArgs() < 2)
984 return 0;
985
Ted Kremenek8bef8232012-01-26 21:29:00 +0000986 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +0000987 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000988 const LocationContext *LCtx = C.getLocationContext();
989 SVal count = state->getSVal(CE->getArg(0), LCtx);
990 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000991 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
992 svalBuilder.getContext().getSizeType());
993 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000994
Anna Zaks87cb5be2012-02-22 19:24:52 +0000995 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000996}
997
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000998LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +0000999MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1000 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001001 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001002 // Walk the ExplodedGraph backwards and find the first node that referred to
1003 // the tracked symbol.
1004 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001005 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001006
1007 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001008 ProgramStateRef State = N->getState();
1009 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001010 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001011
1012 // Find the most recent expression bound to the symbol in the current
1013 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001014 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001015 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1016 SVal Val = State->getSVal(MR);
1017 if (Val.getAsLocSymbol() == Sym)
1018 ReferenceRegion = MR;
1019 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001020 }
1021
Anna Zaks7752d292012-02-27 23:40:55 +00001022 // Allocation node, is the last node in the current context in which the
1023 // symbol was tracked.
1024 if (N->getLocationContext() == LeakContext)
1025 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001026 N = N->pred_empty() ? NULL : *(N->pred_begin());
1027 }
1028
1029 ProgramPoint P = AllocNode->getLocation();
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001030 const Stmt *AllocationStmt = 0;
Jordan Rose852aa0d2012-07-10 22:07:52 +00001031 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
1032 AllocationStmt = Exit->getCalleeContext()->getCallSite();
1033 else if (StmtPoint *SP = dyn_cast<StmtPoint>(&P))
1034 AllocationStmt = SP->getStmt();
Anna Zaks7752d292012-02-27 23:40:55 +00001035
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001036 return LeakInfo(AllocationStmt, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001037}
1038
Anna Zaksda046772012-02-11 21:02:40 +00001039void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1040 CheckerContext &C) const {
1041 assert(N);
1042 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001043 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001044 // Leaks should not be reported if they are post-dominated by a sink:
1045 // (1) Sinks are higher importance bugs.
1046 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1047 // with __noreturn functions such as assert() or exit(). We choose not
1048 // to report leaks on such paths.
1049 BT_Leak->setSuppressOnSink(true);
1050 }
1051
Anna Zaksca8e36e2012-02-23 21:38:21 +00001052 // Most bug reports are cached at the location where they occurred.
1053 // With leaks, we want to unique them by the location where they were
1054 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001055 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001056 const Stmt *AllocStmt = 0;
1057 const MemRegion *Region = 0;
1058 llvm::tie(AllocStmt, Region) = getAllocationSite(N, Sym, C);
1059 if (AllocStmt)
Anna Zaks7752d292012-02-27 23:40:55 +00001060 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
1061 C.getSourceManager(), N->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001062
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001063 SmallString<200> buf;
1064 llvm::raw_svector_ostream os(buf);
1065 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001066 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001067 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001068 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001069 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001070 }
1071
1072 BugReport *R = new BugReport(*BT_Leak, os.str(), N, LocUsedForUniqueing);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001073 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001074 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001075 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001076}
1077
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001078void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1079 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001080{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001081 if (!SymReaper.hasDeadSymbols())
1082 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001083
Ted Kremenek8bef8232012-01-26 21:29:00 +00001084 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001085 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001086 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001087
Anna Zaksf8c17b72012-02-09 06:48:19 +00001088 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001089 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1090 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001091 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001092 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001093 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001094 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001095
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001096 }
1097 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001098
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001099 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001100 ReallocPairsTy RP = state->get<ReallocPairs>();
1101 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001102 if (SymReaper.isDead(I->first) ||
1103 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001104 state = state->remove<ReallocPairs>(I->first);
1105 }
1106 }
1107
Anna Zaks4141e4d2012-11-13 03:18:01 +00001108 // Cleanup the FreeReturnValue Map.
1109 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1110 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1111 if (SymReaper.isDead(I->first) ||
1112 SymReaper.isDead(I->second)) {
1113 state = state->remove<FreeReturnValue>(I->first);
1114 }
1115 }
1116
Anna Zaksca8e36e2012-02-23 21:38:21 +00001117 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001118 ExplodedNode *N = C.getPredecessor();
1119 if (!Errors.empty()) {
1120 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1121 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001122 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001123 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001124 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001125 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001126 }
Anna Zaks54458702012-10-29 22:51:54 +00001127
Anna Zaksca8e36e2012-02-23 21:38:21 +00001128 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001129}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001130
Anna Zaks66c40402012-02-14 21:55:24 +00001131void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001132 // We will check for double free in the post visit.
1133 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001134 return;
1135
1136 // Check use after free, when a freed pointer is passed to a call.
1137 ProgramStateRef State = C.getState();
1138 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1139 E = CE->arg_end(); I != E; ++I) {
1140 const Expr *A = *I;
1141 if (A->getType().getTypePtr()->isAnyPointerType()) {
1142 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1143 if (!Sym)
1144 continue;
1145 if (checkUseAfterFree(Sym, C, A))
1146 return;
1147 }
1148 }
1149}
1150
Anna Zaks91c2a112012-02-08 23:16:56 +00001151void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1152 const Expr *E = S->getRetValue();
1153 if (!E)
1154 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001155
1156 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001157 ProgramStateRef State = C.getState();
1158 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001159 SymbolRef Sym = RetVal.getAsSymbol();
1160 if (!Sym)
1161 // If we are returning a field of the allocated struct or an array element,
1162 // the callee could still free the memory.
1163 // TODO: This logic should be a part of generic symbol escape callback.
1164 if (const MemRegion *MR = RetVal.getAsRegion())
1165 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1166 if (const SymbolicRegion *BMR =
1167 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1168 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001169
Anna Zaks0860cd02012-02-11 21:44:39 +00001170 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001171 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001172 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001173}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001174
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001175// TODO: Blocks should be either inlined or should call invalidate regions
1176// upon invocation. After that's in place, special casing here will not be
1177// needed.
1178void MallocChecker::checkPostStmt(const BlockExpr *BE,
1179 CheckerContext &C) const {
1180
1181 // Scan the BlockDecRefExprs for any object the retain count checker
1182 // may be tracking.
1183 if (!BE->getBlockDecl()->hasCaptures())
1184 return;
1185
1186 ProgramStateRef state = C.getState();
1187 const BlockDataRegion *R =
1188 cast<BlockDataRegion>(state->getSVal(BE,
1189 C.getLocationContext()).getAsRegion());
1190
1191 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1192 E = R->referenced_vars_end();
1193
1194 if (I == E)
1195 return;
1196
1197 SmallVector<const MemRegion*, 10> Regions;
1198 const LocationContext *LC = C.getLocationContext();
1199 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1200
1201 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001202 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001203 if (VR->getSuperRegion() == R) {
1204 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1205 }
1206 Regions.push_back(VR);
1207 }
1208
1209 state =
1210 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1211 Regions.data() + Regions.size()).getState();
1212 C.addTransition(state);
1213}
1214
Anna Zaks14345182012-05-18 01:16:10 +00001215bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001216 assert(Sym);
1217 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001218 return (RS && RS->isReleased());
1219}
1220
1221bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1222 const Stmt *S) const {
1223 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001224 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001225 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001226 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001227
Anna Zaksfebdc322012-02-16 22:26:12 +00001228 BugReport *R = new BugReport(*BT_UseFree,
1229 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001230 if (S)
1231 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001232 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001233 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +00001234 C.emitReport(R);
Anna Zaks91c2a112012-02-08 23:16:56 +00001235 return true;
1236 }
1237 }
1238 return false;
1239}
1240
Zhongxing Xuc8023782010-03-10 04:58:55 +00001241// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001242void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1243 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001244 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001245 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001246 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001247}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001248
Anna Zaks4fb54872012-02-11 21:02:35 +00001249// If a symbolic region is assumed to NULL (or another constant), stop tracking
1250// it - assuming that allocation failed on this path.
1251ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1252 SVal Cond,
1253 bool Assumption) const {
1254 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001255 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001256 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001257 ConstraintManager &CMgr = state->getConstraintManager();
1258 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1259 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001260 state = state->remove<RegionState>(I.getKey());
1261 }
1262
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001263 // Realloc returns 0 when reallocation fails, which means that we should
1264 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001265 ReallocPairsTy RP = state->get<ReallocPairs>();
1266 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001267 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001268 ConstraintManager &CMgr = state->getConstraintManager();
1269 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001270 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001271 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001272
Anna Zaks9dc298b2012-09-12 22:57:34 +00001273 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1274 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1275 if (RS->isReleased()) {
1276 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001277 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001278 RefState::getAllocated(RS->getStmt()));
1279 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1280 state = state->remove<RegionState>(ReallocSym);
1281 else
1282 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001283 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001284 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001285 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001286 }
1287
Anna Zaks4fb54872012-02-11 21:02:35 +00001288 return state;
1289}
1290
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001291// Check if the function is known to us. So, for example, we could
Jordan Rose740d4902012-07-02 19:27:35 +00001292// conservatively assume it can free/reallocate its pointer arguments.
Anna Zaks66c40402012-02-14 21:55:24 +00001293// (We assume that the pointers cannot escape through calls to system
1294// functions not handled by this checker.)
Jordan Rose740d4902012-07-02 19:27:35 +00001295bool MallocChecker::doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001296 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001297 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001298
1299 // For now, assume that any C++ call can free memory.
1300 // TODO: If we want to be more optimistic here, we'll need to make sure that
1301 // regions escape to C++ containers. They seem to do that even now, but for
1302 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001303 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001304 return false;
1305
Jordan Rose740d4902012-07-02 19:27:35 +00001306 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001307 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001308 // If it's not a framework call, or if it takes a callback, assume it
1309 // can free memory.
1310 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001311 return false;
1312
Jordan Rose740d4902012-07-02 19:27:35 +00001313 Selector S = Msg->getSelector();
Anna Zaks52a04812012-06-20 23:35:57 +00001314
Jordan Rose740d4902012-07-02 19:27:35 +00001315 // Whitelist the ObjC methods which do free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001316 // - Anything containing 'freeWhenDone' param set to 1.
1317 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
Anna Zaks3e4f65d2012-06-22 22:08:09 +00001318 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001319 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1320 if (Call->getArgSVal(i).isConstant(1))
1321 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001322 else
1323 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001324 }
1325 }
1326
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001327 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001328 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001329 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
Jordan Rose740d4902012-07-02 19:27:35 +00001330 StringRef FirstSlot = S.getNameForSlot(0);
1331 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001332 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001333
Anna Zaks5f757682012-06-19 05:10:32 +00001334 // If the first selector starts with addPointer, insertPointer,
1335 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1336 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001337 // that the pointers get freed by following the container itself.
1338 if (FirstSlot.startswith("addPointer") ||
1339 FirstSlot.startswith("insertPointer") ||
1340 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001341 return false;
1342 }
1343
Jordan Rose740d4902012-07-02 19:27:35 +00001344 // Otherwise, assume that the method does not free memory.
1345 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001346 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001347 }
1348
Jordan Rose740d4902012-07-02 19:27:35 +00001349 // At this point the only thing left to handle is straight function calls.
1350 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1351 if (!FD)
1352 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001353
Jordan Rose740d4902012-07-02 19:27:35 +00001354 ASTContext &ASTC = State->getStateManager().getContext();
1355
1356 // If it's one of the allocation functions we can reason about, we model
1357 // its behavior explicitly.
1358 if (isMemFunction(FD, ASTC))
1359 return true;
1360
1361 // If it's not a system call, assume it frees memory.
1362 if (!Call->isInSystemHeader())
1363 return false;
1364
1365 // White list the system functions whose arguments escape.
1366 const IdentifierInfo *II = FD->getIdentifier();
1367 if (!II)
1368 return false;
1369 StringRef FName = II->getName();
1370
Jordan Rose740d4902012-07-02 19:27:35 +00001371 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001372 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001373 if (FName.endswith("NoCopy")) {
1374 // Look for the deallocator argument. We know that the memory ownership
1375 // is not transferred only if the deallocator argument is
1376 // 'kCFAllocatorNull'.
1377 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1378 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1379 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1380 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1381 if (DeallocatorName == "kCFAllocatorNull")
1382 return true;
1383 }
1384 }
1385 return false;
1386 }
1387
Jordan Rose740d4902012-07-02 19:27:35 +00001388 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001389 // 'closefn' is specified (and if that function does free memory),
1390 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001391 // Currently, we do not inspect the 'closefn' function (PR12101).
1392 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001393 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1394 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001395
1396 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1397 // these leaks might be intentional when setting the buffer for stdio.
1398 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1399 if (FName == "setbuf" || FName =="setbuffer" ||
1400 FName == "setlinebuf" || FName == "setvbuf") {
1401 if (Call->getNumArgs() >= 1) {
1402 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1403 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1404 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1405 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1406 return false;
1407 }
1408 }
1409
1410 // A bunch of other functions which either take ownership of a pointer or
1411 // wrap the result up in a struct or object, meaning it can be freed later.
1412 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1413 // but the Malloc checker cannot differentiate between them. The right way
1414 // of doing this would be to implement a pointer escapes callback.
1415 if (FName == "CGBitmapContextCreate" ||
1416 FName == "CGBitmapContextCreateWithData" ||
1417 FName == "CVPixelBufferCreateWithBytes" ||
1418 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1419 FName == "OSAtomicEnqueue") {
1420 return false;
1421 }
1422
Jordan Rose85d7e012012-07-02 19:27:51 +00001423 // Handle cases where we know a buffer's /address/ can escape.
1424 // Note that the above checks handle some special cases where we know that
1425 // even though the address escapes, it's still our responsibility to free the
1426 // buffer.
1427 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001428 return false;
1429
1430 // Otherwise, assume that the function does not free memory.
1431 // Most system calls do not free the memory.
1432 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001433}
1434
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001435ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1436 const InvalidatedSymbols &Escaped,
1437 const CallEvent *Call) const {
1438 // If we know that the call does not free memory, keep tracking the top
1439 // level arguments.
1440 if (Call && doesNotFreeMemory(Call, State))
Anna Zaks66c40402012-02-14 21:55:24 +00001441 return State;
Anna Zaks66c40402012-02-14 21:55:24 +00001442
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001443 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
1444 E = Escaped.end();
1445 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001446 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001447
Anna Zaks5b7aa342012-06-22 02:04:31 +00001448 if (const RefState *RS = State->get<RegionState>(sym)) {
1449 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001450 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001451 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001452 }
Anna Zaks66c40402012-02-14 21:55:24 +00001453 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001454}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001455
Jordy Rose393f98b2012-03-18 07:43:35 +00001456static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1457 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001458 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1459 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001460
Jordan Rose166d5022012-11-02 01:54:06 +00001461 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001462 I != E; ++I) {
1463 SymbolRef sym = I.getKey();
1464 if (!currMap.lookup(sym))
1465 return sym;
1466 }
1467
1468 return NULL;
1469}
1470
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001471PathDiagnosticPiece *
1472MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1473 const ExplodedNode *PrevN,
1474 BugReporterContext &BRC,
1475 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001476 ProgramStateRef state = N->getState();
1477 ProgramStateRef statePrev = PrevN->getState();
1478
1479 const RefState *RS = state->get<RegionState>(Sym);
1480 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001481 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001482 return 0;
1483
Anna Zaksfe571602012-02-16 22:26:07 +00001484 const Stmt *S = 0;
1485 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001486 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001487
1488 // Retrieve the associated statement.
1489 ProgramPoint ProgLoc = N->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +00001490 if (StmtPoint *SP = dyn_cast<StmtPoint>(&ProgLoc))
1491 S = SP->getStmt();
1492 else if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&ProgLoc))
1493 S = Exit->getCalleeContext()->getCallSite();
Anna Zaksfe571602012-02-16 22:26:07 +00001494 // If an assumption was made on a branch, it should be caught
1495 // here by looking at the state transition.
Jordan Rose852aa0d2012-07-10 22:07:52 +00001496 else if (BlockEdge *Edge = dyn_cast<BlockEdge>(&ProgLoc)) {
1497 const CFGBlock *srcBlk = Edge->getSrc();
Anna Zaksfe571602012-02-16 22:26:07 +00001498 S = srcBlk->getTerminator();
1499 }
1500 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001501 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001502
Jordan Rose28038f32012-07-10 22:07:42 +00001503 // FIXME: We will eventually need to handle non-statement-based events
1504 // (__attribute__((cleanup))).
1505
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001506 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001507 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001508 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001509 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001510 StackHint = new StackHintGeneratorForSymbol(Sym,
1511 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001512 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001513 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001514 StackHint = new StackHintGeneratorForSymbol(Sym,
1515 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001516 } else if (isRelinquished(RS, RSPrev, S)) {
1517 Msg = "Memory ownership is transfered";
1518 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001519 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001520 Mode = ReallocationFailed;
1521 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001522 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001523 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001524
Jordy Roseb000fb52012-03-24 03:15:09 +00001525 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1526 // Is it possible to fail two reallocs WITHOUT testing in between?
1527 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1528 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001529 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001530 FailedReallocSymbol = sym;
1531 }
Anna Zaksfe571602012-02-16 22:26:07 +00001532 }
1533
1534 // We are in a special mode if a reallocation failed later in the path.
1535 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001536 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001537
Jordy Roseb000fb52012-03-24 03:15:09 +00001538 // Is this is the first appearance of the reallocated symbol?
1539 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001540 // We're at the reallocation point.
1541 Msg = "Attempt to reallocate memory";
1542 StackHint = new StackHintGeneratorForSymbol(Sym,
1543 "Returned reallocated memory");
1544 FailedReallocSymbol = NULL;
1545 Mode = Normal;
1546 }
Anna Zaksfe571602012-02-16 22:26:07 +00001547 }
1548
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001549 if (!Msg)
1550 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001551 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001552
1553 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001554 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001555 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001556 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001557}
1558
Anna Zaks93c5a242012-05-02 00:05:20 +00001559void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1560 const char *NL, const char *Sep) const {
1561
1562 RegionStateTy RS = State->get<RegionState>();
1563
1564 if (!RS.isEmpty())
1565 Out << "Has Malloc data" << NL;
1566}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001567
Anna Zaks231361a2012-02-08 23:16:52 +00001568#define REGISTER_CHECKER(name) \
1569void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001570 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001571 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001572}
Anna Zaks231361a2012-02-08 23:16:52 +00001573
1574REGISTER_CHECKER(MallocPessimistic)
1575REGISTER_CHECKER(MallocOptimistic)