blob: 851aa0ca36ba373f841335f392dbdc530aeac0b1 [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
Anton Yartsev849c7bf2013-03-28 17:05:19 +000038// Used to check correspondence between allocators and deallocators.
39enum AllocationFamily {
40 AF_None,
41 AF_Malloc,
42 AF_CXXNew,
43 AF_CXXNewArray
44};
45
Zhongxing Xu7fb14642009-12-11 00:55:44 +000046class RefState {
Anna Zaks050cdd72012-06-20 20:57:46 +000047 enum Kind { // Reference to allocated memory.
48 Allocated,
49 // Reference to released/freed memory.
50 Released,
Anna Zaks050cdd72012-06-20 20:57:46 +000051 // The responsibility for freeing resources has transfered from
52 // this reference. A relinquished symbol should not be freed.
Anton Yartsev849c7bf2013-03-28 17:05:19 +000053 Relinquished };
54
Zhongxing Xu243fde92009-11-17 07:54:15 +000055 const Stmt *S;
Anton Yartsev849c7bf2013-03-28 17:05:19 +000056 unsigned K : 2; // Kind enum, but stored as a bitfield.
57 unsigned Family : 30; // Rest of 32-bit word, currently just an allocation
58 // family.
Zhongxing Xu243fde92009-11-17 07:54:15 +000059
Anton Yartsev849c7bf2013-03-28 17:05:19 +000060 RefState(Kind k, const Stmt *s, unsigned family)
Eric Christopher03852c82013-03-28 18:22:58 +000061 : S(s), K(k), Family(family) {}
Zhongxing Xu7fb14642009-12-11 00:55:44 +000062public:
Anna Zaks050cdd72012-06-20 20:57:46 +000063 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000064 bool isReleased() const { return K == Released; }
Anna Zaks050cdd72012-06-20 20:57:46 +000065 bool isRelinquished() const { return K == Relinquished; }
Anton Yartsev849c7bf2013-03-28 17:05:19 +000066 AllocationFamily getAllocationFamily() const {
67 return (AllocationFamily)Family;
68 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +000069 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000070
71 bool operator==(const RefState &X) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +000072 return K == X.K && S == X.S && Family == X.Family;
Zhongxing Xu243fde92009-11-17 07:54:15 +000073 }
74
Anton Yartsev849c7bf2013-03-28 17:05:19 +000075 static RefState getAllocated(unsigned family, const Stmt *s) {
76 return RefState(Allocated, s, family);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000077 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +000078 static RefState getReleased(unsigned family, const Stmt *s) {
79 return RefState(Released, s, family);
80 }
81 static RefState getRelinquished(unsigned family, const Stmt *s) {
82 return RefState(Relinquished, s, family);
Ted Kremenekdde201b2010-08-06 21:12:55 +000083 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000084
85 void Profile(llvm::FoldingSetNodeID &ID) const {
86 ID.AddInteger(K);
87 ID.AddPointer(S);
Anton Yartsev849c7bf2013-03-28 17:05:19 +000088 ID.AddInteger(Family);
Zhongxing Xu243fde92009-11-17 07:54:15 +000089 }
Ted Kremenekc37fad62013-01-03 01:30:12 +000090
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000091 void dump(raw_ostream &OS) const {
Ted Kremenekc37fad62013-01-03 01:30:12 +000092 static const char *Table[] = {
93 "Allocated",
94 "Released",
95 "Relinquished"
96 };
97 OS << Table[(unsigned) K];
98 }
99
100 LLVM_ATTRIBUTE_USED void dump() const {
101 dump(llvm::errs());
102 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000103};
104
Anna Zaks9dc298b2012-09-12 22:57:34 +0000105enum ReallocPairKind {
106 RPToBeFreedAfterFailure,
107 // The symbol has been freed when reallocation failed.
108 RPIsFreeOnFailure,
109 // The symbol does not need to be freed after reallocation fails.
110 RPDoNotTrackAfterFailure
111};
112
Anna Zaks55dd9562012-08-24 02:28:20 +0000113/// \class ReallocPair
114/// \brief Stores information about the symbol being reallocated by a call to
115/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaks40add292012-02-15 00:11:25 +0000116struct ReallocPair {
Anna Zaks55dd9562012-08-24 02:28:20 +0000117 // \brief The symbol which realloc reallocated.
Anna Zaks40add292012-02-15 00:11:25 +0000118 SymbolRef ReallocatedSym;
Anna Zaks9dc298b2012-09-12 22:57:34 +0000119 ReallocPairKind Kind;
Anna Zaks55dd9562012-08-24 02:28:20 +0000120
Anna Zaks9dc298b2012-09-12 22:57:34 +0000121 ReallocPair(SymbolRef S, ReallocPairKind K) :
122 ReallocatedSym(S), Kind(K) {}
Anna Zaks40add292012-02-15 00:11:25 +0000123 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks9dc298b2012-09-12 22:57:34 +0000124 ID.AddInteger(Kind);
Anna Zaks40add292012-02-15 00:11:25 +0000125 ID.AddPointer(ReallocatedSym);
126 }
127 bool operator==(const ReallocPair &X) const {
128 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks9dc298b2012-09-12 22:57:34 +0000129 Kind == X.Kind;
Anna Zaks40add292012-02-15 00:11:25 +0000130 }
131};
132
Anna Zaks97bfb552013-01-08 00:25:29 +0000133typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000134
Anna Zaksb319e022012-02-08 20:13:28 +0000135class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000136 check::PointerEscape,
Anna Zaks41988f32013-03-28 23:15:29 +0000137 check::ConstPointerEscape,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000138 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +0000139 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +0000140 check::PostStmt<CallExpr>,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000141 check::PostStmt<CXXNewExpr>,
142 check::PreStmt<CXXDeleteExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000143 check::PostStmt<BlockExpr>,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000144 check::PostObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000145 check::Location,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000146 eval::Assume>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000147{
Anna Zaksfebdc322012-02-16 22:26:12 +0000148 mutable OwningPtr<BugType> BT_DoubleFree;
149 mutable OwningPtr<BugType> BT_Leak;
150 mutable OwningPtr<BugType> BT_UseFree;
151 mutable OwningPtr<BugType> BT_BadFree;
Anton Yartsev648cb712013-04-04 23:46:29 +0000152 mutable OwningPtr<BugType> BT_MismatchedDealloc;
Anna Zaks118aa752013-02-07 23:05:47 +0000153 mutable OwningPtr<BugType> BT_OffsetFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000154 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000155 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
156
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000157public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000158 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000159 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000160
161 /// In pessimistic mode, the checker assumes that it does not know which
162 /// functions might free the memory.
163 struct ChecksFilter {
164 DefaultBool CMallocPessimistic;
165 DefaultBool CMallocOptimistic;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000166 DefaultBool CNewDeleteChecker;
Jordan Rosee85deb32013-04-05 17:55:00 +0000167 DefaultBool CNewDeleteLeaksChecker;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000168 DefaultBool CMismatchedDeallocatorChecker;
Anna Zaks231361a2012-02-08 23:16:52 +0000169 };
170
171 ChecksFilter Filter;
172
Anna Zaks66c40402012-02-14 21:55:24 +0000173 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000174 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000175 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
176 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000177 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000178 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000179 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000180 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000181 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000182 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000183 void checkLocation(SVal l, bool isLoad, const Stmt *S,
184 CheckerContext &C) const;
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000185
186 ProgramStateRef checkPointerEscape(ProgramStateRef State,
187 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +0000188 const CallEvent *Call,
189 PointerEscapeKind Kind) const;
Anna Zaks41988f32013-03-28 23:15:29 +0000190 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
191 const InvalidatedSymbols &Escaped,
192 const CallEvent *Call,
193 PointerEscapeKind Kind) const;
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000194
Anna Zaks93c5a242012-05-02 00:05:20 +0000195 void printState(raw_ostream &Out, ProgramStateRef State,
196 const char *NL, const char *Sep) const;
197
Zhongxing Xu7b760962009-11-13 07:25:27 +0000198private:
Anna Zaks66c40402012-02-14 21:55:24 +0000199 void initIdentifierInfo(ASTContext &C) const;
200
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000201 /// \brief Determine family of a deallocation expression.
Anton Yartsev648cb712013-04-04 23:46:29 +0000202 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000203
204 /// \brief Print names of allocators and deallocators.
205 ///
206 /// \returns true on success.
207 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
208 const Expr *E) const;
209
210 /// \brief Print expected name of an allocator based on the deallocator's
211 /// family derived from the DeallocExpr.
212 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
213 const Expr *DeallocExpr) const;
214 /// \brief Print expected name of a deallocator based on the allocator's
215 /// family.
216 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
217
Jordan Rose9fe09f32013-03-09 00:59:10 +0000218 ///@{
Anna Zaks66c40402012-02-14 21:55:24 +0000219 /// Check if this is one of the functions which can allocate/reallocate memory
220 /// pointed to by one of its arguments.
221 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000222 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
223 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000224 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose9fe09f32013-03-09 00:59:10 +0000225 ///@}
Anna Zaks87cb5be2012-02-22 19:24:52 +0000226 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
227 const CallExpr *CE,
228 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000229 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000230 const Expr *SizeEx, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000231 ProgramStateRef State,
232 AllocationFamily Family = AF_Malloc) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000233 return MallocMemAux(C, CE,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000234 State->getSVal(SizeEx, C.getLocationContext()),
235 Init, State, Family);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000236 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000237
Ted Kremenek8bef8232012-01-26 21:29:00 +0000238 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000239 SVal SizeEx, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000240 ProgramStateRef State,
241 AllocationFamily Family = AF_Malloc);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000242
Anna Zaks87cb5be2012-02-22 19:24:52 +0000243 /// Update the RefState to reflect the new memory allocation.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000244 static ProgramStateRef
245 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
246 AllocationFamily Family = AF_Malloc);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000247
248 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
249 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000250 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000251 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000252 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000253 bool &ReleasedAllocated,
254 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000255 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
256 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000257 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000258 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000259 bool &ReleasedAllocated,
260 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000261
Anna Zaks87cb5be2012-02-22 19:24:52 +0000262 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
263 bool FreesMemOnFailure) const;
264 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000265
Anna Zaks14345182012-05-18 01:16:10 +0000266 ///\brief Check if the memory associated with this symbol was released.
267 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
268
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000269 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
Anna Zaks91c2a112012-02-08 23:16:56 +0000270
Jordan Rose9fe09f32013-03-09 00:59:10 +0000271 /// Check if the function is known not to free memory, or if it is
272 /// "interesting" and should be modeled explicitly.
273 ///
274 /// We assume that pointers do not escape through calls to system functions
275 /// not handled by this checker.
276 bool doesNotFreeMemOrInteresting(const CallEvent *Call,
277 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000278
Anna Zaks41988f32013-03-28 23:15:29 +0000279 // Implementation of the checkPointerEscape callabcks.
280 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
281 const InvalidatedSymbols &Escaped,
282 const CallEvent *Call,
283 PointerEscapeKind Kind,
284 bool(*CheckRefState)(const RefState*)) const;
285
Anton Yartsev648cb712013-04-04 23:46:29 +0000286 // Used to suppress warnings if they are not related to the tracked family
287 // (derived from AllocDeallocStmt).
288 bool isTrackedFamily(AllocationFamily Family) const;
289 bool isTrackedFamily(CheckerContext &C, const Stmt *AllocDeallocStmt) const;
290 bool isTrackedFamily(CheckerContext &C, SymbolRef Sym) const;
291
Ted Kremenek9c378f72011-08-12 23:37:29 +0000292 static bool SummarizeValue(raw_ostream &os, SVal V);
293 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000294 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
295 const Expr *DeallocExpr) const;
Anton Yartsev648cb712013-04-04 23:46:29 +0000296 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
Anton Yartseva3ae9372013-04-05 11:25:10 +0000297 const Expr *DeallocExpr, const RefState *RS,
298 SymbolRef Sym) const;
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000299 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
300 const Expr *DeallocExpr,
301 const Expr *AllocExpr = 0) const;
Anton Yartsevbb369952013-03-13 14:39:10 +0000302 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
303 SymbolRef Sym) const;
304 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
Anton Yartsev3258d4b2013-03-13 17:07:32 +0000305 SymbolRef Sym, SymbolRef PrevSym) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000306
Anna Zaksca8e36e2012-02-23 21:38:21 +0000307 /// Find the location of the allocation for Sym on the path leading to the
308 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000309 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
310 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000311
Anna Zaksda046772012-02-11 21:02:40 +0000312 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
313
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000314 /// The bug visitor which allows us to print extra diagnostics along the
315 /// BugReport path. For example, showing the allocation site of the leaked
316 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000317 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000318 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000319 enum NotificationMode {
320 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000321 ReallocationFailed
322 };
323
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000324 // The allocated region symbol tracked by the main analysis.
325 SymbolRef Sym;
326
Anna Zaks88feba02012-05-10 01:37:40 +0000327 // The mode we are in, i.e. what kind of diagnostics will be emitted.
328 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000329
Anna Zaks88feba02012-05-10 01:37:40 +0000330 // A symbol from when the primary region should have been reallocated.
331 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000332
Anna Zaks88feba02012-05-10 01:37:40 +0000333 bool IsLeak;
334
335 public:
336 MallocBugVisitor(SymbolRef S, bool isLeak = false)
337 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000338
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000339 virtual ~MallocBugVisitor() {}
340
341 void Profile(llvm::FoldingSetNodeID &ID) const {
342 static int X = 0;
343 ID.AddPointer(&X);
344 ID.AddPointer(Sym);
345 }
346
Anna Zaksfe571602012-02-16 22:26:07 +0000347 inline bool isAllocated(const RefState *S, const RefState *SPrev,
348 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000349 // Did not track -> allocated. Other state (released) -> allocated.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000350 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000351 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000352 }
353
Anna Zaksfe571602012-02-16 22:26:07 +0000354 inline bool isReleased(const RefState *S, const RefState *SPrev,
355 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000356 // Did not track -> released. Other state (allocated) -> released.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000357 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
Anna Zaksfe571602012-02-16 22:26:07 +0000358 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
359 }
360
Anna Zaks5b7aa342012-06-22 02:04:31 +0000361 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
362 const Stmt *Stmt) {
363 // Did not track -> relinquished. Other state (allocated) -> relinquished.
364 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
365 isa<ObjCPropertyRefExpr>(Stmt)) &&
366 (S && S->isRelinquished()) &&
367 (!SPrev || !SPrev->isRelinquished()));
368 }
369
Anna Zaksfe571602012-02-16 22:26:07 +0000370 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
371 const Stmt *Stmt) {
372 // If the expression is not a call, and the state change is
373 // released -> allocated, it must be the realloc return value
374 // check. If we have to handle more cases here, it might be cleaner just
375 // to track this extra bit in the state itself.
376 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
377 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000378 }
379
380 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
381 const ExplodedNode *PrevN,
382 BugReporterContext &BRC,
383 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000384
385 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
386 const ExplodedNode *EndPathNode,
387 BugReport &BR) {
388 if (!IsLeak)
389 return 0;
390
391 PathDiagnosticLocation L =
392 PathDiagnosticLocation::createEndOfPath(EndPathNode,
393 BRC.getSourceManager());
394 // Do not add the statement itself as a range in case of leak.
395 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
396 }
397
Anna Zaks56a938f2012-03-16 23:24:20 +0000398 private:
399 class StackHintGeneratorForReallocationFailed
400 : public StackHintGeneratorForSymbol {
401 public:
402 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
403 : StackHintGeneratorForSymbol(S, M) {}
404
405 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000406 // Printed parameters start at 1, not 0.
407 ++ArgIndex;
408
Anna Zaks56a938f2012-03-16 23:24:20 +0000409 SmallString<200> buf;
410 llvm::raw_svector_ostream os(buf);
411
Jordan Rose615a0922012-09-22 01:24:42 +0000412 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
413 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000414
415 return os.str();
416 }
417
418 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000419 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000420 }
421 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000422 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000423};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000424} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000425
Jordan Rose166d5022012-11-02 01:54:06 +0000426REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
427REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000428
Anna Zaks4141e4d2012-11-13 03:18:01 +0000429// A map from the freed symbol to the symbol representing the return value of
430// the free function.
431REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
432
Anna Zaks4fb54872012-02-11 21:02:35 +0000433namespace {
434class StopTrackingCallback : public SymbolVisitor {
435 ProgramStateRef state;
436public:
437 StopTrackingCallback(ProgramStateRef st) : state(st) {}
438 ProgramStateRef getState() const { return state; }
439
440 bool VisitSymbol(SymbolRef sym) {
441 state = state->remove<RegionState>(sym);
442 return true;
443 }
444};
445} // end anonymous namespace
446
Anna Zaks66c40402012-02-14 21:55:24 +0000447void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000448 if (II_malloc)
449 return;
450 II_malloc = &Ctx.Idents.get("malloc");
451 II_free = &Ctx.Idents.get("free");
452 II_realloc = &Ctx.Idents.get("realloc");
453 II_reallocf = &Ctx.Idents.get("reallocf");
454 II_calloc = &Ctx.Idents.get("calloc");
455 II_valloc = &Ctx.Idents.get("valloc");
456 II_strdup = &Ctx.Idents.get("strdup");
457 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000458}
459
Anna Zaks66c40402012-02-14 21:55:24 +0000460bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000461 if (isFreeFunction(FD, C))
462 return true;
463
464 if (isAllocationFunction(FD, C))
465 return true;
466
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000467 if (isStandardNewDelete(FD, C))
468 return true;
469
Anna Zaks14345182012-05-18 01:16:10 +0000470 return false;
471}
472
473bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
474 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000475 if (!FD)
476 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000477
Jordan Rose5ef6e942012-07-10 23:13:01 +0000478 if (FD->getKind() == Decl::Function) {
479 IdentifierInfo *FunI = FD->getIdentifier();
480 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000481
Jordan Rose5ef6e942012-07-10 23:13:01 +0000482 if (FunI == II_malloc || FunI == II_realloc ||
483 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
484 FunI == II_strdup || FunI == II_strndup)
485 return true;
486 }
Anna Zaks66c40402012-02-14 21:55:24 +0000487
Anna Zaks14345182012-05-18 01:16:10 +0000488 if (Filter.CMallocOptimistic && FD->hasAttrs())
489 for (specific_attr_iterator<OwnershipAttr>
490 i = FD->specific_attr_begin<OwnershipAttr>(),
491 e = FD->specific_attr_end<OwnershipAttr>();
492 i != e; ++i)
493 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
494 return true;
495 return false;
496}
497
498bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
499 if (!FD)
500 return false;
501
Jordan Rose5ef6e942012-07-10 23:13:01 +0000502 if (FD->getKind() == Decl::Function) {
503 IdentifierInfo *FunI = FD->getIdentifier();
504 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000505
Jordan Rose5ef6e942012-07-10 23:13:01 +0000506 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
507 return true;
508 }
Anna Zaks66c40402012-02-14 21:55:24 +0000509
Anna Zaks14345182012-05-18 01:16:10 +0000510 if (Filter.CMallocOptimistic && FD->hasAttrs())
511 for (specific_attr_iterator<OwnershipAttr>
512 i = FD->specific_attr_begin<OwnershipAttr>(),
513 e = FD->specific_attr_end<OwnershipAttr>();
514 i != e; ++i)
515 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
516 (*i)->getOwnKind() == OwnershipAttr::Holds)
517 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000518 return false;
519}
520
Anton Yartsev69746282013-03-28 16:10:38 +0000521// Tells if the callee is one of the following:
522// 1) A global non-placement new/delete operator function.
523// 2) A global placement operator function with the single placement argument
524// of type std::nothrow_t.
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000525bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
526 ASTContext &C) const {
527 if (!FD)
528 return false;
529
530 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
531 if (Kind != OO_New && Kind != OO_Array_New &&
532 Kind != OO_Delete && Kind != OO_Array_Delete)
533 return false;
534
Anton Yartsev69746282013-03-28 16:10:38 +0000535 // Skip all operator new/delete methods.
536 if (isa<CXXMethodDecl>(FD))
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000537 return false;
538
539 // Return true if tested operator is a standard placement nothrow operator.
540 if (FD->getNumParams() == 2) {
541 QualType T = FD->getParamDecl(1)->getType();
542 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
543 return II->getName().equals("nothrow_t");
544 }
545
546 // Skip placement operators.
547 if (FD->getNumParams() != 1 || FD->isVariadic())
548 return false;
549
550 // One of the standard new/new[]/delete/delete[] non-placement operators.
551 return true;
552}
553
Anna Zaksb319e022012-02-08 20:13:28 +0000554void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000555 if (C.wasInlined)
556 return;
557
Anna Zaksb319e022012-02-08 20:13:28 +0000558 const FunctionDecl *FD = C.getCalleeDecl(CE);
559 if (!FD)
560 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000561
Anna Zaks87cb5be2012-02-22 19:24:52 +0000562 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000563 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000564
565 if (FD->getKind() == Decl::Function) {
566 initIdentifierInfo(C.getASTContext());
567 IdentifierInfo *FunI = FD->getIdentifier();
568
Anton Yartsev648cb712013-04-04 23:46:29 +0000569 if (FunI == II_malloc || FunI == II_valloc) {
570 if (CE->getNumArgs() < 1)
571 return;
572 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
573 } else if (FunI == II_realloc) {
574 State = ReallocMem(C, CE, false);
575 } else if (FunI == II_reallocf) {
576 State = ReallocMem(C, CE, true);
577 } else if (FunI == II_calloc) {
578 State = CallocMem(C, CE);
579 } else if (FunI == II_free) {
580 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
581 } else if (FunI == II_strdup) {
582 State = MallocUpdateRefState(C, CE, State);
583 } else if (FunI == II_strndup) {
584 State = MallocUpdateRefState(C, CE, State);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000585 }
Anton Yartsev648cb712013-04-04 23:46:29 +0000586 else if (isStandardNewDelete(FD, C.getASTContext())) {
587 // Process direct calls to operator new/new[]/delete/delete[] functions
588 // as distinct from new/new[]/delete/delete[] expressions that are
589 // processed by the checkPostStmt callbacks for CXXNewExpr and
590 // CXXDeleteExpr.
591 OverloadedOperatorKind K = FD->getOverloadedOperator();
592 if (K == OO_New)
593 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
594 AF_CXXNew);
595 else if (K == OO_Array_New)
596 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
597 AF_CXXNewArray);
598 else if (K == OO_Delete || K == OO_Array_Delete)
599 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
600 else
601 llvm_unreachable("not a new/delete operator");
Jordan Rose5ef6e942012-07-10 23:13:01 +0000602 }
603 }
604
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000605 if (Filter.CMallocOptimistic || Filter.CMismatchedDeallocatorChecker) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000606 // Check all the attributes, if there are any.
607 // There can be multiple of these attributes.
608 if (FD->hasAttrs())
609 for (specific_attr_iterator<OwnershipAttr>
610 i = FD->specific_attr_begin<OwnershipAttr>(),
611 e = FD->specific_attr_end<OwnershipAttr>();
612 i != e; ++i) {
613 switch ((*i)->getOwnKind()) {
614 case OwnershipAttr::Returns:
615 State = MallocMemReturnsAttr(C, CE, *i);
616 break;
617 case OwnershipAttr::Takes:
618 case OwnershipAttr::Holds:
619 State = FreeMemAttr(C, CE, *i);
620 break;
621 }
622 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000623 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000624 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000625}
626
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000627void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
628 CheckerContext &C) const {
629
630 if (NE->getNumPlacementArgs())
631 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
632 E = NE->placement_arg_end(); I != E; ++I)
633 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
634 checkUseAfterFree(Sym, C, *I);
635
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000636 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
637 return;
638
639 ProgramStateRef State = C.getState();
640 // The return value from operator new is bound to a specified initialization
641 // value (if any) and we don't want to loose this value. So we call
642 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
643 // existing binding.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000644 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
645 : AF_CXXNew);
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000646 C.addTransition(State);
647}
648
649void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
650 CheckerContext &C) const {
651
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000652 if (!Filter.CNewDeleteChecker)
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000653 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
654 checkUseAfterFree(Sym, C, DE->getArgument());
655
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000656 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
657 return;
658
659 ProgramStateRef State = C.getState();
660 bool ReleasedAllocated;
661 State = FreeMemAux(C, DE->getArgument(), DE, State,
662 /*Hold*/false, ReleasedAllocated);
663
664 C.addTransition(State);
665}
666
Jordan Rose9fe09f32013-03-09 00:59:10 +0000667static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
668 // If the first selector piece is one of the names below, assume that the
669 // object takes ownership of the memory, promising to eventually deallocate it
670 // with free().
671 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
672 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
673 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
674 if (FirstSlot == "dataWithBytesNoCopy" ||
675 FirstSlot == "initWithBytesNoCopy" ||
676 FirstSlot == "initWithCharactersNoCopy")
677 return true;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000678
679 return false;
680}
681
Jordan Rose9fe09f32013-03-09 00:59:10 +0000682static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
683 Selector S = Call.getSelector();
684
685 // FIXME: We should not rely on fully-constrained symbols being folded.
686 for (unsigned i = 1; i < S.getNumArgs(); ++i)
687 if (S.getNameForSlot(i).equals("freeWhenDone"))
688 return !Call.getArgSVal(i).isZeroConstant();
689
690 return None;
691}
692
Anna Zaks4141e4d2012-11-13 03:18:01 +0000693void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
694 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000695 if (C.wasInlined)
696 return;
697
Jordan Rose9fe09f32013-03-09 00:59:10 +0000698 if (!isKnownDeallocObjCMethodName(Call))
699 return;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000700
Jordan Rose9fe09f32013-03-09 00:59:10 +0000701 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
702 if (!*FreeWhenDone)
703 return;
704
705 bool ReleasedAllocatedMemory;
706 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
707 Call.getOriginExpr(), C.getState(),
708 /*Hold=*/true, ReleasedAllocatedMemory,
709 /*RetNullOnFailure=*/true);
710
711 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000712}
713
Anna Zaks87cb5be2012-02-22 19:24:52 +0000714ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
715 const CallExpr *CE,
716 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000717 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000718 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000719
Sean Huntcf807c42010-08-18 23:23:40 +0000720 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000721 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000722 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000723 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000724 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000725}
726
Anna Zaksb319e022012-02-08 20:13:28 +0000727ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000728 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000729 SVal Size, SVal Init,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000730 ProgramStateRef State,
731 AllocationFamily Family) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000732
733 // Bind the return value to the symbolic value from the heap region.
734 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
735 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000736 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000737 SValBuilder &svalBuilder = C.getSValBuilder();
738 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie5251abe2013-02-20 05:52:05 +0000739 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
740 .castAs<DefinedSVal>();
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000741 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000742
Anna Zaksb16ce452012-02-15 00:11:22 +0000743 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000744 if (!RetVal.getAs<Loc>())
Anna Zaksb16ce452012-02-15 00:11:22 +0000745 return 0;
746
Jordy Rose32f26562010-07-04 00:00:41 +0000747 // Fill the region with the initialization value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000748 State = State->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000749
Jordy Rose32f26562010-07-04 00:00:41 +0000750 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000751 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000752 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000753 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000754 return 0;
David Blaikiedc84cd52013-02-20 22:23:23 +0000755 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000756 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000757 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000758 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000759 DefinedOrUnknownSVal extentMatchesSize =
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000760 svalBuilder.evalEQ(State, Extent, *DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000761
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000762 State = State->assume(extentMatchesSize, true);
763 assert(State);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000764 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000765
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000766 return MallocUpdateRefState(C, CE, State, Family);
Anna Zaks87cb5be2012-02-22 19:24:52 +0000767}
768
769ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
Anton Yartsev2de19ed2013-03-25 01:35:45 +0000770 const Expr *E,
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000771 ProgramStateRef State,
772 AllocationFamily Family) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000773 // Get the return value.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000774 SVal retVal = State->getSVal(E, C.getLocationContext());
Anna Zaks87cb5be2012-02-22 19:24:52 +0000775
776 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000777 if (!retVal.getAs<Loc>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000778 return 0;
779
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000780 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000781 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000782
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000783 // Set the symbol's state to Allocated.
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000784 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000785}
786
Anna Zaks87cb5be2012-02-22 19:24:52 +0000787ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
788 const CallExpr *CE,
789 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000790 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000791 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000792
Anna Zaksb3d72752012-03-01 22:06:06 +0000793 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000794 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000795
Sean Huntcf807c42010-08-18 23:23:40 +0000796 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
797 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000798 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000799 Att->getOwnKind() == OwnershipAttr::Holds,
800 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000801 if (StateI)
802 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000803 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000804 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000805}
806
Ted Kremenek8bef8232012-01-26 21:29:00 +0000807ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000808 const CallExpr *CE,
809 ProgramStateRef state,
810 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000811 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000812 bool &ReleasedAllocated,
813 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000814 if (CE->getNumArgs() < (Num + 1))
815 return 0;
816
Anna Zaks4141e4d2012-11-13 03:18:01 +0000817 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
818 ReleasedAllocated, ReturnsNullOnFailure);
819}
820
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000821/// Checks if the previous call to free on the given symbol failed - if free
822/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000823static bool didPreviousFreeFail(ProgramStateRef State,
824 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000825 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000826 if (Ret) {
827 assert(*Ret && "We should not store the null return symbol");
828 ConstraintManager &CMgr = State->getConstraintManager();
829 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000830 RetStatusSymbol = *Ret;
831 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000832 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000833 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000834}
835
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000836AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
Anton Yartsev648cb712013-04-04 23:46:29 +0000837 const Stmt *S) const {
838 if (!S)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000839 return AF_None;
840
Anton Yartsev648cb712013-04-04 23:46:29 +0000841 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000842 const FunctionDecl *FD = C.getCalleeDecl(CE);
Anton Yartsev648cb712013-04-04 23:46:29 +0000843
844 if (!FD)
845 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
846
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000847 ASTContext &Ctx = C.getASTContext();
848
Anton Yartsev648cb712013-04-04 23:46:29 +0000849 if (isAllocationFunction(FD, Ctx) || isFreeFunction(FD, Ctx))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000850 return AF_Malloc;
851
852 if (isStandardNewDelete(FD, Ctx)) {
853 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
Anton Yartsev648cb712013-04-04 23:46:29 +0000854 if (Kind == OO_New || Kind == OO_Delete)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000855 return AF_CXXNew;
Anton Yartsev648cb712013-04-04 23:46:29 +0000856 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000857 return AF_CXXNewArray;
858 }
859
860 return AF_None;
861 }
862
Anton Yartsev648cb712013-04-04 23:46:29 +0000863 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
864 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
865
866 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000867 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
868
Anton Yartsev648cb712013-04-04 23:46:29 +0000869 if (isa<ObjCMessageExpr>(S))
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000870 return AF_Malloc;
871
872 return AF_None;
873}
874
875bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
876 const Expr *E) const {
877 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
878 // FIXME: This doesn't handle indirect calls.
879 const FunctionDecl *FD = CE->getDirectCallee();
880 if (!FD)
881 return false;
882
883 os << *FD;
884 if (!FD->isOverloadedOperator())
885 os << "()";
886 return true;
887 }
888
889 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
890 if (Msg->isInstanceMessage())
891 os << "-";
892 else
893 os << "+";
894 os << Msg->getSelector().getAsString();
895 return true;
896 }
897
898 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
899 os << "'"
900 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
901 << "'";
902 return true;
903 }
904
905 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
906 os << "'"
907 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
908 << "'";
909 return true;
910 }
911
912 return false;
913}
914
915void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
916 const Expr *E) const {
917 AllocationFamily Family = getAllocationFamily(C, E);
918
919 switch(Family) {
920 case AF_Malloc: os << "malloc()"; return;
921 case AF_CXXNew: os << "'new'"; return;
922 case AF_CXXNewArray: os << "'new[]'"; return;
923 case AF_None: llvm_unreachable("not a deallocation expression");
924 }
925}
926
927void MallocChecker::printExpectedDeallocName(raw_ostream &os,
928 AllocationFamily Family) const {
929 switch(Family) {
930 case AF_Malloc: os << "free()"; return;
931 case AF_CXXNew: os << "'delete'"; return;
932 case AF_CXXNewArray: os << "'delete[]'"; return;
933 case AF_None: llvm_unreachable("suspicious AF_None argument");
934 }
935}
936
Anna Zaks5b7aa342012-06-22 02:04:31 +0000937ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
938 const Expr *ArgExpr,
939 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000940 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000941 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000942 bool &ReleasedAllocated,
943 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000944
Anna Zaks4141e4d2012-11-13 03:18:01 +0000945 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie5251abe2013-02-20 05:52:05 +0000946 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zakse9ef5622012-02-10 01:11:00 +0000947 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000948 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000949
950 // Check for null dereferences.
David Blaikie5251abe2013-02-20 05:52:05 +0000951 if (!location.getAs<Loc>())
Anna Zaksb319e022012-02-08 20:13:28 +0000952 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000953
Anna Zaksb276bd92012-02-14 00:26:13 +0000954 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000955 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000956 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000957 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000958 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000959
Jordy Rose43859f62010-06-07 19:32:37 +0000960 // Unknown values could easily be okay
961 // Undefined values are handled elsewhere
962 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000963 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000964
Jordy Rose43859f62010-06-07 19:32:37 +0000965 const MemRegion *R = ArgVal.getAsRegion();
966
967 // Nonlocs can't be freed, of course.
968 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
969 if (!R) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000970 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000971 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000972 }
973
974 R = R->StripCasts();
975
976 // Blocks might show up as heap data, but should not be free()d
977 if (isa<BlockDataRegion>(R)) {
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000978 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000979 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000980 }
981
982 const MemSpaceRegion *MS = R->getMemorySpace();
983
Anton Yartsevbb369952013-03-13 14:39:10 +0000984 // Parameters, locals, statics, globals, and memory returned by alloca()
985 // shouldn't be freed.
Jordy Rose43859f62010-06-07 19:32:37 +0000986 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
987 // FIXME: at the time this code was written, malloc() regions were
988 // represented by conjured symbols, which are all in UnknownSpaceRegion.
989 // This means that there isn't actually anything from HeapSpaceRegion
990 // that should be freed, even though we allow it here.
991 // Of course, free() can work on memory allocated outside the current
992 // function, so UnknownSpaceRegion is always a possibility.
993 // False negatives are better than false positives.
994
Anton Yartsev849c7bf2013-03-28 17:05:19 +0000995 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
Anna Zaksb319e022012-02-08 20:13:28 +0000996 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000997 }
Anna Zaks118aa752013-02-07 23:05:47 +0000998
999 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose43859f62010-06-07 19:32:37 +00001000 // Various cases could lead to non-symbol values here.
1001 // For now, ignore them.
Anna Zaks118aa752013-02-07 23:05:47 +00001002 if (!SrBase)
Anna Zaksb319e022012-02-08 20:13:28 +00001003 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +00001004
Anna Zaks118aa752013-02-07 23:05:47 +00001005 SymbolRef SymBase = SrBase->getSymbol();
1006 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001007 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +00001008
Anton Yartsev648cb712013-04-04 23:46:29 +00001009 if (RsBase) {
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001010
Anton Yartsev648cb712013-04-04 23:46:29 +00001011 bool DeallocMatchesAlloc =
1012 RsBase->getAllocationFamily() == AF_None ||
1013 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001014
Anton Yartsev648cb712013-04-04 23:46:29 +00001015 // Check if an expected deallocation function matches the real one.
1016 if (!DeallocMatchesAlloc && RsBase->isAllocated()) {
Anton Yartseva3ae9372013-04-05 11:25:10 +00001017 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(), ParentExpr, RsBase,
1018 SymBase);
Anton Yartsev648cb712013-04-04 23:46:29 +00001019 return 0;
1020 }
1021
1022 // Check double free.
1023 if (DeallocMatchesAlloc &&
1024 (RsBase->isReleased() || RsBase->isRelinquished()) &&
1025 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1026 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1027 SymBase, PreviousRetStatusSymbol);
1028 return 0;
1029 }
1030
1031 // Check if the memory location being freed is the actual location
1032 // allocated, or an offset.
1033 RegionOffset Offset = R->getAsOffset();
1034 if (RsBase->isAllocated() &&
1035 Offset.isValid() &&
1036 !Offset.hasSymbolicOffset() &&
1037 Offset.getOffset() != 0) {
1038 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1039 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1040 AllocExpr);
1041 return 0;
1042 }
Anna Zaks118aa752013-02-07 23:05:47 +00001043 }
1044
1045 ReleasedAllocated = (RsBase != 0);
Anna Zaks55dd9562012-08-24 02:28:20 +00001046
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001047 // Clean out the info on previous call to free return info.
Anna Zaks118aa752013-02-07 23:05:47 +00001048 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +00001049
Anna Zaks4141e4d2012-11-13 03:18:01 +00001050 // Keep track of the return value. If it is NULL, we will know that free
1051 // failed.
1052 if (ReturnsNullOnFailure) {
1053 SVal RetVal = C.getSVal(ParentExpr);
1054 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1055 if (RetStatusSymbol) {
Anna Zaks118aa752013-02-07 23:05:47 +00001056 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1057 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks4141e4d2012-11-13 03:18:01 +00001058 }
1059 }
1060
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001061 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily() : AF_None;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001062 // Normal free.
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001063 if (Hold)
Anna Zaks118aa752013-02-07 23:05:47 +00001064 return State->set<RegionState>(SymBase,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001065 RefState::getRelinquished(Family,
1066 ParentExpr));
1067
1068 return State->set<RegionState>(SymBase,
1069 RefState::getReleased(Family, ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001070}
1071
Anton Yartsev648cb712013-04-04 23:46:29 +00001072bool MallocChecker::isTrackedFamily(AllocationFamily Family) const {
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001073 switch (Family) {
1074 case AF_Malloc: {
1075 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic)
1076 return false;
Anton Yartsevc8454312013-04-05 02:12:04 +00001077 return true;
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001078 }
1079 case AF_CXXNew:
1080 case AF_CXXNewArray: {
1081 if (!Filter.CNewDeleteChecker)
1082 return false;
Anton Yartsevc8454312013-04-05 02:12:04 +00001083 return true;
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001084 }
1085 case AF_None: {
1086 return true;
1087 }
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001088 }
Anton Yartsevc8454312013-04-05 02:12:04 +00001089 llvm_unreachable("unhandled family");
Anton Yartsev648cb712013-04-04 23:46:29 +00001090}
1091
1092bool MallocChecker::isTrackedFamily(CheckerContext &C,
1093 const Stmt *AllocDeallocStmt) const {
1094 return isTrackedFamily(getAllocationFamily(C, AllocDeallocStmt));
1095}
1096
1097bool MallocChecker::isTrackedFamily(CheckerContext &C, SymbolRef Sym) const {
1098 const RefState *RS = C.getState()->get<RegionState>(Sym);
1099
1100 return RS ? isTrackedFamily(RS->getAllocationFamily())
1101 : isTrackedFamily(AF_None);
1102}
1103
Ted Kremenek9c378f72011-08-12 23:37:29 +00001104bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001105 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001106 os << "an integer (" << IntVal->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001107 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001108 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001109 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner68106302011-02-17 05:38:27 +00001110 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +00001111 else
1112 return false;
1113
1114 return true;
1115}
1116
Ted Kremenek9c378f72011-08-12 23:37:29 +00001117bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +00001118 const MemRegion *MR) {
1119 switch (MR->getKind()) {
1120 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +00001121 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +00001122 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001123 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +00001124 else
1125 os << "the address of a function";
1126 return true;
1127 }
1128 case MemRegion::BlockTextRegionKind:
1129 os << "block text";
1130 return true;
1131 case MemRegion::BlockDataRegionKind:
1132 // FIXME: where the block came from?
1133 os << "a block";
1134 return true;
1135 default: {
1136 const MemSpaceRegion *MS = MR->getMemorySpace();
1137
Anna Zakseb31a762012-01-04 23:54:01 +00001138 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001139 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1140 const VarDecl *VD;
1141 if (VR)
1142 VD = VR->getDecl();
1143 else
1144 VD = NULL;
1145
1146 if (VD)
1147 os << "the address of the local variable '" << VD->getName() << "'";
1148 else
1149 os << "the address of a local stack variable";
1150 return true;
1151 }
Anna Zakseb31a762012-01-04 23:54:01 +00001152
1153 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001154 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1155 const VarDecl *VD;
1156 if (VR)
1157 VD = VR->getDecl();
1158 else
1159 VD = NULL;
1160
1161 if (VD)
1162 os << "the address of the parameter '" << VD->getName() << "'";
1163 else
1164 os << "the address of a parameter";
1165 return true;
1166 }
Anna Zakseb31a762012-01-04 23:54:01 +00001167
1168 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001169 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1170 const VarDecl *VD;
1171 if (VR)
1172 VD = VR->getDecl();
1173 else
1174 VD = NULL;
1175
1176 if (VD) {
1177 if (VD->isStaticLocal())
1178 os << "the address of the static variable '" << VD->getName() << "'";
1179 else
1180 os << "the address of the global variable '" << VD->getName() << "'";
1181 } else
1182 os << "the address of a global variable";
1183 return true;
1184 }
Anna Zakseb31a762012-01-04 23:54:01 +00001185
1186 return false;
Jordy Rose43859f62010-06-07 19:32:37 +00001187 }
1188 }
1189}
1190
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001191void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1192 SourceRange Range,
1193 const Expr *DeallocExpr) const {
1194
1195 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1196 !Filter.CNewDeleteChecker)
1197 return;
1198
Anton Yartsev648cb712013-04-04 23:46:29 +00001199 if (!isTrackedFamily(C, DeallocExpr))
1200 return;
1201
Ted Kremenekd048c6e2010-12-20 21:19:09 +00001202 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +00001203 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001204 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +00001205
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001206 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +00001207 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001208
Jordy Rose43859f62010-06-07 19:32:37 +00001209 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001210 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1211 MR = ER->getSuperRegion();
1212
1213 if (MR && isa<AllocaRegion>(MR))
1214 os << "Memory allocated by alloca() should not be deallocated";
1215 else {
1216 os << "Argument to ";
1217 if (!printAllocDeallocName(os, C, DeallocExpr))
1218 os << "deallocator";
1219
1220 os << " is ";
1221 bool Summarized = MR ? SummarizeRegion(os, MR)
1222 : SummarizeValue(os, ArgVal);
1223 if (Summarized)
1224 os << ", which is not memory allocated by ";
Jordy Rose43859f62010-06-07 19:32:37 +00001225 else
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001226 os << "not memory allocated by ";
1227
1228 printExpectedAllocName(os, C, DeallocExpr);
Jordy Rose43859f62010-06-07 19:32:37 +00001229 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001230
Anna Zakse172e8b2011-08-17 23:00:25 +00001231 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001232 R->markInteresting(MR);
Anton Yartsevbb369952013-03-13 14:39:10 +00001233 R->addRange(Range);
Jordan Rose785950e2012-11-02 01:53:40 +00001234 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +00001235 }
1236}
1237
Anton Yartsev648cb712013-04-04 23:46:29 +00001238void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1239 SourceRange Range,
1240 const Expr *DeallocExpr,
Anton Yartseva3ae9372013-04-05 11:25:10 +00001241 const RefState *RS,
1242 SymbolRef Sym) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001243
1244 if (!Filter.CMismatchedDeallocatorChecker)
1245 return;
1246
1247 if (ExplodedNode *N = C.generateSink()) {
Anton Yartsev648cb712013-04-04 23:46:29 +00001248 if (!BT_MismatchedDealloc)
1249 BT_MismatchedDealloc.reset(new BugType("Bad deallocator",
1250 "Memory Error"));
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001251
1252 SmallString<100> buf;
1253 llvm::raw_svector_ostream os(buf);
1254
1255 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1256 SmallString<20> AllocBuf;
1257 llvm::raw_svector_ostream AllocOs(AllocBuf);
1258 SmallString<20> DeallocBuf;
1259 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1260
1261 os << "Memory";
1262 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1263 os << " allocated by " << AllocOs.str();
1264
1265 os << " should be deallocated by ";
1266 printExpectedDeallocName(os, RS->getAllocationFamily());
1267
1268 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1269 os << ", not " << DeallocOs.str();
1270
Anton Yartsev648cb712013-04-04 23:46:29 +00001271 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartseva3ae9372013-04-05 11:25:10 +00001272 R->markInteresting(Sym);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001273 R->addRange(Range);
Anton Yartseva3ae9372013-04-05 11:25:10 +00001274 R->addVisitor(new MallocBugVisitor(Sym));
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001275 C.emitReport(R);
1276 }
1277}
1278
Anna Zaks118aa752013-02-07 23:05:47 +00001279void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001280 SourceRange Range, const Expr *DeallocExpr,
1281 const Expr *AllocExpr) const {
1282
1283 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1284 !Filter.CNewDeleteChecker)
1285 return;
1286
Anton Yartsev648cb712013-04-04 23:46:29 +00001287 if (!isTrackedFamily(C, AllocExpr))
1288 return;
1289
Anna Zaks118aa752013-02-07 23:05:47 +00001290 ExplodedNode *N = C.generateSink();
1291 if (N == NULL)
1292 return;
1293
1294 if (!BT_OffsetFree)
1295 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
1296
1297 SmallString<100> buf;
1298 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001299 SmallString<20> AllocNameBuf;
1300 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaks118aa752013-02-07 23:05:47 +00001301
1302 const MemRegion *MR = ArgVal.getAsRegion();
1303 assert(MR && "Only MemRegion based symbols can have offset free errors");
1304
1305 RegionOffset Offset = MR->getAsOffset();
1306 assert((Offset.isValid() &&
1307 !Offset.hasSymbolicOffset() &&
1308 Offset.getOffset() != 0) &&
1309 "Only symbols with a valid offset can have offset free errors");
1310
1311 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1312
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001313 os << "Argument to ";
1314 if (!printAllocDeallocName(os, C, DeallocExpr))
1315 os << "deallocator";
1316 os << " is offset by "
Anna Zaks118aa752013-02-07 23:05:47 +00001317 << offsetBytes
1318 << " "
1319 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001320 << " from the start of ";
1321 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1322 os << "memory allocated by " << AllocNameOs.str();
1323 else
1324 os << "allocated memory";
Anna Zaks118aa752013-02-07 23:05:47 +00001325
1326 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
1327 R->markInteresting(MR->getBaseRegion());
1328 R->addRange(Range);
1329 C.emitReport(R);
1330}
1331
Anton Yartsevbb369952013-03-13 14:39:10 +00001332void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1333 SymbolRef Sym) const {
1334
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001335 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1336 !Filter.CNewDeleteChecker)
1337 return;
1338
Anton Yartsev648cb712013-04-04 23:46:29 +00001339 if (!isTrackedFamily(C, Sym))
1340 return;
1341
Anton Yartsevbb369952013-03-13 14:39:10 +00001342 if (ExplodedNode *N = C.generateSink()) {
1343 if (!BT_UseFree)
1344 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
1345
1346 BugReport *R = new BugReport(*BT_UseFree,
1347 "Use of memory after it is freed", N);
1348
1349 R->markInteresting(Sym);
1350 R->addRange(Range);
1351 R->addVisitor(new MallocBugVisitor(Sym));
1352 C.emitReport(R);
1353 }
1354}
1355
1356void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1357 bool Released, SymbolRef Sym,
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001358 SymbolRef PrevSym) const {
Anton Yartsevbb369952013-03-13 14:39:10 +00001359
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001360 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1361 !Filter.CNewDeleteChecker)
1362 return;
1363
Anton Yartsev648cb712013-04-04 23:46:29 +00001364 if (!isTrackedFamily(C, Sym))
1365 return;
1366
Anton Yartsevbb369952013-03-13 14:39:10 +00001367 if (ExplodedNode *N = C.generateSink()) {
1368 if (!BT_DoubleFree)
1369 BT_DoubleFree.reset(new BugType("Double free", "Memory Error"));
1370
1371 BugReport *R = new BugReport(*BT_DoubleFree,
1372 (Released ? "Attempt to free released memory"
1373 : "Attempt to free non-owned memory"),
1374 N);
1375 R->addRange(Range);
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001376 R->markInteresting(Sym);
1377 if (PrevSym)
1378 R->markInteresting(PrevSym);
Anton Yartsevbb369952013-03-13 14:39:10 +00001379 R->addVisitor(new MallocBugVisitor(Sym));
1380 C.emitReport(R);
1381 }
1382}
1383
Anna Zaks87cb5be2012-02-22 19:24:52 +00001384ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1385 const CallExpr *CE,
1386 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001387 if (CE->getNumArgs() < 2)
1388 return 0;
1389
Ted Kremenek8bef8232012-01-26 21:29:00 +00001390 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001391 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001392 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +00001393 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001394 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001395 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001396 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001397
Ted Kremenek846eabd2010-12-01 21:28:31 +00001398 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001399
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001400 DefinedOrUnknownSVal PtrEQ =
1401 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001402
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001403 // Get the size argument. If there is no size arg then give up.
1404 const Expr *Arg1 = CE->getArg(1);
1405 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001406 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001407
1408 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +00001409 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001410 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001411 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001412 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001413
1414 // Compare the size argument to 0.
1415 DefinedOrUnknownSVal SizeZero =
1416 svalBuilder.evalEQ(state, Arg1Val,
1417 svalBuilder.makeIntValWithPtrWidth(0, false));
1418
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001419 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1420 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
1421 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1422 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
1423 // We only assume exceptional states if they are definitely true; if the
1424 // state is under-constrained, assume regular realloc behavior.
1425 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1426 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1427
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001428 // If the ptr is NULL and the size is not 0, the call is equivalent to
1429 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001430 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +00001431 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001432 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001433 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001434 }
1435
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001436 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001437 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001438
Anna Zaks30838b92012-02-13 20:57:07 +00001439 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001440 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001441 SymbolRef FromPtr = arg0Val.getAsSymbol();
1442 SVal RetVal = state->getSVal(CE, LCtx);
1443 SymbolRef ToPtr = RetVal.getAsSymbol();
1444 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001445 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001446
Anna Zaks55dd9562012-08-24 02:28:20 +00001447 bool ReleasedAllocated = false;
1448
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001449 // If the size is 0, free the memory.
1450 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001451 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1452 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001453 // The semantics of the return value are:
1454 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001455 // to free() is returned. We just free the input pointer and do not add
1456 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001457 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001458 }
1459
1460 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001461 if (ProgramStateRef stateFree =
1462 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1463
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001464 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1465 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001466 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001467 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001468
Anna Zaks9dc298b2012-09-12 22:57:34 +00001469 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1470 if (FreesOnFail)
1471 Kind = RPIsFreeOnFailure;
1472 else if (!ReleasedAllocated)
1473 Kind = RPDoNotTrackAfterFailure;
1474
Anna Zaks55dd9562012-08-24 02:28:20 +00001475 // Record the info about the reallocated symbol so that we could properly
1476 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001477 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001478 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001479 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001480 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001481 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001482 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001483 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001484}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001485
Anna Zaks87cb5be2012-02-22 19:24:52 +00001486ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001487 if (CE->getNumArgs() < 2)
1488 return 0;
1489
Ted Kremenek8bef8232012-01-26 21:29:00 +00001490 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001491 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001492 const LocationContext *LCtx = C.getLocationContext();
1493 SVal count = state->getSVal(CE->getArg(0), LCtx);
1494 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001495 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1496 svalBuilder.getContext().getSizeType());
1497 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001498
Anna Zaks87cb5be2012-02-22 19:24:52 +00001499 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001500}
1501
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001502LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001503MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1504 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001505 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001506 // Walk the ExplodedGraph backwards and find the first node that referred to
1507 // the tracked symbol.
1508 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001509 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001510
1511 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001512 ProgramStateRef State = N->getState();
1513 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001514 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001515
1516 // Find the most recent expression bound to the symbol in the current
1517 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001518 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001519 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1520 SVal Val = State->getSVal(MR);
1521 if (Val.getAsLocSymbol() == Sym)
1522 ReferenceRegion = MR;
1523 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001524 }
1525
Anna Zaks7752d292012-02-27 23:40:55 +00001526 // Allocation node, is the last node in the current context in which the
1527 // symbol was tracked.
1528 if (N->getLocationContext() == LeakContext)
1529 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001530 N = N->pred_empty() ? NULL : *(N->pred_begin());
1531 }
1532
Anna Zaks97bfb552013-01-08 00:25:29 +00001533 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001534}
1535
Anna Zaksda046772012-02-11 21:02:40 +00001536void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1537 CheckerContext &C) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001538
1539 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
Jordan Rosee85deb32013-04-05 17:55:00 +00001540 !Filter.CNewDeleteLeaksChecker)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001541 return;
1542
Jordan Rosee85deb32013-04-05 17:55:00 +00001543 const RefState *RS = C.getState()->get<RegionState>(Sym);
1544 assert(RS && "cannot leak an untracked symbol");
1545 AllocationFamily Family = RS->getAllocationFamily();
1546 if (!isTrackedFamily(Family))
Anton Yartsev418780f2013-04-05 02:25:02 +00001547 return;
1548
Jordan Rosee85deb32013-04-05 17:55:00 +00001549 // Special case for new and new[]; these are controlled by a separate checker
1550 // flag so that they can be selectively disabled.
1551 if (Family == AF_CXXNew || Family == AF_CXXNewArray)
1552 if (!Filter.CNewDeleteLeaksChecker)
1553 return;
1554
Anna Zaksda046772012-02-11 21:02:40 +00001555 assert(N);
1556 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001557 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001558 // Leaks should not be reported if they are post-dominated by a sink:
1559 // (1) Sinks are higher importance bugs.
1560 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1561 // with __noreturn functions such as assert() or exit(). We choose not
1562 // to report leaks on such paths.
1563 BT_Leak->setSuppressOnSink(true);
1564 }
1565
Anna Zaksca8e36e2012-02-23 21:38:21 +00001566 // Most bug reports are cached at the location where they occurred.
1567 // With leaks, we want to unique them by the location where they were
1568 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001569 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001570 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001571 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001572 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1573
1574 ProgramPoint P = AllocNode->getLocation();
1575 const Stmt *AllocationStmt = 0;
David Blaikie7a95de62013-02-21 22:23:56 +00001576 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001577 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001578 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001579 AllocationStmt = SP->getStmt();
Anton Yartsev418780f2013-04-05 02:25:02 +00001580 if (AllocationStmt)
Anna Zaks97bfb552013-01-08 00:25:29 +00001581 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1582 C.getSourceManager(),
1583 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001584
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001585 SmallString<200> buf;
1586 llvm::raw_svector_ostream os(buf);
1587 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001588 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001589 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001590 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001591 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001592 }
1593
Anna Zaks97bfb552013-01-08 00:25:29 +00001594 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1595 LocUsedForUniqueing,
1596 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001597 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001598 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001599 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001600}
1601
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001602void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1603 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001604{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001605 if (!SymReaper.hasDeadSymbols())
1606 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001607
Ted Kremenek8bef8232012-01-26 21:29:00 +00001608 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001609 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001610 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001611
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001612 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001613 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1614 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001615 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001616 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001617 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001618 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001619
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001620 }
1621 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001622
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001623 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001624 ReallocPairsTy RP = state->get<ReallocPairs>();
1625 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001626 if (SymReaper.isDead(I->first) ||
1627 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001628 state = state->remove<ReallocPairs>(I->first);
1629 }
1630 }
1631
Anna Zaks4141e4d2012-11-13 03:18:01 +00001632 // Cleanup the FreeReturnValue Map.
1633 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1634 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1635 if (SymReaper.isDead(I->first) ||
1636 SymReaper.isDead(I->second)) {
1637 state = state->remove<FreeReturnValue>(I->first);
1638 }
1639 }
1640
Anna Zaksca8e36e2012-02-23 21:38:21 +00001641 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001642 ExplodedNode *N = C.getPredecessor();
1643 if (!Errors.empty()) {
1644 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1645 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001646 for (SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001647 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001648 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001649 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001650 }
Anna Zaks54458702012-10-29 22:51:54 +00001651
Anna Zaksca8e36e2012-02-23 21:38:21 +00001652 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001653}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001654
Anna Zaks66c40402012-02-14 21:55:24 +00001655void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001656 // We will check for double free in the post visit.
Anton Yartsev2de19ed2013-03-25 01:35:45 +00001657 if ((Filter.CMallocOptimistic || Filter.CMallocPessimistic) &&
1658 isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
1659 return;
1660
1661 if (Filter.CNewDeleteChecker &&
1662 isStandardNewDelete(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001663 return;
1664
1665 // Check use after free, when a freed pointer is passed to a call.
1666 ProgramStateRef State = C.getState();
1667 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1668 E = CE->arg_end(); I != E; ++I) {
1669 const Expr *A = *I;
1670 if (A->getType().getTypePtr()->isAnyPointerType()) {
Anton Yartsevbb369952013-03-13 14:39:10 +00001671 SymbolRef Sym = C.getSVal(A).getAsSymbol();
Anna Zaks66c40402012-02-14 21:55:24 +00001672 if (!Sym)
1673 continue;
1674 if (checkUseAfterFree(Sym, C, A))
1675 return;
1676 }
1677 }
1678}
1679
Anna Zaks91c2a112012-02-08 23:16:56 +00001680void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1681 const Expr *E = S->getRetValue();
1682 if (!E)
1683 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001684
1685 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001686 ProgramStateRef State = C.getState();
1687 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001688 SymbolRef Sym = RetVal.getAsSymbol();
1689 if (!Sym)
1690 // If we are returning a field of the allocated struct or an array element,
1691 // the callee could still free the memory.
1692 // TODO: This logic should be a part of generic symbol escape callback.
1693 if (const MemRegion *MR = RetVal.getAsRegion())
1694 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1695 if (const SymbolicRegion *BMR =
1696 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1697 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001698
Anna Zaks0860cd02012-02-11 21:44:39 +00001699 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001700 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001701 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001702}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001703
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001704// TODO: Blocks should be either inlined or should call invalidate regions
1705// upon invocation. After that's in place, special casing here will not be
1706// needed.
1707void MallocChecker::checkPostStmt(const BlockExpr *BE,
1708 CheckerContext &C) const {
1709
1710 // Scan the BlockDecRefExprs for any object the retain count checker
1711 // may be tracking.
1712 if (!BE->getBlockDecl()->hasCaptures())
1713 return;
1714
1715 ProgramStateRef state = C.getState();
1716 const BlockDataRegion *R =
1717 cast<BlockDataRegion>(state->getSVal(BE,
1718 C.getLocationContext()).getAsRegion());
1719
1720 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1721 E = R->referenced_vars_end();
1722
1723 if (I == E)
1724 return;
1725
1726 SmallVector<const MemRegion*, 10> Regions;
1727 const LocationContext *LC = C.getLocationContext();
1728 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1729
1730 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001731 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001732 if (VR->getSuperRegion() == R) {
1733 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1734 }
1735 Regions.push_back(VR);
1736 }
1737
1738 state =
1739 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1740 Regions.data() + Regions.size()).getState();
1741 C.addTransition(state);
1742}
1743
Anna Zaks14345182012-05-18 01:16:10 +00001744bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001745 assert(Sym);
1746 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001747 return (RS && RS->isReleased());
1748}
1749
1750bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1751 const Stmt *S) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001752
Anton Yartsevbb369952013-03-13 14:39:10 +00001753 if (isReleased(Sym, C)) {
1754 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1755 return true;
Anna Zaks91c2a112012-02-08 23:16:56 +00001756 }
Anton Yartsevbb369952013-03-13 14:39:10 +00001757
Anna Zaks91c2a112012-02-08 23:16:56 +00001758 return false;
1759}
1760
Zhongxing Xuc8023782010-03-10 04:58:55 +00001761// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001762void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1763 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001764 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001765 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001766 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001767}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001768
Anna Zaks4fb54872012-02-11 21:02:35 +00001769// If a symbolic region is assumed to NULL (or another constant), stop tracking
1770// it - assuming that allocation failed on this path.
1771ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1772 SVal Cond,
1773 bool Assumption) const {
1774 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001775 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001776 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001777 ConstraintManager &CMgr = state->getConstraintManager();
1778 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1779 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001780 state = state->remove<RegionState>(I.getKey());
1781 }
1782
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001783 // Realloc returns 0 when reallocation fails, which means that we should
1784 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001785 ReallocPairsTy RP = state->get<ReallocPairs>();
1786 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001787 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001788 ConstraintManager &CMgr = state->getConstraintManager();
1789 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001790 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001791 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001792
Anna Zaks9dc298b2012-09-12 22:57:34 +00001793 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1794 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1795 if (RS->isReleased()) {
1796 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001797 state = state->set<RegionState>(ReallocSym,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001798 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks9dc298b2012-09-12 22:57:34 +00001799 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1800 state = state->remove<RegionState>(ReallocSym);
1801 else
1802 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001803 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001804 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001805 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001806 }
1807
Anna Zaks4fb54872012-02-11 21:02:35 +00001808 return state;
1809}
1810
Jordan Rose9fe09f32013-03-09 00:59:10 +00001811bool MallocChecker::doesNotFreeMemOrInteresting(const CallEvent *Call,
1812 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001813 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001814
1815 // For now, assume that any C++ call can free memory.
1816 // TODO: If we want to be more optimistic here, we'll need to make sure that
1817 // regions escape to C++ containers. They seem to do that even now, but for
1818 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001819 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001820 return false;
1821
Jordan Rose740d4902012-07-02 19:27:35 +00001822 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001823 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001824 // If it's not a framework call, or if it takes a callback, assume it
1825 // can free memory.
1826 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001827 return false;
1828
Jordan Rose9fe09f32013-03-09 00:59:10 +00001829 // If it's a method we know about, handle it explicitly post-call.
1830 // This should happen before the "freeWhenDone" check below.
1831 if (isKnownDeallocObjCMethodName(*Msg))
1832 return true;
Anna Zaks52a04812012-06-20 23:35:57 +00001833
Jordan Rose9fe09f32013-03-09 00:59:10 +00001834 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1835 // about, we can't be sure that the object will use free() to deallocate the
1836 // memory, so we can't model it explicitly. The best we can do is use it to
1837 // decide whether the pointer escapes.
1838 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
1839 return !*FreeWhenDone;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001840
Jordan Rose9fe09f32013-03-09 00:59:10 +00001841 // If the first selector piece ends with "NoCopy", and there is no
1842 // "freeWhenDone" parameter set to zero, we know ownership is being
1843 // transferred. Again, though, we can't be sure that the object will use
1844 // free() to deallocate the memory, so we can't model it explicitly.
1845 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose740d4902012-07-02 19:27:35 +00001846 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001847 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001848
Anna Zaks5f757682012-06-19 05:10:32 +00001849 // If the first selector starts with addPointer, insertPointer,
1850 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1851 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001852 // that the pointers get freed by following the container itself.
1853 if (FirstSlot.startswith("addPointer") ||
1854 FirstSlot.startswith("insertPointer") ||
1855 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001856 return false;
1857 }
1858
Jordan Rose740d4902012-07-02 19:27:35 +00001859 // Otherwise, assume that the method does not free memory.
1860 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001861 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001862 }
1863
Jordan Rose740d4902012-07-02 19:27:35 +00001864 // At this point the only thing left to handle is straight function calls.
1865 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1866 if (!FD)
1867 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001868
Jordan Rose740d4902012-07-02 19:27:35 +00001869 ASTContext &ASTC = State->getStateManager().getContext();
1870
1871 // If it's one of the allocation functions we can reason about, we model
1872 // its behavior explicitly.
1873 if (isMemFunction(FD, ASTC))
1874 return true;
1875
1876 // If it's not a system call, assume it frees memory.
1877 if (!Call->isInSystemHeader())
1878 return false;
1879
1880 // White list the system functions whose arguments escape.
1881 const IdentifierInfo *II = FD->getIdentifier();
1882 if (!II)
1883 return false;
1884 StringRef FName = II->getName();
1885
Jordan Rose740d4902012-07-02 19:27:35 +00001886 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001887 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001888 if (FName.endswith("NoCopy")) {
1889 // Look for the deallocator argument. We know that the memory ownership
1890 // is not transferred only if the deallocator argument is
1891 // 'kCFAllocatorNull'.
1892 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1893 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1894 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1895 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1896 if (DeallocatorName == "kCFAllocatorNull")
1897 return true;
1898 }
1899 }
1900 return false;
1901 }
1902
Jordan Rose740d4902012-07-02 19:27:35 +00001903 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001904 // 'closefn' is specified (and if that function does free memory),
1905 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001906 // Currently, we do not inspect the 'closefn' function (PR12101).
1907 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001908 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1909 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001910
1911 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1912 // these leaks might be intentional when setting the buffer for stdio.
1913 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1914 if (FName == "setbuf" || FName =="setbuffer" ||
1915 FName == "setlinebuf" || FName == "setvbuf") {
1916 if (Call->getNumArgs() >= 1) {
1917 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1918 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1919 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1920 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1921 return false;
1922 }
1923 }
1924
1925 // A bunch of other functions which either take ownership of a pointer or
1926 // wrap the result up in a struct or object, meaning it can be freed later.
1927 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1928 // but the Malloc checker cannot differentiate between them. The right way
1929 // of doing this would be to implement a pointer escapes callback.
1930 if (FName == "CGBitmapContextCreate" ||
1931 FName == "CGBitmapContextCreateWithData" ||
1932 FName == "CVPixelBufferCreateWithBytes" ||
1933 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1934 FName == "OSAtomicEnqueue") {
1935 return false;
1936 }
1937
Jordan Rose85d7e012012-07-02 19:27:51 +00001938 // Handle cases where we know a buffer's /address/ can escape.
1939 // Note that the above checks handle some special cases where we know that
1940 // even though the address escapes, it's still our responsibility to free the
1941 // buffer.
1942 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001943 return false;
1944
1945 // Otherwise, assume that the function does not free memory.
1946 // Most system calls do not free the memory.
1947 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001948}
1949
Anna Zaks41988f32013-03-28 23:15:29 +00001950static bool retTrue(const RefState *RS) {
1951 return true;
1952}
1953
1954static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
1955 return (RS->getAllocationFamily() == AF_CXXNewArray ||
1956 RS->getAllocationFamily() == AF_CXXNew);
1957}
1958
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001959ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1960 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00001961 const CallEvent *Call,
1962 PointerEscapeKind Kind) const {
Anna Zaks41988f32013-03-28 23:15:29 +00001963 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
1964}
1965
1966ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
1967 const InvalidatedSymbols &Escaped,
1968 const CallEvent *Call,
1969 PointerEscapeKind Kind) const {
1970 return checkPointerEscapeAux(State, Escaped, Call, Kind,
1971 &checkIfNewOrNewArrayFamily);
1972}
1973
1974ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
1975 const InvalidatedSymbols &Escaped,
1976 const CallEvent *Call,
1977 PointerEscapeKind Kind,
1978 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose9fe09f32013-03-09 00:59:10 +00001979 // If we know that the call does not free memory, or we want to process the
1980 // call later, keep tracking the top level arguments.
Anna Zaks233e26a2013-02-07 23:05:43 +00001981 if ((Kind == PSK_DirectEscapeOnCall ||
1982 Kind == PSK_IndirectEscapeOnCall) &&
Jordan Rose9fe09f32013-03-09 00:59:10 +00001983 doesNotFreeMemOrInteresting(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001984 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00001985 }
Anna Zaks66c40402012-02-14 21:55:24 +00001986
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001987 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks41988f32013-03-28 23:15:29 +00001988 E = Escaped.end();
1989 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001990 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001991
Anna Zaks5b7aa342012-06-22 02:04:31 +00001992 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks41988f32013-03-28 23:15:29 +00001993 if (RS->isAllocated() && CheckRefState(RS))
Anna Zaks431e35c2012-08-09 00:42:24 +00001994 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001995 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001996 }
Anna Zaks66c40402012-02-14 21:55:24 +00001997 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001998}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001999
Jordy Rose393f98b2012-03-18 07:43:35 +00002000static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2001 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00002002 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2003 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00002004
Jordan Rose166d5022012-11-02 01:54:06 +00002005 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00002006 I != E; ++I) {
2007 SymbolRef sym = I.getKey();
2008 if (!currMap.lookup(sym))
2009 return sym;
2010 }
2011
2012 return NULL;
2013}
2014
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002015PathDiagnosticPiece *
2016MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2017 const ExplodedNode *PrevN,
2018 BugReporterContext &BRC,
2019 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00002020 ProgramStateRef state = N->getState();
2021 ProgramStateRef statePrev = PrevN->getState();
2022
2023 const RefState *RS = state->get<RegionState>(Sym);
2024 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00002025 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002026 return 0;
2027
Anna Zaksfe571602012-02-16 22:26:07 +00002028 const Stmt *S = 0;
2029 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00002030 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00002031
2032 // Retrieve the associated statement.
2033 ProgramPoint ProgLoc = N->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002034 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00002035 S = SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +00002036 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00002037 S = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00002038 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremeneka4a17592013-01-04 19:04:36 +00002039 // If an assumption was made on a branch, it should be caught
2040 // here by looking at the state transition.
2041 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00002042 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00002043
Anna Zaksfe571602012-02-16 22:26:07 +00002044 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002045 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002046
Jordan Rose28038f32012-07-10 22:07:42 +00002047 // FIXME: We will eventually need to handle non-statement-based events
2048 // (__attribute__((cleanup))).
2049
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002050 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00002051 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00002052 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002053 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00002054 StackHint = new StackHintGeneratorForSymbol(Sym,
2055 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00002056 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002057 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00002058 StackHint = new StackHintGeneratorForSymbol(Sym,
2059 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00002060 } else if (isRelinquished(RS, RSPrev, S)) {
2061 Msg = "Memory ownership is transfered";
2062 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00002063 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002064 Mode = ReallocationFailed;
2065 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00002066 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00002067 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00002068
Jordy Roseb000fb52012-03-24 03:15:09 +00002069 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2070 // Is it possible to fail two reallocs WITHOUT testing in between?
2071 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2072 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00002073 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00002074 FailedReallocSymbol = sym;
2075 }
Anna Zaksfe571602012-02-16 22:26:07 +00002076 }
2077
2078 // We are in a special mode if a reallocation failed later in the path.
2079 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002080 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00002081
Jordy Roseb000fb52012-03-24 03:15:09 +00002082 // Is this is the first appearance of the reallocated symbol?
2083 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002084 // We're at the reallocation point.
2085 Msg = "Attempt to reallocate memory";
2086 StackHint = new StackHintGeneratorForSymbol(Sym,
2087 "Returned reallocated memory");
2088 FailedReallocSymbol = NULL;
2089 Mode = Normal;
2090 }
Anna Zaksfe571602012-02-16 22:26:07 +00002091 }
2092
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002093 if (!Msg)
2094 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00002095 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002096
2097 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00002098 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002099 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00002100 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002101}
2102
Anna Zaks93c5a242012-05-02 00:05:20 +00002103void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2104 const char *NL, const char *Sep) const {
2105
2106 RegionStateTy RS = State->get<RegionState>();
2107
Ted Kremenekc37fad62013-01-03 01:30:12 +00002108 if (!RS.isEmpty()) {
2109 Out << Sep << "MallocChecker:" << NL;
2110 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2111 I.getKey()->dumpToStream(Out);
2112 Out << " : ";
2113 I.getData().dump(Out);
2114 Out << NL;
2115 }
2116 }
Anna Zaks93c5a242012-05-02 00:05:20 +00002117}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002118
Anna Zaks231361a2012-02-08 23:16:52 +00002119#define REGISTER_CHECKER(name) \
2120void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00002121 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00002122 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00002123}
Anna Zaks231361a2012-02-08 23:16:52 +00002124
2125REGISTER_CHECKER(MallocPessimistic)
2126REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev2de19ed2013-03-25 01:35:45 +00002127REGISTER_CHECKER(NewDeleteChecker)
Jordan Rosee85deb32013-04-05 17:55:00 +00002128REGISTER_CHECKER(NewDeleteLeaksChecker)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00002129REGISTER_CHECKER(MismatchedDeallocatorChecker)