blob: 068f9ce822a9ca02cc4dae02d9dc07f6d1db9ef2 [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>,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000123 check::PostStmt<CXXNewExpr>,
124 check::PreStmt<CXXDeleteExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000125 check::PostStmt<BlockExpr>,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000126 check::PostObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000127 check::Location,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000128 eval::Assume>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000129{
Anna Zaksfebdc322012-02-16 22:26:12 +0000130 mutable OwningPtr<BugType> BT_DoubleFree;
131 mutable OwningPtr<BugType> BT_Leak;
132 mutable OwningPtr<BugType> BT_UseFree;
133 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaks118aa752013-02-07 23:05:47 +0000134 mutable OwningPtr<BugType> BT_OffsetFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000135 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000136 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
137
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000138public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000139 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000140 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000141
142 /// In pessimistic mode, the checker assumes that it does not know which
143 /// functions might free the memory.
144 struct ChecksFilter {
145 DefaultBool CMallocPessimistic;
146 DefaultBool CMallocOptimistic;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000147 DefaultBool CNewDeleteChecker;
Anna Zaks231361a2012-02-08 23:16:52 +0000148 };
149
150 ChecksFilter Filter;
151
Anna Zaks66c40402012-02-14 21:55:24 +0000152 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000153 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000154 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
155 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000156 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000157 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000158 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000159 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000160 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000161 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000162 void checkLocation(SVal l, bool isLoad, const Stmt *S,
163 CheckerContext &C) const;
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000164
165 ProgramStateRef checkPointerEscape(ProgramStateRef State,
166 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +0000167 const CallEvent *Call,
168 PointerEscapeKind Kind) const;
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000169
Anna Zaks93c5a242012-05-02 00:05:20 +0000170 void printState(raw_ostream &Out, ProgramStateRef State,
171 const char *NL, const char *Sep) const;
172
Zhongxing Xu7b760962009-11-13 07:25:27 +0000173private:
Anna Zaks66c40402012-02-14 21:55:24 +0000174 void initIdentifierInfo(ASTContext &C) const;
175
Jordan Rose9fe09f32013-03-09 00:59:10 +0000176 ///@{
Anna Zaks66c40402012-02-14 21:55:24 +0000177 /// Check if this is one of the functions which can allocate/reallocate memory
178 /// pointed to by one of its arguments.
179 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000180 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
181 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000182 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose9fe09f32013-03-09 00:59:10 +0000183 ///@}
Anna Zaks87cb5be2012-02-22 19:24:52 +0000184 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
185 const CallExpr *CE,
186 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000187 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000188 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000189 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000190 return MallocMemAux(C, CE,
191 state->getSVal(SizeEx, C.getLocationContext()),
192 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000193 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000194
Ted Kremenek8bef8232012-01-26 21:29:00 +0000195 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000196 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000197 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000198
Anna Zaks87cb5be2012-02-22 19:24:52 +0000199 /// Update the RefState to reflect the new memory allocation.
200 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000201 const Expr *E,
Anna Zaks87cb5be2012-02-22 19:24:52 +0000202 ProgramStateRef state);
203
204 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
205 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000206 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000207 ProgramStateRef state, unsigned Num,
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;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000211 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
212 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000213 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000214 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000215 bool &ReleasedAllocated,
216 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000217
Anna Zaks87cb5be2012-02-22 19:24:52 +0000218 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
219 bool FreesMemOnFailure) const;
220 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000221
Anna Zaks14345182012-05-18 01:16:10 +0000222 ///\brief Check if the memory associated with this symbol was released.
223 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
224
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000225 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaks91c2a112012-02-08 23:16:56 +0000226
Jordan Rose9fe09f32013-03-09 00:59:10 +0000227 /// Check if the function is known not to free memory, or if it is
228 /// "interesting" and should be modeled explicitly.
229 ///
230 /// We assume that pointers do not escape through calls to system functions
231 /// not handled by this checker.
232 bool doesNotFreeMemOrInteresting(const CallEvent *Call,
233 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000234
Ted Kremenek9c378f72011-08-12 23:37:29 +0000235 static bool SummarizeValue(raw_ostream &os, SVal V);
236 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsevbb369952013-03-13 14:39:10 +0000237 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range) const;
238 void ReportBadDealloc(CheckerContext &C, SourceRange Range,
239 const Expr *DeallocExpr, const RefState *RS) const;
Anna Zaks118aa752013-02-07 23:05:47 +0000240 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range)const;
Anton Yartsevbb369952013-03-13 14:39:10 +0000241 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
242 SymbolRef Sym) const;
243 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev3258d4b2013-03-13 17:07:32 +0000244 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000245
Anna Zaksca8e36e2012-02-23 21:38:21 +0000246 /// Find the location of the allocation for Sym on the path leading to the
247 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000248 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
249 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000250
Anna Zaksda046772012-02-11 21:02:40 +0000251 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
252
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000253 /// The bug visitor which allows us to print extra diagnostics along the
254 /// BugReport path. For example, showing the allocation site of the leaked
255 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000256 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000257 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000258 enum NotificationMode {
259 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000260 ReallocationFailed
261 };
262
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000263 // The allocated region symbol tracked by the main analysis.
264 SymbolRef Sym;
265
Anna Zaks88feba02012-05-10 01:37:40 +0000266 // The mode we are in, i.e. what kind of diagnostics will be emitted.
267 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000268
Anna Zaks88feba02012-05-10 01:37:40 +0000269 // A symbol from when the primary region should have been reallocated.
270 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000271
Anna Zaks88feba02012-05-10 01:37:40 +0000272 bool IsLeak;
273
274 public:
275 MallocBugVisitor(SymbolRef S, bool isLeak = false)
276 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000277
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000278 virtual ~MallocBugVisitor() {}
279
280 void Profile(llvm::FoldingSetNodeID &ID) const {
281 static int X = 0;
282 ID.AddPointer(&X);
283 ID.AddPointer(Sym);
284 }
285
Anna Zaksfe571602012-02-16 22:26:07 +0000286 inline bool isAllocated(const RefState *S, const RefState *SPrev,
287 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000288 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000289 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000290 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000291 }
292
Anna Zaksfe571602012-02-16 22:26:07 +0000293 inline bool isReleased(const RefState *S, const RefState *SPrev,
294 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000295 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000296 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000297 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
298 }
299
Anna Zaks5b7aa342012-06-22 02:04:31 +0000300 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
301 const Stmt *Stmt) {
302 // Did not track -> relinquished. Other state (allocated) -> relinquished.
303 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
304 isa<ObjCPropertyRefExpr>(Stmt)) &&
305 (S && S->isRelinquished()) &&
306 (!SPrev || !SPrev->isRelinquished()));
307 }
308
Anna Zaksfe571602012-02-16 22:26:07 +0000309 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
310 const Stmt *Stmt) {
311 // If the expression is not a call, and the state change is
312 // released -> allocated, it must be the realloc return value
313 // check. If we have to handle more cases here, it might be cleaner just
314 // to track this extra bit in the state itself.
315 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
316 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000317 }
318
319 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
320 const ExplodedNode *PrevN,
321 BugReporterContext &BRC,
322 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000323
324 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
325 const ExplodedNode *EndPathNode,
326 BugReport &BR) {
327 if (!IsLeak)
328 return 0;
329
330 PathDiagnosticLocation L =
331 PathDiagnosticLocation::createEndOfPath(EndPathNode,
332 BRC.getSourceManager());
333 // Do not add the statement itself as a range in case of leak.
334 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
335 }
336
Anna Zaks56a938f2012-03-16 23:24:20 +0000337 private:
338 class StackHintGeneratorForReallocationFailed
339 : public StackHintGeneratorForSymbol {
340 public:
341 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
342 : StackHintGeneratorForSymbol(S, M) {}
343
344 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000345 // Printed parameters start at 1, not 0.
346 ++ArgIndex;
347
Anna Zaks56a938f2012-03-16 23:24:20 +0000348 SmallString<200> buf;
349 llvm::raw_svector_ostream os(buf);
350
Jordan Rose615a0922012-09-22 01:24:42 +0000351 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
352 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000353
354 return os.str();
355 }
356
357 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000358 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000359 }
360 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000361 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000362};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000363} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000364
Jordan Rose166d5022012-11-02 01:54:06 +0000365REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
366REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000367
Anna Zaks4141e4d2012-11-13 03:18:01 +0000368// A map from the freed symbol to the symbol representing the return value of
369// the free function.
370REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
371
Anna Zaks4fb54872012-02-11 21:02:35 +0000372namespace {
373class StopTrackingCallback : public SymbolVisitor {
374 ProgramStateRef state;
375public:
376 StopTrackingCallback(ProgramStateRef st) : state(st) {}
377 ProgramStateRef getState() const { return state; }
378
379 bool VisitSymbol(SymbolRef sym) {
380 state = state->remove<RegionState>(sym);
381 return true;
382 }
383};
384} // end anonymous namespace
385
Anna Zaks66c40402012-02-14 21:55:24 +0000386void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000387 if (II_malloc)
388 return;
389 II_malloc = &Ctx.Idents.get("malloc");
390 II_free = &Ctx.Idents.get("free");
391 II_realloc = &Ctx.Idents.get("realloc");
392 II_reallocf = &Ctx.Idents.get("reallocf");
393 II_calloc = &Ctx.Idents.get("calloc");
394 II_valloc = &Ctx.Idents.get("valloc");
395 II_strdup = &Ctx.Idents.get("strdup");
396 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000397}
398
Anna Zaks66c40402012-02-14 21:55:24 +0000399bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000400 if (isFreeFunction(FD, C))
401 return true;
402
403 if (isAllocationFunction(FD, C))
404 return true;
405
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000406 if (isStandardNewDelete(FD, C))
407 return true;
408
Anna Zaks14345182012-05-18 01:16:10 +0000409 return false;
410}
411
412bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
413 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000414 if (!FD)
415 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000416
Jordan Rose5ef6e942012-07-10 23:13:01 +0000417 if (FD->getKind() == Decl::Function) {
418 IdentifierInfo *FunI = FD->getIdentifier();
419 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000420
Jordan Rose5ef6e942012-07-10 23:13:01 +0000421 if (FunI == II_malloc || FunI == II_realloc ||
422 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
423 FunI == II_strdup || FunI == II_strndup)
424 return true;
425 }
Anna Zaks66c40402012-02-14 21:55:24 +0000426
Anna Zaks14345182012-05-18 01:16:10 +0000427 if (Filter.CMallocOptimistic && FD->hasAttrs())
428 for (specific_attr_iterator<OwnershipAttr>
429 i = FD->specific_attr_begin<OwnershipAttr>(),
430 e = FD->specific_attr_end<OwnershipAttr>();
431 i != e; ++i)
432 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
433 return true;
434 return false;
435}
436
437bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
438 if (!FD)
439 return false;
440
Jordan Rose5ef6e942012-07-10 23:13:01 +0000441 if (FD->getKind() == Decl::Function) {
442 IdentifierInfo *FunI = FD->getIdentifier();
443 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000444
Jordan Rose5ef6e942012-07-10 23:13:01 +0000445 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
446 return true;
447 }
Anna Zaks66c40402012-02-14 21:55:24 +0000448
Anna Zaks14345182012-05-18 01:16:10 +0000449 if (Filter.CMallocOptimistic && FD->hasAttrs())
450 for (specific_attr_iterator<OwnershipAttr>
451 i = FD->specific_attr_begin<OwnershipAttr>(),
452 e = FD->specific_attr_end<OwnershipAttr>();
453 i != e; ++i)
454 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
455 (*i)->getOwnKind() == OwnershipAttr::Holds)
456 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000457 return false;
458}
459
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000460bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
461 ASTContext &C) const {
462 if (!FD)
463 return false;
464
465 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
466 if (Kind != OO_New && Kind != OO_Array_New &&
467 Kind != OO_Delete && Kind != OO_Array_Delete)
468 return false;
469
470 // Skip custom new operators.
471 if (!FD->isImplicit() &&
472 !C.getSourceManager().isInSystemHeader(FD->getLocStart()))
473 return false;
474
475 // Return true if tested operator is a standard placement nothrow operator.
476 if (FD->getNumParams() == 2) {
477 QualType T = FD->getParamDecl(1)->getType();
478 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
479 return II->getName().equals("nothrow_t");
480 }
481
482 // Skip placement operators.
483 if (FD->getNumParams() != 1 || FD->isVariadic())
484 return false;
485
486 // One of the standard new/new[]/delete/delete[] non-placement operators.
487 return true;
488}
489
Anna Zaksb319e022012-02-08 20:13:28 +0000490void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000491 if (C.wasInlined)
492 return;
493
Anna Zaksb319e022012-02-08 20:13:28 +0000494 const FunctionDecl *FD = C.getCalleeDecl(CE);
495 if (!FD)
496 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000497
Anna Zaks87cb5be2012-02-22 19:24:52 +0000498 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000499 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000500
501 if (FD->getKind() == Decl::Function) {
502 initIdentifierInfo(C.getASTContext());
503 IdentifierInfo *FunI = FD->getIdentifier();
504
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000505 if (Filter.CMallocOptimistic || Filter.CMallocPessimistic) {
506 if (FunI == II_malloc || FunI == II_valloc) {
507 if (CE->getNumArgs() < 1)
508 return;
509 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
510 } else if (FunI == II_realloc) {
511 State = ReallocMem(C, CE, false);
512 } else if (FunI == II_reallocf) {
513 State = ReallocMem(C, CE, true);
514 } else if (FunI == II_calloc) {
515 State = CallocMem(C, CE);
516 } else if (FunI == II_free) {
517 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
518 } else if (FunI == II_strdup) {
519 State = MallocUpdateRefState(C, CE, State);
520 } else if (FunI == II_strndup) {
521 State = MallocUpdateRefState(C, CE, State);
522 }
523 }
524
525 if (Filter.CNewDeleteChecker) {
526 if (isStandardNewDelete(FD, C.getASTContext())) {
527 // Process direct calls to operator new/new[]/delete/delete[] functions
528 // as distinct from new/new[]/delete/delete[] expressions that are
529 // processed by the checkPostStmt callbacks for CXXNewExpr and
530 // CXXDeleteExpr.
531 OverloadedOperatorKind K = FD->getOverloadedOperator();
532 if (K == OO_New)
533 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
534 else if (K == OO_Array_New)
535 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
536 else if (K == OO_Delete || K == OO_Array_Delete)
537 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
538 else
539 llvm_unreachable("not a new/delete operator");
540 }
Jordan Rose5ef6e942012-07-10 23:13:01 +0000541 }
542 }
543
544 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000545 // Check all the attributes, if there are any.
546 // There can be multiple of these attributes.
547 if (FD->hasAttrs())
548 for (specific_attr_iterator<OwnershipAttr>
549 i = FD->specific_attr_begin<OwnershipAttr>(),
550 e = FD->specific_attr_end<OwnershipAttr>();
551 i != e; ++i) {
552 switch ((*i)->getOwnKind()) {
553 case OwnershipAttr::Returns:
554 State = MallocMemReturnsAttr(C, CE, *i);
555 break;
556 case OwnershipAttr::Takes:
557 case OwnershipAttr::Holds:
558 State = FreeMemAttr(C, CE, *i);
559 break;
560 }
561 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000562 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000563 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000564}
565
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000566void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
567 CheckerContext &C) const {
568
569 if (NE->getNumPlacementArgs())
570 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
571 E = NE->placement_arg_end(); I != E; ++I)
572 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
573 checkUseAfterFree(Sym, C, *I);
574
575 if (!Filter.CNewDeleteChecker)
576 return;
577
578 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
579 return;
580
581 ProgramStateRef State = C.getState();
582 // The return value from operator new is bound to a specified initialization
583 // value (if any) and we don't want to loose this value. So we call
584 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
585 // existing binding.
586 State = MallocUpdateRefState(C, NE, State);
587 C.addTransition(State);
588}
589
590void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
591 CheckerContext &C) const {
592
593 if (!Filter.CNewDeleteChecker) {
594 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
595 checkUseAfterFree(Sym, C, DE->getArgument());
596
597 return;
598 }
599
600 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
601 return;
602
603 ProgramStateRef State = C.getState();
604 bool ReleasedAllocated;
605 State = FreeMemAux(C, DE->getArgument(), DE, State,
606 /*Hold*/false, ReleasedAllocated);
607
608 C.addTransition(State);
609}
610
Jordan Rose9fe09f32013-03-09 00:59:10 +0000611static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
612 // If the first selector piece is one of the names below, assume that the
613 // object takes ownership of the memory, promising to eventually deallocate it
614 // with free().
615 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
616 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
617 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
618 if (FirstSlot == "dataWithBytesNoCopy" ||
619 FirstSlot == "initWithBytesNoCopy" ||
620 FirstSlot == "initWithCharactersNoCopy")
621 return true;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000622
623 return false;
624}
625
Jordan Rose9fe09f32013-03-09 00:59:10 +0000626static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
627 Selector S = Call.getSelector();
628
629 // FIXME: We should not rely on fully-constrained symbols being folded.
630 for (unsigned i = 1; i < S.getNumArgs(); ++i)
631 if (S.getNameForSlot(i).equals("freeWhenDone"))
632 return !Call.getArgSVal(i).isZeroConstant();
633
634 return None;
635}
636
Anna Zaks4141e4d2012-11-13 03:18:01 +0000637void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
638 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000639 if (C.wasInlined)
640 return;
641
Jordan Rose9fe09f32013-03-09 00:59:10 +0000642 if (!isKnownDeallocObjCMethodName(Call))
643 return;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000644
Jordan Rose9fe09f32013-03-09 00:59:10 +0000645 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
646 if (!*FreeWhenDone)
647 return;
648
649 bool ReleasedAllocatedMemory;
650 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
651 Call.getOriginExpr(), C.getState(),
652 /*Hold=*/true, ReleasedAllocatedMemory,
653 /*RetNullOnFailure=*/true);
654
655 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000656}
657
Anna Zaks87cb5be2012-02-22 19:24:52 +0000658ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
659 const CallExpr *CE,
660 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000661 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000662 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000663
Sean Huntcf807c42010-08-18 23:23:40 +0000664 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000665 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000666 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000667 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000668 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000669}
670
Anna Zaksb319e022012-02-08 20:13:28 +0000671ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000672 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000673 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000674 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000675
676 // Bind the return value to the symbolic value from the heap region.
677 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
678 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000679 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000680 SValBuilder &svalBuilder = C.getSValBuilder();
681 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie5251abe2013-02-20 05:52:05 +0000682 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
683 .castAs<DefinedSVal>();
Anna Zakse17fdb22012-06-07 03:57:32 +0000684 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000685
Anna Zaksb16ce452012-02-15 00:11:22 +0000686 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000687 if (!RetVal.getAs<Loc>())
Anna Zaksb16ce452012-02-15 00:11:22 +0000688 return 0;
689
Jordy Rose32f26562010-07-04 00:00:41 +0000690 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000691 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000692
Jordy Rose32f26562010-07-04 00:00:41 +0000693 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000694 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000695 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000696 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000697 return 0;
David Blaikiedc84cd52013-02-20 22:23:23 +0000698 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000699 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000700 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000701 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000702 DefinedOrUnknownSVal extentMatchesSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000703 svalBuilder.evalEQ(state, Extent, *DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000704
Anna Zaks60a1fa42012-02-22 03:14:20 +0000705 state = state->assume(extentMatchesSize, true);
706 assert(state);
707 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000708
Anna Zaks87cb5be2012-02-22 19:24:52 +0000709 return MallocUpdateRefState(C, CE, state);
710}
711
712ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000713 const Expr *E,
Anna Zaks87cb5be2012-02-22 19:24:52 +0000714 ProgramStateRef state) {
715 // Get the return value.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000716 SVal retVal = state->getSVal(E, C.getLocationContext());
Anna Zaks87cb5be2012-02-22 19:24:52 +0000717
718 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000719 if (!retVal.getAs<Loc>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000720 return 0;
721
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000722 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000723 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000724
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000725 // Set the symbol's state to Allocated.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000726 return state->set<RegionState>(Sym, RefState::getAllocated(E));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000727
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000728}
729
Anna Zaks87cb5be2012-02-22 19:24:52 +0000730ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
731 const CallExpr *CE,
732 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000733 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000734 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000735
Anna Zaksb3d72752012-03-01 22:06:06 +0000736 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000737 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000738
Sean Huntcf807c42010-08-18 23:23:40 +0000739 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
740 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000741 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000742 Att->getOwnKind() == OwnershipAttr::Holds,
743 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000744 if (StateI)
745 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000746 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000747 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000748}
749
Ted Kremenek8bef8232012-01-26 21:29:00 +0000750ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000751 const CallExpr *CE,
752 ProgramStateRef state,
753 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000754 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000755 bool &ReleasedAllocated,
756 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000757 if (CE->getNumArgs() < (Num + 1))
758 return 0;
759
Anna Zaks4141e4d2012-11-13 03:18:01 +0000760 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
761 ReleasedAllocated, ReturnsNullOnFailure);
762}
763
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000764/// Checks if the previous call to free on the given symbol failed - if free
765/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000766static bool didPreviousFreeFail(ProgramStateRef State,
767 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000768 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000769 if (Ret) {
770 assert(*Ret && "We should not store the null return symbol");
771 ConstraintManager &CMgr = State->getConstraintManager();
772 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000773 RetStatusSymbol = *Ret;
774 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000775 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000776 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000777}
778
779ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
780 const Expr *ArgExpr,
781 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000782 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000783 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000784 bool &ReleasedAllocated,
785 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000786
Anna Zaks4141e4d2012-11-13 03:18:01 +0000787 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie5251abe2013-02-20 05:52:05 +0000788 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zakse9ef5622012-02-10 01:11:00 +0000789 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000790 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000791
792 // Check for null dereferences.
David Blaikie5251abe2013-02-20 05:52:05 +0000793 if (!location.getAs<Loc>())
Anna Zaksb319e022012-02-08 20:13:28 +0000794 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000795
Anna Zaksb276bd92012-02-14 00:26:13 +0000796 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000797 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000798 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000799 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000800 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000801
Jordy Rose43859f62010-06-07 19:32:37 +0000802 // Unknown values could easily be okay
803 // Undefined values are handled elsewhere
804 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000805 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000806
Jordy Rose43859f62010-06-07 19:32:37 +0000807 const MemRegion *R = ArgVal.getAsRegion();
808
809 // Nonlocs can't be freed, of course.
810 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
811 if (!R) {
812 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000813 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000814 }
815
816 R = R->StripCasts();
817
818 // Blocks might show up as heap data, but should not be free()d
819 if (isa<BlockDataRegion>(R)) {
820 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000821 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000822 }
823
824 const MemSpaceRegion *MS = R->getMemorySpace();
825
Anton Yartsevbb369952013-03-13 14:39:10 +0000826 // Parameters, locals, statics, globals, and memory returned by alloca()
827 // shouldn't be freed.
Jordy Rose43859f62010-06-07 19:32:37 +0000828 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
829 // FIXME: at the time this code was written, malloc() regions were
830 // represented by conjured symbols, which are all in UnknownSpaceRegion.
831 // This means that there isn't actually anything from HeapSpaceRegion
832 // that should be freed, even though we allow it here.
833 // Of course, free() can work on memory allocated outside the current
834 // function, so UnknownSpaceRegion is always a possibility.
835 // False negatives are better than false positives.
836
837 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000838 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000839 }
Anna Zaks118aa752013-02-07 23:05:47 +0000840
841 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose43859f62010-06-07 19:32:37 +0000842 // Various cases could lead to non-symbol values here.
843 // For now, ignore them.
Anna Zaks118aa752013-02-07 23:05:47 +0000844 if (!SrBase)
Anna Zaksb319e022012-02-08 20:13:28 +0000845 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000846
Anna Zaks118aa752013-02-07 23:05:47 +0000847 SymbolRef SymBase = SrBase->getSymbol();
848 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000849 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000850
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000851 // Check double free.
Anna Zaks118aa752013-02-07 23:05:47 +0000852 if (RsBase &&
853 (RsBase->isReleased() || RsBase->isRelinquished()) &&
854 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
Anton Yartsevbb369952013-03-13 14:39:10 +0000855 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
856 SymBase, PreviousRetStatusSymbol);
Anna Zaksb319e022012-02-08 20:13:28 +0000857 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000858 }
859
Anna Zaks118aa752013-02-07 23:05:47 +0000860 // Check if the memory location being freed is the actual location
861 // allocated, or an offset.
862 RegionOffset Offset = R->getAsOffset();
863 if (RsBase && RsBase->isAllocated() &&
864 Offset.isValid() &&
865 !Offset.hasSymbolicOffset() &&
866 Offset.getOffset() != 0) {
867 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange());
868 return 0;
869 }
870
871 ReleasedAllocated = (RsBase != 0);
Anna Zaks55dd9562012-08-24 02:28:20 +0000872
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000873 // Clean out the info on previous call to free return info.
Anna Zaks118aa752013-02-07 23:05:47 +0000874 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000875
Anna Zaks4141e4d2012-11-13 03:18:01 +0000876 // Keep track of the return value. If it is NULL, we will know that free
877 // failed.
878 if (ReturnsNullOnFailure) {
879 SVal RetVal = C.getSVal(ParentExpr);
880 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
881 if (RetStatusSymbol) {
Anna Zaks118aa752013-02-07 23:05:47 +0000882 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
883 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000884 }
885 }
886
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000887 // Normal free.
Anna Zaks118aa752013-02-07 23:05:47 +0000888 if (Hold) {
889 return State->set<RegionState>(SymBase,
890 RefState::getRelinquished(ParentExpr));
891 }
892 return State->set<RegionState>(SymBase, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000893}
894
Ted Kremenek9c378f72011-08-12 23:37:29 +0000895bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000896 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +0000897 os << "an integer (" << IntVal->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +0000898 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +0000899 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +0000900 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner68106302011-02-17 05:38:27 +0000901 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000902 else
903 return false;
904
905 return true;
906}
907
Ted Kremenek9c378f72011-08-12 23:37:29 +0000908bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000909 const MemRegion *MR) {
910 switch (MR->getKind()) {
911 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000912 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +0000913 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000914 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000915 else
916 os << "the address of a function";
917 return true;
918 }
919 case MemRegion::BlockTextRegionKind:
920 os << "block text";
921 return true;
922 case MemRegion::BlockDataRegionKind:
923 // FIXME: where the block came from?
924 os << "a block";
925 return true;
926 default: {
927 const MemSpaceRegion *MS = MR->getMemorySpace();
928
Anna Zakseb31a762012-01-04 23:54:01 +0000929 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000930 const VarRegion *VR = dyn_cast<VarRegion>(MR);
931 const VarDecl *VD;
932 if (VR)
933 VD = VR->getDecl();
934 else
935 VD = NULL;
936
937 if (VD)
938 os << "the address of the local variable '" << VD->getName() << "'";
939 else
940 os << "the address of a local stack variable";
941 return true;
942 }
Anna Zakseb31a762012-01-04 23:54:01 +0000943
944 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000945 const VarRegion *VR = dyn_cast<VarRegion>(MR);
946 const VarDecl *VD;
947 if (VR)
948 VD = VR->getDecl();
949 else
950 VD = NULL;
951
952 if (VD)
953 os << "the address of the parameter '" << VD->getName() << "'";
954 else
955 os << "the address of a parameter";
956 return true;
957 }
Anna Zakseb31a762012-01-04 23:54:01 +0000958
959 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000960 const VarRegion *VR = dyn_cast<VarRegion>(MR);
961 const VarDecl *VD;
962 if (VR)
963 VD = VR->getDecl();
964 else
965 VD = NULL;
966
967 if (VD) {
968 if (VD->isStaticLocal())
969 os << "the address of the static variable '" << VD->getName() << "'";
970 else
971 os << "the address of the global variable '" << VD->getName() << "'";
972 } else
973 os << "the address of a global variable";
974 return true;
975 }
Anna Zakseb31a762012-01-04 23:54:01 +0000976
977 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000978 }
979 }
980}
981
982void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Anton Yartsevbb369952013-03-13 14:39:10 +0000983 SourceRange Range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000984 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000985 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000986 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000987
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000988 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000989 llvm::raw_svector_ostream os(buf);
990
991 const MemRegion *MR = ArgVal.getAsRegion();
992 if (MR) {
993 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
994 MR = ER->getSuperRegion();
995
996 // Special case for alloca()
997 if (isa<AllocaRegion>(MR))
998 os << "Argument to free() was allocated by alloca(), not malloc()";
999 else {
1000 os << "Argument to free() is ";
1001 if (SummarizeRegion(os, MR))
1002 os << ", which is not memory allocated by malloc()";
1003 else
1004 os << "not memory allocated by malloc()";
1005 }
1006 } else {
1007 os << "Argument to free() is ";
1008 if (SummarizeValue(os, ArgVal))
1009 os << ", which is not memory allocated by malloc()";
1010 else
1011 os << "not memory allocated by malloc()";
1012 }
1013
Anna Zakse172e8b2011-08-17 23:00:25 +00001014 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001015 R->markInteresting(MR);
Anton Yartsevbb369952013-03-13 14:39:10 +00001016 R->addRange(Range);
Jordan Rose785950e2012-11-02 01:53:40 +00001017 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +00001018 }
1019}
1020
Anna Zaks118aa752013-02-07 23:05:47 +00001021void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
1022 SourceRange Range) const {
1023 ExplodedNode *N = C.generateSink();
1024 if (N == NULL)
1025 return;
1026
1027 if (!BT_OffsetFree)
1028 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
1029
1030 SmallString<100> buf;
1031 llvm::raw_svector_ostream os(buf);
1032
1033 const MemRegion *MR = ArgVal.getAsRegion();
1034 assert(MR && "Only MemRegion based symbols can have offset free errors");
1035
1036 RegionOffset Offset = MR->getAsOffset();
1037 assert((Offset.isValid() &&
1038 !Offset.hasSymbolicOffset() &&
1039 Offset.getOffset() != 0) &&
1040 "Only symbols with a valid offset can have offset free errors");
1041
1042 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1043
1044 os << "Argument to free() is offset by "
1045 << offsetBytes
1046 << " "
1047 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
1048 << " from the start of memory allocated by malloc()";
1049
1050 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
1051 R->markInteresting(MR->getBaseRegion());
1052 R->addRange(Range);
1053 C.emitReport(R);
1054}
1055
Anton Yartsevbb369952013-03-13 14:39:10 +00001056void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1057 SymbolRef Sym) const {
1058
1059 if (ExplodedNode *N = C.generateSink()) {
1060 if (!BT_UseFree)
1061 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
1062
1063 BugReport *R = new BugReport(*BT_UseFree,
1064 "Use of memory after it is freed", N);
1065
1066 R->markInteresting(Sym);
1067 R->addRange(Range);
1068 R->addVisitor(new MallocBugVisitor(Sym));
1069 C.emitReport(R);
1070 }
1071}
1072
1073void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1074 bool Released, SymbolRef Sym,
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001075 SymbolRef PrevSym) const {
Anton Yartsevbb369952013-03-13 14:39:10 +00001076
1077 if (ExplodedNode *N = C.generateSink()) {
1078 if (!BT_DoubleFree)
1079 BT_DoubleFree.reset(new BugType("Double free", "Memory Error"));
1080
1081 BugReport *R = new BugReport(*BT_DoubleFree,
1082 (Released ? "Attempt to free released memory"
1083 : "Attempt to free non-owned memory"),
1084 N);
1085 R->addRange(Range);
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001086 R->markInteresting(Sym);
1087 if (PrevSym)
1088 R->markInteresting(PrevSym);
Anton Yartsevbb369952013-03-13 14:39:10 +00001089 R->addVisitor(new MallocBugVisitor(Sym));
1090 C.emitReport(R);
1091 }
1092}
1093
Anna Zaks87cb5be2012-02-22 19:24:52 +00001094ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1095 const CallExpr *CE,
1096 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001097 if (CE->getNumArgs() < 2)
1098 return 0;
1099
Ted Kremenek8bef8232012-01-26 21:29:00 +00001100 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001101 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001102 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +00001103 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001104 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001105 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001106 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001107
Ted Kremenek846eabd2010-12-01 21:28:31 +00001108 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001109
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001110 DefinedOrUnknownSVal PtrEQ =
1111 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001112
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001113 // Get the size argument. If there is no size arg then give up.
1114 const Expr *Arg1 = CE->getArg(1);
1115 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001116 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001117
1118 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +00001119 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001120 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001121 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001122 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001123
1124 // Compare the size argument to 0.
1125 DefinedOrUnknownSVal SizeZero =
1126 svalBuilder.evalEQ(state, Arg1Val,
1127 svalBuilder.makeIntValWithPtrWidth(0, false));
1128
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001129 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1130 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
1131 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1132 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
1133 // We only assume exceptional states if they are definitely true; if the
1134 // state is under-constrained, assume regular realloc behavior.
1135 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1136 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1137
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001138 // If the ptr is NULL and the size is not 0, the call is equivalent to
1139 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001140 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +00001141 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001142 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001143 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001144 }
1145
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001146 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001147 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001148
Anna Zaks30838b92012-02-13 20:57:07 +00001149 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001150 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001151 SymbolRef FromPtr = arg0Val.getAsSymbol();
1152 SVal RetVal = state->getSVal(CE, LCtx);
1153 SymbolRef ToPtr = RetVal.getAsSymbol();
1154 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001155 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001156
Anna Zaks55dd9562012-08-24 02:28:20 +00001157 bool ReleasedAllocated = false;
1158
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001159 // If the size is 0, free the memory.
1160 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001161 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1162 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001163 // The semantics of the return value are:
1164 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001165 // to free() is returned. We just free the input pointer and do not add
1166 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001167 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001168 }
1169
1170 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001171 if (ProgramStateRef stateFree =
1172 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1173
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001174 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1175 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001176 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001177 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001178
Anna Zaks9dc298b2012-09-12 22:57:34 +00001179 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1180 if (FreesOnFail)
1181 Kind = RPIsFreeOnFailure;
1182 else if (!ReleasedAllocated)
1183 Kind = RPDoNotTrackAfterFailure;
1184
Anna Zaks55dd9562012-08-24 02:28:20 +00001185 // Record the info about the reallocated symbol so that we could properly
1186 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001187 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001188 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001189 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001190 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001191 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001192 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001193 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001194}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001195
Anna Zaks87cb5be2012-02-22 19:24:52 +00001196ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001197 if (CE->getNumArgs() < 2)
1198 return 0;
1199
Ted Kremenek8bef8232012-01-26 21:29:00 +00001200 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001201 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001202 const LocationContext *LCtx = C.getLocationContext();
1203 SVal count = state->getSVal(CE->getArg(0), LCtx);
1204 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001205 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1206 svalBuilder.getContext().getSizeType());
1207 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001208
Anna Zaks87cb5be2012-02-22 19:24:52 +00001209 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001210}
1211
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001212LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001213MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1214 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001215 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001216 // Walk the ExplodedGraph backwards and find the first node that referred to
1217 // the tracked symbol.
1218 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001219 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001220
1221 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001222 ProgramStateRef State = N->getState();
1223 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001224 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001225
1226 // Find the most recent expression bound to the symbol in the current
1227 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001228 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001229 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1230 SVal Val = State->getSVal(MR);
1231 if (Val.getAsLocSymbol() == Sym)
1232 ReferenceRegion = MR;
1233 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001234 }
1235
Anna Zaks7752d292012-02-27 23:40:55 +00001236 // Allocation node, is the last node in the current context in which the
1237 // symbol was tracked.
1238 if (N->getLocationContext() == LeakContext)
1239 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001240 N = N->pred_empty() ? NULL : *(N->pred_begin());
1241 }
1242
Anna Zaks97bfb552013-01-08 00:25:29 +00001243 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001244}
1245
Anna Zaksda046772012-02-11 21:02:40 +00001246void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1247 CheckerContext &C) const {
1248 assert(N);
1249 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001250 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001251 // Leaks should not be reported if they are post-dominated by a sink:
1252 // (1) Sinks are higher importance bugs.
1253 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1254 // with __noreturn functions such as assert() or exit(). We choose not
1255 // to report leaks on such paths.
1256 BT_Leak->setSuppressOnSink(true);
1257 }
1258
Anna Zaksca8e36e2012-02-23 21:38:21 +00001259 // Most bug reports are cached at the location where they occurred.
1260 // With leaks, we want to unique them by the location where they were
1261 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001262 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001263 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001264 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001265 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1266
1267 ProgramPoint P = AllocNode->getLocation();
1268 const Stmt *AllocationStmt = 0;
David Blaikie7a95de62013-02-21 22:23:56 +00001269 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001270 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001271 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001272 AllocationStmt = SP->getStmt();
1273 if (AllocationStmt)
1274 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1275 C.getSourceManager(),
1276 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001277
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001278 SmallString<200> buf;
1279 llvm::raw_svector_ostream os(buf);
1280 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001281 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001282 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001283 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001284 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001285 }
1286
Anna Zaks97bfb552013-01-08 00:25:29 +00001287 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1288 LocUsedForUniqueing,
1289 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001290 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001291 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001292 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001293}
1294
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001295void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1296 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001297{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001298 if (!SymReaper.hasDeadSymbols())
1299 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001300
Ted Kremenek8bef8232012-01-26 21:29:00 +00001301 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001302 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001303 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001304
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001305 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001306 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1307 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001308 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001309 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001310 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001311 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001312
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001313 }
1314 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001315
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001316 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001317 ReallocPairsTy RP = state->get<ReallocPairs>();
1318 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001319 if (SymReaper.isDead(I->first) ||
1320 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001321 state = state->remove<ReallocPairs>(I->first);
1322 }
1323 }
1324
Anna Zaks4141e4d2012-11-13 03:18:01 +00001325 // Cleanup the FreeReturnValue Map.
1326 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1327 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1328 if (SymReaper.isDead(I->first) ||
1329 SymReaper.isDead(I->second)) {
1330 state = state->remove<FreeReturnValue>(I->first);
1331 }
1332 }
1333
Anna Zaksca8e36e2012-02-23 21:38:21 +00001334 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001335 ExplodedNode *N = C.getPredecessor();
1336 if (!Errors.empty()) {
1337 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1338 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001339 for (SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001340 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001341 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001342 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001343 }
Anna Zaks54458702012-10-29 22:51:54 +00001344
Anna Zaksca8e36e2012-02-23 21:38:21 +00001345 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001346}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001347
Anna Zaks66c40402012-02-14 21:55:24 +00001348void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001349 // We will check for double free in the post visit.
Anton Yartsev2de19ed2013-03-25 01:35:45 +00001350 if ((Filter.CMallocOptimistic || Filter.CMallocPessimistic) &&
1351 isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
1352 return;
1353
1354 if (Filter.CNewDeleteChecker &&
1355 isStandardNewDelete(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001356 return;
1357
1358 // Check use after free, when a freed pointer is passed to a call.
1359 ProgramStateRef State = C.getState();
1360 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1361 E = CE->arg_end(); I != E; ++I) {
1362 const Expr *A = *I;
1363 if (A->getType().getTypePtr()->isAnyPointerType()) {
Anton Yartsevbb369952013-03-13 14:39:10 +00001364 SymbolRef Sym = C.getSVal(A).getAsSymbol();
Anna Zaks66c40402012-02-14 21:55:24 +00001365 if (!Sym)
1366 continue;
1367 if (checkUseAfterFree(Sym, C, A))
1368 return;
1369 }
1370 }
1371}
1372
Anna Zaks91c2a112012-02-08 23:16:56 +00001373void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1374 const Expr *E = S->getRetValue();
1375 if (!E)
1376 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001377
1378 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001379 ProgramStateRef State = C.getState();
1380 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001381 SymbolRef Sym = RetVal.getAsSymbol();
1382 if (!Sym)
1383 // If we are returning a field of the allocated struct or an array element,
1384 // the callee could still free the memory.
1385 // TODO: This logic should be a part of generic symbol escape callback.
1386 if (const MemRegion *MR = RetVal.getAsRegion())
1387 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1388 if (const SymbolicRegion *BMR =
1389 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1390 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001391
Anna Zaks0860cd02012-02-11 21:44:39 +00001392 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001393 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001394 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001395}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001396
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001397// TODO: Blocks should be either inlined or should call invalidate regions
1398// upon invocation. After that's in place, special casing here will not be
1399// needed.
1400void MallocChecker::checkPostStmt(const BlockExpr *BE,
1401 CheckerContext &C) const {
1402
1403 // Scan the BlockDecRefExprs for any object the retain count checker
1404 // may be tracking.
1405 if (!BE->getBlockDecl()->hasCaptures())
1406 return;
1407
1408 ProgramStateRef state = C.getState();
1409 const BlockDataRegion *R =
1410 cast<BlockDataRegion>(state->getSVal(BE,
1411 C.getLocationContext()).getAsRegion());
1412
1413 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1414 E = R->referenced_vars_end();
1415
1416 if (I == E)
1417 return;
1418
1419 SmallVector<const MemRegion*, 10> Regions;
1420 const LocationContext *LC = C.getLocationContext();
1421 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1422
1423 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001424 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001425 if (VR->getSuperRegion() == R) {
1426 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1427 }
1428 Regions.push_back(VR);
1429 }
1430
1431 state =
1432 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1433 Regions.data() + Regions.size()).getState();
1434 C.addTransition(state);
1435}
1436
Anna Zaks14345182012-05-18 01:16:10 +00001437bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001438 assert(Sym);
1439 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001440 return (RS && RS->isReleased());
1441}
1442
1443bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1444 const Stmt *S) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001445
Anton Yartsevbb369952013-03-13 14:39:10 +00001446 if (isReleased(Sym, C)) {
1447 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1448 return true;
Anna Zaks91c2a112012-02-08 23:16:56 +00001449 }
Anton Yartsevbb369952013-03-13 14:39:10 +00001450
Anna Zaks91c2a112012-02-08 23:16:56 +00001451 return false;
1452}
1453
Zhongxing Xuc8023782010-03-10 04:58:55 +00001454// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001455void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1456 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001457 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001458 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001459 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001460}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001461
Anna Zaks4fb54872012-02-11 21:02:35 +00001462// If a symbolic region is assumed to NULL (or another constant), stop tracking
1463// it - assuming that allocation failed on this path.
1464ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1465 SVal Cond,
1466 bool Assumption) const {
1467 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001468 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001469 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001470 ConstraintManager &CMgr = state->getConstraintManager();
1471 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1472 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001473 state = state->remove<RegionState>(I.getKey());
1474 }
1475
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001476 // Realloc returns 0 when reallocation fails, which means that we should
1477 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001478 ReallocPairsTy RP = state->get<ReallocPairs>();
1479 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001480 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001481 ConstraintManager &CMgr = state->getConstraintManager();
1482 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001483 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001484 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001485
Anna Zaks9dc298b2012-09-12 22:57:34 +00001486 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1487 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1488 if (RS->isReleased()) {
1489 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001490 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001491 RefState::getAllocated(RS->getStmt()));
1492 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1493 state = state->remove<RegionState>(ReallocSym);
1494 else
1495 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001496 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001497 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001498 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001499 }
1500
Anna Zaks4fb54872012-02-11 21:02:35 +00001501 return state;
1502}
1503
Jordan Rose9fe09f32013-03-09 00:59:10 +00001504bool MallocChecker::doesNotFreeMemOrInteresting(const CallEvent *Call,
1505 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001506 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001507
1508 // For now, assume that any C++ call can free memory.
1509 // TODO: If we want to be more optimistic here, we'll need to make sure that
1510 // regions escape to C++ containers. They seem to do that even now, but for
1511 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001512 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001513 return false;
1514
Jordan Rose740d4902012-07-02 19:27:35 +00001515 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001516 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001517 // If it's not a framework call, or if it takes a callback, assume it
1518 // can free memory.
1519 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001520 return false;
1521
Jordan Rose9fe09f32013-03-09 00:59:10 +00001522 // If it's a method we know about, handle it explicitly post-call.
1523 // This should happen before the "freeWhenDone" check below.
1524 if (isKnownDeallocObjCMethodName(*Msg))
1525 return true;
Anna Zaks52a04812012-06-20 23:35:57 +00001526
Jordan Rose9fe09f32013-03-09 00:59:10 +00001527 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1528 // about, we can't be sure that the object will use free() to deallocate the
1529 // memory, so we can't model it explicitly. The best we can do is use it to
1530 // decide whether the pointer escapes.
1531 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
1532 return !*FreeWhenDone;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001533
Jordan Rose9fe09f32013-03-09 00:59:10 +00001534 // If the first selector piece ends with "NoCopy", and there is no
1535 // "freeWhenDone" parameter set to zero, we know ownership is being
1536 // transferred. Again, though, we can't be sure that the object will use
1537 // free() to deallocate the memory, so we can't model it explicitly.
1538 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose740d4902012-07-02 19:27:35 +00001539 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001540 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001541
Anna Zaks5f757682012-06-19 05:10:32 +00001542 // If the first selector starts with addPointer, insertPointer,
1543 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1544 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001545 // that the pointers get freed by following the container itself.
1546 if (FirstSlot.startswith("addPointer") ||
1547 FirstSlot.startswith("insertPointer") ||
1548 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001549 return false;
1550 }
1551
Jordan Rose740d4902012-07-02 19:27:35 +00001552 // Otherwise, assume that the method does not free memory.
1553 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001554 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001555 }
1556
Jordan Rose740d4902012-07-02 19:27:35 +00001557 // At this point the only thing left to handle is straight function calls.
1558 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1559 if (!FD)
1560 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001561
Jordan Rose740d4902012-07-02 19:27:35 +00001562 ASTContext &ASTC = State->getStateManager().getContext();
1563
1564 // If it's one of the allocation functions we can reason about, we model
1565 // its behavior explicitly.
1566 if (isMemFunction(FD, ASTC))
1567 return true;
1568
1569 // If it's not a system call, assume it frees memory.
1570 if (!Call->isInSystemHeader())
1571 return false;
1572
1573 // White list the system functions whose arguments escape.
1574 const IdentifierInfo *II = FD->getIdentifier();
1575 if (!II)
1576 return false;
1577 StringRef FName = II->getName();
1578
Jordan Rose740d4902012-07-02 19:27:35 +00001579 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001580 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001581 if (FName.endswith("NoCopy")) {
1582 // Look for the deallocator argument. We know that the memory ownership
1583 // is not transferred only if the deallocator argument is
1584 // 'kCFAllocatorNull'.
1585 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1586 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1587 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1588 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1589 if (DeallocatorName == "kCFAllocatorNull")
1590 return true;
1591 }
1592 }
1593 return false;
1594 }
1595
Jordan Rose740d4902012-07-02 19:27:35 +00001596 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001597 // 'closefn' is specified (and if that function does free memory),
1598 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001599 // Currently, we do not inspect the 'closefn' function (PR12101).
1600 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001601 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1602 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001603
1604 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1605 // these leaks might be intentional when setting the buffer for stdio.
1606 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1607 if (FName == "setbuf" || FName =="setbuffer" ||
1608 FName == "setlinebuf" || FName == "setvbuf") {
1609 if (Call->getNumArgs() >= 1) {
1610 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1611 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1612 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1613 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1614 return false;
1615 }
1616 }
1617
1618 // A bunch of other functions which either take ownership of a pointer or
1619 // wrap the result up in a struct or object, meaning it can be freed later.
1620 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1621 // but the Malloc checker cannot differentiate between them. The right way
1622 // of doing this would be to implement a pointer escapes callback.
1623 if (FName == "CGBitmapContextCreate" ||
1624 FName == "CGBitmapContextCreateWithData" ||
1625 FName == "CVPixelBufferCreateWithBytes" ||
1626 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1627 FName == "OSAtomicEnqueue") {
1628 return false;
1629 }
1630
Jordan Rose85d7e012012-07-02 19:27:51 +00001631 // Handle cases where we know a buffer's /address/ can escape.
1632 // Note that the above checks handle some special cases where we know that
1633 // even though the address escapes, it's still our responsibility to free the
1634 // buffer.
1635 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001636 return false;
1637
1638 // Otherwise, assume that the function does not free memory.
1639 // Most system calls do not free the memory.
1640 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001641}
1642
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001643ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1644 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00001645 const CallEvent *Call,
1646 PointerEscapeKind Kind) const {
Jordan Rose9fe09f32013-03-09 00:59:10 +00001647 // If we know that the call does not free memory, or we want to process the
1648 // call later, keep tracking the top level arguments.
Anna Zaks233e26a2013-02-07 23:05:43 +00001649 if ((Kind == PSK_DirectEscapeOnCall ||
1650 Kind == PSK_IndirectEscapeOnCall) &&
Jordan Rose9fe09f32013-03-09 00:59:10 +00001651 doesNotFreeMemOrInteresting(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001652 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00001653 }
Anna Zaks66c40402012-02-14 21:55:24 +00001654
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001655 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
1656 E = Escaped.end();
1657 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001658 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001659
Anna Zaks5b7aa342012-06-22 02:04:31 +00001660 if (const RefState *RS = State->get<RegionState>(sym)) {
1661 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001662 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001663 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001664 }
Anna Zaks66c40402012-02-14 21:55:24 +00001665 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001666}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001667
Jordy Rose393f98b2012-03-18 07:43:35 +00001668static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1669 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001670 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1671 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001672
Jordan Rose166d5022012-11-02 01:54:06 +00001673 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001674 I != E; ++I) {
1675 SymbolRef sym = I.getKey();
1676 if (!currMap.lookup(sym))
1677 return sym;
1678 }
1679
1680 return NULL;
1681}
1682
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001683PathDiagnosticPiece *
1684MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1685 const ExplodedNode *PrevN,
1686 BugReporterContext &BRC,
1687 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001688 ProgramStateRef state = N->getState();
1689 ProgramStateRef statePrev = PrevN->getState();
1690
1691 const RefState *RS = state->get<RegionState>(Sym);
1692 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001693 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001694 return 0;
1695
Anna Zaksfe571602012-02-16 22:26:07 +00001696 const Stmt *S = 0;
1697 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001698 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001699
1700 // Retrieve the associated statement.
1701 ProgramPoint ProgLoc = N->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00001702 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001703 S = SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +00001704 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001705 S = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001706 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremeneka4a17592013-01-04 19:04:36 +00001707 // If an assumption was made on a branch, it should be caught
1708 // here by looking at the state transition.
1709 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00001710 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00001711
Anna Zaksfe571602012-02-16 22:26:07 +00001712 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001713 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001714
Jordan Rose28038f32012-07-10 22:07:42 +00001715 // FIXME: We will eventually need to handle non-statement-based events
1716 // (__attribute__((cleanup))).
1717
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001718 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001719 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001720 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001721 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001722 StackHint = new StackHintGeneratorForSymbol(Sym,
1723 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001724 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001725 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001726 StackHint = new StackHintGeneratorForSymbol(Sym,
1727 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001728 } else if (isRelinquished(RS, RSPrev, S)) {
1729 Msg = "Memory ownership is transfered";
1730 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001731 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001732 Mode = ReallocationFailed;
1733 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001734 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001735 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001736
Jordy Roseb000fb52012-03-24 03:15:09 +00001737 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1738 // Is it possible to fail two reallocs WITHOUT testing in between?
1739 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1740 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001741 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001742 FailedReallocSymbol = sym;
1743 }
Anna Zaksfe571602012-02-16 22:26:07 +00001744 }
1745
1746 // We are in a special mode if a reallocation failed later in the path.
1747 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001748 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001749
Jordy Roseb000fb52012-03-24 03:15:09 +00001750 // Is this is the first appearance of the reallocated symbol?
1751 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001752 // We're at the reallocation point.
1753 Msg = "Attempt to reallocate memory";
1754 StackHint = new StackHintGeneratorForSymbol(Sym,
1755 "Returned reallocated memory");
1756 FailedReallocSymbol = NULL;
1757 Mode = Normal;
1758 }
Anna Zaksfe571602012-02-16 22:26:07 +00001759 }
1760
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001761 if (!Msg)
1762 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001763 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001764
1765 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001766 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001767 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001768 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001769}
1770
Anna Zaks93c5a242012-05-02 00:05:20 +00001771void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1772 const char *NL, const char *Sep) const {
1773
1774 RegionStateTy RS = State->get<RegionState>();
1775
Ted Kremenekc37fad62013-01-03 01:30:12 +00001776 if (!RS.isEmpty()) {
1777 Out << Sep << "MallocChecker:" << NL;
1778 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1779 I.getKey()->dumpToStream(Out);
1780 Out << " : ";
1781 I.getData().dump(Out);
1782 Out << NL;
1783 }
1784 }
Anna Zaks93c5a242012-05-02 00:05:20 +00001785}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001786
Anna Zaks231361a2012-02-08 23:16:52 +00001787#define REGISTER_CHECKER(name) \
1788void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001789 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001790 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001791}
Anna Zaks231361a2012-02-08 23:16:52 +00001792
1793REGISTER_CHECKER(MallocPessimistic)
1794REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev2de19ed2013-03-25 01:35:45 +00001795REGISTER_CHECKER(NewDeleteChecker)