blob: 70f426df204dbc4c1b2a4526564b46107d06ba33 [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 }
Ted Kremenekc37fad62013-01-03 01:30:12 +000073
74 void dump(llvm::raw_ostream &OS) const {
75 static const char *Table[] = {
76 "Allocated",
77 "Released",
78 "Relinquished"
79 };
80 OS << Table[(unsigned) K];
81 }
82
83 LLVM_ATTRIBUTE_USED void dump() const {
84 dump(llvm::errs());
85 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000086};
87
Anna Zaks9dc298b2012-09-12 22:57:34 +000088enum ReallocPairKind {
89 RPToBeFreedAfterFailure,
90 // The symbol has been freed when reallocation failed.
91 RPIsFreeOnFailure,
92 // The symbol does not need to be freed after reallocation fails.
93 RPDoNotTrackAfterFailure
94};
95
Anna Zaks55dd9562012-08-24 02:28:20 +000096/// \class ReallocPair
97/// \brief Stores information about the symbol being reallocated by a call to
98/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaks40add292012-02-15 00:11:25 +000099struct ReallocPair {
Anna Zaks55dd9562012-08-24 02:28:20 +0000100 // \brief The symbol which realloc reallocated.
Anna Zaks40add292012-02-15 00:11:25 +0000101 SymbolRef ReallocatedSym;
Anna Zaks9dc298b2012-09-12 22:57:34 +0000102 ReallocPairKind Kind;
Anna Zaks55dd9562012-08-24 02:28:20 +0000103
Anna Zaks9dc298b2012-09-12 22:57:34 +0000104 ReallocPair(SymbolRef S, ReallocPairKind K) :
105 ReallocatedSym(S), Kind(K) {}
Anna Zaks40add292012-02-15 00:11:25 +0000106 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks9dc298b2012-09-12 22:57:34 +0000107 ID.AddInteger(Kind);
Anna Zaks40add292012-02-15 00:11:25 +0000108 ID.AddPointer(ReallocatedSym);
109 }
110 bool operator==(const ReallocPair &X) const {
111 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks9dc298b2012-09-12 22:57:34 +0000112 Kind == X.Kind;
Anna Zaks40add292012-02-15 00:11:25 +0000113 }
114};
115
Anna Zaks97bfb552013-01-08 00:25:29 +0000116typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000117
Anna Zaksb319e022012-02-08 20:13:28 +0000118class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000119 check::PointerEscape,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000120 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +0000121 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +0000122 check::PostStmt<CallExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000123 check::PostStmt<BlockExpr>,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000124 check::PostObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000125 check::Location,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000126 eval::Assume>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000127{
Anna Zaksfebdc322012-02-16 22:26:12 +0000128 mutable OwningPtr<BugType> BT_DoubleFree;
129 mutable OwningPtr<BugType> BT_Leak;
130 mutable OwningPtr<BugType> BT_UseFree;
131 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000132 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000133 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
134
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000135public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000136 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000137 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000138
139 /// In pessimistic mode, the checker assumes that it does not know which
140 /// functions might free the memory.
141 struct ChecksFilter {
142 DefaultBool CMallocPessimistic;
143 DefaultBool CMallocOptimistic;
144 };
145
146 ChecksFilter Filter;
147
Anna Zaks66c40402012-02-14 21:55:24 +0000148 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000149 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000150 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000151 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000152 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000153 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000154 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000155 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000156 void checkLocation(SVal l, bool isLoad, const Stmt *S,
157 CheckerContext &C) const;
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000158
159 ProgramStateRef checkPointerEscape(ProgramStateRef State,
160 const InvalidatedSymbols &Escaped,
161 const CallEvent *Call) const;
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000162
Anna Zaks93c5a242012-05-02 00:05:20 +0000163 void printState(raw_ostream &Out, ProgramStateRef State,
164 const char *NL, const char *Sep) const;
165
Zhongxing Xu7b760962009-11-13 07:25:27 +0000166private:
Anna Zaks66c40402012-02-14 21:55:24 +0000167 void initIdentifierInfo(ASTContext &C) const;
168
169 /// Check if this is one of the functions which can allocate/reallocate memory
170 /// pointed to by one of its arguments.
171 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000172 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
173 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000174
Anna Zaks87cb5be2012-02-22 19:24:52 +0000175 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
176 const CallExpr *CE,
177 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000178 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000179 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000180 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000181 return MallocMemAux(C, CE,
182 state->getSVal(SizeEx, C.getLocationContext()),
183 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000184 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000185
Ted Kremenek8bef8232012-01-26 21:29:00 +0000186 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000187 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000188 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000189
Anna Zaks87cb5be2012-02-22 19:24:52 +0000190 /// Update the RefState to reflect the new memory allocation.
191 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
192 const CallExpr *CE,
193 ProgramStateRef state);
194
195 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
196 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000197 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000198 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000199 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000200 bool &ReleasedAllocated,
201 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000202 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
203 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000204 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000205 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000206 bool &ReleasedAllocated,
207 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000208
Anna Zaks87cb5be2012-02-22 19:24:52 +0000209 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
210 bool FreesMemOnFailure) const;
211 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000212
Anna Zaks14345182012-05-18 01:16:10 +0000213 ///\brief Check if the memory associated with this symbol was released.
214 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
215
Anna Zaks91c2a112012-02-08 23:16:56 +0000216 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
217 const Stmt *S = 0) const;
218
Anna Zaks66c40402012-02-14 21:55:24 +0000219 /// Check if the function is not known to us. So, for example, we could
220 /// conservatively assume it can free/reallocate it's pointer arguments.
Jordan Rose740d4902012-07-02 19:27:35 +0000221 bool doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000222 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000223
Ted Kremenek9c378f72011-08-12 23:37:29 +0000224 static bool SummarizeValue(raw_ostream &os, SVal V);
225 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000226 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000227
Anna Zaksca8e36e2012-02-23 21:38:21 +0000228 /// Find the location of the allocation for Sym on the path leading to the
229 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000230 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
231 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000232
Anna Zaksda046772012-02-11 21:02:40 +0000233 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
234
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000235 /// The bug visitor which allows us to print extra diagnostics along the
236 /// BugReport path. For example, showing the allocation site of the leaked
237 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000238 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000239 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000240 enum NotificationMode {
241 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000242 ReallocationFailed
243 };
244
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000245 // The allocated region symbol tracked by the main analysis.
246 SymbolRef Sym;
247
Anna Zaks88feba02012-05-10 01:37:40 +0000248 // The mode we are in, i.e. what kind of diagnostics will be emitted.
249 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000250
Anna Zaks88feba02012-05-10 01:37:40 +0000251 // A symbol from when the primary region should have been reallocated.
252 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000253
Anna Zaks88feba02012-05-10 01:37:40 +0000254 bool IsLeak;
255
256 public:
257 MallocBugVisitor(SymbolRef S, bool isLeak = false)
258 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000259
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000260 virtual ~MallocBugVisitor() {}
261
262 void Profile(llvm::FoldingSetNodeID &ID) const {
263 static int X = 0;
264 ID.AddPointer(&X);
265 ID.AddPointer(Sym);
266 }
267
Anna Zaksfe571602012-02-16 22:26:07 +0000268 inline bool isAllocated(const RefState *S, const RefState *SPrev,
269 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000270 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000271 return (Stmt && isa<CallExpr>(Stmt) &&
272 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000273 }
274
Anna Zaksfe571602012-02-16 22:26:07 +0000275 inline bool isReleased(const RefState *S, const RefState *SPrev,
276 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000277 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000278 return (Stmt && isa<CallExpr>(Stmt) &&
279 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
280 }
281
Anna Zaks5b7aa342012-06-22 02:04:31 +0000282 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
283 const Stmt *Stmt) {
284 // Did not track -> relinquished. Other state (allocated) -> relinquished.
285 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
286 isa<ObjCPropertyRefExpr>(Stmt)) &&
287 (S && S->isRelinquished()) &&
288 (!SPrev || !SPrev->isRelinquished()));
289 }
290
Anna Zaksfe571602012-02-16 22:26:07 +0000291 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
292 const Stmt *Stmt) {
293 // If the expression is not a call, and the state change is
294 // released -> allocated, it must be the realloc return value
295 // check. If we have to handle more cases here, it might be cleaner just
296 // to track this extra bit in the state itself.
297 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
298 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000299 }
300
301 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
302 const ExplodedNode *PrevN,
303 BugReporterContext &BRC,
304 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000305
306 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
307 const ExplodedNode *EndPathNode,
308 BugReport &BR) {
309 if (!IsLeak)
310 return 0;
311
312 PathDiagnosticLocation L =
313 PathDiagnosticLocation::createEndOfPath(EndPathNode,
314 BRC.getSourceManager());
315 // Do not add the statement itself as a range in case of leak.
316 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
317 }
318
Anna Zaks56a938f2012-03-16 23:24:20 +0000319 private:
320 class StackHintGeneratorForReallocationFailed
321 : public StackHintGeneratorForSymbol {
322 public:
323 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
324 : StackHintGeneratorForSymbol(S, M) {}
325
326 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000327 // Printed parameters start at 1, not 0.
328 ++ArgIndex;
329
Anna Zaks56a938f2012-03-16 23:24:20 +0000330 SmallString<200> buf;
331 llvm::raw_svector_ostream os(buf);
332
Jordan Rose615a0922012-09-22 01:24:42 +0000333 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
334 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000335
336 return os.str();
337 }
338
339 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000340 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000341 }
342 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000343 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000344};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000345} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000346
Jordan Rose166d5022012-11-02 01:54:06 +0000347REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
348REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000349
Anna Zaks4141e4d2012-11-13 03:18:01 +0000350// A map from the freed symbol to the symbol representing the return value of
351// the free function.
352REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
353
Anna Zaks4fb54872012-02-11 21:02:35 +0000354namespace {
355class StopTrackingCallback : public SymbolVisitor {
356 ProgramStateRef state;
357public:
358 StopTrackingCallback(ProgramStateRef st) : state(st) {}
359 ProgramStateRef getState() const { return state; }
360
361 bool VisitSymbol(SymbolRef sym) {
362 state = state->remove<RegionState>(sym);
363 return true;
364 }
365};
366} // end anonymous namespace
367
Anna Zaks66c40402012-02-14 21:55:24 +0000368void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000369 if (II_malloc)
370 return;
371 II_malloc = &Ctx.Idents.get("malloc");
372 II_free = &Ctx.Idents.get("free");
373 II_realloc = &Ctx.Idents.get("realloc");
374 II_reallocf = &Ctx.Idents.get("reallocf");
375 II_calloc = &Ctx.Idents.get("calloc");
376 II_valloc = &Ctx.Idents.get("valloc");
377 II_strdup = &Ctx.Idents.get("strdup");
378 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000379}
380
Anna Zaks66c40402012-02-14 21:55:24 +0000381bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000382 if (isFreeFunction(FD, C))
383 return true;
384
385 if (isAllocationFunction(FD, C))
386 return true;
387
388 return false;
389}
390
391bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
392 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000393 if (!FD)
394 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000395
Jordan Rose5ef6e942012-07-10 23:13:01 +0000396 if (FD->getKind() == Decl::Function) {
397 IdentifierInfo *FunI = FD->getIdentifier();
398 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000399
Jordan Rose5ef6e942012-07-10 23:13:01 +0000400 if (FunI == II_malloc || FunI == II_realloc ||
401 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
402 FunI == II_strdup || FunI == II_strndup)
403 return true;
404 }
Anna Zaks66c40402012-02-14 21:55:24 +0000405
Anna Zaks14345182012-05-18 01:16:10 +0000406 if (Filter.CMallocOptimistic && FD->hasAttrs())
407 for (specific_attr_iterator<OwnershipAttr>
408 i = FD->specific_attr_begin<OwnershipAttr>(),
409 e = FD->specific_attr_end<OwnershipAttr>();
410 i != e; ++i)
411 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
412 return true;
413 return false;
414}
415
416bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
417 if (!FD)
418 return false;
419
Jordan Rose5ef6e942012-07-10 23:13:01 +0000420 if (FD->getKind() == Decl::Function) {
421 IdentifierInfo *FunI = FD->getIdentifier();
422 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000423
Jordan Rose5ef6e942012-07-10 23:13:01 +0000424 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
425 return true;
426 }
Anna Zaks66c40402012-02-14 21:55:24 +0000427
Anna Zaks14345182012-05-18 01:16:10 +0000428 if (Filter.CMallocOptimistic && FD->hasAttrs())
429 for (specific_attr_iterator<OwnershipAttr>
430 i = FD->specific_attr_begin<OwnershipAttr>(),
431 e = FD->specific_attr_end<OwnershipAttr>();
432 i != e; ++i)
433 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
434 (*i)->getOwnKind() == OwnershipAttr::Holds)
435 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000436 return false;
437}
438
Anna Zaksb319e022012-02-08 20:13:28 +0000439void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000440 if (C.wasInlined)
441 return;
442
Anna Zaksb319e022012-02-08 20:13:28 +0000443 const FunctionDecl *FD = C.getCalleeDecl(CE);
444 if (!FD)
445 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000446
Anna Zaks87cb5be2012-02-22 19:24:52 +0000447 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000448 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000449
450 if (FD->getKind() == Decl::Function) {
451 initIdentifierInfo(C.getASTContext());
452 IdentifierInfo *FunI = FD->getIdentifier();
453
454 if (FunI == II_malloc || FunI == II_valloc) {
455 if (CE->getNumArgs() < 1)
456 return;
457 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
458 } else if (FunI == II_realloc) {
459 State = ReallocMem(C, CE, false);
460 } else if (FunI == II_reallocf) {
461 State = ReallocMem(C, CE, true);
462 } else if (FunI == II_calloc) {
463 State = CallocMem(C, CE);
464 } else if (FunI == II_free) {
Anna Zaks55dd9562012-08-24 02:28:20 +0000465 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose5ef6e942012-07-10 23:13:01 +0000466 } else if (FunI == II_strdup) {
467 State = MallocUpdateRefState(C, CE, State);
468 } else if (FunI == II_strndup) {
469 State = MallocUpdateRefState(C, CE, State);
470 }
471 }
472
473 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000474 // Check all the attributes, if there are any.
475 // There can be multiple of these attributes.
476 if (FD->hasAttrs())
477 for (specific_attr_iterator<OwnershipAttr>
478 i = FD->specific_attr_begin<OwnershipAttr>(),
479 e = FD->specific_attr_end<OwnershipAttr>();
480 i != e; ++i) {
481 switch ((*i)->getOwnKind()) {
482 case OwnershipAttr::Returns:
483 State = MallocMemReturnsAttr(C, CE, *i);
484 break;
485 case OwnershipAttr::Takes:
486 case OwnershipAttr::Holds:
487 State = FreeMemAttr(C, CE, *i);
488 break;
489 }
490 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000491 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000492 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000493}
494
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000495static bool isFreeWhenDoneSetToZero(const ObjCMethodCall &Call) {
496 Selector S = Call.getSelector();
Anna Zaks3e4f65d2012-06-22 22:08:09 +0000497 for (unsigned i = 1; i < S.getNumArgs(); ++i)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000498 if (S.getNameForSlot(i).equals("freeWhenDone"))
499 if (Call.getArgSVal(i).isConstant(0))
500 return true;
501
502 return false;
503}
504
Anna Zaks4141e4d2012-11-13 03:18:01 +0000505void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
506 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000507 if (C.wasInlined)
508 return;
509
Anna Zaks5b7aa342012-06-22 02:04:31 +0000510 // If the first selector is dataWithBytesNoCopy, assume that the memory will
511 // be released with 'free' by the new object.
512 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
513 // Unless 'freeWhenDone' param set to 0.
514 // TODO: Check that the memory was allocated with malloc.
Anna Zaks55dd9562012-08-24 02:28:20 +0000515 bool ReleasedAllocatedMemory = false;
Jordan Rosede507ea2012-07-02 19:28:04 +0000516 Selector S = Call.getSelector();
Anna Zaks7186dc62012-06-22 22:42:30 +0000517 if ((S.getNameForSlot(0) == "dataWithBytesNoCopy" ||
518 S.getNameForSlot(0) == "initWithBytesNoCopy" ||
519 S.getNameForSlot(0) == "initWithCharactersNoCopy") &&
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000520 !isFreeWhenDoneSetToZero(Call)){
Anna Zaks5b7aa342012-06-22 02:04:31 +0000521 unsigned int argIdx = 0;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000522 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(argIdx),
523 Call.getOriginExpr(), C.getState(), true,
524 ReleasedAllocatedMemory,
525 /* RetNullOnFailure*/ true);
526
527 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000528 }
529}
530
Anna Zaks87cb5be2012-02-22 19:24:52 +0000531ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
532 const CallExpr *CE,
533 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000534 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000535 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000536
Sean Huntcf807c42010-08-18 23:23:40 +0000537 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000538 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000539 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000540 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000541 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000542}
543
Anna Zaksb319e022012-02-08 20:13:28 +0000544ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000545 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000546 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000547 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000548
549 // Bind the return value to the symbolic value from the heap region.
550 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
551 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000552 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000553 SValBuilder &svalBuilder = C.getSValBuilder();
554 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
555 DefinedSVal RetVal =
556 cast<DefinedSVal>(svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count));
557 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000558
Anna Zaksb16ce452012-02-15 00:11:22 +0000559 // We expect the malloc functions to return a pointer.
Anna Zakse17fdb22012-06-07 03:57:32 +0000560 if (!isa<Loc>(RetVal))
Anna Zaksb16ce452012-02-15 00:11:22 +0000561 return 0;
562
Jordy Rose32f26562010-07-04 00:00:41 +0000563 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000564 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000565
Jordy Rose32f26562010-07-04 00:00:41 +0000566 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000567 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000568 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000569 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000570 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000571 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000572 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000573 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
574 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
575 DefinedOrUnknownSVal extentMatchesSize =
576 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000577
Anna Zaks60a1fa42012-02-22 03:14:20 +0000578 state = state->assume(extentMatchesSize, true);
579 assert(state);
580 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000581
Anna Zaks87cb5be2012-02-22 19:24:52 +0000582 return MallocUpdateRefState(C, CE, state);
583}
584
585ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
586 const CallExpr *CE,
587 ProgramStateRef state) {
588 // Get the return value.
589 SVal retVal = state->getSVal(CE, C.getLocationContext());
590
591 // We expect the malloc functions to return a pointer.
592 if (!isa<Loc>(retVal))
593 return 0;
594
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000595 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000596 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000597
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000598 // Set the symbol's state to Allocated.
Anna Zaks050cdd72012-06-20 20:57:46 +0000599 return state->set<RegionState>(Sym, RefState::getAllocated(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000600
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000601}
602
Anna Zaks87cb5be2012-02-22 19:24:52 +0000603ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
604 const CallExpr *CE,
605 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000606 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000607 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000608
Anna Zaksb3d72752012-03-01 22:06:06 +0000609 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000610 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000611
Sean Huntcf807c42010-08-18 23:23:40 +0000612 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
613 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000614 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000615 Att->getOwnKind() == OwnershipAttr::Holds,
616 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000617 if (StateI)
618 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000619 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000620 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000621}
622
Ted Kremenek8bef8232012-01-26 21:29:00 +0000623ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000624 const CallExpr *CE,
625 ProgramStateRef state,
626 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000627 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000628 bool &ReleasedAllocated,
629 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000630 if (CE->getNumArgs() < (Num + 1))
631 return 0;
632
Anna Zaks4141e4d2012-11-13 03:18:01 +0000633 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
634 ReleasedAllocated, ReturnsNullOnFailure);
635}
636
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000637/// Checks if the previous call to free on the given symbol failed - if free
638/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000639static bool didPreviousFreeFail(ProgramStateRef State,
640 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000641 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000642 if (Ret) {
643 assert(*Ret && "We should not store the null return symbol");
644 ConstraintManager &CMgr = State->getConstraintManager();
645 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000646 RetStatusSymbol = *Ret;
647 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000648 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000649 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000650}
651
652ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
653 const Expr *ArgExpr,
654 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000655 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000656 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000657 bool &ReleasedAllocated,
658 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000659
Anna Zaks4141e4d2012-11-13 03:18:01 +0000660 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000661 if (!isa<DefinedOrUnknownSVal>(ArgVal))
662 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000663 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
664
665 // Check for null dereferences.
666 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000667 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000668
Anna Zaksb276bd92012-02-14 00:26:13 +0000669 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000670 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000671 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000672 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000673 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000674
Jordy Rose43859f62010-06-07 19:32:37 +0000675 // Unknown values could easily be okay
676 // Undefined values are handled elsewhere
677 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000678 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000679
Jordy Rose43859f62010-06-07 19:32:37 +0000680 const MemRegion *R = ArgVal.getAsRegion();
681
682 // Nonlocs can't be freed, of course.
683 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
684 if (!R) {
685 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000686 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000687 }
688
689 R = R->StripCasts();
690
691 // Blocks might show up as heap data, but should not be free()d
692 if (isa<BlockDataRegion>(R)) {
693 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000694 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000695 }
696
697 const MemSpaceRegion *MS = R->getMemorySpace();
698
699 // Parameters, locals, statics, and globals shouldn't be freed.
700 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
701 // FIXME: at the time this code was written, malloc() regions were
702 // represented by conjured symbols, which are all in UnknownSpaceRegion.
703 // This means that there isn't actually anything from HeapSpaceRegion
704 // that should be freed, even though we allow it here.
705 // Of course, free() can work on memory allocated outside the current
706 // function, so UnknownSpaceRegion is always a possibility.
707 // False negatives are better than false positives.
708
709 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000710 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000711 }
712
713 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
714 // Various cases could lead to non-symbol values here.
715 // For now, ignore them.
716 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000717 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000718
719 SymbolRef Sym = SR->getSymbol();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000720 const RefState *RS = State->get<RegionState>(Sym);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000721 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000722
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000723 // Check double free.
Anna Zaks4141e4d2012-11-13 03:18:01 +0000724 if (RS &&
725 (RS->isReleased() || RS->isRelinquished()) &&
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000726 !didPreviousFreeFail(State, Sym, PreviousRetStatusSymbol)) {
Anna Zaks4141e4d2012-11-13 03:18:01 +0000727
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000728 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000729 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000730 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000731 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000732 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000733 (RS->isReleased() ? "Attempt to free released memory" :
734 "Attempt to free non-owned memory"), N);
Anna Zaksfe571602012-02-16 22:26:07 +0000735 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000736 R->markInteresting(Sym);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000737 if (PreviousRetStatusSymbol)
738 R->markInteresting(PreviousRetStatusSymbol);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000739 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +0000740 C.emitReport(R);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000741 }
Anna Zaksb319e022012-02-08 20:13:28 +0000742 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000743 }
744
Anna Zaks55dd9562012-08-24 02:28:20 +0000745 ReleasedAllocated = (RS != 0);
746
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000747 // Clean out the info on previous call to free return info.
748 State = State->remove<FreeReturnValue>(Sym);
749
Anna Zaks4141e4d2012-11-13 03:18:01 +0000750 // Keep track of the return value. If it is NULL, we will know that free
751 // failed.
752 if (ReturnsNullOnFailure) {
753 SVal RetVal = C.getSVal(ParentExpr);
754 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
755 if (RetStatusSymbol) {
756 C.getSymbolManager().addSymbolDependency(Sym, RetStatusSymbol);
757 State = State->set<FreeReturnValue>(Sym, RetStatusSymbol);
758 }
759 }
760
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000761 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000762 if (Hold)
Anna Zaks4141e4d2012-11-13 03:18:01 +0000763 return State->set<RegionState>(Sym, RefState::getRelinquished(ParentExpr));
764 return State->set<RegionState>(Sym, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000765}
766
Ted Kremenek9c378f72011-08-12 23:37:29 +0000767bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000768 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
769 os << "an integer (" << IntVal->getValue() << ")";
770 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
771 os << "a constant address (" << ConstAddr->getValue() << ")";
772 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000773 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000774 else
775 return false;
776
777 return true;
778}
779
Ted Kremenek9c378f72011-08-12 23:37:29 +0000780bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000781 const MemRegion *MR) {
782 switch (MR->getKind()) {
783 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000784 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +0000785 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000786 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000787 else
788 os << "the address of a function";
789 return true;
790 }
791 case MemRegion::BlockTextRegionKind:
792 os << "block text";
793 return true;
794 case MemRegion::BlockDataRegionKind:
795 // FIXME: where the block came from?
796 os << "a block";
797 return true;
798 default: {
799 const MemSpaceRegion *MS = MR->getMemorySpace();
800
Anna Zakseb31a762012-01-04 23:54:01 +0000801 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000802 const VarRegion *VR = dyn_cast<VarRegion>(MR);
803 const VarDecl *VD;
804 if (VR)
805 VD = VR->getDecl();
806 else
807 VD = NULL;
808
809 if (VD)
810 os << "the address of the local variable '" << VD->getName() << "'";
811 else
812 os << "the address of a local stack variable";
813 return true;
814 }
Anna Zakseb31a762012-01-04 23:54:01 +0000815
816 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000817 const VarRegion *VR = dyn_cast<VarRegion>(MR);
818 const VarDecl *VD;
819 if (VR)
820 VD = VR->getDecl();
821 else
822 VD = NULL;
823
824 if (VD)
825 os << "the address of the parameter '" << VD->getName() << "'";
826 else
827 os << "the address of a parameter";
828 return true;
829 }
Anna Zakseb31a762012-01-04 23:54:01 +0000830
831 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000832 const VarRegion *VR = dyn_cast<VarRegion>(MR);
833 const VarDecl *VD;
834 if (VR)
835 VD = VR->getDecl();
836 else
837 VD = NULL;
838
839 if (VD) {
840 if (VD->isStaticLocal())
841 os << "the address of the static variable '" << VD->getName() << "'";
842 else
843 os << "the address of the global variable '" << VD->getName() << "'";
844 } else
845 os << "the address of a global variable";
846 return true;
847 }
Anna Zakseb31a762012-01-04 23:54:01 +0000848
849 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000850 }
851 }
852}
853
854void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000855 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000856 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000857 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000858 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000859
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000860 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000861 llvm::raw_svector_ostream os(buf);
862
863 const MemRegion *MR = ArgVal.getAsRegion();
864 if (MR) {
865 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
866 MR = ER->getSuperRegion();
867
868 // Special case for alloca()
869 if (isa<AllocaRegion>(MR))
870 os << "Argument to free() was allocated by alloca(), not malloc()";
871 else {
872 os << "Argument to free() is ";
873 if (SummarizeRegion(os, MR))
874 os << ", which is not memory allocated by malloc()";
875 else
876 os << "not memory allocated by malloc()";
877 }
878 } else {
879 os << "Argument to free() is ";
880 if (SummarizeValue(os, ArgVal))
881 os << ", which is not memory allocated by malloc()";
882 else
883 os << "not memory allocated by malloc()";
884 }
885
Anna Zakse172e8b2011-08-17 23:00:25 +0000886 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000887 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000888 R->addRange(range);
Jordan Rose785950e2012-11-02 01:53:40 +0000889 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +0000890 }
891}
892
Anna Zaks87cb5be2012-02-22 19:24:52 +0000893ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
894 const CallExpr *CE,
895 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000896 if (CE->getNumArgs() < 2)
897 return 0;
898
Ted Kremenek8bef8232012-01-26 21:29:00 +0000899 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000900 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000901 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000902 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
903 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000904 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000905 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000906
Ted Kremenek846eabd2010-12-01 21:28:31 +0000907 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000908
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000909 DefinedOrUnknownSVal PtrEQ =
910 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000911
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000912 // Get the size argument. If there is no size arg then give up.
913 const Expr *Arg1 = CE->getArg(1);
914 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000915 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000916
917 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000918 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
919 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000920 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000921 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000922
923 // Compare the size argument to 0.
924 DefinedOrUnknownSVal SizeZero =
925 svalBuilder.evalEQ(state, Arg1Val,
926 svalBuilder.makeIntValWithPtrWidth(0, false));
927
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000928 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
929 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
930 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
931 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
932 // We only assume exceptional states if they are definitely true; if the
933 // state is under-constrained, assume regular realloc behavior.
934 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
935 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
936
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000937 // If the ptr is NULL and the size is not 0, the call is equivalent to
938 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000939 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000940 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000941 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000942 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000943 }
944
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000945 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000946 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000947
Anna Zaks30838b92012-02-13 20:57:07 +0000948 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000949 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000950 SymbolRef FromPtr = arg0Val.getAsSymbol();
951 SVal RetVal = state->getSVal(CE, LCtx);
952 SymbolRef ToPtr = RetVal.getAsSymbol();
953 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000954 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000955
Anna Zaks55dd9562012-08-24 02:28:20 +0000956 bool ReleasedAllocated = false;
957
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000958 // If the size is 0, free the memory.
959 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +0000960 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
961 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000962 // The semantics of the return value are:
963 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +0000964 // to free() is returned. We just free the input pointer and do not add
965 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +0000966 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000967 }
968
969 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +0000970 if (ProgramStateRef stateFree =
971 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
972
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000973 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
974 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000975 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000976 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +0000977
Anna Zaks9dc298b2012-09-12 22:57:34 +0000978 ReallocPairKind Kind = RPToBeFreedAfterFailure;
979 if (FreesOnFail)
980 Kind = RPIsFreeOnFailure;
981 else if (!ReleasedAllocated)
982 Kind = RPDoNotTrackAfterFailure;
983
Anna Zaks55dd9562012-08-24 02:28:20 +0000984 // Record the info about the reallocated symbol so that we could properly
985 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +0000986 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +0000987 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +0000988 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +0000989 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000990 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000991 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000992 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000993}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000994
Anna Zaks87cb5be2012-02-22 19:24:52 +0000995ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +0000996 if (CE->getNumArgs() < 2)
997 return 0;
998
Ted Kremenek8bef8232012-01-26 21:29:00 +0000999 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001000 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001001 const LocationContext *LCtx = C.getLocationContext();
1002 SVal count = state->getSVal(CE->getArg(0), LCtx);
1003 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001004 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1005 svalBuilder.getContext().getSizeType());
1006 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001007
Anna Zaks87cb5be2012-02-22 19:24:52 +00001008 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001009}
1010
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001011LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001012MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1013 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001014 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001015 // Walk the ExplodedGraph backwards and find the first node that referred to
1016 // the tracked symbol.
1017 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001018 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001019
1020 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001021 ProgramStateRef State = N->getState();
1022 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001023 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001024
1025 // Find the most recent expression bound to the symbol in the current
1026 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001027 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001028 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1029 SVal Val = State->getSVal(MR);
1030 if (Val.getAsLocSymbol() == Sym)
1031 ReferenceRegion = MR;
1032 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001033 }
1034
Anna Zaks7752d292012-02-27 23:40:55 +00001035 // Allocation node, is the last node in the current context in which the
1036 // symbol was tracked.
1037 if (N->getLocationContext() == LeakContext)
1038 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001039 N = N->pred_empty() ? NULL : *(N->pred_begin());
1040 }
1041
Anna Zaks97bfb552013-01-08 00:25:29 +00001042 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001043}
1044
Anna Zaksda046772012-02-11 21:02:40 +00001045void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1046 CheckerContext &C) const {
1047 assert(N);
1048 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001049 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001050 // Leaks should not be reported if they are post-dominated by a sink:
1051 // (1) Sinks are higher importance bugs.
1052 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1053 // with __noreturn functions such as assert() or exit(). We choose not
1054 // to report leaks on such paths.
1055 BT_Leak->setSuppressOnSink(true);
1056 }
1057
Anna Zaksca8e36e2012-02-23 21:38:21 +00001058 // Most bug reports are cached at the location where they occurred.
1059 // With leaks, we want to unique them by the location where they were
1060 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001061 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001062 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001063 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001064 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1065
1066 ProgramPoint P = AllocNode->getLocation();
1067 const Stmt *AllocationStmt = 0;
1068 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
1069 AllocationStmt = Exit->getCalleeContext()->getCallSite();
1070 else if (StmtPoint *SP = dyn_cast<StmtPoint>(&P))
1071 AllocationStmt = SP->getStmt();
1072 if (AllocationStmt)
1073 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1074 C.getSourceManager(),
1075 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001076
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001077 SmallString<200> buf;
1078 llvm::raw_svector_ostream os(buf);
1079 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001080 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001081 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001082 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001083 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001084 }
1085
Anna Zaks97bfb552013-01-08 00:25:29 +00001086 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1087 LocUsedForUniqueing,
1088 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001089 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001090 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001091 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001092}
1093
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001094void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1095 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001096{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001097 if (!SymReaper.hasDeadSymbols())
1098 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001099
Ted Kremenek8bef8232012-01-26 21:29:00 +00001100 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001101 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001102 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001103
Anna Zaksf8c17b72012-02-09 06:48:19 +00001104 llvm::SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001105 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1106 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001107 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001108 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001109 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001110 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001111
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001112 }
1113 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001114
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001115 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001116 ReallocPairsTy RP = state->get<ReallocPairs>();
1117 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001118 if (SymReaper.isDead(I->first) ||
1119 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001120 state = state->remove<ReallocPairs>(I->first);
1121 }
1122 }
1123
Anna Zaks4141e4d2012-11-13 03:18:01 +00001124 // Cleanup the FreeReturnValue Map.
1125 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1126 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1127 if (SymReaper.isDead(I->first) ||
1128 SymReaper.isDead(I->second)) {
1129 state = state->remove<FreeReturnValue>(I->first);
1130 }
1131 }
1132
Anna Zaksca8e36e2012-02-23 21:38:21 +00001133 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001134 ExplodedNode *N = C.getPredecessor();
1135 if (!Errors.empty()) {
1136 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1137 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001138 for (llvm::SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001139 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001140 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001141 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001142 }
Anna Zaks54458702012-10-29 22:51:54 +00001143
Anna Zaksca8e36e2012-02-23 21:38:21 +00001144 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001145}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001146
Anna Zaks66c40402012-02-14 21:55:24 +00001147void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001148 // We will check for double free in the post visit.
1149 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001150 return;
1151
1152 // Check use after free, when a freed pointer is passed to a call.
1153 ProgramStateRef State = C.getState();
1154 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1155 E = CE->arg_end(); I != E; ++I) {
1156 const Expr *A = *I;
1157 if (A->getType().getTypePtr()->isAnyPointerType()) {
1158 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1159 if (!Sym)
1160 continue;
1161 if (checkUseAfterFree(Sym, C, A))
1162 return;
1163 }
1164 }
1165}
1166
Anna Zaks91c2a112012-02-08 23:16:56 +00001167void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1168 const Expr *E = S->getRetValue();
1169 if (!E)
1170 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001171
1172 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001173 ProgramStateRef State = C.getState();
1174 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001175 SymbolRef Sym = RetVal.getAsSymbol();
1176 if (!Sym)
1177 // If we are returning a field of the allocated struct or an array element,
1178 // the callee could still free the memory.
1179 // TODO: This logic should be a part of generic symbol escape callback.
1180 if (const MemRegion *MR = RetVal.getAsRegion())
1181 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1182 if (const SymbolicRegion *BMR =
1183 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1184 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001185
Anna Zaks0860cd02012-02-11 21:44:39 +00001186 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001187 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001188 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001189}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001190
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001191// TODO: Blocks should be either inlined or should call invalidate regions
1192// upon invocation. After that's in place, special casing here will not be
1193// needed.
1194void MallocChecker::checkPostStmt(const BlockExpr *BE,
1195 CheckerContext &C) const {
1196
1197 // Scan the BlockDecRefExprs for any object the retain count checker
1198 // may be tracking.
1199 if (!BE->getBlockDecl()->hasCaptures())
1200 return;
1201
1202 ProgramStateRef state = C.getState();
1203 const BlockDataRegion *R =
1204 cast<BlockDataRegion>(state->getSVal(BE,
1205 C.getLocationContext()).getAsRegion());
1206
1207 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1208 E = R->referenced_vars_end();
1209
1210 if (I == E)
1211 return;
1212
1213 SmallVector<const MemRegion*, 10> Regions;
1214 const LocationContext *LC = C.getLocationContext();
1215 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1216
1217 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001218 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001219 if (VR->getSuperRegion() == R) {
1220 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1221 }
1222 Regions.push_back(VR);
1223 }
1224
1225 state =
1226 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1227 Regions.data() + Regions.size()).getState();
1228 C.addTransition(state);
1229}
1230
Anna Zaks14345182012-05-18 01:16:10 +00001231bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001232 assert(Sym);
1233 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001234 return (RS && RS->isReleased());
1235}
1236
1237bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1238 const Stmt *S) const {
1239 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001240 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001241 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001242 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001243
Anna Zaksfebdc322012-02-16 22:26:12 +00001244 BugReport *R = new BugReport(*BT_UseFree,
1245 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001246 if (S)
1247 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001248 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001249 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +00001250 C.emitReport(R);
Anna Zaks91c2a112012-02-08 23:16:56 +00001251 return true;
1252 }
1253 }
1254 return false;
1255}
1256
Zhongxing Xuc8023782010-03-10 04:58:55 +00001257// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001258void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1259 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001260 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001261 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001262 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001263}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001264
Anna Zaks4fb54872012-02-11 21:02:35 +00001265// If a symbolic region is assumed to NULL (or another constant), stop tracking
1266// it - assuming that allocation failed on this path.
1267ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1268 SVal Cond,
1269 bool Assumption) const {
1270 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001271 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001272 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001273 ConstraintManager &CMgr = state->getConstraintManager();
1274 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1275 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001276 state = state->remove<RegionState>(I.getKey());
1277 }
1278
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001279 // Realloc returns 0 when reallocation fails, which means that we should
1280 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001281 ReallocPairsTy RP = state->get<ReallocPairs>();
1282 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001283 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001284 ConstraintManager &CMgr = state->getConstraintManager();
1285 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001286 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001287 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001288
Anna Zaks9dc298b2012-09-12 22:57:34 +00001289 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1290 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1291 if (RS->isReleased()) {
1292 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001293 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001294 RefState::getAllocated(RS->getStmt()));
1295 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1296 state = state->remove<RegionState>(ReallocSym);
1297 else
1298 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001299 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001300 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001301 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001302 }
1303
Anna Zaks4fb54872012-02-11 21:02:35 +00001304 return state;
1305}
1306
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001307// Check if the function is known to us. So, for example, we could
Jordan Rose740d4902012-07-02 19:27:35 +00001308// conservatively assume it can free/reallocate its pointer arguments.
Anna Zaks66c40402012-02-14 21:55:24 +00001309// (We assume that the pointers cannot escape through calls to system
1310// functions not handled by this checker.)
Jordan Rose740d4902012-07-02 19:27:35 +00001311bool MallocChecker::doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001312 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001313 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001314
1315 // For now, assume that any C++ call can free memory.
1316 // TODO: If we want to be more optimistic here, we'll need to make sure that
1317 // regions escape to C++ containers. They seem to do that even now, but for
1318 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001319 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001320 return false;
1321
Jordan Rose740d4902012-07-02 19:27:35 +00001322 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001323 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001324 // If it's not a framework call, or if it takes a callback, assume it
1325 // can free memory.
1326 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001327 return false;
1328
Jordan Rose740d4902012-07-02 19:27:35 +00001329 Selector S = Msg->getSelector();
Anna Zaks52a04812012-06-20 23:35:57 +00001330
Jordan Rose740d4902012-07-02 19:27:35 +00001331 // Whitelist the ObjC methods which do free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001332 // - Anything containing 'freeWhenDone' param set to 1.
1333 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
Anna Zaks3e4f65d2012-06-22 22:08:09 +00001334 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001335 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1336 if (Call->getArgSVal(i).isConstant(1))
1337 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001338 else
1339 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001340 }
1341 }
1342
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001343 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001344 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001345 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
Jordan Rose740d4902012-07-02 19:27:35 +00001346 StringRef FirstSlot = S.getNameForSlot(0);
1347 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001348 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001349
Anna Zaks5f757682012-06-19 05:10:32 +00001350 // If the first selector starts with addPointer, insertPointer,
1351 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1352 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001353 // that the pointers get freed by following the container itself.
1354 if (FirstSlot.startswith("addPointer") ||
1355 FirstSlot.startswith("insertPointer") ||
1356 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001357 return false;
1358 }
1359
Jordan Rose740d4902012-07-02 19:27:35 +00001360 // Otherwise, assume that the method does not free memory.
1361 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001362 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001363 }
1364
Jordan Rose740d4902012-07-02 19:27:35 +00001365 // At this point the only thing left to handle is straight function calls.
1366 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1367 if (!FD)
1368 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001369
Jordan Rose740d4902012-07-02 19:27:35 +00001370 ASTContext &ASTC = State->getStateManager().getContext();
1371
1372 // If it's one of the allocation functions we can reason about, we model
1373 // its behavior explicitly.
1374 if (isMemFunction(FD, ASTC))
1375 return true;
1376
1377 // If it's not a system call, assume it frees memory.
1378 if (!Call->isInSystemHeader())
1379 return false;
1380
1381 // White list the system functions whose arguments escape.
1382 const IdentifierInfo *II = FD->getIdentifier();
1383 if (!II)
1384 return false;
1385 StringRef FName = II->getName();
1386
Jordan Rose740d4902012-07-02 19:27:35 +00001387 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001388 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001389 if (FName.endswith("NoCopy")) {
1390 // Look for the deallocator argument. We know that the memory ownership
1391 // is not transferred only if the deallocator argument is
1392 // 'kCFAllocatorNull'.
1393 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1394 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1395 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1396 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1397 if (DeallocatorName == "kCFAllocatorNull")
1398 return true;
1399 }
1400 }
1401 return false;
1402 }
1403
Jordan Rose740d4902012-07-02 19:27:35 +00001404 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001405 // 'closefn' is specified (and if that function does free memory),
1406 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001407 // Currently, we do not inspect the 'closefn' function (PR12101).
1408 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001409 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1410 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001411
1412 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1413 // these leaks might be intentional when setting the buffer for stdio.
1414 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1415 if (FName == "setbuf" || FName =="setbuffer" ||
1416 FName == "setlinebuf" || FName == "setvbuf") {
1417 if (Call->getNumArgs() >= 1) {
1418 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1419 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1420 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1421 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1422 return false;
1423 }
1424 }
1425
1426 // A bunch of other functions which either take ownership of a pointer or
1427 // wrap the result up in a struct or object, meaning it can be freed later.
1428 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1429 // but the Malloc checker cannot differentiate between them. The right way
1430 // of doing this would be to implement a pointer escapes callback.
1431 if (FName == "CGBitmapContextCreate" ||
1432 FName == "CGBitmapContextCreateWithData" ||
1433 FName == "CVPixelBufferCreateWithBytes" ||
1434 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1435 FName == "OSAtomicEnqueue") {
1436 return false;
1437 }
1438
Jordan Rose85d7e012012-07-02 19:27:51 +00001439 // Handle cases where we know a buffer's /address/ can escape.
1440 // Note that the above checks handle some special cases where we know that
1441 // even though the address escapes, it's still our responsibility to free the
1442 // buffer.
1443 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001444 return false;
1445
1446 // Otherwise, assume that the function does not free memory.
1447 // Most system calls do not free the memory.
1448 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001449}
1450
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001451ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1452 const InvalidatedSymbols &Escaped,
1453 const CallEvent *Call) const {
1454 // If we know that the call does not free memory, keep tracking the top
1455 // level arguments.
1456 if (Call && doesNotFreeMemory(Call, State))
Anna Zaks66c40402012-02-14 21:55:24 +00001457 return State;
Anna Zaks66c40402012-02-14 21:55:24 +00001458
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001459 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
1460 E = Escaped.end();
1461 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001462 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001463
Anna Zaks5b7aa342012-06-22 02:04:31 +00001464 if (const RefState *RS = State->get<RegionState>(sym)) {
1465 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001466 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001467 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001468 }
Anna Zaks66c40402012-02-14 21:55:24 +00001469 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001470}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001471
Jordy Rose393f98b2012-03-18 07:43:35 +00001472static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1473 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001474 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1475 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001476
Jordan Rose166d5022012-11-02 01:54:06 +00001477 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001478 I != E; ++I) {
1479 SymbolRef sym = I.getKey();
1480 if (!currMap.lookup(sym))
1481 return sym;
1482 }
1483
1484 return NULL;
1485}
1486
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001487PathDiagnosticPiece *
1488MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1489 const ExplodedNode *PrevN,
1490 BugReporterContext &BRC,
1491 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001492 ProgramStateRef state = N->getState();
1493 ProgramStateRef statePrev = PrevN->getState();
1494
1495 const RefState *RS = state->get<RegionState>(Sym);
1496 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001497 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001498 return 0;
1499
Anna Zaksfe571602012-02-16 22:26:07 +00001500 const Stmt *S = 0;
1501 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001502 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001503
1504 // Retrieve the associated statement.
1505 ProgramPoint ProgLoc = N->getLocation();
Ted Kremeneka4a17592013-01-04 19:04:36 +00001506 if (StmtPoint *SP = dyn_cast<StmtPoint>(&ProgLoc)) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001507 S = SP->getStmt();
Ted Kremeneka4a17592013-01-04 19:04:36 +00001508 } else if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&ProgLoc)) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001509 S = Exit->getCalleeContext()->getCallSite();
Ted Kremeneka4a17592013-01-04 19:04:36 +00001510 } else if (BlockEdge *Edge = dyn_cast<BlockEdge>(&ProgLoc)) {
1511 // If an assumption was made on a branch, it should be caught
1512 // here by looking at the state transition.
1513 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00001514 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00001515
Anna Zaksfe571602012-02-16 22:26:07 +00001516 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001517 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001518
Jordan Rose28038f32012-07-10 22:07:42 +00001519 // FIXME: We will eventually need to handle non-statement-based events
1520 // (__attribute__((cleanup))).
1521
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001522 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001523 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001524 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001525 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001526 StackHint = new StackHintGeneratorForSymbol(Sym,
1527 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001528 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001529 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001530 StackHint = new StackHintGeneratorForSymbol(Sym,
1531 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001532 } else if (isRelinquished(RS, RSPrev, S)) {
1533 Msg = "Memory ownership is transfered";
1534 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001535 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001536 Mode = ReallocationFailed;
1537 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001538 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001539 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001540
Jordy Roseb000fb52012-03-24 03:15:09 +00001541 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1542 // Is it possible to fail two reallocs WITHOUT testing in between?
1543 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1544 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001545 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001546 FailedReallocSymbol = sym;
1547 }
Anna Zaksfe571602012-02-16 22:26:07 +00001548 }
1549
1550 // We are in a special mode if a reallocation failed later in the path.
1551 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001552 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001553
Jordy Roseb000fb52012-03-24 03:15:09 +00001554 // Is this is the first appearance of the reallocated symbol?
1555 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001556 // We're at the reallocation point.
1557 Msg = "Attempt to reallocate memory";
1558 StackHint = new StackHintGeneratorForSymbol(Sym,
1559 "Returned reallocated memory");
1560 FailedReallocSymbol = NULL;
1561 Mode = Normal;
1562 }
Anna Zaksfe571602012-02-16 22:26:07 +00001563 }
1564
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001565 if (!Msg)
1566 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001567 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001568
1569 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001570 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001571 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001572 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001573}
1574
Anna Zaks93c5a242012-05-02 00:05:20 +00001575void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1576 const char *NL, const char *Sep) const {
1577
1578 RegionStateTy RS = State->get<RegionState>();
1579
Ted Kremenekc37fad62013-01-03 01:30:12 +00001580 if (!RS.isEmpty()) {
1581 Out << Sep << "MallocChecker:" << NL;
1582 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1583 I.getKey()->dumpToStream(Out);
1584 Out << " : ";
1585 I.getData().dump(Out);
1586 Out << NL;
1587 }
1588 }
Anna Zaks93c5a242012-05-02 00:05:20 +00001589}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001590
Anna Zaks231361a2012-02-08 23:16:52 +00001591#define REGISTER_CHECKER(name) \
1592void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001593 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001594 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001595}
Anna Zaks231361a2012-02-08 23:16:52 +00001596
1597REGISTER_CHECKER(MallocPessimistic)
1598REGISTER_CHECKER(MallocOptimistic)