blob: 25984458665cd43bad9e3fe4943523115d09fd83 [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 Yartsev69746282013-03-28 16:10:38 +0000460// Tells if the callee is one of the following:
461// 1) A global non-placement new/delete operator function.
462// 2) A global placement operator function with the single placement argument
463// of type std::nothrow_t.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000464bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
465 ASTContext &C) const {
466 if (!FD)
467 return false;
468
469 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
470 if (Kind != OO_New && Kind != OO_Array_New &&
471 Kind != OO_Delete && Kind != OO_Array_Delete)
472 return false;
473
Anton Yartsev69746282013-03-28 16:10:38 +0000474 // Skip all operator new/delete methods.
475 if (isa<CXXMethodDecl>(FD))
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000476 return false;
477
478 // Return true if tested operator is a standard placement nothrow operator.
479 if (FD->getNumParams() == 2) {
480 QualType T = FD->getParamDecl(1)->getType();
481 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
482 return II->getName().equals("nothrow_t");
483 }
484
485 // Skip placement operators.
486 if (FD->getNumParams() != 1 || FD->isVariadic())
487 return false;
488
489 // One of the standard new/new[]/delete/delete[] non-placement operators.
490 return true;
491}
492
Anna Zaksb319e022012-02-08 20:13:28 +0000493void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000494 if (C.wasInlined)
495 return;
496
Anna Zaksb319e022012-02-08 20:13:28 +0000497 const FunctionDecl *FD = C.getCalleeDecl(CE);
498 if (!FD)
499 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000500
Anna Zaks87cb5be2012-02-22 19:24:52 +0000501 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000502 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000503
504 if (FD->getKind() == Decl::Function) {
505 initIdentifierInfo(C.getASTContext());
506 IdentifierInfo *FunI = FD->getIdentifier();
507
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000508 if (Filter.CMallocOptimistic || Filter.CMallocPessimistic) {
509 if (FunI == II_malloc || FunI == II_valloc) {
510 if (CE->getNumArgs() < 1)
511 return;
512 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
513 } else if (FunI == II_realloc) {
514 State = ReallocMem(C, CE, false);
515 } else if (FunI == II_reallocf) {
516 State = ReallocMem(C, CE, true);
517 } else if (FunI == II_calloc) {
518 State = CallocMem(C, CE);
519 } else if (FunI == II_free) {
520 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
521 } else if (FunI == II_strdup) {
522 State = MallocUpdateRefState(C, CE, State);
523 } else if (FunI == II_strndup) {
524 State = MallocUpdateRefState(C, CE, State);
525 }
526 }
527
528 if (Filter.CNewDeleteChecker) {
529 if (isStandardNewDelete(FD, C.getASTContext())) {
530 // Process direct calls to operator new/new[]/delete/delete[] functions
531 // as distinct from new/new[]/delete/delete[] expressions that are
532 // processed by the checkPostStmt callbacks for CXXNewExpr and
533 // CXXDeleteExpr.
534 OverloadedOperatorKind K = FD->getOverloadedOperator();
535 if (K == OO_New)
536 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
537 else if (K == OO_Array_New)
538 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
539 else if (K == OO_Delete || K == OO_Array_Delete)
540 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
541 else
542 llvm_unreachable("not a new/delete operator");
543 }
Jordan Rose5ef6e942012-07-10 23:13:01 +0000544 }
545 }
546
547 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000548 // Check all the attributes, if there are any.
549 // There can be multiple of these attributes.
550 if (FD->hasAttrs())
551 for (specific_attr_iterator<OwnershipAttr>
552 i = FD->specific_attr_begin<OwnershipAttr>(),
553 e = FD->specific_attr_end<OwnershipAttr>();
554 i != e; ++i) {
555 switch ((*i)->getOwnKind()) {
556 case OwnershipAttr::Returns:
557 State = MallocMemReturnsAttr(C, CE, *i);
558 break;
559 case OwnershipAttr::Takes:
560 case OwnershipAttr::Holds:
561 State = FreeMemAttr(C, CE, *i);
562 break;
563 }
564 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000565 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000566 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000567}
568
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000569void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
570 CheckerContext &C) const {
571
572 if (NE->getNumPlacementArgs())
573 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
574 E = NE->placement_arg_end(); I != E; ++I)
575 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
576 checkUseAfterFree(Sym, C, *I);
577
578 if (!Filter.CNewDeleteChecker)
579 return;
580
581 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
582 return;
583
584 ProgramStateRef State = C.getState();
585 // The return value from operator new is bound to a specified initialization
586 // value (if any) and we don't want to loose this value. So we call
587 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
588 // existing binding.
589 State = MallocUpdateRefState(C, NE, State);
590 C.addTransition(State);
591}
592
593void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
594 CheckerContext &C) const {
595
596 if (!Filter.CNewDeleteChecker) {
597 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
598 checkUseAfterFree(Sym, C, DE->getArgument());
599
600 return;
601 }
602
603 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
604 return;
605
606 ProgramStateRef State = C.getState();
607 bool ReleasedAllocated;
608 State = FreeMemAux(C, DE->getArgument(), DE, State,
609 /*Hold*/false, ReleasedAllocated);
610
611 C.addTransition(State);
612}
613
Jordan Rose9fe09f32013-03-09 00:59:10 +0000614static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
615 // If the first selector piece is one of the names below, assume that the
616 // object takes ownership of the memory, promising to eventually deallocate it
617 // with free().
618 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
619 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
620 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
621 if (FirstSlot == "dataWithBytesNoCopy" ||
622 FirstSlot == "initWithBytesNoCopy" ||
623 FirstSlot == "initWithCharactersNoCopy")
624 return true;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000625
626 return false;
627}
628
Jordan Rose9fe09f32013-03-09 00:59:10 +0000629static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
630 Selector S = Call.getSelector();
631
632 // FIXME: We should not rely on fully-constrained symbols being folded.
633 for (unsigned i = 1; i < S.getNumArgs(); ++i)
634 if (S.getNameForSlot(i).equals("freeWhenDone"))
635 return !Call.getArgSVal(i).isZeroConstant();
636
637 return None;
638}
639
Anna Zaks4141e4d2012-11-13 03:18:01 +0000640void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
641 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000642 if (C.wasInlined)
643 return;
644
Jordan Rose9fe09f32013-03-09 00:59:10 +0000645 if (!isKnownDeallocObjCMethodName(Call))
646 return;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000647
Jordan Rose9fe09f32013-03-09 00:59:10 +0000648 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
649 if (!*FreeWhenDone)
650 return;
651
652 bool ReleasedAllocatedMemory;
653 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
654 Call.getOriginExpr(), C.getState(),
655 /*Hold=*/true, ReleasedAllocatedMemory,
656 /*RetNullOnFailure=*/true);
657
658 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000659}
660
Anna Zaks87cb5be2012-02-22 19:24:52 +0000661ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
662 const CallExpr *CE,
663 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000664 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000665 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000666
Sean Huntcf807c42010-08-18 23:23:40 +0000667 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000668 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000669 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000670 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000671 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000672}
673
Anna Zaksb319e022012-02-08 20:13:28 +0000674ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000675 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000676 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000677 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000678
679 // Bind the return value to the symbolic value from the heap region.
680 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
681 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000682 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000683 SValBuilder &svalBuilder = C.getSValBuilder();
684 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie5251abe2013-02-20 05:52:05 +0000685 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
686 .castAs<DefinedSVal>();
Anna Zakse17fdb22012-06-07 03:57:32 +0000687 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000688
Anna Zaksb16ce452012-02-15 00:11:22 +0000689 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000690 if (!RetVal.getAs<Loc>())
Anna Zaksb16ce452012-02-15 00:11:22 +0000691 return 0;
692
Jordy Rose32f26562010-07-04 00:00:41 +0000693 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000694 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000695
Jordy Rose32f26562010-07-04 00:00:41 +0000696 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000697 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000698 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000699 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000700 return 0;
David Blaikiedc84cd52013-02-20 22:23:23 +0000701 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000702 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000703 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000704 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000705 DefinedOrUnknownSVal extentMatchesSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000706 svalBuilder.evalEQ(state, Extent, *DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000707
Anna Zaks60a1fa42012-02-22 03:14:20 +0000708 state = state->assume(extentMatchesSize, true);
709 assert(state);
710 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000711
Anna Zaks87cb5be2012-02-22 19:24:52 +0000712 return MallocUpdateRefState(C, CE, state);
713}
714
715ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000716 const Expr *E,
Anna Zaks87cb5be2012-02-22 19:24:52 +0000717 ProgramStateRef state) {
718 // Get the return value.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000719 SVal retVal = state->getSVal(E, C.getLocationContext());
Anna Zaks87cb5be2012-02-22 19:24:52 +0000720
721 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000722 if (!retVal.getAs<Loc>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000723 return 0;
724
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000725 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000726 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000727
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000728 // Set the symbol's state to Allocated.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000729 return state->set<RegionState>(Sym, RefState::getAllocated(E));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000730
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000731}
732
Anna Zaks87cb5be2012-02-22 19:24:52 +0000733ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
734 const CallExpr *CE,
735 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000736 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000737 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000738
Anna Zaksb3d72752012-03-01 22:06:06 +0000739 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000740 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000741
Sean Huntcf807c42010-08-18 23:23:40 +0000742 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
743 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000744 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000745 Att->getOwnKind() == OwnershipAttr::Holds,
746 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000747 if (StateI)
748 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000749 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000750 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000751}
752
Ted Kremenek8bef8232012-01-26 21:29:00 +0000753ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000754 const CallExpr *CE,
755 ProgramStateRef state,
756 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000757 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000758 bool &ReleasedAllocated,
759 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000760 if (CE->getNumArgs() < (Num + 1))
761 return 0;
762
Anna Zaks4141e4d2012-11-13 03:18:01 +0000763 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
764 ReleasedAllocated, ReturnsNullOnFailure);
765}
766
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000767/// Checks if the previous call to free on the given symbol failed - if free
768/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000769static bool didPreviousFreeFail(ProgramStateRef State,
770 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000771 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000772 if (Ret) {
773 assert(*Ret && "We should not store the null return symbol");
774 ConstraintManager &CMgr = State->getConstraintManager();
775 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000776 RetStatusSymbol = *Ret;
777 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000778 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000779 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000780}
781
782ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
783 const Expr *ArgExpr,
784 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000785 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000786 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000787 bool &ReleasedAllocated,
788 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000789
Anna Zaks4141e4d2012-11-13 03:18:01 +0000790 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie5251abe2013-02-20 05:52:05 +0000791 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zakse9ef5622012-02-10 01:11:00 +0000792 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000793 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000794
795 // Check for null dereferences.
David Blaikie5251abe2013-02-20 05:52:05 +0000796 if (!location.getAs<Loc>())
Anna Zaksb319e022012-02-08 20:13:28 +0000797 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000798
Anna Zaksb276bd92012-02-14 00:26:13 +0000799 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000800 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000801 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000802 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000803 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000804
Jordy Rose43859f62010-06-07 19:32:37 +0000805 // Unknown values could easily be okay
806 // Undefined values are handled elsewhere
807 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000808 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000809
Jordy Rose43859f62010-06-07 19:32:37 +0000810 const MemRegion *R = ArgVal.getAsRegion();
811
812 // Nonlocs can't be freed, of course.
813 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
814 if (!R) {
815 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000816 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000817 }
818
819 R = R->StripCasts();
820
821 // Blocks might show up as heap data, but should not be free()d
822 if (isa<BlockDataRegion>(R)) {
823 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000824 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000825 }
826
827 const MemSpaceRegion *MS = R->getMemorySpace();
828
Anton Yartsevbb369952013-03-13 14:39:10 +0000829 // Parameters, locals, statics, globals, and memory returned by alloca()
830 // shouldn't be freed.
Jordy Rose43859f62010-06-07 19:32:37 +0000831 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
832 // FIXME: at the time this code was written, malloc() regions were
833 // represented by conjured symbols, which are all in UnknownSpaceRegion.
834 // This means that there isn't actually anything from HeapSpaceRegion
835 // that should be freed, even though we allow it here.
836 // Of course, free() can work on memory allocated outside the current
837 // function, so UnknownSpaceRegion is always a possibility.
838 // False negatives are better than false positives.
839
840 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000841 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000842 }
Anna Zaks118aa752013-02-07 23:05:47 +0000843
844 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose43859f62010-06-07 19:32:37 +0000845 // Various cases could lead to non-symbol values here.
846 // For now, ignore them.
Anna Zaks118aa752013-02-07 23:05:47 +0000847 if (!SrBase)
Anna Zaksb319e022012-02-08 20:13:28 +0000848 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000849
Anna Zaks118aa752013-02-07 23:05:47 +0000850 SymbolRef SymBase = SrBase->getSymbol();
851 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000852 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000853
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000854 // Check double free.
Anna Zaks118aa752013-02-07 23:05:47 +0000855 if (RsBase &&
856 (RsBase->isReleased() || RsBase->isRelinquished()) &&
857 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
Anton Yartsevbb369952013-03-13 14:39:10 +0000858 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
859 SymBase, PreviousRetStatusSymbol);
Anna Zaksb319e022012-02-08 20:13:28 +0000860 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000861 }
862
Anna Zaks118aa752013-02-07 23:05:47 +0000863 // Check if the memory location being freed is the actual location
864 // allocated, or an offset.
865 RegionOffset Offset = R->getAsOffset();
866 if (RsBase && RsBase->isAllocated() &&
867 Offset.isValid() &&
868 !Offset.hasSymbolicOffset() &&
869 Offset.getOffset() != 0) {
870 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange());
871 return 0;
872 }
873
874 ReleasedAllocated = (RsBase != 0);
Anna Zaks55dd9562012-08-24 02:28:20 +0000875
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000876 // Clean out the info on previous call to free return info.
Anna Zaks118aa752013-02-07 23:05:47 +0000877 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000878
Anna Zaks4141e4d2012-11-13 03:18:01 +0000879 // Keep track of the return value. If it is NULL, we will know that free
880 // failed.
881 if (ReturnsNullOnFailure) {
882 SVal RetVal = C.getSVal(ParentExpr);
883 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
884 if (RetStatusSymbol) {
Anna Zaks118aa752013-02-07 23:05:47 +0000885 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
886 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000887 }
888 }
889
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000890 // Normal free.
Anna Zaks118aa752013-02-07 23:05:47 +0000891 if (Hold) {
892 return State->set<RegionState>(SymBase,
893 RefState::getRelinquished(ParentExpr));
894 }
895 return State->set<RegionState>(SymBase, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000896}
897
Ted Kremenek9c378f72011-08-12 23:37:29 +0000898bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000899 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +0000900 os << "an integer (" << IntVal->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +0000901 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +0000902 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +0000903 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner68106302011-02-17 05:38:27 +0000904 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000905 else
906 return false;
907
908 return true;
909}
910
Ted Kremenek9c378f72011-08-12 23:37:29 +0000911bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000912 const MemRegion *MR) {
913 switch (MR->getKind()) {
914 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000915 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +0000916 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000917 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000918 else
919 os << "the address of a function";
920 return true;
921 }
922 case MemRegion::BlockTextRegionKind:
923 os << "block text";
924 return true;
925 case MemRegion::BlockDataRegionKind:
926 // FIXME: where the block came from?
927 os << "a block";
928 return true;
929 default: {
930 const MemSpaceRegion *MS = MR->getMemorySpace();
931
Anna Zakseb31a762012-01-04 23:54:01 +0000932 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000933 const VarRegion *VR = dyn_cast<VarRegion>(MR);
934 const VarDecl *VD;
935 if (VR)
936 VD = VR->getDecl();
937 else
938 VD = NULL;
939
940 if (VD)
941 os << "the address of the local variable '" << VD->getName() << "'";
942 else
943 os << "the address of a local stack variable";
944 return true;
945 }
Anna Zakseb31a762012-01-04 23:54:01 +0000946
947 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000948 const VarRegion *VR = dyn_cast<VarRegion>(MR);
949 const VarDecl *VD;
950 if (VR)
951 VD = VR->getDecl();
952 else
953 VD = NULL;
954
955 if (VD)
956 os << "the address of the parameter '" << VD->getName() << "'";
957 else
958 os << "the address of a parameter";
959 return true;
960 }
Anna Zakseb31a762012-01-04 23:54:01 +0000961
962 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000963 const VarRegion *VR = dyn_cast<VarRegion>(MR);
964 const VarDecl *VD;
965 if (VR)
966 VD = VR->getDecl();
967 else
968 VD = NULL;
969
970 if (VD) {
971 if (VD->isStaticLocal())
972 os << "the address of the static variable '" << VD->getName() << "'";
973 else
974 os << "the address of the global variable '" << VD->getName() << "'";
975 } else
976 os << "the address of a global variable";
977 return true;
978 }
Anna Zakseb31a762012-01-04 23:54:01 +0000979
980 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000981 }
982 }
983}
984
985void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Anton Yartsevbb369952013-03-13 14:39:10 +0000986 SourceRange Range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000987 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000988 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000989 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000990
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000991 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000992 llvm::raw_svector_ostream os(buf);
993
994 const MemRegion *MR = ArgVal.getAsRegion();
995 if (MR) {
996 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
997 MR = ER->getSuperRegion();
998
999 // Special case for alloca()
1000 if (isa<AllocaRegion>(MR))
1001 os << "Argument to free() was allocated by alloca(), not malloc()";
1002 else {
1003 os << "Argument to free() is ";
1004 if (SummarizeRegion(os, MR))
1005 os << ", which is not memory allocated by malloc()";
1006 else
1007 os << "not memory allocated by malloc()";
1008 }
1009 } else {
1010 os << "Argument to free() is ";
1011 if (SummarizeValue(os, ArgVal))
1012 os << ", which is not memory allocated by malloc()";
1013 else
1014 os << "not memory allocated by malloc()";
1015 }
1016
Anna Zakse172e8b2011-08-17 23:00:25 +00001017 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001018 R->markInteresting(MR);
Anton Yartsevbb369952013-03-13 14:39:10 +00001019 R->addRange(Range);
Jordan Rose785950e2012-11-02 01:53:40 +00001020 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +00001021 }
1022}
1023
Anna Zaks118aa752013-02-07 23:05:47 +00001024void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
1025 SourceRange Range) const {
1026 ExplodedNode *N = C.generateSink();
1027 if (N == NULL)
1028 return;
1029
1030 if (!BT_OffsetFree)
1031 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
1032
1033 SmallString<100> buf;
1034 llvm::raw_svector_ostream os(buf);
1035
1036 const MemRegion *MR = ArgVal.getAsRegion();
1037 assert(MR && "Only MemRegion based symbols can have offset free errors");
1038
1039 RegionOffset Offset = MR->getAsOffset();
1040 assert((Offset.isValid() &&
1041 !Offset.hasSymbolicOffset() &&
1042 Offset.getOffset() != 0) &&
1043 "Only symbols with a valid offset can have offset free errors");
1044
1045 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1046
1047 os << "Argument to free() is offset by "
1048 << offsetBytes
1049 << " "
1050 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
1051 << " from the start of memory allocated by malloc()";
1052
1053 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
1054 R->markInteresting(MR->getBaseRegion());
1055 R->addRange(Range);
1056 C.emitReport(R);
1057}
1058
Anton Yartsevbb369952013-03-13 14:39:10 +00001059void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1060 SymbolRef Sym) const {
1061
1062 if (ExplodedNode *N = C.generateSink()) {
1063 if (!BT_UseFree)
1064 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
1065
1066 BugReport *R = new BugReport(*BT_UseFree,
1067 "Use of memory after it is freed", N);
1068
1069 R->markInteresting(Sym);
1070 R->addRange(Range);
1071 R->addVisitor(new MallocBugVisitor(Sym));
1072 C.emitReport(R);
1073 }
1074}
1075
1076void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1077 bool Released, SymbolRef Sym,
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001078 SymbolRef PrevSym) const {
Anton Yartsevbb369952013-03-13 14:39:10 +00001079
1080 if (ExplodedNode *N = C.generateSink()) {
1081 if (!BT_DoubleFree)
1082 BT_DoubleFree.reset(new BugType("Double free", "Memory Error"));
1083
1084 BugReport *R = new BugReport(*BT_DoubleFree,
1085 (Released ? "Attempt to free released memory"
1086 : "Attempt to free non-owned memory"),
1087 N);
1088 R->addRange(Range);
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001089 R->markInteresting(Sym);
1090 if (PrevSym)
1091 R->markInteresting(PrevSym);
Anton Yartsevbb369952013-03-13 14:39:10 +00001092 R->addVisitor(new MallocBugVisitor(Sym));
1093 C.emitReport(R);
1094 }
1095}
1096
Anna Zaks87cb5be2012-02-22 19:24:52 +00001097ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1098 const CallExpr *CE,
1099 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001100 if (CE->getNumArgs() < 2)
1101 return 0;
1102
Ted Kremenek8bef8232012-01-26 21:29:00 +00001103 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001104 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001105 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +00001106 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001107 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001108 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001109 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001110
Ted Kremenek846eabd2010-12-01 21:28:31 +00001111 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001112
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001113 DefinedOrUnknownSVal PtrEQ =
1114 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001115
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001116 // Get the size argument. If there is no size arg then give up.
1117 const Expr *Arg1 = CE->getArg(1);
1118 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001119 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001120
1121 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +00001122 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001123 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001124 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001125 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001126
1127 // Compare the size argument to 0.
1128 DefinedOrUnknownSVal SizeZero =
1129 svalBuilder.evalEQ(state, Arg1Val,
1130 svalBuilder.makeIntValWithPtrWidth(0, false));
1131
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001132 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1133 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
1134 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1135 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
1136 // We only assume exceptional states if they are definitely true; if the
1137 // state is under-constrained, assume regular realloc behavior.
1138 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1139 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1140
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001141 // If the ptr is NULL and the size is not 0, the call is equivalent to
1142 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001143 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +00001144 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001145 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001146 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001147 }
1148
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001149 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001150 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001151
Anna Zaks30838b92012-02-13 20:57:07 +00001152 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001153 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001154 SymbolRef FromPtr = arg0Val.getAsSymbol();
1155 SVal RetVal = state->getSVal(CE, LCtx);
1156 SymbolRef ToPtr = RetVal.getAsSymbol();
1157 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001158 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001159
Anna Zaks55dd9562012-08-24 02:28:20 +00001160 bool ReleasedAllocated = false;
1161
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001162 // If the size is 0, free the memory.
1163 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001164 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1165 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001166 // The semantics of the return value are:
1167 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001168 // to free() is returned. We just free the input pointer and do not add
1169 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001170 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001171 }
1172
1173 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001174 if (ProgramStateRef stateFree =
1175 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1176
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001177 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1178 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001179 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001180 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001181
Anna Zaks9dc298b2012-09-12 22:57:34 +00001182 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1183 if (FreesOnFail)
1184 Kind = RPIsFreeOnFailure;
1185 else if (!ReleasedAllocated)
1186 Kind = RPDoNotTrackAfterFailure;
1187
Anna Zaks55dd9562012-08-24 02:28:20 +00001188 // Record the info about the reallocated symbol so that we could properly
1189 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001190 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001191 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001192 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001193 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001194 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001195 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001196 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001197}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001198
Anna Zaks87cb5be2012-02-22 19:24:52 +00001199ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001200 if (CE->getNumArgs() < 2)
1201 return 0;
1202
Ted Kremenek8bef8232012-01-26 21:29:00 +00001203 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001204 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001205 const LocationContext *LCtx = C.getLocationContext();
1206 SVal count = state->getSVal(CE->getArg(0), LCtx);
1207 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001208 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1209 svalBuilder.getContext().getSizeType());
1210 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001211
Anna Zaks87cb5be2012-02-22 19:24:52 +00001212 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001213}
1214
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001215LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001216MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1217 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001218 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001219 // Walk the ExplodedGraph backwards and find the first node that referred to
1220 // the tracked symbol.
1221 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001222 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001223
1224 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001225 ProgramStateRef State = N->getState();
1226 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001227 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001228
1229 // Find the most recent expression bound to the symbol in the current
1230 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001231 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001232 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1233 SVal Val = State->getSVal(MR);
1234 if (Val.getAsLocSymbol() == Sym)
1235 ReferenceRegion = MR;
1236 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001237 }
1238
Anna Zaks7752d292012-02-27 23:40:55 +00001239 // Allocation node, is the last node in the current context in which the
1240 // symbol was tracked.
1241 if (N->getLocationContext() == LeakContext)
1242 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001243 N = N->pred_empty() ? NULL : *(N->pred_begin());
1244 }
1245
Anna Zaks97bfb552013-01-08 00:25:29 +00001246 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001247}
1248
Anna Zaksda046772012-02-11 21:02:40 +00001249void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1250 CheckerContext &C) const {
1251 assert(N);
1252 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001253 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001254 // Leaks should not be reported if they are post-dominated by a sink:
1255 // (1) Sinks are higher importance bugs.
1256 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1257 // with __noreturn functions such as assert() or exit(). We choose not
1258 // to report leaks on such paths.
1259 BT_Leak->setSuppressOnSink(true);
1260 }
1261
Anna Zaksca8e36e2012-02-23 21:38:21 +00001262 // Most bug reports are cached at the location where they occurred.
1263 // With leaks, we want to unique them by the location where they were
1264 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001265 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001266 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001267 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001268 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1269
1270 ProgramPoint P = AllocNode->getLocation();
1271 const Stmt *AllocationStmt = 0;
David Blaikie7a95de62013-02-21 22:23:56 +00001272 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001273 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001274 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001275 AllocationStmt = SP->getStmt();
1276 if (AllocationStmt)
1277 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1278 C.getSourceManager(),
1279 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001280
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001281 SmallString<200> buf;
1282 llvm::raw_svector_ostream os(buf);
1283 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001284 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001285 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001286 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001287 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001288 }
1289
Anna Zaks97bfb552013-01-08 00:25:29 +00001290 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1291 LocUsedForUniqueing,
1292 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001293 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001294 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001295 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001296}
1297
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001298void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1299 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001300{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001301 if (!SymReaper.hasDeadSymbols())
1302 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001303
Ted Kremenek8bef8232012-01-26 21:29:00 +00001304 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001305 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001306 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001307
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001308 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001309 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1310 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001311 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001312 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001313 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001314 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001315
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001316 }
1317 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001318
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001319 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001320 ReallocPairsTy RP = state->get<ReallocPairs>();
1321 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001322 if (SymReaper.isDead(I->first) ||
1323 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001324 state = state->remove<ReallocPairs>(I->first);
1325 }
1326 }
1327
Anna Zaks4141e4d2012-11-13 03:18:01 +00001328 // Cleanup the FreeReturnValue Map.
1329 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1330 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1331 if (SymReaper.isDead(I->first) ||
1332 SymReaper.isDead(I->second)) {
1333 state = state->remove<FreeReturnValue>(I->first);
1334 }
1335 }
1336
Anna Zaksca8e36e2012-02-23 21:38:21 +00001337 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001338 ExplodedNode *N = C.getPredecessor();
1339 if (!Errors.empty()) {
1340 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1341 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001342 for (SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001343 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001344 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001345 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001346 }
Anna Zaks54458702012-10-29 22:51:54 +00001347
Anna Zaksca8e36e2012-02-23 21:38:21 +00001348 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001349}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001350
Anna Zaks66c40402012-02-14 21:55:24 +00001351void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001352 // We will check for double free in the post visit.
Anton Yartsev2de19ed2013-03-25 01:35:45 +00001353 if ((Filter.CMallocOptimistic || Filter.CMallocPessimistic) &&
1354 isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
1355 return;
1356
1357 if (Filter.CNewDeleteChecker &&
1358 isStandardNewDelete(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001359 return;
1360
1361 // Check use after free, when a freed pointer is passed to a call.
1362 ProgramStateRef State = C.getState();
1363 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1364 E = CE->arg_end(); I != E; ++I) {
1365 const Expr *A = *I;
1366 if (A->getType().getTypePtr()->isAnyPointerType()) {
Anton Yartsevbb369952013-03-13 14:39:10 +00001367 SymbolRef Sym = C.getSVal(A).getAsSymbol();
Anna Zaks66c40402012-02-14 21:55:24 +00001368 if (!Sym)
1369 continue;
1370 if (checkUseAfterFree(Sym, C, A))
1371 return;
1372 }
1373 }
1374}
1375
Anna Zaks91c2a112012-02-08 23:16:56 +00001376void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1377 const Expr *E = S->getRetValue();
1378 if (!E)
1379 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001380
1381 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001382 ProgramStateRef State = C.getState();
1383 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001384 SymbolRef Sym = RetVal.getAsSymbol();
1385 if (!Sym)
1386 // If we are returning a field of the allocated struct or an array element,
1387 // the callee could still free the memory.
1388 // TODO: This logic should be a part of generic symbol escape callback.
1389 if (const MemRegion *MR = RetVal.getAsRegion())
1390 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1391 if (const SymbolicRegion *BMR =
1392 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1393 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001394
Anna Zaks0860cd02012-02-11 21:44:39 +00001395 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001396 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001397 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001398}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001399
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001400// TODO: Blocks should be either inlined or should call invalidate regions
1401// upon invocation. After that's in place, special casing here will not be
1402// needed.
1403void MallocChecker::checkPostStmt(const BlockExpr *BE,
1404 CheckerContext &C) const {
1405
1406 // Scan the BlockDecRefExprs for any object the retain count checker
1407 // may be tracking.
1408 if (!BE->getBlockDecl()->hasCaptures())
1409 return;
1410
1411 ProgramStateRef state = C.getState();
1412 const BlockDataRegion *R =
1413 cast<BlockDataRegion>(state->getSVal(BE,
1414 C.getLocationContext()).getAsRegion());
1415
1416 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1417 E = R->referenced_vars_end();
1418
1419 if (I == E)
1420 return;
1421
1422 SmallVector<const MemRegion*, 10> Regions;
1423 const LocationContext *LC = C.getLocationContext();
1424 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1425
1426 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001427 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001428 if (VR->getSuperRegion() == R) {
1429 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1430 }
1431 Regions.push_back(VR);
1432 }
1433
1434 state =
1435 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1436 Regions.data() + Regions.size()).getState();
1437 C.addTransition(state);
1438}
1439
Anna Zaks14345182012-05-18 01:16:10 +00001440bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001441 assert(Sym);
1442 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001443 return (RS && RS->isReleased());
1444}
1445
1446bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1447 const Stmt *S) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001448
Anton Yartsevbb369952013-03-13 14:39:10 +00001449 if (isReleased(Sym, C)) {
1450 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1451 return true;
Anna Zaks91c2a112012-02-08 23:16:56 +00001452 }
Anton Yartsevbb369952013-03-13 14:39:10 +00001453
Anna Zaks91c2a112012-02-08 23:16:56 +00001454 return false;
1455}
1456
Zhongxing Xuc8023782010-03-10 04:58:55 +00001457// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001458void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1459 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001460 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001461 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001462 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001463}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001464
Anna Zaks4fb54872012-02-11 21:02:35 +00001465// If a symbolic region is assumed to NULL (or another constant), stop tracking
1466// it - assuming that allocation failed on this path.
1467ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1468 SVal Cond,
1469 bool Assumption) const {
1470 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001471 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001472 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001473 ConstraintManager &CMgr = state->getConstraintManager();
1474 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1475 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001476 state = state->remove<RegionState>(I.getKey());
1477 }
1478
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001479 // Realloc returns 0 when reallocation fails, which means that we should
1480 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001481 ReallocPairsTy RP = state->get<ReallocPairs>();
1482 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001483 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001484 ConstraintManager &CMgr = state->getConstraintManager();
1485 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001486 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001487 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001488
Anna Zaks9dc298b2012-09-12 22:57:34 +00001489 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1490 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1491 if (RS->isReleased()) {
1492 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001493 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001494 RefState::getAllocated(RS->getStmt()));
1495 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1496 state = state->remove<RegionState>(ReallocSym);
1497 else
1498 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001499 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001500 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001501 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001502 }
1503
Anna Zaks4fb54872012-02-11 21:02:35 +00001504 return state;
1505}
1506
Jordan Rose9fe09f32013-03-09 00:59:10 +00001507bool MallocChecker::doesNotFreeMemOrInteresting(const CallEvent *Call,
1508 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001509 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001510
1511 // For now, assume that any C++ call can free memory.
1512 // TODO: If we want to be more optimistic here, we'll need to make sure that
1513 // regions escape to C++ containers. They seem to do that even now, but for
1514 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001515 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001516 return false;
1517
Jordan Rose740d4902012-07-02 19:27:35 +00001518 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001519 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001520 // If it's not a framework call, or if it takes a callback, assume it
1521 // can free memory.
1522 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001523 return false;
1524
Jordan Rose9fe09f32013-03-09 00:59:10 +00001525 // If it's a method we know about, handle it explicitly post-call.
1526 // This should happen before the "freeWhenDone" check below.
1527 if (isKnownDeallocObjCMethodName(*Msg))
1528 return true;
Anna Zaks52a04812012-06-20 23:35:57 +00001529
Jordan Rose9fe09f32013-03-09 00:59:10 +00001530 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1531 // about, we can't be sure that the object will use free() to deallocate the
1532 // memory, so we can't model it explicitly. The best we can do is use it to
1533 // decide whether the pointer escapes.
1534 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
1535 return !*FreeWhenDone;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001536
Jordan Rose9fe09f32013-03-09 00:59:10 +00001537 // If the first selector piece ends with "NoCopy", and there is no
1538 // "freeWhenDone" parameter set to zero, we know ownership is being
1539 // transferred. Again, though, we can't be sure that the object will use
1540 // free() to deallocate the memory, so we can't model it explicitly.
1541 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose740d4902012-07-02 19:27:35 +00001542 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001543 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001544
Anna Zaks5f757682012-06-19 05:10:32 +00001545 // If the first selector starts with addPointer, insertPointer,
1546 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1547 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001548 // that the pointers get freed by following the container itself.
1549 if (FirstSlot.startswith("addPointer") ||
1550 FirstSlot.startswith("insertPointer") ||
1551 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001552 return false;
1553 }
1554
Jordan Rose740d4902012-07-02 19:27:35 +00001555 // Otherwise, assume that the method does not free memory.
1556 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001557 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001558 }
1559
Jordan Rose740d4902012-07-02 19:27:35 +00001560 // At this point the only thing left to handle is straight function calls.
1561 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1562 if (!FD)
1563 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001564
Jordan Rose740d4902012-07-02 19:27:35 +00001565 ASTContext &ASTC = State->getStateManager().getContext();
1566
1567 // If it's one of the allocation functions we can reason about, we model
1568 // its behavior explicitly.
1569 if (isMemFunction(FD, ASTC))
1570 return true;
1571
1572 // If it's not a system call, assume it frees memory.
1573 if (!Call->isInSystemHeader())
1574 return false;
1575
1576 // White list the system functions whose arguments escape.
1577 const IdentifierInfo *II = FD->getIdentifier();
1578 if (!II)
1579 return false;
1580 StringRef FName = II->getName();
1581
Jordan Rose740d4902012-07-02 19:27:35 +00001582 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001583 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001584 if (FName.endswith("NoCopy")) {
1585 // Look for the deallocator argument. We know that the memory ownership
1586 // is not transferred only if the deallocator argument is
1587 // 'kCFAllocatorNull'.
1588 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1589 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1590 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1591 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1592 if (DeallocatorName == "kCFAllocatorNull")
1593 return true;
1594 }
1595 }
1596 return false;
1597 }
1598
Jordan Rose740d4902012-07-02 19:27:35 +00001599 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001600 // 'closefn' is specified (and if that function does free memory),
1601 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001602 // Currently, we do not inspect the 'closefn' function (PR12101).
1603 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001604 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1605 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001606
1607 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1608 // these leaks might be intentional when setting the buffer for stdio.
1609 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1610 if (FName == "setbuf" || FName =="setbuffer" ||
1611 FName == "setlinebuf" || FName == "setvbuf") {
1612 if (Call->getNumArgs() >= 1) {
1613 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1614 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1615 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1616 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1617 return false;
1618 }
1619 }
1620
1621 // A bunch of other functions which either take ownership of a pointer or
1622 // wrap the result up in a struct or object, meaning it can be freed later.
1623 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1624 // but the Malloc checker cannot differentiate between them. The right way
1625 // of doing this would be to implement a pointer escapes callback.
1626 if (FName == "CGBitmapContextCreate" ||
1627 FName == "CGBitmapContextCreateWithData" ||
1628 FName == "CVPixelBufferCreateWithBytes" ||
1629 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1630 FName == "OSAtomicEnqueue") {
1631 return false;
1632 }
1633
Jordan Rose85d7e012012-07-02 19:27:51 +00001634 // Handle cases where we know a buffer's /address/ can escape.
1635 // Note that the above checks handle some special cases where we know that
1636 // even though the address escapes, it's still our responsibility to free the
1637 // buffer.
1638 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001639 return false;
1640
1641 // Otherwise, assume that the function does not free memory.
1642 // Most system calls do not free the memory.
1643 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001644}
1645
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001646ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1647 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00001648 const CallEvent *Call,
1649 PointerEscapeKind Kind) const {
Jordan Rose9fe09f32013-03-09 00:59:10 +00001650 // If we know that the call does not free memory, or we want to process the
1651 // call later, keep tracking the top level arguments.
Anna Zaks233e26a2013-02-07 23:05:43 +00001652 if ((Kind == PSK_DirectEscapeOnCall ||
1653 Kind == PSK_IndirectEscapeOnCall) &&
Jordan Rose9fe09f32013-03-09 00:59:10 +00001654 doesNotFreeMemOrInteresting(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001655 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00001656 }
Anna Zaks66c40402012-02-14 21:55:24 +00001657
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001658 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
1659 E = Escaped.end();
1660 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001661 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001662
Anna Zaks5b7aa342012-06-22 02:04:31 +00001663 if (const RefState *RS = State->get<RegionState>(sym)) {
1664 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001665 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001666 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001667 }
Anna Zaks66c40402012-02-14 21:55:24 +00001668 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001669}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001670
Jordy Rose393f98b2012-03-18 07:43:35 +00001671static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1672 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001673 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1674 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001675
Jordan Rose166d5022012-11-02 01:54:06 +00001676 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001677 I != E; ++I) {
1678 SymbolRef sym = I.getKey();
1679 if (!currMap.lookup(sym))
1680 return sym;
1681 }
1682
1683 return NULL;
1684}
1685
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001686PathDiagnosticPiece *
1687MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1688 const ExplodedNode *PrevN,
1689 BugReporterContext &BRC,
1690 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001691 ProgramStateRef state = N->getState();
1692 ProgramStateRef statePrev = PrevN->getState();
1693
1694 const RefState *RS = state->get<RegionState>(Sym);
1695 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001696 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001697 return 0;
1698
Anna Zaksfe571602012-02-16 22:26:07 +00001699 const Stmt *S = 0;
1700 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001701 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001702
1703 // Retrieve the associated statement.
1704 ProgramPoint ProgLoc = N->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00001705 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001706 S = SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +00001707 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001708 S = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001709 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremeneka4a17592013-01-04 19:04:36 +00001710 // If an assumption was made on a branch, it should be caught
1711 // here by looking at the state transition.
1712 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00001713 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00001714
Anna Zaksfe571602012-02-16 22:26:07 +00001715 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001716 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001717
Jordan Rose28038f32012-07-10 22:07:42 +00001718 // FIXME: We will eventually need to handle non-statement-based events
1719 // (__attribute__((cleanup))).
1720
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001721 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001722 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001723 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001724 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001725 StackHint = new StackHintGeneratorForSymbol(Sym,
1726 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001727 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001728 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001729 StackHint = new StackHintGeneratorForSymbol(Sym,
1730 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001731 } else if (isRelinquished(RS, RSPrev, S)) {
1732 Msg = "Memory ownership is transfered";
1733 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001734 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001735 Mode = ReallocationFailed;
1736 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001737 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001738 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001739
Jordy Roseb000fb52012-03-24 03:15:09 +00001740 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1741 // Is it possible to fail two reallocs WITHOUT testing in between?
1742 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1743 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001744 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001745 FailedReallocSymbol = sym;
1746 }
Anna Zaksfe571602012-02-16 22:26:07 +00001747 }
1748
1749 // We are in a special mode if a reallocation failed later in the path.
1750 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001751 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001752
Jordy Roseb000fb52012-03-24 03:15:09 +00001753 // Is this is the first appearance of the reallocated symbol?
1754 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001755 // We're at the reallocation point.
1756 Msg = "Attempt to reallocate memory";
1757 StackHint = new StackHintGeneratorForSymbol(Sym,
1758 "Returned reallocated memory");
1759 FailedReallocSymbol = NULL;
1760 Mode = Normal;
1761 }
Anna Zaksfe571602012-02-16 22:26:07 +00001762 }
1763
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001764 if (!Msg)
1765 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001766 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001767
1768 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001769 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001770 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001771 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001772}
1773
Anna Zaks93c5a242012-05-02 00:05:20 +00001774void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1775 const char *NL, const char *Sep) const {
1776
1777 RegionStateTy RS = State->get<RegionState>();
1778
Ted Kremenekc37fad62013-01-03 01:30:12 +00001779 if (!RS.isEmpty()) {
1780 Out << Sep << "MallocChecker:" << NL;
1781 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1782 I.getKey()->dumpToStream(Out);
1783 Out << " : ";
1784 I.getData().dump(Out);
1785 Out << NL;
1786 }
1787 }
Anna Zaks93c5a242012-05-02 00:05:20 +00001788}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001789
Anna Zaks231361a2012-02-08 23:16:52 +00001790#define REGISTER_CHECKER(name) \
1791void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001792 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001793 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001794}
Anna Zaks231361a2012-02-08 23:16:52 +00001795
1796REGISTER_CHECKER(MallocPessimistic)
1797REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev2de19ed2013-03-25 01:35:45 +00001798REGISTER_CHECKER(NewDeleteChecker)