blob: 2242b21efb6f91268ef0d74de0d04aa7748d64d4 [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 Zaks118aa752013-02-07 23:05:47 +0000132 mutable OwningPtr<BugType> BT_OffsetFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000133 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000134 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
135
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000136public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000137 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000138 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000139
140 /// In pessimistic mode, the checker assumes that it does not know which
141 /// functions might free the memory.
142 struct ChecksFilter {
143 DefaultBool CMallocPessimistic;
144 DefaultBool CMallocOptimistic;
145 };
146
147 ChecksFilter Filter;
148
Anna Zaks66c40402012-02-14 21:55:24 +0000149 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000150 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000151 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000152 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000153 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000154 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000155 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000156 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000157 void checkLocation(SVal l, bool isLoad, const Stmt *S,
158 CheckerContext &C) const;
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000159
160 ProgramStateRef checkPointerEscape(ProgramStateRef State,
161 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +0000162 const CallEvent *Call,
163 PointerEscapeKind Kind) const;
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000164
Anna Zaks93c5a242012-05-02 00:05:20 +0000165 void printState(raw_ostream &Out, ProgramStateRef State,
166 const char *NL, const char *Sep) const;
167
Zhongxing Xu7b760962009-11-13 07:25:27 +0000168private:
Anna Zaks66c40402012-02-14 21:55:24 +0000169 void initIdentifierInfo(ASTContext &C) const;
170
171 /// Check if this is one of the functions which can allocate/reallocate memory
172 /// pointed to by one of its arguments.
173 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000174 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
175 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000176
Anna Zaks87cb5be2012-02-22 19:24:52 +0000177 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
178 const CallExpr *CE,
179 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000180 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000181 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000182 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000183 return MallocMemAux(C, CE,
184 state->getSVal(SizeEx, C.getLocationContext()),
185 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000186 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000187
Ted Kremenek8bef8232012-01-26 21:29:00 +0000188 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000189 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000190 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000191
Anna Zaks87cb5be2012-02-22 19:24:52 +0000192 /// Update the RefState to reflect the new memory allocation.
193 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
194 const CallExpr *CE,
195 ProgramStateRef state);
196
197 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
198 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000199 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000200 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000201 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000202 bool &ReleasedAllocated,
203 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000204 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
205 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000206 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000207 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000208 bool &ReleasedAllocated,
209 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000210
Anna Zaks87cb5be2012-02-22 19:24:52 +0000211 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
212 bool FreesMemOnFailure) const;
213 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000214
Anna Zaks14345182012-05-18 01:16:10 +0000215 ///\brief Check if the memory associated with this symbol was released.
216 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
217
Anna Zaks91c2a112012-02-08 23:16:56 +0000218 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
219 const Stmt *S = 0) const;
220
Anna Zaks66c40402012-02-14 21:55:24 +0000221 /// Check if the function is not known to us. So, for example, we could
222 /// conservatively assume it can free/reallocate it's pointer arguments.
Jordan Rose740d4902012-07-02 19:27:35 +0000223 bool doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +0000224 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000225
Ted Kremenek9c378f72011-08-12 23:37:29 +0000226 static bool SummarizeValue(raw_ostream &os, SVal V);
227 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000228 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaks118aa752013-02-07 23:05:47 +0000229 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range)const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000230
Anna Zaksca8e36e2012-02-23 21:38:21 +0000231 /// Find the location of the allocation for Sym on the path leading to the
232 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000233 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
234 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000235
Anna Zaksda046772012-02-11 21:02:40 +0000236 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
237
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000238 /// The bug visitor which allows us to print extra diagnostics along the
239 /// BugReport path. For example, showing the allocation site of the leaked
240 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000241 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000242 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000243 enum NotificationMode {
244 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000245 ReallocationFailed
246 };
247
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000248 // The allocated region symbol tracked by the main analysis.
249 SymbolRef Sym;
250
Anna Zaks88feba02012-05-10 01:37:40 +0000251 // The mode we are in, i.e. what kind of diagnostics will be emitted.
252 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000253
Anna Zaks88feba02012-05-10 01:37:40 +0000254 // A symbol from when the primary region should have been reallocated.
255 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000256
Anna Zaks88feba02012-05-10 01:37:40 +0000257 bool IsLeak;
258
259 public:
260 MallocBugVisitor(SymbolRef S, bool isLeak = false)
261 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000262
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000263 virtual ~MallocBugVisitor() {}
264
265 void Profile(llvm::FoldingSetNodeID &ID) const {
266 static int X = 0;
267 ID.AddPointer(&X);
268 ID.AddPointer(Sym);
269 }
270
Anna Zaksfe571602012-02-16 22:26:07 +0000271 inline bool isAllocated(const RefState *S, const RefState *SPrev,
272 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000273 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000274 return (Stmt && isa<CallExpr>(Stmt) &&
275 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000276 }
277
Anna Zaksfe571602012-02-16 22:26:07 +0000278 inline bool isReleased(const RefState *S, const RefState *SPrev,
279 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000280 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000281 return (Stmt && isa<CallExpr>(Stmt) &&
282 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
283 }
284
Anna Zaks5b7aa342012-06-22 02:04:31 +0000285 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
286 const Stmt *Stmt) {
287 // Did not track -> relinquished. Other state (allocated) -> relinquished.
288 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
289 isa<ObjCPropertyRefExpr>(Stmt)) &&
290 (S && S->isRelinquished()) &&
291 (!SPrev || !SPrev->isRelinquished()));
292 }
293
Anna Zaksfe571602012-02-16 22:26:07 +0000294 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
295 const Stmt *Stmt) {
296 // If the expression is not a call, and the state change is
297 // released -> allocated, it must be the realloc return value
298 // check. If we have to handle more cases here, it might be cleaner just
299 // to track this extra bit in the state itself.
300 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
301 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000302 }
303
304 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
305 const ExplodedNode *PrevN,
306 BugReporterContext &BRC,
307 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000308
309 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
310 const ExplodedNode *EndPathNode,
311 BugReport &BR) {
312 if (!IsLeak)
313 return 0;
314
315 PathDiagnosticLocation L =
316 PathDiagnosticLocation::createEndOfPath(EndPathNode,
317 BRC.getSourceManager());
318 // Do not add the statement itself as a range in case of leak.
319 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
320 }
321
Anna Zaks56a938f2012-03-16 23:24:20 +0000322 private:
323 class StackHintGeneratorForReallocationFailed
324 : public StackHintGeneratorForSymbol {
325 public:
326 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
327 : StackHintGeneratorForSymbol(S, M) {}
328
329 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000330 // Printed parameters start at 1, not 0.
331 ++ArgIndex;
332
Anna Zaks56a938f2012-03-16 23:24:20 +0000333 SmallString<200> buf;
334 llvm::raw_svector_ostream os(buf);
335
Jordan Rose615a0922012-09-22 01:24:42 +0000336 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
337 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000338
339 return os.str();
340 }
341
342 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000343 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000344 }
345 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000346 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000347};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000348} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000349
Jordan Rose166d5022012-11-02 01:54:06 +0000350REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
351REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000352
Anna Zaks4141e4d2012-11-13 03:18:01 +0000353// A map from the freed symbol to the symbol representing the return value of
354// the free function.
355REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
356
Anna Zaks4fb54872012-02-11 21:02:35 +0000357namespace {
358class StopTrackingCallback : public SymbolVisitor {
359 ProgramStateRef state;
360public:
361 StopTrackingCallback(ProgramStateRef st) : state(st) {}
362 ProgramStateRef getState() const { return state; }
363
364 bool VisitSymbol(SymbolRef sym) {
365 state = state->remove<RegionState>(sym);
366 return true;
367 }
368};
369} // end anonymous namespace
370
Anna Zaks66c40402012-02-14 21:55:24 +0000371void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000372 if (II_malloc)
373 return;
374 II_malloc = &Ctx.Idents.get("malloc");
375 II_free = &Ctx.Idents.get("free");
376 II_realloc = &Ctx.Idents.get("realloc");
377 II_reallocf = &Ctx.Idents.get("reallocf");
378 II_calloc = &Ctx.Idents.get("calloc");
379 II_valloc = &Ctx.Idents.get("valloc");
380 II_strdup = &Ctx.Idents.get("strdup");
381 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000382}
383
Anna Zaks66c40402012-02-14 21:55:24 +0000384bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000385 if (isFreeFunction(FD, C))
386 return true;
387
388 if (isAllocationFunction(FD, C))
389 return true;
390
391 return false;
392}
393
394bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
395 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000396 if (!FD)
397 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000398
Jordan Rose5ef6e942012-07-10 23:13:01 +0000399 if (FD->getKind() == Decl::Function) {
400 IdentifierInfo *FunI = FD->getIdentifier();
401 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000402
Jordan Rose5ef6e942012-07-10 23:13:01 +0000403 if (FunI == II_malloc || FunI == II_realloc ||
404 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
405 FunI == II_strdup || FunI == II_strndup)
406 return true;
407 }
Anna Zaks66c40402012-02-14 21:55:24 +0000408
Anna Zaks14345182012-05-18 01:16:10 +0000409 if (Filter.CMallocOptimistic && FD->hasAttrs())
410 for (specific_attr_iterator<OwnershipAttr>
411 i = FD->specific_attr_begin<OwnershipAttr>(),
412 e = FD->specific_attr_end<OwnershipAttr>();
413 i != e; ++i)
414 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
415 return true;
416 return false;
417}
418
419bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
420 if (!FD)
421 return false;
422
Jordan Rose5ef6e942012-07-10 23:13:01 +0000423 if (FD->getKind() == Decl::Function) {
424 IdentifierInfo *FunI = FD->getIdentifier();
425 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000426
Jordan Rose5ef6e942012-07-10 23:13:01 +0000427 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
428 return true;
429 }
Anna Zaks66c40402012-02-14 21:55:24 +0000430
Anna Zaks14345182012-05-18 01:16:10 +0000431 if (Filter.CMallocOptimistic && FD->hasAttrs())
432 for (specific_attr_iterator<OwnershipAttr>
433 i = FD->specific_attr_begin<OwnershipAttr>(),
434 e = FD->specific_attr_end<OwnershipAttr>();
435 i != e; ++i)
436 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
437 (*i)->getOwnKind() == OwnershipAttr::Holds)
438 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000439 return false;
440}
441
Anna Zaksb319e022012-02-08 20:13:28 +0000442void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000443 if (C.wasInlined)
444 return;
445
Anna Zaksb319e022012-02-08 20:13:28 +0000446 const FunctionDecl *FD = C.getCalleeDecl(CE);
447 if (!FD)
448 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000449
Anna Zaks87cb5be2012-02-22 19:24:52 +0000450 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000451 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000452
453 if (FD->getKind() == Decl::Function) {
454 initIdentifierInfo(C.getASTContext());
455 IdentifierInfo *FunI = FD->getIdentifier();
456
457 if (FunI == II_malloc || FunI == II_valloc) {
458 if (CE->getNumArgs() < 1)
459 return;
460 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
461 } else if (FunI == II_realloc) {
462 State = ReallocMem(C, CE, false);
463 } else if (FunI == II_reallocf) {
464 State = ReallocMem(C, CE, true);
465 } else if (FunI == II_calloc) {
466 State = CallocMem(C, CE);
467 } else if (FunI == II_free) {
Anna Zaks55dd9562012-08-24 02:28:20 +0000468 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose5ef6e942012-07-10 23:13:01 +0000469 } else if (FunI == II_strdup) {
470 State = MallocUpdateRefState(C, CE, State);
471 } else if (FunI == II_strndup) {
472 State = MallocUpdateRefState(C, CE, State);
473 }
474 }
475
476 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000477 // Check all the attributes, if there are any.
478 // There can be multiple of these attributes.
479 if (FD->hasAttrs())
480 for (specific_attr_iterator<OwnershipAttr>
481 i = FD->specific_attr_begin<OwnershipAttr>(),
482 e = FD->specific_attr_end<OwnershipAttr>();
483 i != e; ++i) {
484 switch ((*i)->getOwnKind()) {
485 case OwnershipAttr::Returns:
486 State = MallocMemReturnsAttr(C, CE, *i);
487 break;
488 case OwnershipAttr::Takes:
489 case OwnershipAttr::Holds:
490 State = FreeMemAttr(C, CE, *i);
491 break;
492 }
493 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000494 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000495 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000496}
497
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000498static bool isFreeWhenDoneSetToZero(const ObjCMethodCall &Call) {
499 Selector S = Call.getSelector();
Anna Zaks3e4f65d2012-06-22 22:08:09 +0000500 for (unsigned i = 1; i < S.getNumArgs(); ++i)
Anna Zaks5b7aa342012-06-22 02:04:31 +0000501 if (S.getNameForSlot(i).equals("freeWhenDone"))
502 if (Call.getArgSVal(i).isConstant(0))
503 return true;
504
505 return false;
506}
507
Anna Zaks4141e4d2012-11-13 03:18:01 +0000508void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
509 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000510 if (C.wasInlined)
511 return;
512
Anna Zaks5b7aa342012-06-22 02:04:31 +0000513 // If the first selector is dataWithBytesNoCopy, assume that the memory will
514 // be released with 'free' by the new object.
515 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
516 // Unless 'freeWhenDone' param set to 0.
517 // TODO: Check that the memory was allocated with malloc.
Anna Zaks55dd9562012-08-24 02:28:20 +0000518 bool ReleasedAllocatedMemory = false;
Jordan Rosede507ea2012-07-02 19:28:04 +0000519 Selector S = Call.getSelector();
Anna Zaks7186dc62012-06-22 22:42:30 +0000520 if ((S.getNameForSlot(0) == "dataWithBytesNoCopy" ||
521 S.getNameForSlot(0) == "initWithBytesNoCopy" ||
522 S.getNameForSlot(0) == "initWithCharactersNoCopy") &&
Jordan Rosecde8cdb2012-07-02 19:27:56 +0000523 !isFreeWhenDoneSetToZero(Call)){
Anna Zaks5b7aa342012-06-22 02:04:31 +0000524 unsigned int argIdx = 0;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000525 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(argIdx),
526 Call.getOriginExpr(), C.getState(), true,
527 ReleasedAllocatedMemory,
528 /* RetNullOnFailure*/ true);
529
530 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000531 }
532}
533
Anna Zaks87cb5be2012-02-22 19:24:52 +0000534ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
535 const CallExpr *CE,
536 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000537 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000538 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000539
Sean Huntcf807c42010-08-18 23:23:40 +0000540 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000541 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000542 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000543 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000544 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000545}
546
Anna Zaksb319e022012-02-08 20:13:28 +0000547ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000548 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000549 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000550 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000551
552 // Bind the return value to the symbolic value from the heap region.
553 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
554 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000555 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000556 SValBuilder &svalBuilder = C.getSValBuilder();
557 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
558 DefinedSVal RetVal =
559 cast<DefinedSVal>(svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count));
560 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000561
Anna Zaksb16ce452012-02-15 00:11:22 +0000562 // We expect the malloc functions to return a pointer.
Anna Zakse17fdb22012-06-07 03:57:32 +0000563 if (!isa<Loc>(RetVal))
Anna Zaksb16ce452012-02-15 00:11:22 +0000564 return 0;
565
Jordy Rose32f26562010-07-04 00:00:41 +0000566 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000567 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000568
Jordy Rose32f26562010-07-04 00:00:41 +0000569 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000570 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000571 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000572 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000573 return 0;
Anna Zaks60a1fa42012-02-22 03:14:20 +0000574 if (isa<DefinedOrUnknownSVal>(Size)) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000575 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000576 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
577 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size);
578 DefinedOrUnknownSVal extentMatchesSize =
579 svalBuilder.evalEQ(state, Extent, DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000580
Anna Zaks60a1fa42012-02-22 03:14:20 +0000581 state = state->assume(extentMatchesSize, true);
582 assert(state);
583 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000584
Anna Zaks87cb5be2012-02-22 19:24:52 +0000585 return MallocUpdateRefState(C, CE, state);
586}
587
588ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
589 const CallExpr *CE,
590 ProgramStateRef state) {
591 // Get the return value.
592 SVal retVal = state->getSVal(CE, C.getLocationContext());
593
594 // We expect the malloc functions to return a pointer.
595 if (!isa<Loc>(retVal))
596 return 0;
597
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000598 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000599 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000600
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000601 // Set the symbol's state to Allocated.
Anna Zaks050cdd72012-06-20 20:57:46 +0000602 return state->set<RegionState>(Sym, RefState::getAllocated(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000603
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000604}
605
Anna Zaks87cb5be2012-02-22 19:24:52 +0000606ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
607 const CallExpr *CE,
608 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000609 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000610 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000611
Anna Zaksb3d72752012-03-01 22:06:06 +0000612 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000613 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000614
Sean Huntcf807c42010-08-18 23:23:40 +0000615 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
616 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000617 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000618 Att->getOwnKind() == OwnershipAttr::Holds,
619 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000620 if (StateI)
621 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000622 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000623 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000624}
625
Ted Kremenek8bef8232012-01-26 21:29:00 +0000626ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000627 const CallExpr *CE,
628 ProgramStateRef state,
629 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000630 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000631 bool &ReleasedAllocated,
632 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000633 if (CE->getNumArgs() < (Num + 1))
634 return 0;
635
Anna Zaks4141e4d2012-11-13 03:18:01 +0000636 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
637 ReleasedAllocated, ReturnsNullOnFailure);
638}
639
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000640/// Checks if the previous call to free on the given symbol failed - if free
641/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000642static bool didPreviousFreeFail(ProgramStateRef State,
643 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000644 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000645 if (Ret) {
646 assert(*Ret && "We should not store the null return symbol");
647 ConstraintManager &CMgr = State->getConstraintManager();
648 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000649 RetStatusSymbol = *Ret;
650 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000651 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000652 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000653}
654
655ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
656 const Expr *ArgExpr,
657 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000658 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000659 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000660 bool &ReleasedAllocated,
661 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000662
Anna Zaks4141e4d2012-11-13 03:18:01 +0000663 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zakse9ef5622012-02-10 01:11:00 +0000664 if (!isa<DefinedOrUnknownSVal>(ArgVal))
665 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000666 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal);
667
668 // Check for null dereferences.
669 if (!isa<Loc>(location))
Anna Zaksb319e022012-02-08 20:13:28 +0000670 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000671
Anna Zaksb276bd92012-02-14 00:26:13 +0000672 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000673 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000674 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000675 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000676 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000677
Jordy Rose43859f62010-06-07 19:32:37 +0000678 // Unknown values could easily be okay
679 // Undefined values are handled elsewhere
680 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000681 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000682
Jordy Rose43859f62010-06-07 19:32:37 +0000683 const MemRegion *R = ArgVal.getAsRegion();
684
685 // Nonlocs can't be freed, of course.
686 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
687 if (!R) {
688 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000689 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000690 }
691
692 R = R->StripCasts();
693
694 // Blocks might show up as heap data, but should not be free()d
695 if (isa<BlockDataRegion>(R)) {
696 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000697 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000698 }
699
700 const MemSpaceRegion *MS = R->getMemorySpace();
701
702 // Parameters, locals, statics, and globals shouldn't be freed.
703 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
704 // FIXME: at the time this code was written, malloc() regions were
705 // represented by conjured symbols, which are all in UnknownSpaceRegion.
706 // This means that there isn't actually anything from HeapSpaceRegion
707 // that should be freed, even though we allow it here.
708 // Of course, free() can work on memory allocated outside the current
709 // function, so UnknownSpaceRegion is always a possibility.
710 // False negatives are better than false positives.
711
712 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000713 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000714 }
Anna Zaks118aa752013-02-07 23:05:47 +0000715
716 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose43859f62010-06-07 19:32:37 +0000717 // Various cases could lead to non-symbol values here.
718 // For now, ignore them.
Anna Zaks118aa752013-02-07 23:05:47 +0000719 if (!SrBase)
Anna Zaksb319e022012-02-08 20:13:28 +0000720 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000721
Anna Zaks118aa752013-02-07 23:05:47 +0000722 SymbolRef SymBase = SrBase->getSymbol();
723 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000724 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000725
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000726 // Check double free.
Anna Zaks118aa752013-02-07 23:05:47 +0000727 if (RsBase &&
728 (RsBase->isReleased() || RsBase->isRelinquished()) &&
729 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
Anna Zaks4141e4d2012-11-13 03:18:01 +0000730
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000731 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000732 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000733 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000734 new BugType("Double free", "Memory Error"));
Anna Zaks118aa752013-02-07 23:05:47 +0000735 BugReport *R = new BugReport(*BT_DoubleFree,
736 (RsBase->isReleased() ? "Attempt to free released memory"
737 : "Attempt to free non-owned memory"),
738 N);
Anna Zaksfe571602012-02-16 22:26:07 +0000739 R->addRange(ArgExpr->getSourceRange());
Anna Zaks118aa752013-02-07 23:05:47 +0000740 R->markInteresting(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000741 if (PreviousRetStatusSymbol)
742 R->markInteresting(PreviousRetStatusSymbol);
Anna Zaks118aa752013-02-07 23:05:47 +0000743 R->addVisitor(new MallocBugVisitor(SymBase));
Jordan Rose785950e2012-11-02 01:53:40 +0000744 C.emitReport(R);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000745 }
Anna Zaksb319e022012-02-08 20:13:28 +0000746 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000747 }
748
Anna Zaks118aa752013-02-07 23:05:47 +0000749 // Check if the memory location being freed is the actual location
750 // allocated, or an offset.
751 RegionOffset Offset = R->getAsOffset();
752 if (RsBase && RsBase->isAllocated() &&
753 Offset.isValid() &&
754 !Offset.hasSymbolicOffset() &&
755 Offset.getOffset() != 0) {
756 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange());
757 return 0;
758 }
759
760 ReleasedAllocated = (RsBase != 0);
Anna Zaks55dd9562012-08-24 02:28:20 +0000761
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000762 // Clean out the info on previous call to free return info.
Anna Zaks118aa752013-02-07 23:05:47 +0000763 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000764
Anna Zaks4141e4d2012-11-13 03:18:01 +0000765 // Keep track of the return value. If it is NULL, we will know that free
766 // failed.
767 if (ReturnsNullOnFailure) {
768 SVal RetVal = C.getSVal(ParentExpr);
769 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
770 if (RetStatusSymbol) {
Anna Zaks118aa752013-02-07 23:05:47 +0000771 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
772 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000773 }
774 }
775
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000776 // Normal free.
Anna Zaks118aa752013-02-07 23:05:47 +0000777 if (Hold) {
778 return State->set<RegionState>(SymBase,
779 RefState::getRelinquished(ParentExpr));
780 }
781 return State->set<RegionState>(SymBase, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000782}
783
Ted Kremenek9c378f72011-08-12 23:37:29 +0000784bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
Jordy Rose43859f62010-06-07 19:32:37 +0000785 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V))
786 os << "an integer (" << IntVal->getValue() << ")";
787 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V))
788 os << "a constant address (" << ConstAddr->getValue() << ")";
789 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V))
Chris Lattner68106302011-02-17 05:38:27 +0000790 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000791 else
792 return false;
793
794 return true;
795}
796
Ted Kremenek9c378f72011-08-12 23:37:29 +0000797bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000798 const MemRegion *MR) {
799 switch (MR->getKind()) {
800 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000801 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +0000802 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000803 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000804 else
805 os << "the address of a function";
806 return true;
807 }
808 case MemRegion::BlockTextRegionKind:
809 os << "block text";
810 return true;
811 case MemRegion::BlockDataRegionKind:
812 // FIXME: where the block came from?
813 os << "a block";
814 return true;
815 default: {
816 const MemSpaceRegion *MS = MR->getMemorySpace();
817
Anna Zakseb31a762012-01-04 23:54:01 +0000818 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000819 const VarRegion *VR = dyn_cast<VarRegion>(MR);
820 const VarDecl *VD;
821 if (VR)
822 VD = VR->getDecl();
823 else
824 VD = NULL;
825
826 if (VD)
827 os << "the address of the local variable '" << VD->getName() << "'";
828 else
829 os << "the address of a local stack variable";
830 return true;
831 }
Anna Zakseb31a762012-01-04 23:54:01 +0000832
833 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000834 const VarRegion *VR = dyn_cast<VarRegion>(MR);
835 const VarDecl *VD;
836 if (VR)
837 VD = VR->getDecl();
838 else
839 VD = NULL;
840
841 if (VD)
842 os << "the address of the parameter '" << VD->getName() << "'";
843 else
844 os << "the address of a parameter";
845 return true;
846 }
Anna Zakseb31a762012-01-04 23:54:01 +0000847
848 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000849 const VarRegion *VR = dyn_cast<VarRegion>(MR);
850 const VarDecl *VD;
851 if (VR)
852 VD = VR->getDecl();
853 else
854 VD = NULL;
855
856 if (VD) {
857 if (VD->isStaticLocal())
858 os << "the address of the static variable '" << VD->getName() << "'";
859 else
860 os << "the address of the global variable '" << VD->getName() << "'";
861 } else
862 os << "the address of a global variable";
863 return true;
864 }
Anna Zakseb31a762012-01-04 23:54:01 +0000865
866 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000867 }
868 }
869}
870
871void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000872 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000873 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000874 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000875 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000876
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000877 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000878 llvm::raw_svector_ostream os(buf);
879
880 const MemRegion *MR = ArgVal.getAsRegion();
881 if (MR) {
882 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
883 MR = ER->getSuperRegion();
884
885 // Special case for alloca()
886 if (isa<AllocaRegion>(MR))
887 os << "Argument to free() was allocated by alloca(), not malloc()";
888 else {
889 os << "Argument to free() is ";
890 if (SummarizeRegion(os, MR))
891 os << ", which is not memory allocated by malloc()";
892 else
893 os << "not memory allocated by malloc()";
894 }
895 } else {
896 os << "Argument to free() is ";
897 if (SummarizeValue(os, ArgVal))
898 os << ", which is not memory allocated by malloc()";
899 else
900 os << "not memory allocated by malloc()";
901 }
902
Anna Zakse172e8b2011-08-17 23:00:25 +0000903 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000904 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000905 R->addRange(range);
Jordan Rose785950e2012-11-02 01:53:40 +0000906 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +0000907 }
908}
909
Anna Zaks118aa752013-02-07 23:05:47 +0000910void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
911 SourceRange Range) const {
912 ExplodedNode *N = C.generateSink();
913 if (N == NULL)
914 return;
915
916 if (!BT_OffsetFree)
917 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
918
919 SmallString<100> buf;
920 llvm::raw_svector_ostream os(buf);
921
922 const MemRegion *MR = ArgVal.getAsRegion();
923 assert(MR && "Only MemRegion based symbols can have offset free errors");
924
925 RegionOffset Offset = MR->getAsOffset();
926 assert((Offset.isValid() &&
927 !Offset.hasSymbolicOffset() &&
928 Offset.getOffset() != 0) &&
929 "Only symbols with a valid offset can have offset free errors");
930
931 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
932
933 os << "Argument to free() is offset by "
934 << offsetBytes
935 << " "
936 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
937 << " from the start of memory allocated by malloc()";
938
939 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
940 R->markInteresting(MR->getBaseRegion());
941 R->addRange(Range);
942 C.emitReport(R);
943}
944
Anna Zaks87cb5be2012-02-22 19:24:52 +0000945ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
946 const CallExpr *CE,
947 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000948 if (CE->getNumArgs() < 2)
949 return 0;
950
Ted Kremenek8bef8232012-01-26 21:29:00 +0000951 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000952 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000953 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000954 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
955 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000956 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000957 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000958
Ted Kremenek846eabd2010-12-01 21:28:31 +0000959 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000960
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000961 DefinedOrUnknownSVal PtrEQ =
962 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000963
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000964 // Get the size argument. If there is no size arg then give up.
965 const Expr *Arg1 = CE->getArg(1);
966 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000967 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000968
969 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000970 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
971 if (!isa<DefinedOrUnknownSVal>(Arg1ValG))
Anna Zaks87cb5be2012-02-22 19:24:52 +0000972 return 0;
Anna Zakse9ef5622012-02-10 01:11:00 +0000973 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG);
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000974
975 // Compare the size argument to 0.
976 DefinedOrUnknownSVal SizeZero =
977 svalBuilder.evalEQ(state, Arg1Val,
978 svalBuilder.makeIntValWithPtrWidth(0, false));
979
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000980 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
981 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
982 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
983 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
984 // We only assume exceptional states if they are definitely true; if the
985 // state is under-constrained, assume regular realloc behavior.
986 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
987 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
988
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000989 // If the ptr is NULL and the size is not 0, the call is equivalent to
990 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000991 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000992 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000993 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000994 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000995 }
996
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000997 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000998 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000999
Anna Zaks30838b92012-02-13 20:57:07 +00001000 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001001 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001002 SymbolRef FromPtr = arg0Val.getAsSymbol();
1003 SVal RetVal = state->getSVal(CE, LCtx);
1004 SymbolRef ToPtr = RetVal.getAsSymbol();
1005 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001006 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001007
Anna Zaks55dd9562012-08-24 02:28:20 +00001008 bool ReleasedAllocated = false;
1009
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001010 // If the size is 0, free the memory.
1011 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001012 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1013 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001014 // The semantics of the return value are:
1015 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001016 // to free() is returned. We just free the input pointer and do not add
1017 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001018 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001019 }
1020
1021 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001022 if (ProgramStateRef stateFree =
1023 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1024
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001025 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1026 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001027 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001028 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001029
Anna Zaks9dc298b2012-09-12 22:57:34 +00001030 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1031 if (FreesOnFail)
1032 Kind = RPIsFreeOnFailure;
1033 else if (!ReleasedAllocated)
1034 Kind = RPDoNotTrackAfterFailure;
1035
Anna Zaks55dd9562012-08-24 02:28:20 +00001036 // Record the info about the reallocated symbol so that we could properly
1037 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001038 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001039 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001040 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001041 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001042 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001043 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001044 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001045}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001046
Anna Zaks87cb5be2012-02-22 19:24:52 +00001047ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001048 if (CE->getNumArgs() < 2)
1049 return 0;
1050
Ted Kremenek8bef8232012-01-26 21:29:00 +00001051 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001052 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001053 const LocationContext *LCtx = C.getLocationContext();
1054 SVal count = state->getSVal(CE->getArg(0), LCtx);
1055 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001056 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1057 svalBuilder.getContext().getSizeType());
1058 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001059
Anna Zaks87cb5be2012-02-22 19:24:52 +00001060 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001061}
1062
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001063LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001064MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1065 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001066 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001067 // Walk the ExplodedGraph backwards and find the first node that referred to
1068 // the tracked symbol.
1069 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001070 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001071
1072 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001073 ProgramStateRef State = N->getState();
1074 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001075 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001076
1077 // Find the most recent expression bound to the symbol in the current
1078 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001079 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001080 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1081 SVal Val = State->getSVal(MR);
1082 if (Val.getAsLocSymbol() == Sym)
1083 ReferenceRegion = MR;
1084 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001085 }
1086
Anna Zaks7752d292012-02-27 23:40:55 +00001087 // Allocation node, is the last node in the current context in which the
1088 // symbol was tracked.
1089 if (N->getLocationContext() == LeakContext)
1090 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001091 N = N->pred_empty() ? NULL : *(N->pred_begin());
1092 }
1093
Anna Zaks97bfb552013-01-08 00:25:29 +00001094 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001095}
1096
Anna Zaksda046772012-02-11 21:02:40 +00001097void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1098 CheckerContext &C) const {
1099 assert(N);
1100 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001101 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001102 // Leaks should not be reported if they are post-dominated by a sink:
1103 // (1) Sinks are higher importance bugs.
1104 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1105 // with __noreturn functions such as assert() or exit(). We choose not
1106 // to report leaks on such paths.
1107 BT_Leak->setSuppressOnSink(true);
1108 }
1109
Anna Zaksca8e36e2012-02-23 21:38:21 +00001110 // Most bug reports are cached at the location where they occurred.
1111 // With leaks, we want to unique them by the location where they were
1112 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001113 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001114 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001115 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001116 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1117
1118 ProgramPoint P = AllocNode->getLocation();
1119 const Stmt *AllocationStmt = 0;
1120 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
1121 AllocationStmt = Exit->getCalleeContext()->getCallSite();
1122 else if (StmtPoint *SP = dyn_cast<StmtPoint>(&P))
1123 AllocationStmt = SP->getStmt();
1124 if (AllocationStmt)
1125 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1126 C.getSourceManager(),
1127 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001128
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001129 SmallString<200> buf;
1130 llvm::raw_svector_ostream os(buf);
1131 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001132 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001133 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001134 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001135 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001136 }
1137
Anna Zaks97bfb552013-01-08 00:25:29 +00001138 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1139 LocUsedForUniqueing,
1140 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001141 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001142 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001143 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001144}
1145
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001146void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1147 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001148{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001149 if (!SymReaper.hasDeadSymbols())
1150 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001151
Ted Kremenek8bef8232012-01-26 21:29:00 +00001152 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001153 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001154 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001155
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001156 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001157 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1158 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001159 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001160 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001161 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001162 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001163
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001164 }
1165 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001166
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001167 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001168 ReallocPairsTy RP = state->get<ReallocPairs>();
1169 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001170 if (SymReaper.isDead(I->first) ||
1171 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001172 state = state->remove<ReallocPairs>(I->first);
1173 }
1174 }
1175
Anna Zaks4141e4d2012-11-13 03:18:01 +00001176 // Cleanup the FreeReturnValue Map.
1177 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1178 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1179 if (SymReaper.isDead(I->first) ||
1180 SymReaper.isDead(I->second)) {
1181 state = state->remove<FreeReturnValue>(I->first);
1182 }
1183 }
1184
Anna Zaksca8e36e2012-02-23 21:38:21 +00001185 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001186 ExplodedNode *N = C.getPredecessor();
1187 if (!Errors.empty()) {
1188 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1189 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001190 for (SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001191 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001192 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001193 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001194 }
Anna Zaks54458702012-10-29 22:51:54 +00001195
Anna Zaksca8e36e2012-02-23 21:38:21 +00001196 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001197}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001198
Anna Zaks66c40402012-02-14 21:55:24 +00001199void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001200 // We will check for double free in the post visit.
1201 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001202 return;
1203
1204 // Check use after free, when a freed pointer is passed to a call.
1205 ProgramStateRef State = C.getState();
1206 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1207 E = CE->arg_end(); I != E; ++I) {
1208 const Expr *A = *I;
1209 if (A->getType().getTypePtr()->isAnyPointerType()) {
1210 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1211 if (!Sym)
1212 continue;
1213 if (checkUseAfterFree(Sym, C, A))
1214 return;
1215 }
1216 }
1217}
1218
Anna Zaks91c2a112012-02-08 23:16:56 +00001219void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1220 const Expr *E = S->getRetValue();
1221 if (!E)
1222 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001223
1224 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001225 ProgramStateRef State = C.getState();
1226 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001227 SymbolRef Sym = RetVal.getAsSymbol();
1228 if (!Sym)
1229 // If we are returning a field of the allocated struct or an array element,
1230 // the callee could still free the memory.
1231 // TODO: This logic should be a part of generic symbol escape callback.
1232 if (const MemRegion *MR = RetVal.getAsRegion())
1233 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1234 if (const SymbolicRegion *BMR =
1235 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1236 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001237
Anna Zaks0860cd02012-02-11 21:44:39 +00001238 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001239 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001240 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001241}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001242
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001243// TODO: Blocks should be either inlined or should call invalidate regions
1244// upon invocation. After that's in place, special casing here will not be
1245// needed.
1246void MallocChecker::checkPostStmt(const BlockExpr *BE,
1247 CheckerContext &C) const {
1248
1249 // Scan the BlockDecRefExprs for any object the retain count checker
1250 // may be tracking.
1251 if (!BE->getBlockDecl()->hasCaptures())
1252 return;
1253
1254 ProgramStateRef state = C.getState();
1255 const BlockDataRegion *R =
1256 cast<BlockDataRegion>(state->getSVal(BE,
1257 C.getLocationContext()).getAsRegion());
1258
1259 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1260 E = R->referenced_vars_end();
1261
1262 if (I == E)
1263 return;
1264
1265 SmallVector<const MemRegion*, 10> Regions;
1266 const LocationContext *LC = C.getLocationContext();
1267 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1268
1269 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001270 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001271 if (VR->getSuperRegion() == R) {
1272 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1273 }
1274 Regions.push_back(VR);
1275 }
1276
1277 state =
1278 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1279 Regions.data() + Regions.size()).getState();
1280 C.addTransition(state);
1281}
1282
Anna Zaks14345182012-05-18 01:16:10 +00001283bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001284 assert(Sym);
1285 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001286 return (RS && RS->isReleased());
1287}
1288
1289bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1290 const Stmt *S) const {
1291 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001292 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001293 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001294 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001295
Anna Zaksfebdc322012-02-16 22:26:12 +00001296 BugReport *R = new BugReport(*BT_UseFree,
1297 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001298 if (S)
1299 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001300 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001301 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +00001302 C.emitReport(R);
Anna Zaks91c2a112012-02-08 23:16:56 +00001303 return true;
1304 }
1305 }
1306 return false;
1307}
1308
Zhongxing Xuc8023782010-03-10 04:58:55 +00001309// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001310void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1311 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001312 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001313 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001314 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001315}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001316
Anna Zaks4fb54872012-02-11 21:02:35 +00001317// If a symbolic region is assumed to NULL (or another constant), stop tracking
1318// it - assuming that allocation failed on this path.
1319ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1320 SVal Cond,
1321 bool Assumption) const {
1322 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001323 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001324 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001325 ConstraintManager &CMgr = state->getConstraintManager();
1326 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1327 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001328 state = state->remove<RegionState>(I.getKey());
1329 }
1330
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001331 // Realloc returns 0 when reallocation fails, which means that we should
1332 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001333 ReallocPairsTy RP = state->get<ReallocPairs>();
1334 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001335 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001336 ConstraintManager &CMgr = state->getConstraintManager();
1337 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001338 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001339 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001340
Anna Zaks9dc298b2012-09-12 22:57:34 +00001341 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1342 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1343 if (RS->isReleased()) {
1344 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001345 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001346 RefState::getAllocated(RS->getStmt()));
1347 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1348 state = state->remove<RegionState>(ReallocSym);
1349 else
1350 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001351 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001352 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001353 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001354 }
1355
Anna Zaks4fb54872012-02-11 21:02:35 +00001356 return state;
1357}
1358
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001359// Check if the function is known to us. So, for example, we could
Jordan Rose740d4902012-07-02 19:27:35 +00001360// conservatively assume it can free/reallocate its pointer arguments.
Anna Zaks66c40402012-02-14 21:55:24 +00001361// (We assume that the pointers cannot escape through calls to system
1362// functions not handled by this checker.)
Jordan Rose740d4902012-07-02 19:27:35 +00001363bool MallocChecker::doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001364 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001365 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001366
1367 // For now, assume that any C++ call can free memory.
1368 // TODO: If we want to be more optimistic here, we'll need to make sure that
1369 // regions escape to C++ containers. They seem to do that even now, but for
1370 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001371 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001372 return false;
1373
Jordan Rose740d4902012-07-02 19:27:35 +00001374 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001375 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001376 // If it's not a framework call, or if it takes a callback, assume it
1377 // can free memory.
1378 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001379 return false;
1380
Jordan Rose740d4902012-07-02 19:27:35 +00001381 Selector S = Msg->getSelector();
Anna Zaks52a04812012-06-20 23:35:57 +00001382
Jordan Rose740d4902012-07-02 19:27:35 +00001383 // Whitelist the ObjC methods which do free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001384 // - Anything containing 'freeWhenDone' param set to 1.
1385 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
Anna Zaks3e4f65d2012-06-22 22:08:09 +00001386 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001387 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1388 if (Call->getArgSVal(i).isConstant(1))
1389 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001390 else
1391 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001392 }
1393 }
1394
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001395 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001396 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001397 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
Jordan Rose740d4902012-07-02 19:27:35 +00001398 StringRef FirstSlot = S.getNameForSlot(0);
1399 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001400 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001401
Anna Zaks5f757682012-06-19 05:10:32 +00001402 // If the first selector starts with addPointer, insertPointer,
1403 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1404 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001405 // that the pointers get freed by following the container itself.
1406 if (FirstSlot.startswith("addPointer") ||
1407 FirstSlot.startswith("insertPointer") ||
1408 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001409 return false;
1410 }
1411
Jordan Rose740d4902012-07-02 19:27:35 +00001412 // Otherwise, assume that the method does not free memory.
1413 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001414 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001415 }
1416
Jordan Rose740d4902012-07-02 19:27:35 +00001417 // At this point the only thing left to handle is straight function calls.
1418 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1419 if (!FD)
1420 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001421
Jordan Rose740d4902012-07-02 19:27:35 +00001422 ASTContext &ASTC = State->getStateManager().getContext();
1423
1424 // If it's one of the allocation functions we can reason about, we model
1425 // its behavior explicitly.
1426 if (isMemFunction(FD, ASTC))
1427 return true;
1428
1429 // If it's not a system call, assume it frees memory.
1430 if (!Call->isInSystemHeader())
1431 return false;
1432
1433 // White list the system functions whose arguments escape.
1434 const IdentifierInfo *II = FD->getIdentifier();
1435 if (!II)
1436 return false;
1437 StringRef FName = II->getName();
1438
Jordan Rose740d4902012-07-02 19:27:35 +00001439 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001440 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001441 if (FName.endswith("NoCopy")) {
1442 // Look for the deallocator argument. We know that the memory ownership
1443 // is not transferred only if the deallocator argument is
1444 // 'kCFAllocatorNull'.
1445 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1446 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1447 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1448 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1449 if (DeallocatorName == "kCFAllocatorNull")
1450 return true;
1451 }
1452 }
1453 return false;
1454 }
1455
Jordan Rose740d4902012-07-02 19:27:35 +00001456 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001457 // 'closefn' is specified (and if that function does free memory),
1458 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001459 // Currently, we do not inspect the 'closefn' function (PR12101).
1460 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001461 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1462 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001463
1464 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1465 // these leaks might be intentional when setting the buffer for stdio.
1466 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1467 if (FName == "setbuf" || FName =="setbuffer" ||
1468 FName == "setlinebuf" || FName == "setvbuf") {
1469 if (Call->getNumArgs() >= 1) {
1470 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1471 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1472 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1473 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1474 return false;
1475 }
1476 }
1477
1478 // A bunch of other functions which either take ownership of a pointer or
1479 // wrap the result up in a struct or object, meaning it can be freed later.
1480 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1481 // but the Malloc checker cannot differentiate between them. The right way
1482 // of doing this would be to implement a pointer escapes callback.
1483 if (FName == "CGBitmapContextCreate" ||
1484 FName == "CGBitmapContextCreateWithData" ||
1485 FName == "CVPixelBufferCreateWithBytes" ||
1486 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1487 FName == "OSAtomicEnqueue") {
1488 return false;
1489 }
1490
Jordan Rose85d7e012012-07-02 19:27:51 +00001491 // Handle cases where we know a buffer's /address/ can escape.
1492 // Note that the above checks handle some special cases where we know that
1493 // even though the address escapes, it's still our responsibility to free the
1494 // buffer.
1495 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001496 return false;
1497
1498 // Otherwise, assume that the function does not free memory.
1499 // Most system calls do not free the memory.
1500 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001501}
1502
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001503ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1504 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00001505 const CallEvent *Call,
1506 PointerEscapeKind Kind) const {
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001507 // If we know that the call does not free memory, keep tracking the top
1508 // level arguments.
Anna Zaks233e26a2013-02-07 23:05:43 +00001509 if ((Kind == PSK_DirectEscapeOnCall ||
1510 Kind == PSK_IndirectEscapeOnCall) &&
1511 doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001512 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00001513 }
Anna Zaks66c40402012-02-14 21:55:24 +00001514
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001515 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
1516 E = Escaped.end();
1517 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001518 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001519
Anna Zaks5b7aa342012-06-22 02:04:31 +00001520 if (const RefState *RS = State->get<RegionState>(sym)) {
1521 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001522 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001523 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001524 }
Anna Zaks66c40402012-02-14 21:55:24 +00001525 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001526}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001527
Jordy Rose393f98b2012-03-18 07:43:35 +00001528static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1529 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001530 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1531 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001532
Jordan Rose166d5022012-11-02 01:54:06 +00001533 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001534 I != E; ++I) {
1535 SymbolRef sym = I.getKey();
1536 if (!currMap.lookup(sym))
1537 return sym;
1538 }
1539
1540 return NULL;
1541}
1542
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001543PathDiagnosticPiece *
1544MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1545 const ExplodedNode *PrevN,
1546 BugReporterContext &BRC,
1547 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001548 ProgramStateRef state = N->getState();
1549 ProgramStateRef statePrev = PrevN->getState();
1550
1551 const RefState *RS = state->get<RegionState>(Sym);
1552 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001553 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001554 return 0;
1555
Anna Zaksfe571602012-02-16 22:26:07 +00001556 const Stmt *S = 0;
1557 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001558 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001559
1560 // Retrieve the associated statement.
1561 ProgramPoint ProgLoc = N->getLocation();
Ted Kremeneka4a17592013-01-04 19:04:36 +00001562 if (StmtPoint *SP = dyn_cast<StmtPoint>(&ProgLoc)) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001563 S = SP->getStmt();
Ted Kremeneka4a17592013-01-04 19:04:36 +00001564 } else if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&ProgLoc)) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001565 S = Exit->getCalleeContext()->getCallSite();
Ted Kremeneka4a17592013-01-04 19:04:36 +00001566 } else if (BlockEdge *Edge = dyn_cast<BlockEdge>(&ProgLoc)) {
1567 // If an assumption was made on a branch, it should be caught
1568 // here by looking at the state transition.
1569 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00001570 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00001571
Anna Zaksfe571602012-02-16 22:26:07 +00001572 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001573 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001574
Jordan Rose28038f32012-07-10 22:07:42 +00001575 // FIXME: We will eventually need to handle non-statement-based events
1576 // (__attribute__((cleanup))).
1577
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001578 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001579 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001580 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001581 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001582 StackHint = new StackHintGeneratorForSymbol(Sym,
1583 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001584 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001585 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001586 StackHint = new StackHintGeneratorForSymbol(Sym,
1587 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001588 } else if (isRelinquished(RS, RSPrev, S)) {
1589 Msg = "Memory ownership is transfered";
1590 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001591 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001592 Mode = ReallocationFailed;
1593 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001594 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001595 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001596
Jordy Roseb000fb52012-03-24 03:15:09 +00001597 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1598 // Is it possible to fail two reallocs WITHOUT testing in between?
1599 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1600 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001601 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001602 FailedReallocSymbol = sym;
1603 }
Anna Zaksfe571602012-02-16 22:26:07 +00001604 }
1605
1606 // We are in a special mode if a reallocation failed later in the path.
1607 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001608 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001609
Jordy Roseb000fb52012-03-24 03:15:09 +00001610 // Is this is the first appearance of the reallocated symbol?
1611 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001612 // We're at the reallocation point.
1613 Msg = "Attempt to reallocate memory";
1614 StackHint = new StackHintGeneratorForSymbol(Sym,
1615 "Returned reallocated memory");
1616 FailedReallocSymbol = NULL;
1617 Mode = Normal;
1618 }
Anna Zaksfe571602012-02-16 22:26:07 +00001619 }
1620
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001621 if (!Msg)
1622 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001623 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001624
1625 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001626 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001627 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001628 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001629}
1630
Anna Zaks93c5a242012-05-02 00:05:20 +00001631void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1632 const char *NL, const char *Sep) const {
1633
1634 RegionStateTy RS = State->get<RegionState>();
1635
Ted Kremenekc37fad62013-01-03 01:30:12 +00001636 if (!RS.isEmpty()) {
1637 Out << Sep << "MallocChecker:" << NL;
1638 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1639 I.getKey()->dumpToStream(Out);
1640 Out << " : ";
1641 I.getData().dump(Out);
1642 Out << NL;
1643 }
1644 }
Anna Zaks93c5a242012-05-02 00:05:20 +00001645}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001646
Anna Zaks231361a2012-02-08 23:16:52 +00001647#define REGISTER_CHECKER(name) \
1648void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001649 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001650 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001651}
Anna Zaks231361a2012-02-08 23:16:52 +00001652
1653REGISTER_CHECKER(MallocPessimistic)
1654REGISTER_CHECKER(MallocOptimistic)