blob: 9afd8cff4c7e7b02bcae0e34fb456be54a4685a9 [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
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000074 void dump(raw_ostream &OS) const {
Ted Kremenekc37fad62013-01-03 01:30:12 +000075 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,
Anna Zaks233e26a2013-02-07 23:05:43 +0000161 const CallEvent *Call,
162 PointerEscapeKind Kind) const;
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000163
Anna Zaks93c5a242012-05-02 00:05:20 +0000164 void printState(raw_ostream &Out, ProgramStateRef State,
165 const char *NL, const char *Sep) const;
166
Zhongxing Xu7b760962009-11-13 07:25:27 +0000167private:
Anna Zaks66c40402012-02-14 21:55:24 +0000168 void initIdentifierInfo(ASTContext &C) const;
169
170 /// Check if this is one of the functions which can allocate/reallocate memory
171 /// pointed to by one of its arguments.
172 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000173 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
174 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000175
Anna Zaks87cb5be2012-02-22 19:24:52 +0000176 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
177 const CallExpr *CE,
178 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000179 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000180 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000181 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000182 return MallocMemAux(C, CE,
183 state->getSVal(SizeEx, C.getLocationContext()),
184 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000185 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000186
Ted Kremenek8bef8232012-01-26 21:29:00 +0000187 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000188 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000189 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000190
Anna Zaks87cb5be2012-02-22 19:24:52 +0000191 /// Update the RefState to reflect the new memory allocation.
192 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
193 const CallExpr *CE,
194 ProgramStateRef state);
195
196 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
197 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000198 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000199 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000200 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000201 bool &ReleasedAllocated,
202 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000203 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
204 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000205 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000206 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000207 bool &ReleasedAllocated,
208 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000209
Anna Zaks87cb5be2012-02-22 19:24:52 +0000210 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
211 bool FreesMemOnFailure) const;
212 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000213
Anna Zaks14345182012-05-18 01:16:10 +0000214 ///\brief Check if the memory associated with this symbol was released.
215 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
216
Anna Zaks91c2a112012-02-08 23:16:56 +0000217 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
218 const Stmt *S = 0) const;
219
Anna Zaks66c40402012-02-14 21:55:24 +0000220 /// Check if the function is not known to us. So, for example, we could
221 /// conservatively assume it can free/reallocate it's pointer arguments.
Jordan Rose740d4902012-07-02 19:27:35 +0000222 bool doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000223 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000224
Ted Kremenek9c378f72011-08-12 23:37:29 +0000225 static bool SummarizeValue(raw_ostream &os, SVal V);
226 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000227 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000228
Anna Zaksca8e36e2012-02-23 21:38:21 +0000229 /// Find the location of the allocation for Sym on the path leading to the
230 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000231 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
232 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000233
Anna Zaksda046772012-02-11 21:02:40 +0000234 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
235
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000236 /// The bug visitor which allows us to print extra diagnostics along the
237 /// BugReport path. For example, showing the allocation site of the leaked
238 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000239 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000240 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000241 enum NotificationMode {
242 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000243 ReallocationFailed
244 };
245
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000246 // The allocated region symbol tracked by the main analysis.
247 SymbolRef Sym;
248
Anna Zaks88feba02012-05-10 01:37:40 +0000249 // The mode we are in, i.e. what kind of diagnostics will be emitted.
250 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000251
Anna Zaks88feba02012-05-10 01:37:40 +0000252 // A symbol from when the primary region should have been reallocated.
253 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000254
Anna Zaks88feba02012-05-10 01:37:40 +0000255 bool IsLeak;
256
257 public:
258 MallocBugVisitor(SymbolRef S, bool isLeak = false)
259 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000260
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000261 virtual ~MallocBugVisitor() {}
262
263 void Profile(llvm::FoldingSetNodeID &ID) const {
264 static int X = 0;
265 ID.AddPointer(&X);
266 ID.AddPointer(Sym);
267 }
268
Anna Zaksfe571602012-02-16 22:26:07 +0000269 inline bool isAllocated(const RefState *S, const RefState *SPrev,
270 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000271 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000272 return (Stmt && isa<CallExpr>(Stmt) &&
273 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000274 }
275
Anna Zaksfe571602012-02-16 22:26:07 +0000276 inline bool isReleased(const RefState *S, const RefState *SPrev,
277 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000278 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000279 return (Stmt && isa<CallExpr>(Stmt) &&
280 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
281 }
282
Anna Zaks5b7aa342012-06-22 02:04:31 +0000283 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
284 const Stmt *Stmt) {
285 // Did not track -> relinquished. Other state (allocated) -> relinquished.
286 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
287 isa<ObjCPropertyRefExpr>(Stmt)) &&
288 (S && S->isRelinquished()) &&
289 (!SPrev || !SPrev->isRelinquished()));
290 }
291
Anna Zaksfe571602012-02-16 22:26:07 +0000292 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
293 const Stmt *Stmt) {
294 // If the expression is not a call, and the state change is
295 // released -> allocated, it must be the realloc return value
296 // check. If we have to handle more cases here, it might be cleaner just
297 // to track this extra bit in the state itself.
298 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
299 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000300 }
301
302 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
303 const ExplodedNode *PrevN,
304 BugReporterContext &BRC,
305 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000306
307 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
308 const ExplodedNode *EndPathNode,
309 BugReport &BR) {
310 if (!IsLeak)
311 return 0;
312
313 PathDiagnosticLocation L =
314 PathDiagnosticLocation::createEndOfPath(EndPathNode,
315 BRC.getSourceManager());
316 // Do not add the statement itself as a range in case of leak.
317 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
318 }
319
Anna Zaks56a938f2012-03-16 23:24:20 +0000320 private:
321 class StackHintGeneratorForReallocationFailed
322 : public StackHintGeneratorForSymbol {
323 public:
324 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
325 : StackHintGeneratorForSymbol(S, M) {}
326
327 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000328 // Printed parameters start at 1, not 0.
329 ++ArgIndex;
330
Anna Zaks56a938f2012-03-16 23:24:20 +0000331 SmallString<200> buf;
332 llvm::raw_svector_ostream os(buf);
333
Jordan Rose615a0922012-09-22 01:24:42 +0000334 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
335 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000336
337 return os.str();
338 }
339
340 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000341 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000342 }
343 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000344 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000345};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000346} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000347
Jordan Rose166d5022012-11-02 01:54:06 +0000348REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
349REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000350
Anna Zaks4141e4d2012-11-13 03:18:01 +0000351// A map from the freed symbol to the symbol representing the return value of
352// the free function.
353REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
354
Anna Zaks4fb54872012-02-11 21:02:35 +0000355namespace {
356class StopTrackingCallback : public SymbolVisitor {
357 ProgramStateRef state;
358public:
359 StopTrackingCallback(ProgramStateRef st) : state(st) {}
360 ProgramStateRef getState() const { return state; }
361
362 bool VisitSymbol(SymbolRef sym) {
363 state = state->remove<RegionState>(sym);
364 return true;
365 }
366};
367} // end anonymous namespace
368
Anna Zaks66c40402012-02-14 21:55:24 +0000369void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000370 if (II_malloc)
371 return;
372 II_malloc = &Ctx.Idents.get("malloc");
373 II_free = &Ctx.Idents.get("free");
374 II_realloc = &Ctx.Idents.get("realloc");
375 II_reallocf = &Ctx.Idents.get("reallocf");
376 II_calloc = &Ctx.Idents.get("calloc");
377 II_valloc = &Ctx.Idents.get("valloc");
378 II_strdup = &Ctx.Idents.get("strdup");
379 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000380}
381
Anna Zaks66c40402012-02-14 21:55:24 +0000382bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000383 if (isFreeFunction(FD, C))
384 return true;
385
386 if (isAllocationFunction(FD, C))
387 return true;
388
389 return false;
390}
391
392bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
393 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000394 if (!FD)
395 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000396
Jordan Rose5ef6e942012-07-10 23:13:01 +0000397 if (FD->getKind() == Decl::Function) {
398 IdentifierInfo *FunI = FD->getIdentifier();
399 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000400
Jordan Rose5ef6e942012-07-10 23:13:01 +0000401 if (FunI == II_malloc || FunI == II_realloc ||
402 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
403 FunI == II_strdup || FunI == II_strndup)
404 return true;
405 }
Anna Zaks66c40402012-02-14 21:55:24 +0000406
Anna Zaks14345182012-05-18 01:16:10 +0000407 if (Filter.CMallocOptimistic && FD->hasAttrs())
408 for (specific_attr_iterator<OwnershipAttr>
409 i = FD->specific_attr_begin<OwnershipAttr>(),
410 e = FD->specific_attr_end<OwnershipAttr>();
411 i != e; ++i)
412 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
413 return true;
414 return false;
415}
416
417bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
418 if (!FD)
419 return false;
420
Jordan Rose5ef6e942012-07-10 23:13:01 +0000421 if (FD->getKind() == Decl::Function) {
422 IdentifierInfo *FunI = FD->getIdentifier();
423 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000424
Jordan Rose5ef6e942012-07-10 23:13:01 +0000425 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
426 return true;
427 }
Anna Zaks66c40402012-02-14 21:55:24 +0000428
Anna Zaks14345182012-05-18 01:16:10 +0000429 if (Filter.CMallocOptimistic && FD->hasAttrs())
430 for (specific_attr_iterator<OwnershipAttr>
431 i = FD->specific_attr_begin<OwnershipAttr>(),
432 e = FD->specific_attr_end<OwnershipAttr>();
433 i != e; ++i)
434 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
435 (*i)->getOwnKind() == OwnershipAttr::Holds)
436 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000437 return false;
438}
439
Anna Zaksb319e022012-02-08 20:13:28 +0000440void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000441 if (C.wasInlined)
442 return;
443
Anna Zaksb319e022012-02-08 20:13:28 +0000444 const FunctionDecl *FD = C.getCalleeDecl(CE);
445 if (!FD)
446 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000447
Anna Zaks87cb5be2012-02-22 19:24:52 +0000448 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000449 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000450
451 if (FD->getKind() == Decl::Function) {
452 initIdentifierInfo(C.getASTContext());
453 IdentifierInfo *FunI = FD->getIdentifier();
454
455 if (FunI == II_malloc || FunI == II_valloc) {
456 if (CE->getNumArgs() < 1)
457 return;
458 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
459 } else if (FunI == II_realloc) {
460 State = ReallocMem(C, CE, false);
461 } else if (FunI == II_reallocf) {
462 State = ReallocMem(C, CE, true);
463 } else if (FunI == II_calloc) {
464 State = CallocMem(C, CE);
465 } else if (FunI == II_free) {
Anna Zaks55dd9562012-08-24 02:28:20 +0000466 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose5ef6e942012-07-10 23:13:01 +0000467 } else if (FunI == II_strdup) {
468 State = MallocUpdateRefState(C, CE, State);
469 } else if (FunI == II_strndup) {
470 State = MallocUpdateRefState(C, CE, State);
471 }
472 }
473
474 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000475 // Check all the attributes, if there are any.
476 // There can be multiple of these attributes.
477 if (FD->hasAttrs())
478 for (specific_attr_iterator<OwnershipAttr>
479 i = FD->specific_attr_begin<OwnershipAttr>(),
480 e = FD->specific_attr_end<OwnershipAttr>();
481 i != e; ++i) {
482 switch ((*i)->getOwnKind()) {
483 case OwnershipAttr::Returns:
484 State = MallocMemReturnsAttr(C, CE, *i);
485 break;
486 case OwnershipAttr::Takes:
487 case OwnershipAttr::Holds:
488 State = FreeMemAttr(C, CE, *i);
489 break;
490 }
491 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000492 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000493 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000494}
495
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000496static bool isFreeWhenDoneSetToZero(const ObjCMethodCall &Call) {
497 Selector S = Call.getSelector();
Anna Zaks3e4f65d2012-06-22 22:08:09 +0000498 for (unsigned i = 1; i < S.getNumArgs(); ++i)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000499 if (S.getNameForSlot(i).equals("freeWhenDone"))
500 if (Call.getArgSVal(i).isConstant(0))
501 return true;
502
503 return false;
504}
505
Anna Zaks4141e4d2012-11-13 03:18:01 +0000506void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
507 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000508 if (C.wasInlined)
509 return;
510
Anna Zaks5b7aa342012-06-22 02:04:31 +0000511 // If the first selector is dataWithBytesNoCopy, assume that the memory will
512 // be released with 'free' by the new object.
513 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
514 // Unless 'freeWhenDone' param set to 0.
515 // TODO: Check that the memory was allocated with malloc.
Anna Zaks55dd9562012-08-24 02:28:20 +0000516 bool ReleasedAllocatedMemory = false;
Jordan Rosede507ea2012-07-02 19:28:04 +0000517 Selector S = Call.getSelector();
Anna Zaks7186dc62012-06-22 22:42:30 +0000518 if ((S.getNameForSlot(0) == "dataWithBytesNoCopy" ||
519 S.getNameForSlot(0) == "initWithBytesNoCopy" ||
520 S.getNameForSlot(0) == "initWithCharactersNoCopy") &&
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000521 !isFreeWhenDoneSetToZero(Call)){
Anna Zaks5b7aa342012-06-22 02:04:31 +0000522 unsigned int argIdx = 0;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000523 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(argIdx),
524 Call.getOriginExpr(), C.getState(), true,
525 ReleasedAllocatedMemory,
526 /* RetNullOnFailure*/ true);
527
528 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000529 }
530}
531
Anna Zaks87cb5be2012-02-22 19:24:52 +0000532ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
533 const CallExpr *CE,
534 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000535 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000536 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000537
Sean Huntcf807c42010-08-18 23:23:40 +0000538 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000539 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000540 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000541 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000542 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000543}
544
Anna Zaksb319e022012-02-08 20:13:28 +0000545ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000546 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000547 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000548 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000549
550 // Bind the return value to the symbolic value from the heap region.
551 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
552 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000553 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000554 SValBuilder &svalBuilder = C.getSValBuilder();
555 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
556 DefinedSVal RetVal =
557 cast<DefinedSVal>(svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count));
558 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000559
Anna Zaksb16ce452012-02-15 00:11:22 +0000560 // We expect the malloc functions to return a pointer.
Anna Zakse17fdb22012-06-07 03:57:32 +0000561 if (!isa<Loc>(RetVal))
Anna Zaksb16ce452012-02-15 00:11:22 +0000562 return 0;
563
Jordy Rose32f26562010-07-04 00:00:41 +0000564 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000565 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000566
Jordy Rose32f26562010-07-04 00:00:41 +0000567 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000568 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000569 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000570 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000571 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000572 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000573 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000574 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
575 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
576 DefinedOrUnknownSVal extentMatchesSize =
577 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000578
Anna Zaks60a1fa42012-02-22 03:14:20 +0000579 state = state->assume(extentMatchesSize, true);
580 assert(state);
581 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000582
Anna Zaks87cb5be2012-02-22 19:24:52 +0000583 return MallocUpdateRefState(C, CE, state);
584}
585
586ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
587 const CallExpr *CE,
588 ProgramStateRef state) {
589 // Get the return value.
590 SVal retVal = state->getSVal(CE, C.getLocationContext());
591
592 // We expect the malloc functions to return a pointer.
593 if (!isa<Loc>(retVal))
594 return 0;
595
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000596 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000597 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000598
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000599 // Set the symbol's state to Allocated.
Anna Zaks050cdd72012-06-20 20:57:46 +0000600 return state->set<RegionState>(Sym, RefState::getAllocated(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000601
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000602}
603
Anna Zaks87cb5be2012-02-22 19:24:52 +0000604ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
605 const CallExpr *CE,
606 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000607 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000608 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000609
Anna Zaksb3d72752012-03-01 22:06:06 +0000610 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000611 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000612
Sean Huntcf807c42010-08-18 23:23:40 +0000613 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
614 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000615 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000616 Att->getOwnKind() == OwnershipAttr::Holds,
617 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000618 if (StateI)
619 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000620 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000621 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000622}
623
Ted Kremenek8bef8232012-01-26 21:29:00 +0000624ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000625 const CallExpr *CE,
626 ProgramStateRef state,
627 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000628 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000629 bool &ReleasedAllocated,
630 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000631 if (CE->getNumArgs() < (Num + 1))
632 return 0;
633
Anna Zaks4141e4d2012-11-13 03:18:01 +0000634 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
635 ReleasedAllocated, ReturnsNullOnFailure);
636}
637
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000638/// Checks if the previous call to free on the given symbol failed - if free
639/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000640static bool didPreviousFreeFail(ProgramStateRef State,
641 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000642 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000643 if (Ret) {
644 assert(*Ret && "We should not store the null return symbol");
645 ConstraintManager &CMgr = State->getConstraintManager();
646 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000647 RetStatusSymbol = *Ret;
648 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000649 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000650 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000651}
652
653ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
654 const Expr *ArgExpr,
655 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000656 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000657 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000658 bool &ReleasedAllocated,
659 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000660
Anna Zaks4141e4d2012-11-13 03:18:01 +0000661 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000662 if (!isa<DefinedOrUnknownSVal>(ArgVal))
663 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000664 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
665
666 // Check for null dereferences.
667 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000668 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000669
Anna Zaksb276bd92012-02-14 00:26:13 +0000670 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000671 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000672 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000673 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000674 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000675
Jordy Rose43859f62010-06-07 19:32:37 +0000676 // Unknown values could easily be okay
677 // Undefined values are handled elsewhere
678 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000679 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000680
Jordy Rose43859f62010-06-07 19:32:37 +0000681 const MemRegion *R = ArgVal.getAsRegion();
682
683 // Nonlocs can't be freed, of course.
684 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
685 if (!R) {
686 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000687 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000688 }
689
690 R = R->StripCasts();
691
692 // Blocks might show up as heap data, but should not be free()d
693 if (isa<BlockDataRegion>(R)) {
694 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000695 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000696 }
697
698 const MemSpaceRegion *MS = R->getMemorySpace();
699
700 // Parameters, locals, statics, and globals shouldn't be freed.
701 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
702 // FIXME: at the time this code was written, malloc() regions were
703 // represented by conjured symbols, which are all in UnknownSpaceRegion.
704 // This means that there isn't actually anything from HeapSpaceRegion
705 // that should be freed, even though we allow it here.
706 // Of course, free() can work on memory allocated outside the current
707 // function, so UnknownSpaceRegion is always a possibility.
708 // False negatives are better than false positives.
709
710 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000711 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000712 }
713
714 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R);
715 // Various cases could lead to non-symbol values here.
716 // For now, ignore them.
717 if (!SR)
Anna Zaksb319e022012-02-08 20:13:28 +0000718 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000719
720 SymbolRef Sym = SR->getSymbol();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000721 const RefState *RS = State->get<RegionState>(Sym);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000722 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000723
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000724 // Check double free.
Anna Zaks4141e4d2012-11-13 03:18:01 +0000725 if (RS &&
726 (RS->isReleased() || RS->isRelinquished()) &&
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000727 !didPreviousFreeFail(State, Sym, PreviousRetStatusSymbol)) {
Anna Zaks4141e4d2012-11-13 03:18:01 +0000728
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000729 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000730 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000731 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000732 new BugType("Double free", "Memory Error"));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000733 BugReport *R = new BugReport(*BT_DoubleFree,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000734 (RS->isReleased() ? "Attempt to free released memory" :
735 "Attempt to free non-owned memory"), N);
Anna Zaksfe571602012-02-16 22:26:07 +0000736 R->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000737 R->markInteresting(Sym);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000738 if (PreviousRetStatusSymbol)
739 R->markInteresting(PreviousRetStatusSymbol);
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000740 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +0000741 C.emitReport(R);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000742 }
Anna Zaksb319e022012-02-08 20:13:28 +0000743 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000744 }
745
Anna Zaks55dd9562012-08-24 02:28:20 +0000746 ReleasedAllocated = (RS != 0);
747
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000748 // Clean out the info on previous call to free return info.
749 State = State->remove<FreeReturnValue>(Sym);
750
Anna Zaks4141e4d2012-11-13 03:18:01 +0000751 // Keep track of the return value. If it is NULL, we will know that free
752 // failed.
753 if (ReturnsNullOnFailure) {
754 SVal RetVal = C.getSVal(ParentExpr);
755 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
756 if (RetStatusSymbol) {
757 C.getSymbolManager().addSymbolDependency(Sym, RetStatusSymbol);
758 State = State->set<FreeReturnValue>(Sym, RetStatusSymbol);
759 }
760 }
761
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000762 // Normal free.
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000763 if (Hold)
Anna Zaks4141e4d2012-11-13 03:18:01 +0000764 return State->set<RegionState>(Sym, RefState::getRelinquished(ParentExpr));
765 return State->set<RegionState>(Sym, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000766}
767
Ted Kremenek9c378f72011-08-12 23:37:29 +0000768bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000769 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
770 os << "an integer (" << IntVal->getValue() << ")";
771 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
772 os << "a constant address (" << ConstAddr->getValue() << ")";
773 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000774 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000775 else
776 return false;
777
778 return true;
779}
780
Ted Kremenek9c378f72011-08-12 23:37:29 +0000781bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000782 const MemRegion *MR) {
783 switch (MR->getKind()) {
784 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000785 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +0000786 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000787 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000788 else
789 os << "the address of a function";
790 return true;
791 }
792 case MemRegion::BlockTextRegionKind:
793 os << "block text";
794 return true;
795 case MemRegion::BlockDataRegionKind:
796 // FIXME: where the block came from?
797 os << "a block";
798 return true;
799 default: {
800 const MemSpaceRegion *MS = MR->getMemorySpace();
801
Anna Zakseb31a762012-01-04 23:54:01 +0000802 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000803 const VarRegion *VR = dyn_cast<VarRegion>(MR);
804 const VarDecl *VD;
805 if (VR)
806 VD = VR->getDecl();
807 else
808 VD = NULL;
809
810 if (VD)
811 os << "the address of the local variable '" << VD->getName() << "'";
812 else
813 os << "the address of a local stack variable";
814 return true;
815 }
Anna Zakseb31a762012-01-04 23:54:01 +0000816
817 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000818 const VarRegion *VR = dyn_cast<VarRegion>(MR);
819 const VarDecl *VD;
820 if (VR)
821 VD = VR->getDecl();
822 else
823 VD = NULL;
824
825 if (VD)
826 os << "the address of the parameter '" << VD->getName() << "'";
827 else
828 os << "the address of a parameter";
829 return true;
830 }
Anna Zakseb31a762012-01-04 23:54:01 +0000831
832 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000833 const VarRegion *VR = dyn_cast<VarRegion>(MR);
834 const VarDecl *VD;
835 if (VR)
836 VD = VR->getDecl();
837 else
838 VD = NULL;
839
840 if (VD) {
841 if (VD->isStaticLocal())
842 os << "the address of the static variable '" << VD->getName() << "'";
843 else
844 os << "the address of the global variable '" << VD->getName() << "'";
845 } else
846 os << "the address of a global variable";
847 return true;
848 }
Anna Zakseb31a762012-01-04 23:54:01 +0000849
850 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000851 }
852 }
853}
854
855void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000856 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000857 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000858 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000859 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000860
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000861 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000862 llvm::raw_svector_ostream os(buf);
863
864 const MemRegion *MR = ArgVal.getAsRegion();
865 if (MR) {
866 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
867 MR = ER->getSuperRegion();
868
869 // Special case for alloca()
870 if (isa<AllocaRegion>(MR))
871 os << "Argument to free() was allocated by alloca(), not malloc()";
872 else {
873 os << "Argument to free() is ";
874 if (SummarizeRegion(os, MR))
875 os << ", which is not memory allocated by malloc()";
876 else
877 os << "not memory allocated by malloc()";
878 }
879 } else {
880 os << "Argument to free() is ";
881 if (SummarizeValue(os, ArgVal))
882 os << ", which is not memory allocated by malloc()";
883 else
884 os << "not memory allocated by malloc()";
885 }
886
Anna Zakse172e8b2011-08-17 23:00:25 +0000887 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000888 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000889 R->addRange(range);
Jordan Rose785950e2012-11-02 01:53:40 +0000890 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +0000891 }
892}
893
Anna Zaks87cb5be2012-02-22 19:24:52 +0000894ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
895 const CallExpr *CE,
896 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000897 if (CE->getNumArgs() < 2)
898 return 0;
899
Ted Kremenek8bef8232012-01-26 21:29:00 +0000900 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000901 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000902 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000903 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
904 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000905 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000906 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000907
Ted Kremenek846eabd2010-12-01 21:28:31 +0000908 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000909
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000910 DefinedOrUnknownSVal PtrEQ =
911 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000912
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000913 // Get the size argument. If there is no size arg then give up.
914 const Expr *Arg1 = CE->getArg(1);
915 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000916 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000917
918 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000919 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
920 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000921 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000922 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000923
924 // Compare the size argument to 0.
925 DefinedOrUnknownSVal SizeZero =
926 svalBuilder.evalEQ(state, Arg1Val,
927 svalBuilder.makeIntValWithPtrWidth(0, false));
928
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000929 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
930 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
931 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
932 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
933 // We only assume exceptional states if they are definitely true; if the
934 // state is under-constrained, assume regular realloc behavior.
935 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
936 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
937
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000938 // If the ptr is NULL and the size is not 0, the call is equivalent to
939 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000940 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000941 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000942 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000943 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000944 }
945
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000946 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000947 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000948
Anna Zaks30838b92012-02-13 20:57:07 +0000949 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000950 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +0000951 SymbolRef FromPtr = arg0Val.getAsSymbol();
952 SVal RetVal = state->getSVal(CE, LCtx);
953 SymbolRef ToPtr = RetVal.getAsSymbol();
954 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000955 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000956
Anna Zaks55dd9562012-08-24 02:28:20 +0000957 bool ReleasedAllocated = false;
958
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000959 // If the size is 0, free the memory.
960 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +0000961 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
962 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000963 // The semantics of the return value are:
964 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +0000965 // to free() is returned. We just free the input pointer and do not add
966 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +0000967 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000968 }
969
970 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +0000971 if (ProgramStateRef stateFree =
972 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
973
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000974 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
975 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +0000976 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000977 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +0000978
Anna Zaks9dc298b2012-09-12 22:57:34 +0000979 ReallocPairKind Kind = RPToBeFreedAfterFailure;
980 if (FreesOnFail)
981 Kind = RPIsFreeOnFailure;
982 else if (!ReleasedAllocated)
983 Kind = RPDoNotTrackAfterFailure;
984
Anna Zaks55dd9562012-08-24 02:28:20 +0000985 // Record the info about the reallocated symbol so that we could properly
986 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +0000987 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +0000988 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +0000989 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +0000990 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000991 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000992 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000993 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000994}
Zhongxing Xu7b760962009-11-13 07:25:27 +0000995
Anna Zaks87cb5be2012-02-22 19:24:52 +0000996ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +0000997 if (CE->getNumArgs() < 2)
998 return 0;
999
Ted Kremenek8bef8232012-01-26 21:29:00 +00001000 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001001 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001002 const LocationContext *LCtx = C.getLocationContext();
1003 SVal count = state->getSVal(CE->getArg(0), LCtx);
1004 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001005 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1006 svalBuilder.getContext().getSizeType());
1007 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001008
Anna Zaks87cb5be2012-02-22 19:24:52 +00001009 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001010}
1011
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001012LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001013MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1014 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001015 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001016 // Walk the ExplodedGraph backwards and find the first node that referred to
1017 // the tracked symbol.
1018 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001019 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001020
1021 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001022 ProgramStateRef State = N->getState();
1023 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001024 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001025
1026 // Find the most recent expression bound to the symbol in the current
1027 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001028 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001029 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1030 SVal Val = State->getSVal(MR);
1031 if (Val.getAsLocSymbol() == Sym)
1032 ReferenceRegion = MR;
1033 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001034 }
1035
Anna Zaks7752d292012-02-27 23:40:55 +00001036 // Allocation node, is the last node in the current context in which the
1037 // symbol was tracked.
1038 if (N->getLocationContext() == LeakContext)
1039 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001040 N = N->pred_empty() ? NULL : *(N->pred_begin());
1041 }
1042
Anna Zaks97bfb552013-01-08 00:25:29 +00001043 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001044}
1045
Anna Zaksda046772012-02-11 21:02:40 +00001046void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1047 CheckerContext &C) const {
1048 assert(N);
1049 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001050 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001051 // Leaks should not be reported if they are post-dominated by a sink:
1052 // (1) Sinks are higher importance bugs.
1053 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1054 // with __noreturn functions such as assert() or exit(). We choose not
1055 // to report leaks on such paths.
1056 BT_Leak->setSuppressOnSink(true);
1057 }
1058
Anna Zaksca8e36e2012-02-23 21:38:21 +00001059 // Most bug reports are cached at the location where they occurred.
1060 // With leaks, we want to unique them by the location where they were
1061 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001062 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001063 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001064 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001065 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1066
1067 ProgramPoint P = AllocNode->getLocation();
1068 const Stmt *AllocationStmt = 0;
1069 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
1070 AllocationStmt = Exit->getCalleeContext()->getCallSite();
1071 else if (StmtPoint *SP = dyn_cast<StmtPoint>(&P))
1072 AllocationStmt = SP->getStmt();
1073 if (AllocationStmt)
1074 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1075 C.getSourceManager(),
1076 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001077
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001078 SmallString<200> buf;
1079 llvm::raw_svector_ostream os(buf);
1080 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001081 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001082 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001083 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001084 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001085 }
1086
Anna Zaks97bfb552013-01-08 00:25:29 +00001087 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1088 LocUsedForUniqueing,
1089 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001090 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001091 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001092 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001093}
1094
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001095void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1096 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001097{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001098 if (!SymReaper.hasDeadSymbols())
1099 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001100
Ted Kremenek8bef8232012-01-26 21:29:00 +00001101 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001102 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001103 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001104
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001105 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001106 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1107 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001108 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001109 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001110 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001111 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001112
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001113 }
1114 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001115
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001116 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001117 ReallocPairsTy RP = state->get<ReallocPairs>();
1118 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001119 if (SymReaper.isDead(I->first) ||
1120 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001121 state = state->remove<ReallocPairs>(I->first);
1122 }
1123 }
1124
Anna Zaks4141e4d2012-11-13 03:18:01 +00001125 // Cleanup the FreeReturnValue Map.
1126 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1127 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1128 if (SymReaper.isDead(I->first) ||
1129 SymReaper.isDead(I->second)) {
1130 state = state->remove<FreeReturnValue>(I->first);
1131 }
1132 }
1133
Anna Zaksca8e36e2012-02-23 21:38:21 +00001134 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001135 ExplodedNode *N = C.getPredecessor();
1136 if (!Errors.empty()) {
1137 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1138 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001139 for (SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001140 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001141 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001142 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001143 }
Anna Zaks54458702012-10-29 22:51:54 +00001144
Anna Zaksca8e36e2012-02-23 21:38:21 +00001145 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001146}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001147
Anna Zaks66c40402012-02-14 21:55:24 +00001148void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001149 // We will check for double free in the post visit.
1150 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001151 return;
1152
1153 // Check use after free, when a freed pointer is passed to a call.
1154 ProgramStateRef State = C.getState();
1155 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1156 E = CE->arg_end(); I != E; ++I) {
1157 const Expr *A = *I;
1158 if (A->getType().getTypePtr()->isAnyPointerType()) {
1159 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1160 if (!Sym)
1161 continue;
1162 if (checkUseAfterFree(Sym, C, A))
1163 return;
1164 }
1165 }
1166}
1167
Anna Zaks91c2a112012-02-08 23:16:56 +00001168void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1169 const Expr *E = S->getRetValue();
1170 if (!E)
1171 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001172
1173 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001174 ProgramStateRef State = C.getState();
1175 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001176 SymbolRef Sym = RetVal.getAsSymbol();
1177 if (!Sym)
1178 // If we are returning a field of the allocated struct or an array element,
1179 // the callee could still free the memory.
1180 // TODO: This logic should be a part of generic symbol escape callback.
1181 if (const MemRegion *MR = RetVal.getAsRegion())
1182 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1183 if (const SymbolicRegion *BMR =
1184 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1185 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001186
Anna Zaks0860cd02012-02-11 21:44:39 +00001187 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001188 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001189 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001190}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001191
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001192// TODO: Blocks should be either inlined or should call invalidate regions
1193// upon invocation. After that's in place, special casing here will not be
1194// needed.
1195void MallocChecker::checkPostStmt(const BlockExpr *BE,
1196 CheckerContext &C) const {
1197
1198 // Scan the BlockDecRefExprs for any object the retain count checker
1199 // may be tracking.
1200 if (!BE->getBlockDecl()->hasCaptures())
1201 return;
1202
1203 ProgramStateRef state = C.getState();
1204 const BlockDataRegion *R =
1205 cast<BlockDataRegion>(state->getSVal(BE,
1206 C.getLocationContext()).getAsRegion());
1207
1208 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1209 E = R->referenced_vars_end();
1210
1211 if (I == E)
1212 return;
1213
1214 SmallVector<const MemRegion*, 10> Regions;
1215 const LocationContext *LC = C.getLocationContext();
1216 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1217
1218 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001219 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001220 if (VR->getSuperRegion() == R) {
1221 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1222 }
1223 Regions.push_back(VR);
1224 }
1225
1226 state =
1227 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1228 Regions.data() + Regions.size()).getState();
1229 C.addTransition(state);
1230}
1231
Anna Zaks14345182012-05-18 01:16:10 +00001232bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001233 assert(Sym);
1234 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001235 return (RS && RS->isReleased());
1236}
1237
1238bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1239 const Stmt *S) const {
1240 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001241 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001242 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001243 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001244
Anna Zaksfebdc322012-02-16 22:26:12 +00001245 BugReport *R = new BugReport(*BT_UseFree,
1246 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001247 if (S)
1248 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001249 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001250 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +00001251 C.emitReport(R);
Anna Zaks91c2a112012-02-08 23:16:56 +00001252 return true;
1253 }
1254 }
1255 return false;
1256}
1257
Zhongxing Xuc8023782010-03-10 04:58:55 +00001258// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001259void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1260 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001261 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001262 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001263 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001264}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001265
Anna Zaks4fb54872012-02-11 21:02:35 +00001266// If a symbolic region is assumed to NULL (or another constant), stop tracking
1267// it - assuming that allocation failed on this path.
1268ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1269 SVal Cond,
1270 bool Assumption) const {
1271 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001272 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001273 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001274 ConstraintManager &CMgr = state->getConstraintManager();
1275 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1276 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001277 state = state->remove<RegionState>(I.getKey());
1278 }
1279
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001280 // Realloc returns 0 when reallocation fails, which means that we should
1281 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001282 ReallocPairsTy RP = state->get<ReallocPairs>();
1283 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001284 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001285 ConstraintManager &CMgr = state->getConstraintManager();
1286 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001287 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001288 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001289
Anna Zaks9dc298b2012-09-12 22:57:34 +00001290 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1291 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1292 if (RS->isReleased()) {
1293 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001294 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001295 RefState::getAllocated(RS->getStmt()));
1296 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1297 state = state->remove<RegionState>(ReallocSym);
1298 else
1299 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001300 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001301 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001302 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001303 }
1304
Anna Zaks4fb54872012-02-11 21:02:35 +00001305 return state;
1306}
1307
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001308// Check if the function is known to us. So, for example, we could
Jordan Rose740d4902012-07-02 19:27:35 +00001309// conservatively assume it can free/reallocate its pointer arguments.
Anna Zaks66c40402012-02-14 21:55:24 +00001310// (We assume that the pointers cannot escape through calls to system
1311// functions not handled by this checker.)
Jordan Rose740d4902012-07-02 19:27:35 +00001312bool MallocChecker::doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001313 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001314 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001315
1316 // For now, assume that any C++ call can free memory.
1317 // TODO: If we want to be more optimistic here, we'll need to make sure that
1318 // regions escape to C++ containers. They seem to do that even now, but for
1319 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001320 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001321 return false;
1322
Jordan Rose740d4902012-07-02 19:27:35 +00001323 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001324 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001325 // If it's not a framework call, or if it takes a callback, assume it
1326 // can free memory.
1327 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001328 return false;
1329
Jordan Rose740d4902012-07-02 19:27:35 +00001330 Selector S = Msg->getSelector();
Anna Zaks52a04812012-06-20 23:35:57 +00001331
Jordan Rose740d4902012-07-02 19:27:35 +00001332 // Whitelist the ObjC methods which do free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001333 // - Anything containing 'freeWhenDone' param set to 1.
1334 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
Anna Zaks3e4f65d2012-06-22 22:08:09 +00001335 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001336 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1337 if (Call->getArgSVal(i).isConstant(1))
1338 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001339 else
1340 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001341 }
1342 }
1343
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001344 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001345 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001346 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
Jordan Rose740d4902012-07-02 19:27:35 +00001347 StringRef FirstSlot = S.getNameForSlot(0);
1348 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001349 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001350
Anna Zaks5f757682012-06-19 05:10:32 +00001351 // If the first selector starts with addPointer, insertPointer,
1352 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1353 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001354 // that the pointers get freed by following the container itself.
1355 if (FirstSlot.startswith("addPointer") ||
1356 FirstSlot.startswith("insertPointer") ||
1357 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001358 return false;
1359 }
1360
Jordan Rose740d4902012-07-02 19:27:35 +00001361 // Otherwise, assume that the method does not free memory.
1362 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001363 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001364 }
1365
Jordan Rose740d4902012-07-02 19:27:35 +00001366 // At this point the only thing left to handle is straight function calls.
1367 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1368 if (!FD)
1369 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001370
Jordan Rose740d4902012-07-02 19:27:35 +00001371 ASTContext &ASTC = State->getStateManager().getContext();
1372
1373 // If it's one of the allocation functions we can reason about, we model
1374 // its behavior explicitly.
1375 if (isMemFunction(FD, ASTC))
1376 return true;
1377
1378 // If it's not a system call, assume it frees memory.
1379 if (!Call->isInSystemHeader())
1380 return false;
1381
1382 // White list the system functions whose arguments escape.
1383 const IdentifierInfo *II = FD->getIdentifier();
1384 if (!II)
1385 return false;
1386 StringRef FName = II->getName();
1387
Jordan Rose740d4902012-07-02 19:27:35 +00001388 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001389 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001390 if (FName.endswith("NoCopy")) {
1391 // Look for the deallocator argument. We know that the memory ownership
1392 // is not transferred only if the deallocator argument is
1393 // 'kCFAllocatorNull'.
1394 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1395 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1396 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1397 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1398 if (DeallocatorName == "kCFAllocatorNull")
1399 return true;
1400 }
1401 }
1402 return false;
1403 }
1404
Jordan Rose740d4902012-07-02 19:27:35 +00001405 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001406 // 'closefn' is specified (and if that function does free memory),
1407 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001408 // Currently, we do not inspect the 'closefn' function (PR12101).
1409 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001410 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1411 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001412
1413 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1414 // these leaks might be intentional when setting the buffer for stdio.
1415 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1416 if (FName == "setbuf" || FName =="setbuffer" ||
1417 FName == "setlinebuf" || FName == "setvbuf") {
1418 if (Call->getNumArgs() >= 1) {
1419 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1420 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1421 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1422 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1423 return false;
1424 }
1425 }
1426
1427 // A bunch of other functions which either take ownership of a pointer or
1428 // wrap the result up in a struct or object, meaning it can be freed later.
1429 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1430 // but the Malloc checker cannot differentiate between them. The right way
1431 // of doing this would be to implement a pointer escapes callback.
1432 if (FName == "CGBitmapContextCreate" ||
1433 FName == "CGBitmapContextCreateWithData" ||
1434 FName == "CVPixelBufferCreateWithBytes" ||
1435 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1436 FName == "OSAtomicEnqueue") {
1437 return false;
1438 }
1439
Jordan Rose85d7e012012-07-02 19:27:51 +00001440 // Handle cases where we know a buffer's /address/ can escape.
1441 // Note that the above checks handle some special cases where we know that
1442 // even though the address escapes, it's still our responsibility to free the
1443 // buffer.
1444 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001445 return false;
1446
1447 // Otherwise, assume that the function does not free memory.
1448 // Most system calls do not free the memory.
1449 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001450}
1451
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001452ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1453 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00001454 const CallEvent *Call,
1455 PointerEscapeKind Kind) const {
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001456 // If we know that the call does not free memory, keep tracking the top
1457 // level arguments.
Anna Zaks233e26a2013-02-07 23:05:43 +00001458 if ((Kind == PSK_DirectEscapeOnCall ||
1459 Kind == PSK_IndirectEscapeOnCall) &&
1460 doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001461 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00001462 }
Anna Zaks66c40402012-02-14 21:55:24 +00001463
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001464 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
1465 E = Escaped.end();
1466 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001467 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001468
Anna Zaks5b7aa342012-06-22 02:04:31 +00001469 if (const RefState *RS = State->get<RegionState>(sym)) {
1470 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001471 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001472 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001473 }
Anna Zaks66c40402012-02-14 21:55:24 +00001474 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001475}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001476
Jordy Rose393f98b2012-03-18 07:43:35 +00001477static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1478 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001479 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1480 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001481
Jordan Rose166d5022012-11-02 01:54:06 +00001482 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001483 I != E; ++I) {
1484 SymbolRef sym = I.getKey();
1485 if (!currMap.lookup(sym))
1486 return sym;
1487 }
1488
1489 return NULL;
1490}
1491
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001492PathDiagnosticPiece *
1493MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1494 const ExplodedNode *PrevN,
1495 BugReporterContext &BRC,
1496 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001497 ProgramStateRef state = N->getState();
1498 ProgramStateRef statePrev = PrevN->getState();
1499
1500 const RefState *RS = state->get<RegionState>(Sym);
1501 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001502 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001503 return 0;
1504
Anna Zaksfe571602012-02-16 22:26:07 +00001505 const Stmt *S = 0;
1506 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001507 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001508
1509 // Retrieve the associated statement.
1510 ProgramPoint ProgLoc = N->getLocation();
Ted Kremeneka4a17592013-01-04 19:04:36 +00001511 if (StmtPoint *SP = dyn_cast<StmtPoint>(&ProgLoc)) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001512 S = SP->getStmt();
Ted Kremeneka4a17592013-01-04 19:04:36 +00001513 } else if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&ProgLoc)) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001514 S = Exit->getCalleeContext()->getCallSite();
Ted Kremeneka4a17592013-01-04 19:04:36 +00001515 } else if (BlockEdge *Edge = dyn_cast<BlockEdge>(&ProgLoc)) {
1516 // If an assumption was made on a branch, it should be caught
1517 // here by looking at the state transition.
1518 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00001519 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00001520
Anna Zaksfe571602012-02-16 22:26:07 +00001521 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001522 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001523
Jordan Rose28038f32012-07-10 22:07:42 +00001524 // FIXME: We will eventually need to handle non-statement-based events
1525 // (__attribute__((cleanup))).
1526
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001527 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001528 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001529 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001530 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001531 StackHint = new StackHintGeneratorForSymbol(Sym,
1532 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001533 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001534 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001535 StackHint = new StackHintGeneratorForSymbol(Sym,
1536 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001537 } else if (isRelinquished(RS, RSPrev, S)) {
1538 Msg = "Memory ownership is transfered";
1539 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001540 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001541 Mode = ReallocationFailed;
1542 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001543 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001544 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001545
Jordy Roseb000fb52012-03-24 03:15:09 +00001546 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1547 // Is it possible to fail two reallocs WITHOUT testing in between?
1548 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1549 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001550 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001551 FailedReallocSymbol = sym;
1552 }
Anna Zaksfe571602012-02-16 22:26:07 +00001553 }
1554
1555 // We are in a special mode if a reallocation failed later in the path.
1556 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001557 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001558
Jordy Roseb000fb52012-03-24 03:15:09 +00001559 // Is this is the first appearance of the reallocated symbol?
1560 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001561 // We're at the reallocation point.
1562 Msg = "Attempt to reallocate memory";
1563 StackHint = new StackHintGeneratorForSymbol(Sym,
1564 "Returned reallocated memory");
1565 FailedReallocSymbol = NULL;
1566 Mode = Normal;
1567 }
Anna Zaksfe571602012-02-16 22:26:07 +00001568 }
1569
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001570 if (!Msg)
1571 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001572 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001573
1574 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001575 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001576 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001577 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001578}
1579
Anna Zaks93c5a242012-05-02 00:05:20 +00001580void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1581 const char *NL, const char *Sep) const {
1582
1583 RegionStateTy RS = State->get<RegionState>();
1584
Ted Kremenekc37fad62013-01-03 01:30:12 +00001585 if (!RS.isEmpty()) {
1586 Out << Sep << "MallocChecker:" << NL;
1587 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1588 I.getKey()->dumpToStream(Out);
1589 Out << " : ";
1590 I.getData().dump(Out);
1591 Out << NL;
1592 }
1593 }
Anna Zaks93c5a242012-05-02 00:05:20 +00001594}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001595
Anna Zaks231361a2012-02-08 23:16:52 +00001596#define REGISTER_CHECKER(name) \
1597void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001598 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001599 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001600}
Anna Zaks231361a2012-02-08 23:16:52 +00001601
1602REGISTER_CHECKER(MallocPessimistic)
1603REGISTER_CHECKER(MallocOptimistic)