blob: 28a2999f04148f0724f4071347c75c286a54359e [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
Jordan Rose9fe09f32013-03-09 00:59:10 +0000171 ///@{
Anna Zaks66c40402012-02-14 21:55:24 +0000172 /// Check if this is one of the functions which can allocate/reallocate memory
173 /// pointed to by one of its arguments.
174 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000175 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
176 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose9fe09f32013-03-09 00:59:10 +0000177 ///@}
Anna Zaks87cb5be2012-02-22 19:24:52 +0000178 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
179 const CallExpr *CE,
180 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000181 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000182 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000183 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000184 return MallocMemAux(C, CE,
185 state->getSVal(SizeEx, C.getLocationContext()),
186 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000187 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000188
Ted Kremenek8bef8232012-01-26 21:29:00 +0000189 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000190 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000191 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000192
Anna Zaks87cb5be2012-02-22 19:24:52 +0000193 /// Update the RefState to reflect the new memory allocation.
194 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
195 const CallExpr *CE,
196 ProgramStateRef state);
197
198 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
199 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000200 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000201 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000202 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000203 bool &ReleasedAllocated,
204 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000205 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
206 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000207 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000208 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000209 bool &ReleasedAllocated,
210 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000211
Anna Zaks87cb5be2012-02-22 19:24:52 +0000212 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
213 bool FreesMemOnFailure) const;
214 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000215
Anna Zaks14345182012-05-18 01:16:10 +0000216 ///\brief Check if the memory associated with this symbol was released.
217 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
218
Anna Zaks91c2a112012-02-08 23:16:56 +0000219 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
220 const Stmt *S = 0) const;
221
Jordan Rose9fe09f32013-03-09 00:59:10 +0000222 /// Check if the function is known not to free memory, or if it is
223 /// "interesting" and should be modeled explicitly.
224 ///
225 /// We assume that pointers do not escape through calls to system functions
226 /// not handled by this checker.
227 bool doesNotFreeMemOrInteresting(const CallEvent *Call,
228 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000229
Ted Kremenek9c378f72011-08-12 23:37:29 +0000230 static bool SummarizeValue(raw_ostream &os, SVal V);
231 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000232 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
Anna Zaks118aa752013-02-07 23:05:47 +0000233 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range)const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000234
Anna Zaksca8e36e2012-02-23 21:38:21 +0000235 /// Find the location of the allocation for Sym on the path leading to the
236 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000237 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
238 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000239
Anna Zaksda046772012-02-11 21:02:40 +0000240 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
241
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000242 /// The bug visitor which allows us to print extra diagnostics along the
243 /// BugReport path. For example, showing the allocation site of the leaked
244 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000245 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000246 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000247 enum NotificationMode {
248 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000249 ReallocationFailed
250 };
251
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000252 // The allocated region symbol tracked by the main analysis.
253 SymbolRef Sym;
254
Anna Zaks88feba02012-05-10 01:37:40 +0000255 // The mode we are in, i.e. what kind of diagnostics will be emitted.
256 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000257
Anna Zaks88feba02012-05-10 01:37:40 +0000258 // A symbol from when the primary region should have been reallocated.
259 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000260
Anna Zaks88feba02012-05-10 01:37:40 +0000261 bool IsLeak;
262
263 public:
264 MallocBugVisitor(SymbolRef S, bool isLeak = false)
265 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000266
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000267 virtual ~MallocBugVisitor() {}
268
269 void Profile(llvm::FoldingSetNodeID &ID) const {
270 static int X = 0;
271 ID.AddPointer(&X);
272 ID.AddPointer(Sym);
273 }
274
Anna Zaksfe571602012-02-16 22:26:07 +0000275 inline bool isAllocated(const RefState *S, const RefState *SPrev,
276 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000277 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000278 return (Stmt && isa<CallExpr>(Stmt) &&
279 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000280 }
281
Anna Zaksfe571602012-02-16 22:26:07 +0000282 inline bool isReleased(const RefState *S, const RefState *SPrev,
283 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000284 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000285 return (Stmt && isa<CallExpr>(Stmt) &&
286 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
287 }
288
Anna Zaks5b7aa342012-06-22 02:04:31 +0000289 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
290 const Stmt *Stmt) {
291 // Did not track -> relinquished. Other state (allocated) -> relinquished.
292 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
293 isa<ObjCPropertyRefExpr>(Stmt)) &&
294 (S && S->isRelinquished()) &&
295 (!SPrev || !SPrev->isRelinquished()));
296 }
297
Anna Zaksfe571602012-02-16 22:26:07 +0000298 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
299 const Stmt *Stmt) {
300 // If the expression is not a call, and the state change is
301 // released -> allocated, it must be the realloc return value
302 // check. If we have to handle more cases here, it might be cleaner just
303 // to track this extra bit in the state itself.
304 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
305 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000306 }
307
308 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
309 const ExplodedNode *PrevN,
310 BugReporterContext &BRC,
311 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000312
313 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
314 const ExplodedNode *EndPathNode,
315 BugReport &BR) {
316 if (!IsLeak)
317 return 0;
318
319 PathDiagnosticLocation L =
320 PathDiagnosticLocation::createEndOfPath(EndPathNode,
321 BRC.getSourceManager());
322 // Do not add the statement itself as a range in case of leak.
323 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
324 }
325
Anna Zaks56a938f2012-03-16 23:24:20 +0000326 private:
327 class StackHintGeneratorForReallocationFailed
328 : public StackHintGeneratorForSymbol {
329 public:
330 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
331 : StackHintGeneratorForSymbol(S, M) {}
332
333 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000334 // Printed parameters start at 1, not 0.
335 ++ArgIndex;
336
Anna Zaks56a938f2012-03-16 23:24:20 +0000337 SmallString<200> buf;
338 llvm::raw_svector_ostream os(buf);
339
Jordan Rose615a0922012-09-22 01:24:42 +0000340 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
341 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000342
343 return os.str();
344 }
345
346 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000347 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000348 }
349 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000350 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000351};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000352} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000353
Jordan Rose166d5022012-11-02 01:54:06 +0000354REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
355REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000356
Anna Zaks4141e4d2012-11-13 03:18:01 +0000357// A map from the freed symbol to the symbol representing the return value of
358// the free function.
359REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
360
Anna Zaks4fb54872012-02-11 21:02:35 +0000361namespace {
362class StopTrackingCallback : public SymbolVisitor {
363 ProgramStateRef state;
364public:
365 StopTrackingCallback(ProgramStateRef st) : state(st) {}
366 ProgramStateRef getState() const { return state; }
367
368 bool VisitSymbol(SymbolRef sym) {
369 state = state->remove<RegionState>(sym);
370 return true;
371 }
372};
373} // end anonymous namespace
374
Anna Zaks66c40402012-02-14 21:55:24 +0000375void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000376 if (II_malloc)
377 return;
378 II_malloc = &Ctx.Idents.get("malloc");
379 II_free = &Ctx.Idents.get("free");
380 II_realloc = &Ctx.Idents.get("realloc");
381 II_reallocf = &Ctx.Idents.get("reallocf");
382 II_calloc = &Ctx.Idents.get("calloc");
383 II_valloc = &Ctx.Idents.get("valloc");
384 II_strdup = &Ctx.Idents.get("strdup");
385 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000386}
387
Anna Zaks66c40402012-02-14 21:55:24 +0000388bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000389 if (isFreeFunction(FD, C))
390 return true;
391
392 if (isAllocationFunction(FD, C))
393 return true;
394
395 return false;
396}
397
398bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
399 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000400 if (!FD)
401 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000402
Jordan Rose5ef6e942012-07-10 23:13:01 +0000403 if (FD->getKind() == Decl::Function) {
404 IdentifierInfo *FunI = FD->getIdentifier();
405 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000406
Jordan Rose5ef6e942012-07-10 23:13:01 +0000407 if (FunI == II_malloc || FunI == II_realloc ||
408 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
409 FunI == II_strdup || FunI == II_strndup)
410 return true;
411 }
Anna Zaks66c40402012-02-14 21:55:24 +0000412
Anna Zaks14345182012-05-18 01:16:10 +0000413 if (Filter.CMallocOptimistic && FD->hasAttrs())
414 for (specific_attr_iterator<OwnershipAttr>
415 i = FD->specific_attr_begin<OwnershipAttr>(),
416 e = FD->specific_attr_end<OwnershipAttr>();
417 i != e; ++i)
418 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
419 return true;
420 return false;
421}
422
423bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
424 if (!FD)
425 return false;
426
Jordan Rose5ef6e942012-07-10 23:13:01 +0000427 if (FD->getKind() == Decl::Function) {
428 IdentifierInfo *FunI = FD->getIdentifier();
429 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000430
Jordan Rose5ef6e942012-07-10 23:13:01 +0000431 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
432 return true;
433 }
Anna Zaks66c40402012-02-14 21:55:24 +0000434
Anna Zaks14345182012-05-18 01:16:10 +0000435 if (Filter.CMallocOptimistic && FD->hasAttrs())
436 for (specific_attr_iterator<OwnershipAttr>
437 i = FD->specific_attr_begin<OwnershipAttr>(),
438 e = FD->specific_attr_end<OwnershipAttr>();
439 i != e; ++i)
440 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
441 (*i)->getOwnKind() == OwnershipAttr::Holds)
442 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000443 return false;
444}
445
Anna Zaksb319e022012-02-08 20:13:28 +0000446void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000447 if (C.wasInlined)
448 return;
449
Anna Zaksb319e022012-02-08 20:13:28 +0000450 const FunctionDecl *FD = C.getCalleeDecl(CE);
451 if (!FD)
452 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000453
Anna Zaks87cb5be2012-02-22 19:24:52 +0000454 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000455 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000456
457 if (FD->getKind() == Decl::Function) {
458 initIdentifierInfo(C.getASTContext());
459 IdentifierInfo *FunI = FD->getIdentifier();
460
461 if (FunI == II_malloc || FunI == II_valloc) {
462 if (CE->getNumArgs() < 1)
463 return;
464 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
465 } else if (FunI == II_realloc) {
466 State = ReallocMem(C, CE, false);
467 } else if (FunI == II_reallocf) {
468 State = ReallocMem(C, CE, true);
469 } else if (FunI == II_calloc) {
470 State = CallocMem(C, CE);
471 } else if (FunI == II_free) {
Anna Zaks55dd9562012-08-24 02:28:20 +0000472 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose5ef6e942012-07-10 23:13:01 +0000473 } else if (FunI == II_strdup) {
474 State = MallocUpdateRefState(C, CE, State);
475 } else if (FunI == II_strndup) {
476 State = MallocUpdateRefState(C, CE, State);
477 }
478 }
479
480 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000481 // Check all the attributes, if there are any.
482 // There can be multiple of these attributes.
483 if (FD->hasAttrs())
484 for (specific_attr_iterator<OwnershipAttr>
485 i = FD->specific_attr_begin<OwnershipAttr>(),
486 e = FD->specific_attr_end<OwnershipAttr>();
487 i != e; ++i) {
488 switch ((*i)->getOwnKind()) {
489 case OwnershipAttr::Returns:
490 State = MallocMemReturnsAttr(C, CE, *i);
491 break;
492 case OwnershipAttr::Takes:
493 case OwnershipAttr::Holds:
494 State = FreeMemAttr(C, CE, *i);
495 break;
496 }
497 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000498 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000499 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000500}
501
Jordan Rose9fe09f32013-03-09 00:59:10 +0000502static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
503 // If the first selector piece is one of the names below, assume that the
504 // object takes ownership of the memory, promising to eventually deallocate it
505 // with free().
506 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
507 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
508 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
509 if (FirstSlot == "dataWithBytesNoCopy" ||
510 FirstSlot == "initWithBytesNoCopy" ||
511 FirstSlot == "initWithCharactersNoCopy")
512 return true;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000513
514 return false;
515}
516
Jordan Rose9fe09f32013-03-09 00:59:10 +0000517static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
518 Selector S = Call.getSelector();
519
520 // FIXME: We should not rely on fully-constrained symbols being folded.
521 for (unsigned i = 1; i < S.getNumArgs(); ++i)
522 if (S.getNameForSlot(i).equals("freeWhenDone"))
523 return !Call.getArgSVal(i).isZeroConstant();
524
525 return None;
526}
527
Anna Zaks4141e4d2012-11-13 03:18:01 +0000528void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
529 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000530 if (C.wasInlined)
531 return;
532
Jordan Rose9fe09f32013-03-09 00:59:10 +0000533 if (!isKnownDeallocObjCMethodName(Call))
534 return;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000535
Jordan Rose9fe09f32013-03-09 00:59:10 +0000536 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
537 if (!*FreeWhenDone)
538 return;
539
540 bool ReleasedAllocatedMemory;
541 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
542 Call.getOriginExpr(), C.getState(),
543 /*Hold=*/true, ReleasedAllocatedMemory,
544 /*RetNullOnFailure=*/true);
545
546 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000547}
548
Anna Zaks87cb5be2012-02-22 19:24:52 +0000549ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
550 const CallExpr *CE,
551 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000552 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000553 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000554
Sean Huntcf807c42010-08-18 23:23:40 +0000555 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000556 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000557 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000558 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000559 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000560}
561
Anna Zaksb319e022012-02-08 20:13:28 +0000562ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000563 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000564 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000565 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000566
567 // Bind the return value to the symbolic value from the heap region.
568 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
569 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000570 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000571 SValBuilder &svalBuilder = C.getSValBuilder();
572 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie5251abe2013-02-20 05:52:05 +0000573 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
574 .castAs<DefinedSVal>();
Anna Zakse17fdb22012-06-07 03:57:32 +0000575 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000576
Anna Zaksb16ce452012-02-15 00:11:22 +0000577 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000578 if (!RetVal.getAs<Loc>())
Anna Zaksb16ce452012-02-15 00:11:22 +0000579 return 0;
580
Jordy Rose32f26562010-07-04 00:00:41 +0000581 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000582 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000583
Jordy Rose32f26562010-07-04 00:00:41 +0000584 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000585 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000586 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000587 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000588 return 0;
David Blaikiedc84cd52013-02-20 22:23:23 +0000589 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000590 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000591 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000592 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000593 DefinedOrUnknownSVal extentMatchesSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000594 svalBuilder.evalEQ(state, Extent, *DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000595
Anna Zaks60a1fa42012-02-22 03:14:20 +0000596 state = state->assume(extentMatchesSize, true);
597 assert(state);
598 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000599
Anna Zaks87cb5be2012-02-22 19:24:52 +0000600 return MallocUpdateRefState(C, CE, state);
601}
602
603ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
604 const CallExpr *CE,
605 ProgramStateRef state) {
606 // Get the return value.
607 SVal retVal = state->getSVal(CE, C.getLocationContext());
608
609 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000610 if (!retVal.getAs<Loc>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000611 return 0;
612
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000613 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000614 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000615
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000616 // Set the symbol's state to Allocated.
Anna Zaks050cdd72012-06-20 20:57:46 +0000617 return state->set<RegionState>(Sym, RefState::getAllocated(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000618
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000619}
620
Anna Zaks87cb5be2012-02-22 19:24:52 +0000621ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
622 const CallExpr *CE,
623 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000624 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000625 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000626
Anna Zaksb3d72752012-03-01 22:06:06 +0000627 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000628 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000629
Sean Huntcf807c42010-08-18 23:23:40 +0000630 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
631 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000632 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000633 Att->getOwnKind() == OwnershipAttr::Holds,
634 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000635 if (StateI)
636 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000637 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000638 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000639}
640
Ted Kremenek8bef8232012-01-26 21:29:00 +0000641ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000642 const CallExpr *CE,
643 ProgramStateRef state,
644 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000645 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000646 bool &ReleasedAllocated,
647 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000648 if (CE->getNumArgs() < (Num + 1))
649 return 0;
650
Anna Zaks4141e4d2012-11-13 03:18:01 +0000651 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
652 ReleasedAllocated, ReturnsNullOnFailure);
653}
654
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000655/// Checks if the previous call to free on the given symbol failed - if free
656/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000657static bool didPreviousFreeFail(ProgramStateRef State,
658 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000659 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000660 if (Ret) {
661 assert(*Ret && "We should not store the null return symbol");
662 ConstraintManager &CMgr = State->getConstraintManager();
663 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000664 RetStatusSymbol = *Ret;
665 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000666 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000667 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000668}
669
670ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
671 const Expr *ArgExpr,
672 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000673 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000674 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000675 bool &ReleasedAllocated,
676 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000677
Anna Zaks4141e4d2012-11-13 03:18:01 +0000678 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie5251abe2013-02-20 05:52:05 +0000679 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zakse9ef5622012-02-10 01:11:00 +0000680 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000681 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000682
683 // Check for null dereferences.
David Blaikie5251abe2013-02-20 05:52:05 +0000684 if (!location.getAs<Loc>())
Anna Zaksb319e022012-02-08 20:13:28 +0000685 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000686
Anna Zaksb276bd92012-02-14 00:26:13 +0000687 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000688 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000689 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000690 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000691 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000692
Jordy Rose43859f62010-06-07 19:32:37 +0000693 // Unknown values could easily be okay
694 // Undefined values are handled elsewhere
695 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000696 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000697
Jordy Rose43859f62010-06-07 19:32:37 +0000698 const MemRegion *R = ArgVal.getAsRegion();
699
700 // Nonlocs can't be freed, of course.
701 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
702 if (!R) {
703 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000704 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000705 }
706
707 R = R->StripCasts();
708
709 // Blocks might show up as heap data, but should not be free()d
710 if (isa<BlockDataRegion>(R)) {
711 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000712 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000713 }
714
715 const MemSpaceRegion *MS = R->getMemorySpace();
716
717 // Parameters, locals, statics, and globals shouldn't be freed.
718 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
719 // FIXME: at the time this code was written, malloc() regions were
720 // represented by conjured symbols, which are all in UnknownSpaceRegion.
721 // This means that there isn't actually anything from HeapSpaceRegion
722 // that should be freed, even though we allow it here.
723 // Of course, free() can work on memory allocated outside the current
724 // function, so UnknownSpaceRegion is always a possibility.
725 // False negatives are better than false positives.
726
727 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000728 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000729 }
Anna Zaks118aa752013-02-07 23:05:47 +0000730
731 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose43859f62010-06-07 19:32:37 +0000732 // Various cases could lead to non-symbol values here.
733 // For now, ignore them.
Anna Zaks118aa752013-02-07 23:05:47 +0000734 if (!SrBase)
Anna Zaksb319e022012-02-08 20:13:28 +0000735 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000736
Anna Zaks118aa752013-02-07 23:05:47 +0000737 SymbolRef SymBase = SrBase->getSymbol();
738 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000739 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000740
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000741 // Check double free.
Anna Zaks118aa752013-02-07 23:05:47 +0000742 if (RsBase &&
743 (RsBase->isReleased() || RsBase->isRelinquished()) &&
744 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
Anna Zaks4141e4d2012-11-13 03:18:01 +0000745
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000746 if (ExplodedNode *N = C.generateSink()) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000747 if (!BT_DoubleFree)
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000748 BT_DoubleFree.reset(
Anna Zaksfebdc322012-02-16 22:26:12 +0000749 new BugType("Double free", "Memory Error"));
Anna Zaks118aa752013-02-07 23:05:47 +0000750 BugReport *R = new BugReport(*BT_DoubleFree,
751 (RsBase->isReleased() ? "Attempt to free released memory"
752 : "Attempt to free non-owned memory"),
753 N);
Anna Zaksfe571602012-02-16 22:26:07 +0000754 R->addRange(ArgExpr->getSourceRange());
Anna Zaks118aa752013-02-07 23:05:47 +0000755 R->markInteresting(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000756 if (PreviousRetStatusSymbol)
757 R->markInteresting(PreviousRetStatusSymbol);
Anna Zaks118aa752013-02-07 23:05:47 +0000758 R->addVisitor(new MallocBugVisitor(SymBase));
Jordan Rose785950e2012-11-02 01:53:40 +0000759 C.emitReport(R);
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000760 }
Anna Zaksb319e022012-02-08 20:13:28 +0000761 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000762 }
763
Anna Zaks118aa752013-02-07 23:05:47 +0000764 // Check if the memory location being freed is the actual location
765 // allocated, or an offset.
766 RegionOffset Offset = R->getAsOffset();
767 if (RsBase && RsBase->isAllocated() &&
768 Offset.isValid() &&
769 !Offset.hasSymbolicOffset() &&
770 Offset.getOffset() != 0) {
771 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange());
772 return 0;
773 }
774
775 ReleasedAllocated = (RsBase != 0);
Anna Zaks55dd9562012-08-24 02:28:20 +0000776
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000777 // Clean out the info on previous call to free return info.
Anna Zaks118aa752013-02-07 23:05:47 +0000778 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000779
Anna Zaks4141e4d2012-11-13 03:18:01 +0000780 // Keep track of the return value. If it is NULL, we will know that free
781 // failed.
782 if (ReturnsNullOnFailure) {
783 SVal RetVal = C.getSVal(ParentExpr);
784 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
785 if (RetStatusSymbol) {
Anna Zaks118aa752013-02-07 23:05:47 +0000786 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
787 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000788 }
789 }
790
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000791 // Normal free.
Anna Zaks118aa752013-02-07 23:05:47 +0000792 if (Hold) {
793 return State->set<RegionState>(SymBase,
794 RefState::getRelinquished(ParentExpr));
795 }
796 return State->set<RegionState>(SymBase, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000797}
798
Ted Kremenek9c378f72011-08-12 23:37:29 +0000799bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000800 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +0000801 os << "an integer (" << IntVal->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +0000802 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +0000803 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +0000804 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner68106302011-02-17 05:38:27 +0000805 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000806 else
807 return false;
808
809 return true;
810}
811
Ted Kremenek9c378f72011-08-12 23:37:29 +0000812bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000813 const MemRegion *MR) {
814 switch (MR->getKind()) {
815 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000816 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +0000817 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000818 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000819 else
820 os << "the address of a function";
821 return true;
822 }
823 case MemRegion::BlockTextRegionKind:
824 os << "block text";
825 return true;
826 case MemRegion::BlockDataRegionKind:
827 // FIXME: where the block came from?
828 os << "a block";
829 return true;
830 default: {
831 const MemSpaceRegion *MS = MR->getMemorySpace();
832
Anna Zakseb31a762012-01-04 23:54:01 +0000833 if (isa<StackLocalsSpaceRegion>(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 local variable '" << VD->getName() << "'";
843 else
844 os << "the address of a local stack variable";
845 return true;
846 }
Anna Zakseb31a762012-01-04 23:54:01 +0000847
848 if (isa<StackArgumentsSpaceRegion>(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 os << "the address of the parameter '" << VD->getName() << "'";
858 else
859 os << "the address of a parameter";
860 return true;
861 }
Anna Zakseb31a762012-01-04 23:54:01 +0000862
863 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000864 const VarRegion *VR = dyn_cast<VarRegion>(MR);
865 const VarDecl *VD;
866 if (VR)
867 VD = VR->getDecl();
868 else
869 VD = NULL;
870
871 if (VD) {
872 if (VD->isStaticLocal())
873 os << "the address of the static variable '" << VD->getName() << "'";
874 else
875 os << "the address of the global variable '" << VD->getName() << "'";
876 } else
877 os << "the address of a global variable";
878 return true;
879 }
Anna Zakseb31a762012-01-04 23:54:01 +0000880
881 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000882 }
883 }
884}
885
886void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000887 SourceRange range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000888 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000889 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000890 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000891
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000892 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000893 llvm::raw_svector_ostream os(buf);
894
895 const MemRegion *MR = ArgVal.getAsRegion();
896 if (MR) {
897 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
898 MR = ER->getSuperRegion();
899
900 // Special case for alloca()
901 if (isa<AllocaRegion>(MR))
902 os << "Argument to free() was allocated by alloca(), not malloc()";
903 else {
904 os << "Argument to free() is ";
905 if (SummarizeRegion(os, MR))
906 os << ", which is not memory allocated by malloc()";
907 else
908 os << "not memory allocated by malloc()";
909 }
910 } else {
911 os << "Argument to free() is ";
912 if (SummarizeValue(os, ArgVal))
913 os << ", which is not memory allocated by malloc()";
914 else
915 os << "not memory allocated by malloc()";
916 }
917
Anna Zakse172e8b2011-08-17 23:00:25 +0000918 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000919 R->markInteresting(MR);
Jordy Rose43859f62010-06-07 19:32:37 +0000920 R->addRange(range);
Jordan Rose785950e2012-11-02 01:53:40 +0000921 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +0000922 }
923}
924
Anna Zaks118aa752013-02-07 23:05:47 +0000925void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
926 SourceRange Range) const {
927 ExplodedNode *N = C.generateSink();
928 if (N == NULL)
929 return;
930
931 if (!BT_OffsetFree)
932 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
933
934 SmallString<100> buf;
935 llvm::raw_svector_ostream os(buf);
936
937 const MemRegion *MR = ArgVal.getAsRegion();
938 assert(MR && "Only MemRegion based symbols can have offset free errors");
939
940 RegionOffset Offset = MR->getAsOffset();
941 assert((Offset.isValid() &&
942 !Offset.hasSymbolicOffset() &&
943 Offset.getOffset() != 0) &&
944 "Only symbols with a valid offset can have offset free errors");
945
946 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
947
948 os << "Argument to free() is offset by "
949 << offsetBytes
950 << " "
951 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
952 << " from the start of memory allocated by malloc()";
953
954 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
955 R->markInteresting(MR->getBaseRegion());
956 R->addRange(Range);
957 C.emitReport(R);
958}
959
Anna Zaks87cb5be2012-02-22 19:24:52 +0000960ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
961 const CallExpr *CE,
962 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000963 if (CE->getNumArgs() < 2)
964 return 0;
965
Ted Kremenek8bef8232012-01-26 21:29:00 +0000966 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000967 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000968 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000969 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +0000970 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000971 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000972 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000973
Ted Kremenek846eabd2010-12-01 21:28:31 +0000974 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000975
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000976 DefinedOrUnknownSVal PtrEQ =
977 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000978
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000979 // Get the size argument. If there is no size arg then give up.
980 const Expr *Arg1 = CE->getArg(1);
981 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +0000982 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000983
984 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +0000985 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +0000986 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000987 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000988 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +0000989
990 // Compare the size argument to 0.
991 DefinedOrUnknownSVal SizeZero =
992 svalBuilder.evalEQ(state, Arg1Val,
993 svalBuilder.makeIntValWithPtrWidth(0, false));
994
Anna Zaksc8bb3be2012-02-13 18:05:39 +0000995 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
996 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
997 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
998 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
999 // We only assume exceptional states if they are definitely true; if the
1000 // state is under-constrained, assume regular realloc behavior.
1001 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1002 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1003
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001004 // If the ptr is NULL and the size is not 0, the call is equivalent to
1005 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001006 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +00001007 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001008 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001009 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001010 }
1011
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001012 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001013 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001014
Anna Zaks30838b92012-02-13 20:57:07 +00001015 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001016 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001017 SymbolRef FromPtr = arg0Val.getAsSymbol();
1018 SVal RetVal = state->getSVal(CE, LCtx);
1019 SymbolRef ToPtr = RetVal.getAsSymbol();
1020 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001021 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001022
Anna Zaks55dd9562012-08-24 02:28:20 +00001023 bool ReleasedAllocated = false;
1024
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001025 // If the size is 0, free the memory.
1026 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001027 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1028 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001029 // The semantics of the return value are:
1030 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001031 // to free() is returned. We just free the input pointer and do not add
1032 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001033 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001034 }
1035
1036 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001037 if (ProgramStateRef stateFree =
1038 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1039
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001040 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1041 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001042 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001043 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001044
Anna Zaks9dc298b2012-09-12 22:57:34 +00001045 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1046 if (FreesOnFail)
1047 Kind = RPIsFreeOnFailure;
1048 else if (!ReleasedAllocated)
1049 Kind = RPDoNotTrackAfterFailure;
1050
Anna Zaks55dd9562012-08-24 02:28:20 +00001051 // Record the info about the reallocated symbol so that we could properly
1052 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001053 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001054 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001055 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001056 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001057 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001058 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001059 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001060}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001061
Anna Zaks87cb5be2012-02-22 19:24:52 +00001062ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001063 if (CE->getNumArgs() < 2)
1064 return 0;
1065
Ted Kremenek8bef8232012-01-26 21:29:00 +00001066 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001067 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001068 const LocationContext *LCtx = C.getLocationContext();
1069 SVal count = state->getSVal(CE->getArg(0), LCtx);
1070 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001071 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1072 svalBuilder.getContext().getSizeType());
1073 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001074
Anna Zaks87cb5be2012-02-22 19:24:52 +00001075 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001076}
1077
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001078LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001079MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1080 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001081 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001082 // Walk the ExplodedGraph backwards and find the first node that referred to
1083 // the tracked symbol.
1084 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001085 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001086
1087 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001088 ProgramStateRef State = N->getState();
1089 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001090 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001091
1092 // Find the most recent expression bound to the symbol in the current
1093 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001094 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001095 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1096 SVal Val = State->getSVal(MR);
1097 if (Val.getAsLocSymbol() == Sym)
1098 ReferenceRegion = MR;
1099 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001100 }
1101
Anna Zaks7752d292012-02-27 23:40:55 +00001102 // Allocation node, is the last node in the current context in which the
1103 // symbol was tracked.
1104 if (N->getLocationContext() == LeakContext)
1105 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001106 N = N->pred_empty() ? NULL : *(N->pred_begin());
1107 }
1108
Anna Zaks97bfb552013-01-08 00:25:29 +00001109 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001110}
1111
Anna Zaksda046772012-02-11 21:02:40 +00001112void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1113 CheckerContext &C) const {
1114 assert(N);
1115 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001116 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001117 // Leaks should not be reported if they are post-dominated by a sink:
1118 // (1) Sinks are higher importance bugs.
1119 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1120 // with __noreturn functions such as assert() or exit(). We choose not
1121 // to report leaks on such paths.
1122 BT_Leak->setSuppressOnSink(true);
1123 }
1124
Anna Zaksca8e36e2012-02-23 21:38:21 +00001125 // Most bug reports are cached at the location where they occurred.
1126 // With leaks, we want to unique them by the location where they were
1127 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001128 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001129 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001130 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001131 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1132
1133 ProgramPoint P = AllocNode->getLocation();
1134 const Stmt *AllocationStmt = 0;
David Blaikie7a95de62013-02-21 22:23:56 +00001135 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001136 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001137 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001138 AllocationStmt = SP->getStmt();
1139 if (AllocationStmt)
1140 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1141 C.getSourceManager(),
1142 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001143
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001144 SmallString<200> buf;
1145 llvm::raw_svector_ostream os(buf);
1146 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001147 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001148 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001149 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001150 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001151 }
1152
Anna Zaks97bfb552013-01-08 00:25:29 +00001153 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1154 LocUsedForUniqueing,
1155 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001156 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001157 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001158 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001159}
1160
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001161void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1162 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001163{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001164 if (!SymReaper.hasDeadSymbols())
1165 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001166
Ted Kremenek8bef8232012-01-26 21:29:00 +00001167 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001168 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001169 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001170
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001171 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001172 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1173 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001174 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001175 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001176 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001177 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001178
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001179 }
1180 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001181
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001182 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001183 ReallocPairsTy RP = state->get<ReallocPairs>();
1184 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001185 if (SymReaper.isDead(I->first) ||
1186 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001187 state = state->remove<ReallocPairs>(I->first);
1188 }
1189 }
1190
Anna Zaks4141e4d2012-11-13 03:18:01 +00001191 // Cleanup the FreeReturnValue Map.
1192 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1193 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1194 if (SymReaper.isDead(I->first) ||
1195 SymReaper.isDead(I->second)) {
1196 state = state->remove<FreeReturnValue>(I->first);
1197 }
1198 }
1199
Anna Zaksca8e36e2012-02-23 21:38:21 +00001200 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001201 ExplodedNode *N = C.getPredecessor();
1202 if (!Errors.empty()) {
1203 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1204 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001205 for (SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001206 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001207 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001208 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001209 }
Anna Zaks54458702012-10-29 22:51:54 +00001210
Anna Zaksca8e36e2012-02-23 21:38:21 +00001211 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001212}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001213
Anna Zaks66c40402012-02-14 21:55:24 +00001214void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001215 // We will check for double free in the post visit.
1216 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001217 return;
1218
1219 // Check use after free, when a freed pointer is passed to a call.
1220 ProgramStateRef State = C.getState();
1221 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1222 E = CE->arg_end(); I != E; ++I) {
1223 const Expr *A = *I;
1224 if (A->getType().getTypePtr()->isAnyPointerType()) {
1225 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
1226 if (!Sym)
1227 continue;
1228 if (checkUseAfterFree(Sym, C, A))
1229 return;
1230 }
1231 }
1232}
1233
Anna Zaks91c2a112012-02-08 23:16:56 +00001234void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1235 const Expr *E = S->getRetValue();
1236 if (!E)
1237 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001238
1239 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001240 ProgramStateRef State = C.getState();
1241 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001242 SymbolRef Sym = RetVal.getAsSymbol();
1243 if (!Sym)
1244 // If we are returning a field of the allocated struct or an array element,
1245 // the callee could still free the memory.
1246 // TODO: This logic should be a part of generic symbol escape callback.
1247 if (const MemRegion *MR = RetVal.getAsRegion())
1248 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1249 if (const SymbolicRegion *BMR =
1250 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1251 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001252
Anna Zaks0860cd02012-02-11 21:44:39 +00001253 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001254 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001255 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001256}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001257
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001258// TODO: Blocks should be either inlined or should call invalidate regions
1259// upon invocation. After that's in place, special casing here will not be
1260// needed.
1261void MallocChecker::checkPostStmt(const BlockExpr *BE,
1262 CheckerContext &C) const {
1263
1264 // Scan the BlockDecRefExprs for any object the retain count checker
1265 // may be tracking.
1266 if (!BE->getBlockDecl()->hasCaptures())
1267 return;
1268
1269 ProgramStateRef state = C.getState();
1270 const BlockDataRegion *R =
1271 cast<BlockDataRegion>(state->getSVal(BE,
1272 C.getLocationContext()).getAsRegion());
1273
1274 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1275 E = R->referenced_vars_end();
1276
1277 if (I == E)
1278 return;
1279
1280 SmallVector<const MemRegion*, 10> Regions;
1281 const LocationContext *LC = C.getLocationContext();
1282 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1283
1284 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001285 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001286 if (VR->getSuperRegion() == R) {
1287 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1288 }
1289 Regions.push_back(VR);
1290 }
1291
1292 state =
1293 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1294 Regions.data() + Regions.size()).getState();
1295 C.addTransition(state);
1296}
1297
Anna Zaks14345182012-05-18 01:16:10 +00001298bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001299 assert(Sym);
1300 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001301 return (RS && RS->isReleased());
1302}
1303
1304bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1305 const Stmt *S) const {
1306 if (isReleased(Sym, C)) {
Anna Zaks15d0ae12012-02-11 23:46:36 +00001307 if (ExplodedNode *N = C.generateSink()) {
Anna Zaks91c2a112012-02-08 23:16:56 +00001308 if (!BT_UseFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001309 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
Anna Zaks91c2a112012-02-08 23:16:56 +00001310
Anna Zaksfebdc322012-02-16 22:26:12 +00001311 BugReport *R = new BugReport(*BT_UseFree,
1312 "Use of memory after it is freed",N);
Anna Zaks91c2a112012-02-08 23:16:56 +00001313 if (S)
1314 R->addRange(S->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001315 R->markInteresting(Sym);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001316 R->addVisitor(new MallocBugVisitor(Sym));
Jordan Rose785950e2012-11-02 01:53:40 +00001317 C.emitReport(R);
Anna Zaks91c2a112012-02-08 23:16:56 +00001318 return true;
1319 }
1320 }
1321 return false;
1322}
1323
Zhongxing Xuc8023782010-03-10 04:58:55 +00001324// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001325void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1326 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001327 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001328 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001329 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001330}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001331
Anna Zaks4fb54872012-02-11 21:02:35 +00001332// If a symbolic region is assumed to NULL (or another constant), stop tracking
1333// it - assuming that allocation failed on this path.
1334ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1335 SVal Cond,
1336 bool Assumption) const {
1337 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001338 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001339 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001340 ConstraintManager &CMgr = state->getConstraintManager();
1341 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1342 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001343 state = state->remove<RegionState>(I.getKey());
1344 }
1345
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001346 // Realloc returns 0 when reallocation fails, which means that we should
1347 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001348 ReallocPairsTy RP = state->get<ReallocPairs>();
1349 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001350 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001351 ConstraintManager &CMgr = state->getConstraintManager();
1352 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001353 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001354 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001355
Anna Zaks9dc298b2012-09-12 22:57:34 +00001356 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1357 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1358 if (RS->isReleased()) {
1359 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001360 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001361 RefState::getAllocated(RS->getStmt()));
1362 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1363 state = state->remove<RegionState>(ReallocSym);
1364 else
1365 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001366 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001367 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001368 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001369 }
1370
Anna Zaks4fb54872012-02-11 21:02:35 +00001371 return state;
1372}
1373
Jordan Rose9fe09f32013-03-09 00:59:10 +00001374bool MallocChecker::doesNotFreeMemOrInteresting(const CallEvent *Call,
1375 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001376 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001377
1378 // For now, assume that any C++ call can free memory.
1379 // TODO: If we want to be more optimistic here, we'll need to make sure that
1380 // regions escape to C++ containers. They seem to do that even now, but for
1381 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001382 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001383 return false;
1384
Jordan Rose740d4902012-07-02 19:27:35 +00001385 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001386 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001387 // If it's not a framework call, or if it takes a callback, assume it
1388 // can free memory.
1389 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001390 return false;
1391
Jordan Rose9fe09f32013-03-09 00:59:10 +00001392 // If it's a method we know about, handle it explicitly post-call.
1393 // This should happen before the "freeWhenDone" check below.
1394 if (isKnownDeallocObjCMethodName(*Msg))
1395 return true;
Anna Zaks52a04812012-06-20 23:35:57 +00001396
Jordan Rose9fe09f32013-03-09 00:59:10 +00001397 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1398 // about, we can't be sure that the object will use free() to deallocate the
1399 // memory, so we can't model it explicitly. The best we can do is use it to
1400 // decide whether the pointer escapes.
1401 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
1402 return !*FreeWhenDone;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001403
Jordan Rose9fe09f32013-03-09 00:59:10 +00001404 // If the first selector piece ends with "NoCopy", and there is no
1405 // "freeWhenDone" parameter set to zero, we know ownership is being
1406 // transferred. Again, though, we can't be sure that the object will use
1407 // free() to deallocate the memory, so we can't model it explicitly.
1408 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose740d4902012-07-02 19:27:35 +00001409 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001410 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001411
Anna Zaks5f757682012-06-19 05:10:32 +00001412 // If the first selector starts with addPointer, insertPointer,
1413 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1414 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001415 // that the pointers get freed by following the container itself.
1416 if (FirstSlot.startswith("addPointer") ||
1417 FirstSlot.startswith("insertPointer") ||
1418 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001419 return false;
1420 }
1421
Jordan Rose740d4902012-07-02 19:27:35 +00001422 // Otherwise, assume that the method does not free memory.
1423 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001424 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001425 }
1426
Jordan Rose740d4902012-07-02 19:27:35 +00001427 // At this point the only thing left to handle is straight function calls.
1428 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1429 if (!FD)
1430 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001431
Jordan Rose740d4902012-07-02 19:27:35 +00001432 ASTContext &ASTC = State->getStateManager().getContext();
1433
1434 // If it's one of the allocation functions we can reason about, we model
1435 // its behavior explicitly.
1436 if (isMemFunction(FD, ASTC))
1437 return true;
1438
1439 // If it's not a system call, assume it frees memory.
1440 if (!Call->isInSystemHeader())
1441 return false;
1442
1443 // White list the system functions whose arguments escape.
1444 const IdentifierInfo *II = FD->getIdentifier();
1445 if (!II)
1446 return false;
1447 StringRef FName = II->getName();
1448
Jordan Rose740d4902012-07-02 19:27:35 +00001449 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001450 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001451 if (FName.endswith("NoCopy")) {
1452 // Look for the deallocator argument. We know that the memory ownership
1453 // is not transferred only if the deallocator argument is
1454 // 'kCFAllocatorNull'.
1455 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1456 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1457 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1458 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1459 if (DeallocatorName == "kCFAllocatorNull")
1460 return true;
1461 }
1462 }
1463 return false;
1464 }
1465
Jordan Rose740d4902012-07-02 19:27:35 +00001466 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001467 // 'closefn' is specified (and if that function does free memory),
1468 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001469 // Currently, we do not inspect the 'closefn' function (PR12101).
1470 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001471 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1472 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001473
1474 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1475 // these leaks might be intentional when setting the buffer for stdio.
1476 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1477 if (FName == "setbuf" || FName =="setbuffer" ||
1478 FName == "setlinebuf" || FName == "setvbuf") {
1479 if (Call->getNumArgs() >= 1) {
1480 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1481 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1482 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1483 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1484 return false;
1485 }
1486 }
1487
1488 // A bunch of other functions which either take ownership of a pointer or
1489 // wrap the result up in a struct or object, meaning it can be freed later.
1490 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1491 // but the Malloc checker cannot differentiate between them. The right way
1492 // of doing this would be to implement a pointer escapes callback.
1493 if (FName == "CGBitmapContextCreate" ||
1494 FName == "CGBitmapContextCreateWithData" ||
1495 FName == "CVPixelBufferCreateWithBytes" ||
1496 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1497 FName == "OSAtomicEnqueue") {
1498 return false;
1499 }
1500
Jordan Rose85d7e012012-07-02 19:27:51 +00001501 // Handle cases where we know a buffer's /address/ can escape.
1502 // Note that the above checks handle some special cases where we know that
1503 // even though the address escapes, it's still our responsibility to free the
1504 // buffer.
1505 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001506 return false;
1507
1508 // Otherwise, assume that the function does not free memory.
1509 // Most system calls do not free the memory.
1510 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001511}
1512
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001513ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1514 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00001515 const CallEvent *Call,
1516 PointerEscapeKind Kind) const {
Jordan Rose9fe09f32013-03-09 00:59:10 +00001517 // If we know that the call does not free memory, or we want to process the
1518 // call later, keep tracking the top level arguments.
Anna Zaks233e26a2013-02-07 23:05:43 +00001519 if ((Kind == PSK_DirectEscapeOnCall ||
1520 Kind == PSK_IndirectEscapeOnCall) &&
Jordan Rose9fe09f32013-03-09 00:59:10 +00001521 doesNotFreeMemOrInteresting(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001522 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00001523 }
Anna Zaks66c40402012-02-14 21:55:24 +00001524
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001525 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
1526 E = Escaped.end();
1527 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001528 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001529
Anna Zaks5b7aa342012-06-22 02:04:31 +00001530 if (const RefState *RS = State->get<RegionState>(sym)) {
1531 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001532 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001533 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001534 }
Anna Zaks66c40402012-02-14 21:55:24 +00001535 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001536}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001537
Jordy Rose393f98b2012-03-18 07:43:35 +00001538static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1539 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001540 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1541 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001542
Jordan Rose166d5022012-11-02 01:54:06 +00001543 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001544 I != E; ++I) {
1545 SymbolRef sym = I.getKey();
1546 if (!currMap.lookup(sym))
1547 return sym;
1548 }
1549
1550 return NULL;
1551}
1552
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001553PathDiagnosticPiece *
1554MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1555 const ExplodedNode *PrevN,
1556 BugReporterContext &BRC,
1557 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001558 ProgramStateRef state = N->getState();
1559 ProgramStateRef statePrev = PrevN->getState();
1560
1561 const RefState *RS = state->get<RegionState>(Sym);
1562 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001563 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001564 return 0;
1565
Anna Zaksfe571602012-02-16 22:26:07 +00001566 const Stmt *S = 0;
1567 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001568 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001569
1570 // Retrieve the associated statement.
1571 ProgramPoint ProgLoc = N->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00001572 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001573 S = SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +00001574 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001575 S = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001576 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremeneka4a17592013-01-04 19:04:36 +00001577 // If an assumption was made on a branch, it should be caught
1578 // here by looking at the state transition.
1579 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00001580 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00001581
Anna Zaksfe571602012-02-16 22:26:07 +00001582 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001583 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001584
Jordan Rose28038f32012-07-10 22:07:42 +00001585 // FIXME: We will eventually need to handle non-statement-based events
1586 // (__attribute__((cleanup))).
1587
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001588 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001589 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001590 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001591 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001592 StackHint = new StackHintGeneratorForSymbol(Sym,
1593 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001594 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001595 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001596 StackHint = new StackHintGeneratorForSymbol(Sym,
1597 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001598 } else if (isRelinquished(RS, RSPrev, S)) {
1599 Msg = "Memory ownership is transfered";
1600 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001601 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001602 Mode = ReallocationFailed;
1603 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001604 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001605 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001606
Jordy Roseb000fb52012-03-24 03:15:09 +00001607 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1608 // Is it possible to fail two reallocs WITHOUT testing in between?
1609 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1610 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001611 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001612 FailedReallocSymbol = sym;
1613 }
Anna Zaksfe571602012-02-16 22:26:07 +00001614 }
1615
1616 // We are in a special mode if a reallocation failed later in the path.
1617 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001618 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001619
Jordy Roseb000fb52012-03-24 03:15:09 +00001620 // Is this is the first appearance of the reallocated symbol?
1621 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001622 // We're at the reallocation point.
1623 Msg = "Attempt to reallocate memory";
1624 StackHint = new StackHintGeneratorForSymbol(Sym,
1625 "Returned reallocated memory");
1626 FailedReallocSymbol = NULL;
1627 Mode = Normal;
1628 }
Anna Zaksfe571602012-02-16 22:26:07 +00001629 }
1630
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001631 if (!Msg)
1632 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001633 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001634
1635 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001636 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001637 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001638 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001639}
1640
Anna Zaks93c5a242012-05-02 00:05:20 +00001641void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1642 const char *NL, const char *Sep) const {
1643
1644 RegionStateTy RS = State->get<RegionState>();
1645
Ted Kremenekc37fad62013-01-03 01:30:12 +00001646 if (!RS.isEmpty()) {
1647 Out << Sep << "MallocChecker:" << NL;
1648 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1649 I.getKey()->dumpToStream(Out);
1650 Out << " : ";
1651 I.getData().dump(Out);
1652 Out << NL;
1653 }
1654 }
Anna Zaks93c5a242012-05-02 00:05:20 +00001655}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001656
Anna Zaks231361a2012-02-08 23:16:52 +00001657#define REGISTER_CHECKER(name) \
1658void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001659 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001660 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001661}
Anna Zaks231361a2012-02-08 23:16:52 +00001662
1663REGISTER_CHECKER(MallocPessimistic)
1664REGISTER_CHECKER(MallocOptimistic)