blob: a1ec819ef287e6004b4ebff391e94dc24b12cade [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
Anton Yartseva3989b82013-04-05 19:08:04 +0000287 // (derived from Sym or AllocDeallocStmt).
Anton Yartsev648cb712013-04-04 23:46:29 +0000288 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 Yartseva3989b82013-04-05 19:08:04 +00001061 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1062 : getAllocationFamily(C, ParentExpr);
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001063 // Normal free.
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001064 if (Hold)
Anna Zaks118aa752013-02-07 23:05:47 +00001065 return State->set<RegionState>(SymBase,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001066 RefState::getRelinquished(Family,
1067 ParentExpr));
1068
1069 return State->set<RegionState>(SymBase,
1070 RefState::getReleased(Family, ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001071}
1072
Anton Yartsev648cb712013-04-04 23:46:29 +00001073bool MallocChecker::isTrackedFamily(AllocationFamily Family) const {
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001074 switch (Family) {
1075 case AF_Malloc: {
1076 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic)
1077 return false;
Anton Yartsevc8454312013-04-05 02:12:04 +00001078 return true;
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001079 }
1080 case AF_CXXNew:
1081 case AF_CXXNewArray: {
1082 if (!Filter.CNewDeleteChecker)
1083 return false;
Anton Yartsevc8454312013-04-05 02:12:04 +00001084 return true;
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001085 }
1086 case AF_None: {
Anton Yartseva3989b82013-04-05 19:08:04 +00001087 llvm_unreachable("no family");
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001088 }
Anton Yartsev9c6bbb32013-04-05 00:31:02 +00001089 }
Anton Yartsevc8454312013-04-05 02:12:04 +00001090 llvm_unreachable("unhandled family");
Anton Yartsev648cb712013-04-04 23:46:29 +00001091}
1092
1093bool MallocChecker::isTrackedFamily(CheckerContext &C,
1094 const Stmt *AllocDeallocStmt) const {
1095 return isTrackedFamily(getAllocationFamily(C, AllocDeallocStmt));
1096}
1097
1098bool MallocChecker::isTrackedFamily(CheckerContext &C, SymbolRef Sym) const {
Anton Yartsev648cb712013-04-04 23:46:29 +00001099
Anton Yartseva3989b82013-04-05 19:08:04 +00001100 const RefState *RS = C.getState()->get<RegionState>(Sym);
1101 assert(RS);
1102 return isTrackedFamily(RS->getAllocationFamily());
Anton Yartsev648cb712013-04-04 23:46:29 +00001103}
1104
Ted Kremenek9c378f72011-08-12 23:37:29 +00001105bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001106 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001107 os << "an integer (" << IntVal->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001108 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +00001109 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +00001110 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner68106302011-02-17 05:38:27 +00001111 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +00001112 else
1113 return false;
1114
1115 return true;
1116}
1117
Ted Kremenek9c378f72011-08-12 23:37:29 +00001118bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +00001119 const MemRegion *MR) {
1120 switch (MR->getKind()) {
1121 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +00001122 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +00001123 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001124 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +00001125 else
1126 os << "the address of a function";
1127 return true;
1128 }
1129 case MemRegion::BlockTextRegionKind:
1130 os << "block text";
1131 return true;
1132 case MemRegion::BlockDataRegionKind:
1133 // FIXME: where the block came from?
1134 os << "a block";
1135 return true;
1136 default: {
1137 const MemSpaceRegion *MS = MR->getMemorySpace();
1138
Anna Zakseb31a762012-01-04 23:54:01 +00001139 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001140 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1141 const VarDecl *VD;
1142 if (VR)
1143 VD = VR->getDecl();
1144 else
1145 VD = NULL;
1146
1147 if (VD)
1148 os << "the address of the local variable '" << VD->getName() << "'";
1149 else
1150 os << "the address of a local stack variable";
1151 return true;
1152 }
Anna Zakseb31a762012-01-04 23:54:01 +00001153
1154 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001155 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1156 const VarDecl *VD;
1157 if (VR)
1158 VD = VR->getDecl();
1159 else
1160 VD = NULL;
1161
1162 if (VD)
1163 os << "the address of the parameter '" << VD->getName() << "'";
1164 else
1165 os << "the address of a parameter";
1166 return true;
1167 }
Anna Zakseb31a762012-01-04 23:54:01 +00001168
1169 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +00001170 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1171 const VarDecl *VD;
1172 if (VR)
1173 VD = VR->getDecl();
1174 else
1175 VD = NULL;
1176
1177 if (VD) {
1178 if (VD->isStaticLocal())
1179 os << "the address of the static variable '" << VD->getName() << "'";
1180 else
1181 os << "the address of the global variable '" << VD->getName() << "'";
1182 } else
1183 os << "the address of a global variable";
1184 return true;
1185 }
Anna Zakseb31a762012-01-04 23:54:01 +00001186
1187 return false;
Jordy Rose43859f62010-06-07 19:32:37 +00001188 }
1189 }
1190}
1191
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001192void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1193 SourceRange Range,
1194 const Expr *DeallocExpr) const {
1195
1196 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1197 !Filter.CNewDeleteChecker)
1198 return;
1199
Anton Yartsev648cb712013-04-04 23:46:29 +00001200 if (!isTrackedFamily(C, DeallocExpr))
1201 return;
1202
Ted Kremenekd048c6e2010-12-20 21:19:09 +00001203 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +00001204 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +00001205 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +00001206
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00001207 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +00001208 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001209
Jordy Rose43859f62010-06-07 19:32:37 +00001210 const MemRegion *MR = ArgVal.getAsRegion();
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001211 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1212 MR = ER->getSuperRegion();
1213
1214 if (MR && isa<AllocaRegion>(MR))
1215 os << "Memory allocated by alloca() should not be deallocated";
1216 else {
1217 os << "Argument to ";
1218 if (!printAllocDeallocName(os, C, DeallocExpr))
1219 os << "deallocator";
1220
1221 os << " is ";
1222 bool Summarized = MR ? SummarizeRegion(os, MR)
1223 : SummarizeValue(os, ArgVal);
1224 if (Summarized)
1225 os << ", which is not memory allocated by ";
Jordy Rose43859f62010-06-07 19:32:37 +00001226 else
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001227 os << "not memory allocated by ";
1228
1229 printExpectedAllocName(os, C, DeallocExpr);
Jordy Rose43859f62010-06-07 19:32:37 +00001230 }
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001231
Anna Zakse172e8b2011-08-17 23:00:25 +00001232 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +00001233 R->markInteresting(MR);
Anton Yartsevbb369952013-03-13 14:39:10 +00001234 R->addRange(Range);
Jordan Rose785950e2012-11-02 01:53:40 +00001235 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +00001236 }
1237}
1238
Anton Yartsev648cb712013-04-04 23:46:29 +00001239void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1240 SourceRange Range,
1241 const Expr *DeallocExpr,
Anton Yartseva3ae9372013-04-05 11:25:10 +00001242 const RefState *RS,
1243 SymbolRef Sym) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001244
1245 if (!Filter.CMismatchedDeallocatorChecker)
1246 return;
1247
1248 if (ExplodedNode *N = C.generateSink()) {
Anton Yartsev648cb712013-04-04 23:46:29 +00001249 if (!BT_MismatchedDealloc)
1250 BT_MismatchedDealloc.reset(new BugType("Bad deallocator",
1251 "Memory Error"));
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001252
1253 SmallString<100> buf;
1254 llvm::raw_svector_ostream os(buf);
1255
1256 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1257 SmallString<20> AllocBuf;
1258 llvm::raw_svector_ostream AllocOs(AllocBuf);
1259 SmallString<20> DeallocBuf;
1260 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1261
1262 os << "Memory";
1263 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1264 os << " allocated by " << AllocOs.str();
1265
1266 os << " should be deallocated by ";
1267 printExpectedDeallocName(os, RS->getAllocationFamily());
1268
1269 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1270 os << ", not " << DeallocOs.str();
1271
Anton Yartsev648cb712013-04-04 23:46:29 +00001272 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
Anton Yartseva3ae9372013-04-05 11:25:10 +00001273 R->markInteresting(Sym);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001274 R->addRange(Range);
Anton Yartseva3ae9372013-04-05 11:25:10 +00001275 R->addVisitor(new MallocBugVisitor(Sym));
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001276 C.emitReport(R);
1277 }
1278}
1279
Anna Zaks118aa752013-02-07 23:05:47 +00001280void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001281 SourceRange Range, const Expr *DeallocExpr,
1282 const Expr *AllocExpr) const {
1283
1284 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1285 !Filter.CNewDeleteChecker)
1286 return;
1287
Anton Yartsev648cb712013-04-04 23:46:29 +00001288 if (!isTrackedFamily(C, AllocExpr))
1289 return;
1290
Anna Zaks118aa752013-02-07 23:05:47 +00001291 ExplodedNode *N = C.generateSink();
1292 if (N == NULL)
1293 return;
1294
1295 if (!BT_OffsetFree)
1296 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
1297
1298 SmallString<100> buf;
1299 llvm::raw_svector_ostream os(buf);
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001300 SmallString<20> AllocNameBuf;
1301 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
Anna Zaks118aa752013-02-07 23:05:47 +00001302
1303 const MemRegion *MR = ArgVal.getAsRegion();
1304 assert(MR && "Only MemRegion based symbols can have offset free errors");
1305
1306 RegionOffset Offset = MR->getAsOffset();
1307 assert((Offset.isValid() &&
1308 !Offset.hasSymbolicOffset() &&
1309 Offset.getOffset() != 0) &&
1310 "Only symbols with a valid offset can have offset free errors");
1311
1312 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1313
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001314 os << "Argument to ";
1315 if (!printAllocDeallocName(os, C, DeallocExpr))
1316 os << "deallocator";
1317 os << " is offset by "
Anna Zaks118aa752013-02-07 23:05:47 +00001318 << offsetBytes
1319 << " "
1320 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001321 << " from the start of ";
1322 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1323 os << "memory allocated by " << AllocNameOs.str();
1324 else
1325 os << "allocated memory";
Anna Zaks118aa752013-02-07 23:05:47 +00001326
1327 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
1328 R->markInteresting(MR->getBaseRegion());
1329 R->addRange(Range);
1330 C.emitReport(R);
1331}
1332
Anton Yartsevbb369952013-03-13 14:39:10 +00001333void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1334 SymbolRef Sym) const {
1335
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001336 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1337 !Filter.CNewDeleteChecker)
1338 return;
1339
Anton Yartsev648cb712013-04-04 23:46:29 +00001340 if (!isTrackedFamily(C, Sym))
1341 return;
1342
Anton Yartsevbb369952013-03-13 14:39:10 +00001343 if (ExplodedNode *N = C.generateSink()) {
1344 if (!BT_UseFree)
1345 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
1346
1347 BugReport *R = new BugReport(*BT_UseFree,
1348 "Use of memory after it is freed", N);
1349
1350 R->markInteresting(Sym);
1351 R->addRange(Range);
1352 R->addVisitor(new MallocBugVisitor(Sym));
1353 C.emitReport(R);
1354 }
1355}
1356
1357void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1358 bool Released, SymbolRef Sym,
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001359 SymbolRef PrevSym) const {
Anton Yartsevbb369952013-03-13 14:39:10 +00001360
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001361 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
1362 !Filter.CNewDeleteChecker)
1363 return;
1364
Anton Yartsev648cb712013-04-04 23:46:29 +00001365 if (!isTrackedFamily(C, Sym))
1366 return;
1367
Anton Yartsevbb369952013-03-13 14:39:10 +00001368 if (ExplodedNode *N = C.generateSink()) {
1369 if (!BT_DoubleFree)
1370 BT_DoubleFree.reset(new BugType("Double free", "Memory Error"));
1371
1372 BugReport *R = new BugReport(*BT_DoubleFree,
1373 (Released ? "Attempt to free released memory"
1374 : "Attempt to free non-owned memory"),
1375 N);
1376 R->addRange(Range);
Anton Yartsev3258d4b2013-03-13 17:07:32 +00001377 R->markInteresting(Sym);
1378 if (PrevSym)
1379 R->markInteresting(PrevSym);
Anton Yartsevbb369952013-03-13 14:39:10 +00001380 R->addVisitor(new MallocBugVisitor(Sym));
1381 C.emitReport(R);
1382 }
1383}
1384
Anna Zaks87cb5be2012-02-22 19:24:52 +00001385ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1386 const CallExpr *CE,
1387 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +00001388 if (CE->getNumArgs() < 2)
1389 return 0;
1390
Ted Kremenek8bef8232012-01-26 21:29:00 +00001391 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001392 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +00001393 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +00001394 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001395 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001396 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001397 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001398
Ted Kremenek846eabd2010-12-01 21:28:31 +00001399 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001400
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001401 DefinedOrUnknownSVal PtrEQ =
1402 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001403
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001404 // Get the size argument. If there is no size arg then give up.
1405 const Expr *Arg1 = CE->getArg(1);
1406 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001407 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001408
1409 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +00001410 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001411 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001412 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001413 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001414
1415 // Compare the size argument to 0.
1416 DefinedOrUnknownSVal SizeZero =
1417 svalBuilder.evalEQ(state, Arg1Val,
1418 svalBuilder.makeIntValWithPtrWidth(0, false));
1419
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001420 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1421 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
1422 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1423 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
1424 // We only assume exceptional states if they are definitely true; if the
1425 // state is under-constrained, assume regular realloc behavior.
1426 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1427 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1428
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001429 // If the ptr is NULL and the size is not 0, the call is equivalent to
1430 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001431 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +00001432 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001433 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001434 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001435 }
1436
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001437 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001438 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001439
Anna Zaks30838b92012-02-13 20:57:07 +00001440 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001441 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001442 SymbolRef FromPtr = arg0Val.getAsSymbol();
1443 SVal RetVal = state->getSVal(CE, LCtx);
1444 SymbolRef ToPtr = RetVal.getAsSymbol();
1445 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001446 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001447
Anna Zaks55dd9562012-08-24 02:28:20 +00001448 bool ReleasedAllocated = false;
1449
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001450 // If the size is 0, free the memory.
1451 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001452 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1453 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001454 // The semantics of the return value are:
1455 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001456 // to free() is returned. We just free the input pointer and do not add
1457 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001458 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001459 }
1460
1461 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001462 if (ProgramStateRef stateFree =
1463 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1464
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001465 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1466 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001467 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001468 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001469
Anna Zaks9dc298b2012-09-12 22:57:34 +00001470 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1471 if (FreesOnFail)
1472 Kind = RPIsFreeOnFailure;
1473 else if (!ReleasedAllocated)
1474 Kind = RPDoNotTrackAfterFailure;
1475
Anna Zaks55dd9562012-08-24 02:28:20 +00001476 // Record the info about the reallocated symbol so that we could properly
1477 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001478 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001479 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001480 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001481 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001482 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001483 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001484 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001485}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001486
Anna Zaks87cb5be2012-02-22 19:24:52 +00001487ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001488 if (CE->getNumArgs() < 2)
1489 return 0;
1490
Ted Kremenek8bef8232012-01-26 21:29:00 +00001491 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001492 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001493 const LocationContext *LCtx = C.getLocationContext();
1494 SVal count = state->getSVal(CE->getArg(0), LCtx);
1495 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001496 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1497 svalBuilder.getContext().getSizeType());
1498 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001499
Anna Zaks87cb5be2012-02-22 19:24:52 +00001500 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001501}
1502
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001503LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001504MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1505 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001506 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001507 // Walk the ExplodedGraph backwards and find the first node that referred to
1508 // the tracked symbol.
1509 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001510 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001511
1512 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001513 ProgramStateRef State = N->getState();
1514 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001515 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001516
1517 // Find the most recent expression bound to the symbol in the current
1518 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001519 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001520 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1521 SVal Val = State->getSVal(MR);
1522 if (Val.getAsLocSymbol() == Sym)
1523 ReferenceRegion = MR;
1524 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001525 }
1526
Anna Zaks7752d292012-02-27 23:40:55 +00001527 // Allocation node, is the last node in the current context in which the
1528 // symbol was tracked.
1529 if (N->getLocationContext() == LeakContext)
1530 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001531 N = N->pred_empty() ? NULL : *(N->pred_begin());
1532 }
1533
Anna Zaks97bfb552013-01-08 00:25:29 +00001534 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001535}
1536
Anna Zaksda046772012-02-11 21:02:40 +00001537void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1538 CheckerContext &C) const {
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001539
1540 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic &&
Jordan Rosee85deb32013-04-05 17:55:00 +00001541 !Filter.CNewDeleteLeaksChecker)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001542 return;
1543
Jordan Rosee85deb32013-04-05 17:55:00 +00001544 const RefState *RS = C.getState()->get<RegionState>(Sym);
1545 assert(RS && "cannot leak an untracked symbol");
1546 AllocationFamily Family = RS->getAllocationFamily();
1547 if (!isTrackedFamily(Family))
Anton Yartsev418780f2013-04-05 02:25:02 +00001548 return;
1549
Jordan Rosee85deb32013-04-05 17:55:00 +00001550 // Special case for new and new[]; these are controlled by a separate checker
1551 // flag so that they can be selectively disabled.
1552 if (Family == AF_CXXNew || Family == AF_CXXNewArray)
1553 if (!Filter.CNewDeleteLeaksChecker)
1554 return;
1555
Anna Zaksda046772012-02-11 21:02:40 +00001556 assert(N);
1557 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001558 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001559 // Leaks should not be reported if they are post-dominated by a sink:
1560 // (1) Sinks are higher importance bugs.
1561 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1562 // with __noreturn functions such as assert() or exit(). We choose not
1563 // to report leaks on such paths.
1564 BT_Leak->setSuppressOnSink(true);
1565 }
1566
Anna Zaksca8e36e2012-02-23 21:38:21 +00001567 // Most bug reports are cached at the location where they occurred.
1568 // With leaks, we want to unique them by the location where they were
1569 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001570 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001571 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001572 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001573 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1574
1575 ProgramPoint P = AllocNode->getLocation();
1576 const Stmt *AllocationStmt = 0;
David Blaikie7a95de62013-02-21 22:23:56 +00001577 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001578 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001579 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001580 AllocationStmt = SP->getStmt();
Anton Yartsev418780f2013-04-05 02:25:02 +00001581 if (AllocationStmt)
Anna Zaks97bfb552013-01-08 00:25:29 +00001582 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1583 C.getSourceManager(),
1584 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001585
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001586 SmallString<200> buf;
1587 llvm::raw_svector_ostream os(buf);
1588 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001589 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001590 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001591 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001592 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001593 }
1594
Anna Zaks97bfb552013-01-08 00:25:29 +00001595 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1596 LocUsedForUniqueing,
1597 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001598 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001599 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001600 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001601}
1602
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001603void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1604 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001605{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001606 if (!SymReaper.hasDeadSymbols())
1607 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001608
Ted Kremenek8bef8232012-01-26 21:29:00 +00001609 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001610 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001611 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001612
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001613 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001614 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1615 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001616 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001617 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001618 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001619 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001620
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001621 }
1622 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001623
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001624 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001625 ReallocPairsTy RP = state->get<ReallocPairs>();
1626 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001627 if (SymReaper.isDead(I->first) ||
1628 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001629 state = state->remove<ReallocPairs>(I->first);
1630 }
1631 }
1632
Anna Zaks4141e4d2012-11-13 03:18:01 +00001633 // Cleanup the FreeReturnValue Map.
1634 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1635 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1636 if (SymReaper.isDead(I->first) ||
1637 SymReaper.isDead(I->second)) {
1638 state = state->remove<FreeReturnValue>(I->first);
1639 }
1640 }
1641
Anna Zaksca8e36e2012-02-23 21:38:21 +00001642 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001643 ExplodedNode *N = C.getPredecessor();
1644 if (!Errors.empty()) {
1645 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1646 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001647 for (SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001648 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001649 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001650 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001651 }
Anna Zaks54458702012-10-29 22:51:54 +00001652
Anna Zaksca8e36e2012-02-23 21:38:21 +00001653 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001654}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001655
Anna Zaks66c40402012-02-14 21:55:24 +00001656void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001657 // We will check for double free in the post visit.
Anton Yartsev2de19ed2013-03-25 01:35:45 +00001658 if ((Filter.CMallocOptimistic || Filter.CMallocPessimistic) &&
1659 isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
1660 return;
1661
1662 if (Filter.CNewDeleteChecker &&
1663 isStandardNewDelete(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001664 return;
1665
1666 // Check use after free, when a freed pointer is passed to a call.
1667 ProgramStateRef State = C.getState();
1668 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1669 E = CE->arg_end(); I != E; ++I) {
1670 const Expr *A = *I;
1671 if (A->getType().getTypePtr()->isAnyPointerType()) {
Anton Yartsevbb369952013-03-13 14:39:10 +00001672 SymbolRef Sym = C.getSVal(A).getAsSymbol();
Anna Zaks66c40402012-02-14 21:55:24 +00001673 if (!Sym)
1674 continue;
1675 if (checkUseAfterFree(Sym, C, A))
1676 return;
1677 }
1678 }
1679}
1680
Anna Zaks91c2a112012-02-08 23:16:56 +00001681void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1682 const Expr *E = S->getRetValue();
1683 if (!E)
1684 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001685
1686 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001687 ProgramStateRef State = C.getState();
1688 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001689 SymbolRef Sym = RetVal.getAsSymbol();
1690 if (!Sym)
1691 // If we are returning a field of the allocated struct or an array element,
1692 // the callee could still free the memory.
1693 // TODO: This logic should be a part of generic symbol escape callback.
1694 if (const MemRegion *MR = RetVal.getAsRegion())
1695 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1696 if (const SymbolicRegion *BMR =
1697 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1698 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001699
Anna Zaks0860cd02012-02-11 21:44:39 +00001700 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001701 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001702 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001703}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001704
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001705// TODO: Blocks should be either inlined or should call invalidate regions
1706// upon invocation. After that's in place, special casing here will not be
1707// needed.
1708void MallocChecker::checkPostStmt(const BlockExpr *BE,
1709 CheckerContext &C) const {
1710
1711 // Scan the BlockDecRefExprs for any object the retain count checker
1712 // may be tracking.
1713 if (!BE->getBlockDecl()->hasCaptures())
1714 return;
1715
1716 ProgramStateRef state = C.getState();
1717 const BlockDataRegion *R =
1718 cast<BlockDataRegion>(state->getSVal(BE,
1719 C.getLocationContext()).getAsRegion());
1720
1721 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1722 E = R->referenced_vars_end();
1723
1724 if (I == E)
1725 return;
1726
1727 SmallVector<const MemRegion*, 10> Regions;
1728 const LocationContext *LC = C.getLocationContext();
1729 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1730
1731 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001732 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001733 if (VR->getSuperRegion() == R) {
1734 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1735 }
1736 Regions.push_back(VR);
1737 }
1738
1739 state =
1740 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1741 Regions.data() + Regions.size()).getState();
1742 C.addTransition(state);
1743}
1744
Anna Zaks14345182012-05-18 01:16:10 +00001745bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001746 assert(Sym);
1747 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001748 return (RS && RS->isReleased());
1749}
1750
1751bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1752 const Stmt *S) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001753
Anton Yartsevbb369952013-03-13 14:39:10 +00001754 if (isReleased(Sym, C)) {
1755 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1756 return true;
Anna Zaks91c2a112012-02-08 23:16:56 +00001757 }
Anton Yartsevbb369952013-03-13 14:39:10 +00001758
Anna Zaks91c2a112012-02-08 23:16:56 +00001759 return false;
1760}
1761
Zhongxing Xuc8023782010-03-10 04:58:55 +00001762// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001763void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1764 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001765 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001766 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001767 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001768}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001769
Anna Zaks4fb54872012-02-11 21:02:35 +00001770// If a symbolic region is assumed to NULL (or another constant), stop tracking
1771// it - assuming that allocation failed on this path.
1772ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1773 SVal Cond,
1774 bool Assumption) const {
1775 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001776 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001777 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001778 ConstraintManager &CMgr = state->getConstraintManager();
1779 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1780 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001781 state = state->remove<RegionState>(I.getKey());
1782 }
1783
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001784 // Realloc returns 0 when reallocation fails, which means that we should
1785 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001786 ReallocPairsTy RP = state->get<ReallocPairs>();
1787 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001788 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001789 ConstraintManager &CMgr = state->getConstraintManager();
1790 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001791 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001792 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001793
Anna Zaks9dc298b2012-09-12 22:57:34 +00001794 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1795 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1796 if (RS->isReleased()) {
1797 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001798 state = state->set<RegionState>(ReallocSym,
Anton Yartsev849c7bf2013-03-28 17:05:19 +00001799 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
Anna Zaks9dc298b2012-09-12 22:57:34 +00001800 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1801 state = state->remove<RegionState>(ReallocSym);
1802 else
1803 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001804 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001805 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001806 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001807 }
1808
Anna Zaks4fb54872012-02-11 21:02:35 +00001809 return state;
1810}
1811
Jordan Rose9fe09f32013-03-09 00:59:10 +00001812bool MallocChecker::doesNotFreeMemOrInteresting(const CallEvent *Call,
1813 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001814 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001815
1816 // For now, assume that any C++ call can free memory.
1817 // TODO: If we want to be more optimistic here, we'll need to make sure that
1818 // regions escape to C++ containers. They seem to do that even now, but for
1819 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001820 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001821 return false;
1822
Jordan Rose740d4902012-07-02 19:27:35 +00001823 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001824 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001825 // If it's not a framework call, or if it takes a callback, assume it
1826 // can free memory.
1827 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001828 return false;
1829
Jordan Rose9fe09f32013-03-09 00:59:10 +00001830 // If it's a method we know about, handle it explicitly post-call.
1831 // This should happen before the "freeWhenDone" check below.
1832 if (isKnownDeallocObjCMethodName(*Msg))
1833 return true;
Anna Zaks52a04812012-06-20 23:35:57 +00001834
Jordan Rose9fe09f32013-03-09 00:59:10 +00001835 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1836 // about, we can't be sure that the object will use free() to deallocate the
1837 // memory, so we can't model it explicitly. The best we can do is use it to
1838 // decide whether the pointer escapes.
1839 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
1840 return !*FreeWhenDone;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001841
Jordan Rose9fe09f32013-03-09 00:59:10 +00001842 // If the first selector piece ends with "NoCopy", and there is no
1843 // "freeWhenDone" parameter set to zero, we know ownership is being
1844 // transferred. Again, though, we can't be sure that the object will use
1845 // free() to deallocate the memory, so we can't model it explicitly.
1846 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose740d4902012-07-02 19:27:35 +00001847 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001848 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001849
Anna Zaks5f757682012-06-19 05:10:32 +00001850 // If the first selector starts with addPointer, insertPointer,
1851 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1852 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001853 // that the pointers get freed by following the container itself.
1854 if (FirstSlot.startswith("addPointer") ||
1855 FirstSlot.startswith("insertPointer") ||
1856 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001857 return false;
1858 }
1859
Jordan Rose740d4902012-07-02 19:27:35 +00001860 // Otherwise, assume that the method does not free memory.
1861 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001862 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001863 }
1864
Jordan Rose740d4902012-07-02 19:27:35 +00001865 // At this point the only thing left to handle is straight function calls.
1866 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1867 if (!FD)
1868 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001869
Jordan Rose740d4902012-07-02 19:27:35 +00001870 ASTContext &ASTC = State->getStateManager().getContext();
1871
1872 // If it's one of the allocation functions we can reason about, we model
1873 // its behavior explicitly.
1874 if (isMemFunction(FD, ASTC))
1875 return true;
1876
1877 // If it's not a system call, assume it frees memory.
1878 if (!Call->isInSystemHeader())
1879 return false;
1880
1881 // White list the system functions whose arguments escape.
1882 const IdentifierInfo *II = FD->getIdentifier();
1883 if (!II)
1884 return false;
1885 StringRef FName = II->getName();
1886
Jordan Rose740d4902012-07-02 19:27:35 +00001887 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001888 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001889 if (FName.endswith("NoCopy")) {
1890 // Look for the deallocator argument. We know that the memory ownership
1891 // is not transferred only if the deallocator argument is
1892 // 'kCFAllocatorNull'.
1893 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1894 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1895 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1896 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1897 if (DeallocatorName == "kCFAllocatorNull")
1898 return true;
1899 }
1900 }
1901 return false;
1902 }
1903
Jordan Rose740d4902012-07-02 19:27:35 +00001904 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001905 // 'closefn' is specified (and if that function does free memory),
1906 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001907 // Currently, we do not inspect the 'closefn' function (PR12101).
1908 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001909 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1910 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001911
1912 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1913 // these leaks might be intentional when setting the buffer for stdio.
1914 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1915 if (FName == "setbuf" || FName =="setbuffer" ||
1916 FName == "setlinebuf" || FName == "setvbuf") {
1917 if (Call->getNumArgs() >= 1) {
1918 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1919 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1920 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1921 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1922 return false;
1923 }
1924 }
1925
1926 // A bunch of other functions which either take ownership of a pointer or
1927 // wrap the result up in a struct or object, meaning it can be freed later.
1928 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1929 // but the Malloc checker cannot differentiate between them. The right way
1930 // of doing this would be to implement a pointer escapes callback.
1931 if (FName == "CGBitmapContextCreate" ||
1932 FName == "CGBitmapContextCreateWithData" ||
1933 FName == "CVPixelBufferCreateWithBytes" ||
1934 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1935 FName == "OSAtomicEnqueue") {
1936 return false;
1937 }
1938
Jordan Rose85d7e012012-07-02 19:27:51 +00001939 // Handle cases where we know a buffer's /address/ can escape.
1940 // Note that the above checks handle some special cases where we know that
1941 // even though the address escapes, it's still our responsibility to free the
1942 // buffer.
1943 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001944 return false;
1945
1946 // Otherwise, assume that the function does not free memory.
1947 // Most system calls do not free the memory.
1948 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001949}
1950
Anna Zaks41988f32013-03-28 23:15:29 +00001951static bool retTrue(const RefState *RS) {
1952 return true;
1953}
1954
1955static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
1956 return (RS->getAllocationFamily() == AF_CXXNewArray ||
1957 RS->getAllocationFamily() == AF_CXXNew);
1958}
1959
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001960ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1961 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00001962 const CallEvent *Call,
1963 PointerEscapeKind Kind) const {
Anna Zaks41988f32013-03-28 23:15:29 +00001964 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
1965}
1966
1967ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
1968 const InvalidatedSymbols &Escaped,
1969 const CallEvent *Call,
1970 PointerEscapeKind Kind) const {
1971 return checkPointerEscapeAux(State, Escaped, Call, Kind,
1972 &checkIfNewOrNewArrayFamily);
1973}
1974
1975ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
1976 const InvalidatedSymbols &Escaped,
1977 const CallEvent *Call,
1978 PointerEscapeKind Kind,
1979 bool(*CheckRefState)(const RefState*)) const {
Jordan Rose9fe09f32013-03-09 00:59:10 +00001980 // If we know that the call does not free memory, or we want to process the
1981 // call later, keep tracking the top level arguments.
Anna Zaks233e26a2013-02-07 23:05:43 +00001982 if ((Kind == PSK_DirectEscapeOnCall ||
1983 Kind == PSK_IndirectEscapeOnCall) &&
Jordan Rose9fe09f32013-03-09 00:59:10 +00001984 doesNotFreeMemOrInteresting(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001985 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00001986 }
Anna Zaks66c40402012-02-14 21:55:24 +00001987
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001988 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
Anna Zaks41988f32013-03-28 23:15:29 +00001989 E = Escaped.end();
1990 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001991 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001992
Anna Zaks5b7aa342012-06-22 02:04:31 +00001993 if (const RefState *RS = State->get<RegionState>(sym)) {
Anna Zaks41988f32013-03-28 23:15:29 +00001994 if (RS->isAllocated() && CheckRefState(RS))
Anna Zaks431e35c2012-08-09 00:42:24 +00001995 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001996 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001997 }
Anna Zaks66c40402012-02-14 21:55:24 +00001998 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001999}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00002000
Jordy Rose393f98b2012-03-18 07:43:35 +00002001static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2002 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00002003 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2004 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00002005
Jordan Rose166d5022012-11-02 01:54:06 +00002006 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00002007 I != E; ++I) {
2008 SymbolRef sym = I.getKey();
2009 if (!currMap.lookup(sym))
2010 return sym;
2011 }
2012
2013 return NULL;
2014}
2015
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002016PathDiagnosticPiece *
2017MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2018 const ExplodedNode *PrevN,
2019 BugReporterContext &BRC,
2020 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00002021 ProgramStateRef state = N->getState();
2022 ProgramStateRef statePrev = PrevN->getState();
2023
2024 const RefState *RS = state->get<RegionState>(Sym);
2025 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00002026 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002027 return 0;
2028
Anna Zaksfe571602012-02-16 22:26:07 +00002029 const Stmt *S = 0;
2030 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00002031 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00002032
2033 // Retrieve the associated statement.
2034 ProgramPoint ProgLoc = N->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00002035 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00002036 S = SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +00002037 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00002038 S = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00002039 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremeneka4a17592013-01-04 19:04:36 +00002040 // If an assumption was made on a branch, it should be caught
2041 // here by looking at the state transition.
2042 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00002043 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00002044
Anna Zaksfe571602012-02-16 22:26:07 +00002045 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002046 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002047
Jordan Rose28038f32012-07-10 22:07:42 +00002048 // FIXME: We will eventually need to handle non-statement-based events
2049 // (__attribute__((cleanup))).
2050
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002051 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00002052 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00002053 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002054 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00002055 StackHint = new StackHintGeneratorForSymbol(Sym,
2056 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00002057 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002058 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00002059 StackHint = new StackHintGeneratorForSymbol(Sym,
2060 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00002061 } else if (isRelinquished(RS, RSPrev, S)) {
2062 Msg = "Memory ownership is transfered";
2063 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00002064 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00002065 Mode = ReallocationFailed;
2066 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00002067 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00002068 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00002069
Jordy Roseb000fb52012-03-24 03:15:09 +00002070 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2071 // Is it possible to fail two reallocs WITHOUT testing in between?
2072 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2073 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00002074 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00002075 FailedReallocSymbol = sym;
2076 }
Anna Zaksfe571602012-02-16 22:26:07 +00002077 }
2078
2079 // We are in a special mode if a reallocation failed later in the path.
2080 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002081 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00002082
Jordy Roseb000fb52012-03-24 03:15:09 +00002083 // Is this is the first appearance of the reallocated symbol?
2084 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00002085 // We're at the reallocation point.
2086 Msg = "Attempt to reallocate memory";
2087 StackHint = new StackHintGeneratorForSymbol(Sym,
2088 "Returned reallocated memory");
2089 FailedReallocSymbol = NULL;
2090 Mode = Normal;
2091 }
Anna Zaksfe571602012-02-16 22:26:07 +00002092 }
2093
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002094 if (!Msg)
2095 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00002096 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002097
2098 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00002099 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002100 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00002101 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002102}
2103
Anna Zaks93c5a242012-05-02 00:05:20 +00002104void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2105 const char *NL, const char *Sep) const {
2106
2107 RegionStateTy RS = State->get<RegionState>();
2108
Ted Kremenekc37fad62013-01-03 01:30:12 +00002109 if (!RS.isEmpty()) {
2110 Out << Sep << "MallocChecker:" << NL;
2111 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2112 I.getKey()->dumpToStream(Out);
2113 Out << " : ";
2114 I.getData().dump(Out);
2115 Out << NL;
2116 }
2117 }
Anna Zaks93c5a242012-05-02 00:05:20 +00002118}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00002119
Anna Zaks231361a2012-02-08 23:16:52 +00002120#define REGISTER_CHECKER(name) \
2121void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00002122 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00002123 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00002124}
Anna Zaks231361a2012-02-08 23:16:52 +00002125
2126REGISTER_CHECKER(MallocPessimistic)
2127REGISTER_CHECKER(MallocOptimistic)
Anton Yartsev2de19ed2013-03-25 01:35:45 +00002128REGISTER_CHECKER(NewDeleteChecker)
Jordan Rosee85deb32013-04-05 17:55:00 +00002129REGISTER_CHECKER(NewDeleteLeaksChecker)
Anton Yartsev849c7bf2013-03-28 17:05:19 +00002130REGISTER_CHECKER(MismatchedDeallocatorChecker)