blob: aaaafeb5ef294a74442faed0f566f15caafe2a1a [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();
David Blaikie5251abe2013-02-20 05:52:05 +0000558 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
559 .castAs<DefinedSVal>();
Anna Zakse17fdb22012-06-07 03:57:32 +0000560 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.
David Blaikie5251abe2013-02-20 05:52:05 +0000563 if (!RetVal.getAs<Loc>())
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;
David Blaikie5251abe2013-02-20 05:52:05 +0000574 if (llvm::Optional<DefinedOrUnknownSVal> DefinedSize =
575 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000576 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000577 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000578 DefinedOrUnknownSVal extentMatchesSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000579 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.
David Blaikie5251abe2013-02-20 05:52:05 +0000595 if (!retVal.getAs<Loc>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000596 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());
David Blaikie5251abe2013-02-20 05:52:05 +0000664 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zakse9ef5622012-02-10 01:11:00 +0000665 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000666 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000667
668 // Check for null dereferences.
David Blaikie5251abe2013-02-20 05:52:05 +0000669 if (!location.getAs<Loc>())
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) {
David Blaikie5251abe2013-02-20 05:52:05 +0000785 if (llvm::Optional<nonloc::ConcreteInt> IntVal =
786 V.getAs<nonloc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +0000787 os << "an integer (" << IntVal->getValue() << ")";
David Blaikie5251abe2013-02-20 05:52:05 +0000788 else if (llvm::Optional<loc::ConcreteInt> ConstAddr =
789 V.getAs<loc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +0000790 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikie5251abe2013-02-20 05:52:05 +0000791 else if (llvm::Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner68106302011-02-17 05:38:27 +0000792 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000793 else
794 return false;
795
796 return true;
797}
798
Ted Kremenek9c378f72011-08-12 23:37:29 +0000799bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000800 const MemRegion *MR) {
801 switch (MR->getKind()) {
802 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000803 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +0000804 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000805 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000806 else
807 os << "the address of a function";
808 return true;
809 }
810 case MemRegion::BlockTextRegionKind:
811 os << "block text";
812 return true;
813 case MemRegion::BlockDataRegionKind:
814 // FIXME: where the block came from?
815 os << "a block";
816 return true;
817 default: {
818 const MemSpaceRegion *MS = MR->getMemorySpace();
819
Anna Zakseb31a762012-01-04 23:54:01 +0000820 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000821 const VarRegion *VR = dyn_cast<VarRegion>(MR);
822 const VarDecl *VD;
823 if (VR)
824 VD = VR->getDecl();
825 else
826 VD = NULL;
827
828 if (VD)
829 os << "the address of the local variable '" << VD->getName() << "'";
830 else
831 os << "the address of a local stack variable";
832 return true;
833 }
Anna Zakseb31a762012-01-04 23:54:01 +0000834
835 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000836 const VarRegion *VR = dyn_cast<VarRegion>(MR);
837 const VarDecl *VD;
838 if (VR)
839 VD = VR->getDecl();
840 else
841 VD = NULL;
842
843 if (VD)
844 os << "the address of the parameter '" << VD->getName() << "'";
845 else
846 os << "the address of a parameter";
847 return true;
848 }
Anna Zakseb31a762012-01-04 23:54:01 +0000849
850 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000851 const VarRegion *VR = dyn_cast<VarRegion>(MR);
852 const VarDecl *VD;
853 if (VR)
854 VD = VR->getDecl();
855 else
856 VD = NULL;
857
858 if (VD) {
859 if (VD->isStaticLocal())
860 os << "the address of the static variable '" << VD->getName() << "'";
861 else
862 os << "the address of the global variable '" << VD->getName() << "'";
863 } else
864 os << "the address of a global variable";
865 return true;
866 }
Anna Zakseb31a762012-01-04 23:54:01 +0000867
868 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000869 }
870 }
871}
872
873void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000874 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000875 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000876 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000877 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000878
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000879 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000880 llvm::raw_svector_ostream os(buf);
881
882 const MemRegion *MR = ArgVal.getAsRegion();
883 if (MR) {
884 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
885 MR = ER->getSuperRegion();
886
887 // Special case for alloca()
888 if (isa<AllocaRegion>(MR))
889 os << "Argument to free() was allocated by alloca(), not malloc()";
890 else {
891 os << "Argument to free() is ";
892 if (SummarizeRegion(os, MR))
893 os << ", which is not memory allocated by malloc()";
894 else
895 os << "not memory allocated by malloc()";
896 }
897 } else {
898 os << "Argument to free() is ";
899 if (SummarizeValue(os, ArgVal))
900 os << ", which is not memory allocated by malloc()";
901 else
902 os << "not memory allocated by malloc()";
903 }
904
Anna Zakse172e8b2011-08-17 23:00:25 +0000905 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000906 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000907 R->addRange(range);
Jordan Rose785950e2012-11-02 01:53:40 +0000908 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +0000909 }
910}
911
Anna Zaks118aa752013-02-07 23:05:47 +0000912void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
913 SourceRange Range) const {
914 ExplodedNode *N = C.generateSink();
915 if (N == NULL)
916 return;
917
918 if (!BT_OffsetFree)
919 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
920
921 SmallString<100> buf;
922 llvm::raw_svector_ostream os(buf);
923
924 const MemRegion *MR = ArgVal.getAsRegion();
925 assert(MR && "Only MemRegion based symbols can have offset free errors");
926
927 RegionOffset Offset = MR->getAsOffset();
928 assert((Offset.isValid() &&
929 !Offset.hasSymbolicOffset() &&
930 Offset.getOffset() != 0) &&
931 "Only symbols with a valid offset can have offset free errors");
932
933 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
934
935 os << "Argument to free() is offset by "
936 << offsetBytes
937 << " "
938 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
939 << " from the start of memory allocated by malloc()";
940
941 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
942 R->markInteresting(MR->getBaseRegion());
943 R->addRange(Range);
944 C.emitReport(R);
945}
946
Anna Zaks87cb5be2012-02-22 19:24:52 +0000947ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
948 const CallExpr *CE,
949 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000950 if (CE->getNumArgs() < 2)
951 return 0;
952
Ted Kremenek8bef8232012-01-26 21:29:00 +0000953 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000954 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000955 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000956 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +0000957 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000958 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000959 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000960
Ted Kremenek846eabd2010-12-01 21:28:31 +0000961 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000962
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000963 DefinedOrUnknownSVal PtrEQ =
964 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000965
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000966 // Get the size argument. If there is no size arg then give up.
967 const Expr *Arg1 = CE->getArg(1);
968 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000969 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000970
971 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000972 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +0000973 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000974 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000975 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000976
977 // Compare the size argument to 0.
978 DefinedOrUnknownSVal SizeZero =
979 svalBuilder.evalEQ(state, Arg1Val,
980 svalBuilder.makeIntValWithPtrWidth(0, false));
981
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000982 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
983 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
984 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
985 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
986 // We only assume exceptional states if they are definitely true; if the
987 // state is under-constrained, assume regular realloc behavior.
988 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
989 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
990
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000991 // If the ptr is NULL and the size is not 0, the call is equivalent to
992 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000993 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000994 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000995 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000996 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000997 }
998
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000999 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001000 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001001
Anna Zaks30838b92012-02-13 20:57:07 +00001002 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001003 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001004 SymbolRef FromPtr = arg0Val.getAsSymbol();
1005 SVal RetVal = state->getSVal(CE, LCtx);
1006 SymbolRef ToPtr = RetVal.getAsSymbol();
1007 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001008 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001009
Anna Zaks55dd9562012-08-24 02:28:20 +00001010 bool ReleasedAllocated = false;
1011
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001012 // If the size is 0, free the memory.
1013 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001014 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1015 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001016 // The semantics of the return value are:
1017 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001018 // to free() is returned. We just free the input pointer and do not add
1019 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001020 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001021 }
1022
1023 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001024 if (ProgramStateRef stateFree =
1025 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1026
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001027 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1028 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001029 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001030 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001031
Anna Zaks9dc298b2012-09-12 22:57:34 +00001032 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1033 if (FreesOnFail)
1034 Kind = RPIsFreeOnFailure;
1035 else if (!ReleasedAllocated)
1036 Kind = RPDoNotTrackAfterFailure;
1037
Anna Zaks55dd9562012-08-24 02:28:20 +00001038 // Record the info about the reallocated symbol so that we could properly
1039 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001040 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001041 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001042 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001043 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001044 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001045 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001046 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001047}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001048
Anna Zaks87cb5be2012-02-22 19:24:52 +00001049ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001050 if (CE->getNumArgs() < 2)
1051 return 0;
1052
Ted Kremenek8bef8232012-01-26 21:29:00 +00001053 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001054 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001055 const LocationContext *LCtx = C.getLocationContext();
1056 SVal count = state->getSVal(CE->getArg(0), LCtx);
1057 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001058 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1059 svalBuilder.getContext().getSizeType());
1060 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001061
Anna Zaks87cb5be2012-02-22 19:24:52 +00001062 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001063}
1064
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001065LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001066MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1067 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001068 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001069 // Walk the ExplodedGraph backwards and find the first node that referred to
1070 // the tracked symbol.
1071 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001072 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001073
1074 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001075 ProgramStateRef State = N->getState();
1076 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001077 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001078
1079 // Find the most recent expression bound to the symbol in the current
1080 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001081 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001082 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1083 SVal Val = State->getSVal(MR);
1084 if (Val.getAsLocSymbol() == Sym)
1085 ReferenceRegion = MR;
1086 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001087 }
1088
Anna Zaks7752d292012-02-27 23:40:55 +00001089 // Allocation node, is the last node in the current context in which the
1090 // symbol was tracked.
1091 if (N->getLocationContext() == LeakContext)
1092 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001093 N = N->pred_empty() ? NULL : *(N->pred_begin());
1094 }
1095
Anna Zaks97bfb552013-01-08 00:25:29 +00001096 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001097}
1098
Anna Zaksda046772012-02-11 21:02:40 +00001099void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1100 CheckerContext &C) const {
1101 assert(N);
1102 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001103 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001104 // Leaks should not be reported if they are post-dominated by a sink:
1105 // (1) Sinks are higher importance bugs.
1106 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1107 // with __noreturn functions such as assert() or exit(). We choose not
1108 // to report leaks on such paths.
1109 BT_Leak->setSuppressOnSink(true);
1110 }
1111
Anna Zaksca8e36e2012-02-23 21:38:21 +00001112 // Most bug reports are cached at the location where they occurred.
1113 // With leaks, we want to unique them by the location where they were
1114 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001115 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001116 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001117 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001118 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1119
1120 ProgramPoint P = AllocNode->getLocation();
1121 const Stmt *AllocationStmt = 0;
1122 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
1123 AllocationStmt = Exit->getCalleeContext()->getCallSite();
1124 else if (StmtPoint *SP = dyn_cast<StmtPoint>(&P))
1125 AllocationStmt = SP->getStmt();
1126 if (AllocationStmt)
1127 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1128 C.getSourceManager(),
1129 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001130
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001131 SmallString<200> buf;
1132 llvm::raw_svector_ostream os(buf);
1133 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001134 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001135 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001136 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001137 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001138 }
1139
Anna Zaks97bfb552013-01-08 00:25:29 +00001140 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1141 LocUsedForUniqueing,
1142 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001143 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001144 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001145 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001146}
1147
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001148void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1149 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001150{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001151 if (!SymReaper.hasDeadSymbols())
1152 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001153
Ted Kremenek8bef8232012-01-26 21:29:00 +00001154 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001155 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001156 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001157
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001158 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001159 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1160 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001161 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001162 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001163 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001164 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001165
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001166 }
1167 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001168
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001169 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001170 ReallocPairsTy RP = state->get<ReallocPairs>();
1171 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001172 if (SymReaper.isDead(I->first) ||
1173 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001174 state = state->remove<ReallocPairs>(I->first);
1175 }
1176 }
1177
Anna Zaks4141e4d2012-11-13 03:18:01 +00001178 // Cleanup the FreeReturnValue Map.
1179 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1180 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1181 if (SymReaper.isDead(I->first) ||
1182 SymReaper.isDead(I->second)) {
1183 state = state->remove<FreeReturnValue>(I->first);
1184 }
1185 }
1186
Anna Zaksca8e36e2012-02-23 21:38:21 +00001187 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001188 ExplodedNode *N = C.getPredecessor();
1189 if (!Errors.empty()) {
1190 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1191 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001192 for (SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001193 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001194 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001195 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001196 }
Anna Zaks54458702012-10-29 22:51:54 +00001197
Anna Zaksca8e36e2012-02-23 21:38:21 +00001198 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001199}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001200
Anna Zaks66c40402012-02-14 21:55:24 +00001201void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001202 // We will check for double free in the post visit.
1203 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001204 return;
1205
1206 // Check use after free, when a freed pointer is passed to a call.
1207 ProgramStateRef State = C.getState();
1208 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1209 E = CE->arg_end(); I != E; ++I) {
1210 const Expr *A = *I;
1211 if (A->getType().getTypePtr()->isAnyPointerType()) {
1212 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1213 if (!Sym)
1214 continue;
1215 if (checkUseAfterFree(Sym, C, A))
1216 return;
1217 }
1218 }
1219}
1220
Anna Zaks91c2a112012-02-08 23:16:56 +00001221void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1222 const Expr *E = S->getRetValue();
1223 if (!E)
1224 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001225
1226 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001227 ProgramStateRef State = C.getState();
1228 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001229 SymbolRef Sym = RetVal.getAsSymbol();
1230 if (!Sym)
1231 // If we are returning a field of the allocated struct or an array element,
1232 // the callee could still free the memory.
1233 // TODO: This logic should be a part of generic symbol escape callback.
1234 if (const MemRegion *MR = RetVal.getAsRegion())
1235 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1236 if (const SymbolicRegion *BMR =
1237 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1238 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001239
Anna Zaks0860cd02012-02-11 21:44:39 +00001240 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001241 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001242 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001243}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001244
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001245// TODO: Blocks should be either inlined or should call invalidate regions
1246// upon invocation. After that's in place, special casing here will not be
1247// needed.
1248void MallocChecker::checkPostStmt(const BlockExpr *BE,
1249 CheckerContext &C) const {
1250
1251 // Scan the BlockDecRefExprs for any object the retain count checker
1252 // may be tracking.
1253 if (!BE->getBlockDecl()->hasCaptures())
1254 return;
1255
1256 ProgramStateRef state = C.getState();
1257 const BlockDataRegion *R =
1258 cast<BlockDataRegion>(state->getSVal(BE,
1259 C.getLocationContext()).getAsRegion());
1260
1261 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1262 E = R->referenced_vars_end();
1263
1264 if (I == E)
1265 return;
1266
1267 SmallVector<const MemRegion*, 10> Regions;
1268 const LocationContext *LC = C.getLocationContext();
1269 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1270
1271 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001272 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001273 if (VR->getSuperRegion() == R) {
1274 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1275 }
1276 Regions.push_back(VR);
1277 }
1278
1279 state =
1280 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1281 Regions.data() + Regions.size()).getState();
1282 C.addTransition(state);
1283}
1284
Anna Zaks14345182012-05-18 01:16:10 +00001285bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001286 assert(Sym);
1287 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001288 return (RS && RS->isReleased());
1289}
1290
1291bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1292 const Stmt *S) const {
1293 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001294 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001295 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001296 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001297
Anna Zaksfebdc322012-02-16 22:26:12 +00001298 BugReport *R = new BugReport(*BT_UseFree,
1299 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001300 if (S)
1301 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001302 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001303 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +00001304 C.emitReport(R);
Anna Zaks91c2a112012-02-08 23:16:56 +00001305 return true;
1306 }
1307 }
1308 return false;
1309}
1310
Zhongxing Xuc8023782010-03-10 04:58:55 +00001311// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001312void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1313 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001314 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001315 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001316 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001317}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001318
Anna Zaks4fb54872012-02-11 21:02:35 +00001319// If a symbolic region is assumed to NULL (or another constant), stop tracking
1320// it - assuming that allocation failed on this path.
1321ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1322 SVal Cond,
1323 bool Assumption) const {
1324 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001325 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001326 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001327 ConstraintManager &CMgr = state->getConstraintManager();
1328 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1329 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001330 state = state->remove<RegionState>(I.getKey());
1331 }
1332
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001333 // Realloc returns 0 when reallocation fails, which means that we should
1334 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001335 ReallocPairsTy RP = state->get<ReallocPairs>();
1336 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001337 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001338 ConstraintManager &CMgr = state->getConstraintManager();
1339 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001340 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001341 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001342
Anna Zaks9dc298b2012-09-12 22:57:34 +00001343 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1344 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1345 if (RS->isReleased()) {
1346 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001347 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001348 RefState::getAllocated(RS->getStmt()));
1349 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1350 state = state->remove<RegionState>(ReallocSym);
1351 else
1352 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001353 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001354 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001355 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001356 }
1357
Anna Zaks4fb54872012-02-11 21:02:35 +00001358 return state;
1359}
1360
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001361// Check if the function is known to us. So, for example, we could
Jordan Rose740d4902012-07-02 19:27:35 +00001362// conservatively assume it can free/reallocate its pointer arguments.
Anna Zaks66c40402012-02-14 21:55:24 +00001363// (We assume that the pointers cannot escape through calls to system
1364// functions not handled by this checker.)
Jordan Rose740d4902012-07-02 19:27:35 +00001365bool MallocChecker::doesNotFreeMemory(const CallEvent *Call,
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001366 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001367 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001368
1369 // For now, assume that any C++ call can free memory.
1370 // TODO: If we want to be more optimistic here, we'll need to make sure that
1371 // regions escape to C++ containers. They seem to do that even now, but for
1372 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001373 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001374 return false;
1375
Jordan Rose740d4902012-07-02 19:27:35 +00001376 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001377 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001378 // If it's not a framework call, or if it takes a callback, assume it
1379 // can free memory.
1380 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001381 return false;
1382
Jordan Rose740d4902012-07-02 19:27:35 +00001383 Selector S = Msg->getSelector();
Anna Zaks52a04812012-06-20 23:35:57 +00001384
Jordan Rose740d4902012-07-02 19:27:35 +00001385 // Whitelist the ObjC methods which do free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001386 // - Anything containing 'freeWhenDone' param set to 1.
1387 // Ex: dataWithBytesNoCopy:length:freeWhenDone.
Anna Zaks3e4f65d2012-06-22 22:08:09 +00001388 for (unsigned i = 1; i < S.getNumArgs(); ++i) {
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001389 if (S.getNameForSlot(i).equals("freeWhenDone")) {
1390 if (Call->getArgSVal(i).isConstant(1))
1391 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001392 else
1393 return true;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001394 }
1395 }
1396
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001397 // If the first selector ends with NoCopy, assume that the ownership is
Benjamin Kramer48d798c2012-06-02 10:20:41 +00001398 // transferred as well.
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001399 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
Jordan Rose740d4902012-07-02 19:27:35 +00001400 StringRef FirstSlot = S.getNameForSlot(0);
1401 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001402 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001403
Anna Zaks5f757682012-06-19 05:10:32 +00001404 // If the first selector starts with addPointer, insertPointer,
1405 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1406 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001407 // that the pointers get freed by following the container itself.
1408 if (FirstSlot.startswith("addPointer") ||
1409 FirstSlot.startswith("insertPointer") ||
1410 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001411 return false;
1412 }
1413
Jordan Rose740d4902012-07-02 19:27:35 +00001414 // Otherwise, assume that the method does not free memory.
1415 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001416 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001417 }
1418
Jordan Rose740d4902012-07-02 19:27:35 +00001419 // At this point the only thing left to handle is straight function calls.
1420 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1421 if (!FD)
1422 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001423
Jordan Rose740d4902012-07-02 19:27:35 +00001424 ASTContext &ASTC = State->getStateManager().getContext();
1425
1426 // If it's one of the allocation functions we can reason about, we model
1427 // its behavior explicitly.
1428 if (isMemFunction(FD, ASTC))
1429 return true;
1430
1431 // If it's not a system call, assume it frees memory.
1432 if (!Call->isInSystemHeader())
1433 return false;
1434
1435 // White list the system functions whose arguments escape.
1436 const IdentifierInfo *II = FD->getIdentifier();
1437 if (!II)
1438 return false;
1439 StringRef FName = II->getName();
1440
Jordan Rose740d4902012-07-02 19:27:35 +00001441 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001442 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001443 if (FName.endswith("NoCopy")) {
1444 // Look for the deallocator argument. We know that the memory ownership
1445 // is not transferred only if the deallocator argument is
1446 // 'kCFAllocatorNull'.
1447 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1448 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1449 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1450 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1451 if (DeallocatorName == "kCFAllocatorNull")
1452 return true;
1453 }
1454 }
1455 return false;
1456 }
1457
Jordan Rose740d4902012-07-02 19:27:35 +00001458 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001459 // 'closefn' is specified (and if that function does free memory),
1460 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001461 // Currently, we do not inspect the 'closefn' function (PR12101).
1462 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001463 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1464 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001465
1466 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1467 // these leaks might be intentional when setting the buffer for stdio.
1468 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1469 if (FName == "setbuf" || FName =="setbuffer" ||
1470 FName == "setlinebuf" || FName == "setvbuf") {
1471 if (Call->getNumArgs() >= 1) {
1472 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1473 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1474 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1475 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1476 return false;
1477 }
1478 }
1479
1480 // A bunch of other functions which either take ownership of a pointer or
1481 // wrap the result up in a struct or object, meaning it can be freed later.
1482 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1483 // but the Malloc checker cannot differentiate between them. The right way
1484 // of doing this would be to implement a pointer escapes callback.
1485 if (FName == "CGBitmapContextCreate" ||
1486 FName == "CGBitmapContextCreateWithData" ||
1487 FName == "CVPixelBufferCreateWithBytes" ||
1488 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1489 FName == "OSAtomicEnqueue") {
1490 return false;
1491 }
1492
Jordan Rose85d7e012012-07-02 19:27:51 +00001493 // Handle cases where we know a buffer's /address/ can escape.
1494 // Note that the above checks handle some special cases where we know that
1495 // even though the address escapes, it's still our responsibility to free the
1496 // buffer.
1497 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001498 return false;
1499
1500 // Otherwise, assume that the function does not free memory.
1501 // Most system calls do not free the memory.
1502 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001503}
1504
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001505ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1506 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00001507 const CallEvent *Call,
1508 PointerEscapeKind Kind) const {
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001509 // If we know that the call does not free memory, keep tracking the top
1510 // level arguments.
Anna Zaks233e26a2013-02-07 23:05:43 +00001511 if ((Kind == PSK_DirectEscapeOnCall ||
1512 Kind == PSK_IndirectEscapeOnCall) &&
1513 doesNotFreeMemory(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001514 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00001515 }
Anna Zaks66c40402012-02-14 21:55:24 +00001516
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001517 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
1518 E = Escaped.end();
1519 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001520 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001521
Anna Zaks5b7aa342012-06-22 02:04:31 +00001522 if (const RefState *RS = State->get<RegionState>(sym)) {
1523 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001524 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001525 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001526 }
Anna Zaks66c40402012-02-14 21:55:24 +00001527 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001528}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001529
Jordy Rose393f98b2012-03-18 07:43:35 +00001530static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1531 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001532 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1533 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001534
Jordan Rose166d5022012-11-02 01:54:06 +00001535 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001536 I != E; ++I) {
1537 SymbolRef sym = I.getKey();
1538 if (!currMap.lookup(sym))
1539 return sym;
1540 }
1541
1542 return NULL;
1543}
1544
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001545PathDiagnosticPiece *
1546MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1547 const ExplodedNode *PrevN,
1548 BugReporterContext &BRC,
1549 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001550 ProgramStateRef state = N->getState();
1551 ProgramStateRef statePrev = PrevN->getState();
1552
1553 const RefState *RS = state->get<RegionState>(Sym);
1554 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001555 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001556 return 0;
1557
Anna Zaksfe571602012-02-16 22:26:07 +00001558 const Stmt *S = 0;
1559 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001560 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001561
1562 // Retrieve the associated statement.
1563 ProgramPoint ProgLoc = N->getLocation();
Ted Kremeneka4a17592013-01-04 19:04:36 +00001564 if (StmtPoint *SP = dyn_cast<StmtPoint>(&ProgLoc)) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001565 S = SP->getStmt();
Ted Kremeneka4a17592013-01-04 19:04:36 +00001566 } else if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&ProgLoc)) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001567 S = Exit->getCalleeContext()->getCallSite();
Ted Kremeneka4a17592013-01-04 19:04:36 +00001568 } else if (BlockEdge *Edge = dyn_cast<BlockEdge>(&ProgLoc)) {
1569 // If an assumption was made on a branch, it should be caught
1570 // here by looking at the state transition.
1571 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00001572 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00001573
Anna Zaksfe571602012-02-16 22:26:07 +00001574 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001575 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001576
Jordan Rose28038f32012-07-10 22:07:42 +00001577 // FIXME: We will eventually need to handle non-statement-based events
1578 // (__attribute__((cleanup))).
1579
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001580 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001581 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001582 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001583 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001584 StackHint = new StackHintGeneratorForSymbol(Sym,
1585 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001586 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001587 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001588 StackHint = new StackHintGeneratorForSymbol(Sym,
1589 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001590 } else if (isRelinquished(RS, RSPrev, S)) {
1591 Msg = "Memory ownership is transfered";
1592 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001593 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001594 Mode = ReallocationFailed;
1595 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001596 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001597 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001598
Jordy Roseb000fb52012-03-24 03:15:09 +00001599 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1600 // Is it possible to fail two reallocs WITHOUT testing in between?
1601 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1602 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001603 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001604 FailedReallocSymbol = sym;
1605 }
Anna Zaksfe571602012-02-16 22:26:07 +00001606 }
1607
1608 // We are in a special mode if a reallocation failed later in the path.
1609 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001610 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001611
Jordy Roseb000fb52012-03-24 03:15:09 +00001612 // Is this is the first appearance of the reallocated symbol?
1613 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001614 // We're at the reallocation point.
1615 Msg = "Attempt to reallocate memory";
1616 StackHint = new StackHintGeneratorForSymbol(Sym,
1617 "Returned reallocated memory");
1618 FailedReallocSymbol = NULL;
1619 Mode = Normal;
1620 }
Anna Zaksfe571602012-02-16 22:26:07 +00001621 }
1622
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001623 if (!Msg)
1624 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001625 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001626
1627 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001628 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001629 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001630 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001631}
1632
Anna Zaks93c5a242012-05-02 00:05:20 +00001633void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1634 const char *NL, const char *Sep) const {
1635
1636 RegionStateTy RS = State->get<RegionState>();
1637
Ted Kremenekc37fad62013-01-03 01:30:12 +00001638 if (!RS.isEmpty()) {
1639 Out << Sep << "MallocChecker:" << NL;
1640 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1641 I.getKey()->dumpToStream(Out);
1642 Out << " : ";
1643 I.getData().dump(Out);
1644 Out << NL;
1645 }
1646 }
Anna Zaks93c5a242012-05-02 00:05:20 +00001647}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001648
Anna Zaks231361a2012-02-08 23:16:52 +00001649#define REGISTER_CHECKER(name) \
1650void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001651 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001652 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001653}
Anna Zaks231361a2012-02-08 23:16:52 +00001654
1655REGISTER_CHECKER(MallocPessimistic)
1656REGISTER_CHECKER(MallocOptimistic)