blob: 5a02965a786a3b53d415aa7681a02c244a421457 [file] [log] [blame]
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001//=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines malloc/free checker, which checks for potential memory
11// leaks, double free, and use-after-free problems.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000015#include "ClangSACheckers.h"
Anna Zaksf0dfc9c2012-02-17 22:35:31 +000016#include "InterCheckerAPI.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/AST/Attr.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000020#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +000021#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Jordan Rosef540c542012-07-26 21:39:41 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000024#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
25#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000026#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
Zhongxing Xu589c0f22009-11-12 08:38:56 +000027#include "llvm/ADT/ImmutableMap.h"
Benjamin Kramer00bd44d2012-02-04 12:31:12 +000028#include "llvm/ADT/STLExtras.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000029#include "llvm/ADT/SmallString.h"
Jordan Rose615a0922012-09-22 01:24:42 +000030#include "llvm/ADT/StringExtras.h"
Anna Zaks60a1fa42012-02-22 03:14:20 +000031#include <climits>
32
Zhongxing Xu589c0f22009-11-12 08:38:56 +000033using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000034using namespace ento;
Zhongxing Xu589c0f22009-11-12 08:38:56 +000035
36namespace {
37
Zhongxing Xu7fb14642009-12-11 00:55:44 +000038class RefState {
Anna Zaks050cdd72012-06-20 20:57:46 +000039 enum Kind { // Reference to allocated memory.
40 Allocated,
41 // Reference to released/freed memory.
42 Released,
Anna Zaks050cdd72012-06-20 20:57:46 +000043 // The responsibility for freeing resources has transfered from
44 // this reference. A relinquished symbol should not be freed.
Ted Kremenekdde201b2010-08-06 21:12:55 +000045 Relinquished } K;
Zhongxing Xu243fde92009-11-17 07:54:15 +000046 const Stmt *S;
47
Zhongxing Xu7fb14642009-12-11 00:55:44 +000048public:
Zhongxing Xu243fde92009-11-17 07:54:15 +000049 RefState(Kind k, const Stmt *s) : K(k), S(s) {}
50
Anna Zaks050cdd72012-06-20 20:57:46 +000051 bool isAllocated() const { return K == Allocated; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000052 bool isReleased() const { return K == Released; }
Anna Zaks050cdd72012-06-20 20:57:46 +000053 bool isRelinquished() const { return K == Relinquished; }
Anna Zaksca23eb22012-02-29 18:42:47 +000054
Anna Zaksc8bb3be2012-02-13 18:05:39 +000055 const Stmt *getStmt() const { return S; }
Zhongxing Xu243fde92009-11-17 07:54:15 +000056
57 bool operator==(const RefState &X) const {
58 return K == X.K && S == X.S;
59 }
60
Anna Zaks050cdd72012-06-20 20:57:46 +000061 static RefState getAllocated(const Stmt *s) {
62 return RefState(Allocated, s);
Zhongxing Xub94b81a2009-12-31 06:13:07 +000063 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000064 static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
Ted Kremenekdde201b2010-08-06 21:12:55 +000065 static RefState getRelinquished(const Stmt *s) {
66 return RefState(Relinquished, s);
67 }
Zhongxing Xu243fde92009-11-17 07:54:15 +000068
69 void Profile(llvm::FoldingSetNodeID &ID) const {
70 ID.AddInteger(K);
71 ID.AddPointer(S);
72 }
Ted Kremenekc37fad62013-01-03 01:30:12 +000073
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000074 void dump(raw_ostream &OS) const {
Ted Kremenekc37fad62013-01-03 01:30:12 +000075 static const char *Table[] = {
76 "Allocated",
77 "Released",
78 "Relinquished"
79 };
80 OS << Table[(unsigned) K];
81 }
82
83 LLVM_ATTRIBUTE_USED void dump() const {
84 dump(llvm::errs());
85 }
Zhongxing Xu589c0f22009-11-12 08:38:56 +000086};
87
Anna Zaks9dc298b2012-09-12 22:57:34 +000088enum ReallocPairKind {
89 RPToBeFreedAfterFailure,
90 // The symbol has been freed when reallocation failed.
91 RPIsFreeOnFailure,
92 // The symbol does not need to be freed after reallocation fails.
93 RPDoNotTrackAfterFailure
94};
95
Anna Zaks55dd9562012-08-24 02:28:20 +000096/// \class ReallocPair
97/// \brief Stores information about the symbol being reallocated by a call to
98/// 'realloc' to allow modeling failed reallocation later in the path.
Anna Zaks40add292012-02-15 00:11:25 +000099struct ReallocPair {
Anna Zaks55dd9562012-08-24 02:28:20 +0000100 // \brief The symbol which realloc reallocated.
Anna Zaks40add292012-02-15 00:11:25 +0000101 SymbolRef ReallocatedSym;
Anna Zaks9dc298b2012-09-12 22:57:34 +0000102 ReallocPairKind Kind;
Anna Zaks55dd9562012-08-24 02:28:20 +0000103
Anna Zaks9dc298b2012-09-12 22:57:34 +0000104 ReallocPair(SymbolRef S, ReallocPairKind K) :
105 ReallocatedSym(S), Kind(K) {}
Anna Zaks40add292012-02-15 00:11:25 +0000106 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks9dc298b2012-09-12 22:57:34 +0000107 ID.AddInteger(Kind);
Anna Zaks40add292012-02-15 00:11:25 +0000108 ID.AddPointer(ReallocatedSym);
109 }
110 bool operator==(const ReallocPair &X) const {
111 return ReallocatedSym == X.ReallocatedSym &&
Anna Zaks9dc298b2012-09-12 22:57:34 +0000112 Kind == X.Kind;
Anna Zaks40add292012-02-15 00:11:25 +0000113 }
114};
115
Anna Zaks97bfb552013-01-08 00:25:29 +0000116typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000117
Anna Zaksb319e022012-02-08 20:13:28 +0000118class MallocChecker : public Checker<check::DeadSymbols,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000119 check::PointerEscape,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000120 check::PreStmt<ReturnStmt>,
Anna Zaks66c40402012-02-14 21:55:24 +0000121 check::PreStmt<CallExpr>,
Anna Zaksb319e022012-02-08 20:13:28 +0000122 check::PostStmt<CallExpr>,
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000123 check::PostStmt<BlockExpr>,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000124 check::PostObjCMessage,
Ted Kremeneke3659a72012-01-04 23:48:37 +0000125 check::Location,
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000126 eval::Assume>
Ted Kremeneke3659a72012-01-04 23:48:37 +0000127{
Anna Zaksfebdc322012-02-16 22:26:12 +0000128 mutable OwningPtr<BugType> BT_DoubleFree;
129 mutable OwningPtr<BugType> BT_Leak;
130 mutable OwningPtr<BugType> BT_UseFree;
131 mutable OwningPtr<BugType> BT_BadFree;
Anna Zaks118aa752013-02-07 23:05:47 +0000132 mutable OwningPtr<BugType> BT_OffsetFree;
Anna Zaksb16ce452012-02-15 00:11:22 +0000133 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
Anna Zaks60a1fa42012-02-22 03:14:20 +0000134 *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
135
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000136public:
Anna Zaksb16ce452012-02-15 00:11:22 +0000137 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
Anna Zaks60a1fa42012-02-22 03:14:20 +0000138 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
Anna Zaks231361a2012-02-08 23:16:52 +0000139
140 /// In pessimistic mode, the checker assumes that it does not know which
141 /// functions might free the memory.
142 struct ChecksFilter {
143 DefaultBool CMallocPessimistic;
144 DefaultBool CMallocOptimistic;
145 };
146
147 ChecksFilter Filter;
148
Anna Zaks66c40402012-02-14 21:55:24 +0000149 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksb319e022012-02-08 20:13:28 +0000150 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000151 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
Anna Zaksf5aa3f52012-03-22 00:57:20 +0000152 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000153 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000154 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000155 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000156 bool Assumption) const;
Anna Zaks390909c2011-10-06 00:43:15 +0000157 void checkLocation(SVal l, bool isLoad, const Stmt *S,
158 CheckerContext &C) const;
Anna Zaksbf53dfa2012-12-20 00:38:25 +0000159
160 ProgramStateRef checkPointerEscape(ProgramStateRef State,
161 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +0000162 const CallEvent *Call,
163 PointerEscapeKind Kind) const;
Zhongxing Xub94b81a2009-12-31 06:13:07 +0000164
Anna Zaks93c5a242012-05-02 00:05:20 +0000165 void printState(raw_ostream &Out, ProgramStateRef State,
166 const char *NL, const char *Sep) const;
167
Zhongxing Xu7b760962009-11-13 07:25:27 +0000168private:
Anna Zaks66c40402012-02-14 21:55:24 +0000169 void initIdentifierInfo(ASTContext &C) const;
170
Jordan Rose9fe09f32013-03-09 00:59:10 +0000171 ///@{
Anna Zaks66c40402012-02-14 21:55:24 +0000172 /// Check if this is one of the functions which can allocate/reallocate memory
173 /// pointed to by one of its arguments.
174 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
Anna Zaks14345182012-05-18 01:16:10 +0000175 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
176 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
Jordan Rose9fe09f32013-03-09 00:59:10 +0000177 ///@}
Anna Zaks87cb5be2012-02-22 19:24:52 +0000178 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
179 const CallExpr *CE,
180 const OwnershipAttr* Att);
Ted Kremenek8bef8232012-01-26 21:29:00 +0000181 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000182 const Expr *SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000183 ProgramStateRef state) {
Ted Kremenek5eca4822012-01-06 22:09:28 +0000184 return MallocMemAux(C, CE,
185 state->getSVal(SizeEx, C.getLocationContext()),
186 Init, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000187 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000188
Ted Kremenek8bef8232012-01-26 21:29:00 +0000189 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +0000190 SVal SizeEx, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000191 ProgramStateRef state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000192
Anna Zaks87cb5be2012-02-22 19:24:52 +0000193 /// Update the RefState to reflect the new memory allocation.
194 static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
195 const CallExpr *CE,
196 ProgramStateRef state);
197
198 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
199 const OwnershipAttr* Att) const;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000200 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
Anna Zaks5b7aa342012-06-22 02:04:31 +0000201 ProgramStateRef state, unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000202 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000203 bool &ReleasedAllocated,
204 bool ReturnsNullOnFailure = false) const;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000205 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
206 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000207 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000208 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000209 bool &ReleasedAllocated,
210 bool ReturnsNullOnFailure = false) const;
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000211
Anna Zaks87cb5be2012-02-22 19:24:52 +0000212 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
213 bool FreesMemOnFailure) const;
214 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
Jordy Rose43859f62010-06-07 19:32:37 +0000215
Anna Zaks14345182012-05-18 01:16:10 +0000216 ///\brief Check if the memory associated with this symbol was released.
217 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
218
Anna Zaks91c2a112012-02-08 23:16:56 +0000219 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
220 const Stmt *S = 0) const;
221
Jordan Rose9fe09f32013-03-09 00:59:10 +0000222 /// Check if the function is known not to free memory, or if it is
223 /// "interesting" and should be modeled explicitly.
224 ///
225 /// We assume that pointers do not escape through calls to system functions
226 /// not handled by this checker.
227 bool doesNotFreeMemOrInteresting(const CallEvent *Call,
228 ProgramStateRef State) const;
Anna Zaks66c40402012-02-14 21:55:24 +0000229
Ted Kremenek9c378f72011-08-12 23:37:29 +0000230 static bool SummarizeValue(raw_ostream &os, SVal V);
231 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
Anton Yartsevbb369952013-03-13 14:39:10 +0000232 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range) const;
233 void ReportBadDealloc(CheckerContext &C, SourceRange Range,
234 const Expr *DeallocExpr, const RefState *RS) const;
Anna Zaks118aa752013-02-07 23:05:47 +0000235 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range)const;
Anton Yartsevbb369952013-03-13 14:39:10 +0000236 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
237 SymbolRef Sym) const;
238 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
239 SymbolRef Sym, bool Interesting) const;
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000240
Anna Zaksca8e36e2012-02-23 21:38:21 +0000241 /// Find the location of the allocation for Sym on the path leading to the
242 /// exploded node N.
Anna Zaks3d7c44e2012-03-21 19:45:08 +0000243 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
244 CheckerContext &C) const;
Anna Zaksca8e36e2012-02-23 21:38:21 +0000245
Anna Zaksda046772012-02-11 21:02:40 +0000246 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
247
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000248 /// The bug visitor which allows us to print extra diagnostics along the
249 /// BugReport path. For example, showing the allocation site of the leaked
250 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000251 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000252 protected:
Anna Zaksfe571602012-02-16 22:26:07 +0000253 enum NotificationMode {
254 Normal,
Anna Zaksfe571602012-02-16 22:26:07 +0000255 ReallocationFailed
256 };
257
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000258 // The allocated region symbol tracked by the main analysis.
259 SymbolRef Sym;
260
Anna Zaks88feba02012-05-10 01:37:40 +0000261 // The mode we are in, i.e. what kind of diagnostics will be emitted.
262 NotificationMode Mode;
Jordy Roseb000fb52012-03-24 03:15:09 +0000263
Anna Zaks88feba02012-05-10 01:37:40 +0000264 // A symbol from when the primary region should have been reallocated.
265 SymbolRef FailedReallocSymbol;
Jordy Roseb000fb52012-03-24 03:15:09 +0000266
Anna Zaks88feba02012-05-10 01:37:40 +0000267 bool IsLeak;
268
269 public:
270 MallocBugVisitor(SymbolRef S, bool isLeak = false)
271 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
Jordy Roseb000fb52012-03-24 03:15:09 +0000272
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000273 virtual ~MallocBugVisitor() {}
274
275 void Profile(llvm::FoldingSetNodeID &ID) const {
276 static int X = 0;
277 ID.AddPointer(&X);
278 ID.AddPointer(Sym);
279 }
280
Anna Zaksfe571602012-02-16 22:26:07 +0000281 inline bool isAllocated(const RefState *S, const RefState *SPrev,
282 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000283 // Did not track -> allocated. Other state (released) -> allocated.
Anna Zaksfe571602012-02-16 22:26:07 +0000284 return (Stmt && isa<CallExpr>(Stmt) &&
285 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000286 }
287
Anna Zaksfe571602012-02-16 22:26:07 +0000288 inline bool isReleased(const RefState *S, const RefState *SPrev,
289 const Stmt *Stmt) {
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000290 // Did not track -> released. Other state (allocated) -> released.
Anna Zaksfe571602012-02-16 22:26:07 +0000291 return (Stmt && isa<CallExpr>(Stmt) &&
292 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
293 }
294
Anna Zaks5b7aa342012-06-22 02:04:31 +0000295 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
296 const Stmt *Stmt) {
297 // Did not track -> relinquished. Other state (allocated) -> relinquished.
298 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
299 isa<ObjCPropertyRefExpr>(Stmt)) &&
300 (S && S->isRelinquished()) &&
301 (!SPrev || !SPrev->isRelinquished()));
302 }
303
Anna Zaksfe571602012-02-16 22:26:07 +0000304 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
305 const Stmt *Stmt) {
306 // If the expression is not a call, and the state change is
307 // released -> allocated, it must be the realloc return value
308 // check. If we have to handle more cases here, it might be cleaner just
309 // to track this extra bit in the state itself.
310 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
311 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000312 }
313
314 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
315 const ExplodedNode *PrevN,
316 BugReporterContext &BRC,
317 BugReport &BR);
Anna Zaks88feba02012-05-10 01:37:40 +0000318
319 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
320 const ExplodedNode *EndPathNode,
321 BugReport &BR) {
322 if (!IsLeak)
323 return 0;
324
325 PathDiagnosticLocation L =
326 PathDiagnosticLocation::createEndOfPath(EndPathNode,
327 BRC.getSourceManager());
328 // Do not add the statement itself as a range in case of leak.
329 return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
330 }
331
Anna Zaks56a938f2012-03-16 23:24:20 +0000332 private:
333 class StackHintGeneratorForReallocationFailed
334 : public StackHintGeneratorForSymbol {
335 public:
336 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
337 : StackHintGeneratorForSymbol(S, M) {}
338
339 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
Jordan Rose615a0922012-09-22 01:24:42 +0000340 // Printed parameters start at 1, not 0.
341 ++ArgIndex;
342
Anna Zaks56a938f2012-03-16 23:24:20 +0000343 SmallString<200> buf;
344 llvm::raw_svector_ostream os(buf);
345
Jordan Rose615a0922012-09-22 01:24:42 +0000346 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
347 << " parameter failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000348
349 return os.str();
350 }
351
352 virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
Anna Zaksfbd58742012-03-16 23:44:28 +0000353 return "Reallocation of returned value failed";
Anna Zaks56a938f2012-03-16 23:24:20 +0000354 }
355 };
Anna Zaksff3b9fd2012-02-09 06:25:51 +0000356 };
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000357};
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +0000358} // end anonymous namespace
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000359
Jordan Rose166d5022012-11-02 01:54:06 +0000360REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
361REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000362
Anna Zaks4141e4d2012-11-13 03:18:01 +0000363// A map from the freed symbol to the symbol representing the return value of
364// the free function.
365REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
366
Anna Zaks4fb54872012-02-11 21:02:35 +0000367namespace {
368class StopTrackingCallback : public SymbolVisitor {
369 ProgramStateRef state;
370public:
371 StopTrackingCallback(ProgramStateRef st) : state(st) {}
372 ProgramStateRef getState() const { return state; }
373
374 bool VisitSymbol(SymbolRef sym) {
375 state = state->remove<RegionState>(sym);
376 return true;
377 }
378};
379} // end anonymous namespace
380
Anna Zaks66c40402012-02-14 21:55:24 +0000381void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
Anna Zaksa38cb2c2012-05-18 22:47:40 +0000382 if (II_malloc)
383 return;
384 II_malloc = &Ctx.Idents.get("malloc");
385 II_free = &Ctx.Idents.get("free");
386 II_realloc = &Ctx.Idents.get("realloc");
387 II_reallocf = &Ctx.Idents.get("reallocf");
388 II_calloc = &Ctx.Idents.get("calloc");
389 II_valloc = &Ctx.Idents.get("valloc");
390 II_strdup = &Ctx.Idents.get("strdup");
391 II_strndup = &Ctx.Idents.get("strndup");
Anna Zaksb319e022012-02-08 20:13:28 +0000392}
393
Anna Zaks66c40402012-02-14 21:55:24 +0000394bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +0000395 if (isFreeFunction(FD, C))
396 return true;
397
398 if (isAllocationFunction(FD, C))
399 return true;
400
401 return false;
402}
403
404bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
405 ASTContext &C) const {
Anna Zaks1d6cc6a2012-02-15 02:12:00 +0000406 if (!FD)
407 return false;
Anna Zaks14345182012-05-18 01:16:10 +0000408
Jordan Rose5ef6e942012-07-10 23:13:01 +0000409 if (FD->getKind() == Decl::Function) {
410 IdentifierInfo *FunI = FD->getIdentifier();
411 initIdentifierInfo(C);
Anna Zaks66c40402012-02-14 21:55:24 +0000412
Jordan Rose5ef6e942012-07-10 23:13:01 +0000413 if (FunI == II_malloc || FunI == II_realloc ||
414 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
415 FunI == II_strdup || FunI == II_strndup)
416 return true;
417 }
Anna Zaks66c40402012-02-14 21:55:24 +0000418
Anna Zaks14345182012-05-18 01:16:10 +0000419 if (Filter.CMallocOptimistic && FD->hasAttrs())
420 for (specific_attr_iterator<OwnershipAttr>
421 i = FD->specific_attr_begin<OwnershipAttr>(),
422 e = FD->specific_attr_end<OwnershipAttr>();
423 i != e; ++i)
424 if ((*i)->getOwnKind() == OwnershipAttr::Returns)
425 return true;
426 return false;
427}
428
429bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
430 if (!FD)
431 return false;
432
Jordan Rose5ef6e942012-07-10 23:13:01 +0000433 if (FD->getKind() == Decl::Function) {
434 IdentifierInfo *FunI = FD->getIdentifier();
435 initIdentifierInfo(C);
Anna Zaks14345182012-05-18 01:16:10 +0000436
Jordan Rose5ef6e942012-07-10 23:13:01 +0000437 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
438 return true;
439 }
Anna Zaks66c40402012-02-14 21:55:24 +0000440
Anna Zaks14345182012-05-18 01:16:10 +0000441 if (Filter.CMallocOptimistic && FD->hasAttrs())
442 for (specific_attr_iterator<OwnershipAttr>
443 i = FD->specific_attr_begin<OwnershipAttr>(),
444 e = FD->specific_attr_end<OwnershipAttr>();
445 i != e; ++i)
446 if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
447 (*i)->getOwnKind() == OwnershipAttr::Holds)
448 return true;
Anna Zaks66c40402012-02-14 21:55:24 +0000449 return false;
450}
451
Anna Zaksb319e022012-02-08 20:13:28 +0000452void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
Jordan Rosec20c7272012-09-20 01:55:32 +0000453 if (C.wasInlined)
454 return;
455
Anna Zaksb319e022012-02-08 20:13:28 +0000456 const FunctionDecl *FD = C.getCalleeDecl(CE);
457 if (!FD)
458 return;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000459
Anna Zaks87cb5be2012-02-22 19:24:52 +0000460 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000461 bool ReleasedAllocatedMemory = false;
Jordan Rose5ef6e942012-07-10 23:13:01 +0000462
463 if (FD->getKind() == Decl::Function) {
464 initIdentifierInfo(C.getASTContext());
465 IdentifierInfo *FunI = FD->getIdentifier();
466
467 if (FunI == II_malloc || FunI == II_valloc) {
468 if (CE->getNumArgs() < 1)
469 return;
470 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
471 } else if (FunI == II_realloc) {
472 State = ReallocMem(C, CE, false);
473 } else if (FunI == II_reallocf) {
474 State = ReallocMem(C, CE, true);
475 } else if (FunI == II_calloc) {
476 State = CallocMem(C, CE);
477 } else if (FunI == II_free) {
Anna Zaks55dd9562012-08-24 02:28:20 +0000478 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
Jordan Rose5ef6e942012-07-10 23:13:01 +0000479 } else if (FunI == II_strdup) {
480 State = MallocUpdateRefState(C, CE, State);
481 } else if (FunI == II_strndup) {
482 State = MallocUpdateRefState(C, CE, State);
483 }
484 }
485
486 if (Filter.CMallocOptimistic) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000487 // Check all the attributes, if there are any.
488 // There can be multiple of these attributes.
489 if (FD->hasAttrs())
490 for (specific_attr_iterator<OwnershipAttr>
491 i = FD->specific_attr_begin<OwnershipAttr>(),
492 e = FD->specific_attr_end<OwnershipAttr>();
493 i != e; ++i) {
494 switch ((*i)->getOwnKind()) {
495 case OwnershipAttr::Returns:
496 State = MallocMemReturnsAttr(C, CE, *i);
497 break;
498 case OwnershipAttr::Takes:
499 case OwnershipAttr::Holds:
500 State = FreeMemAttr(C, CE, *i);
501 break;
502 }
503 }
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000504 }
Anna Zaks60a1fa42012-02-22 03:14:20 +0000505 C.addTransition(State);
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000506}
507
Jordan Rose9fe09f32013-03-09 00:59:10 +0000508static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
509 // If the first selector piece is one of the names below, assume that the
510 // object takes ownership of the memory, promising to eventually deallocate it
511 // with free().
512 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
513 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
514 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
515 if (FirstSlot == "dataWithBytesNoCopy" ||
516 FirstSlot == "initWithBytesNoCopy" ||
517 FirstSlot == "initWithCharactersNoCopy")
518 return true;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000519
520 return false;
521}
522
Jordan Rose9fe09f32013-03-09 00:59:10 +0000523static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
524 Selector S = Call.getSelector();
525
526 // FIXME: We should not rely on fully-constrained symbols being folded.
527 for (unsigned i = 1; i < S.getNumArgs(); ++i)
528 if (S.getNameForSlot(i).equals("freeWhenDone"))
529 return !Call.getArgSVal(i).isZeroConstant();
530
531 return None;
532}
533
Anna Zaks4141e4d2012-11-13 03:18:01 +0000534void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
535 CheckerContext &C) const {
Anna Zaksc2cca232012-12-11 00:17:53 +0000536 if (C.wasInlined)
537 return;
538
Jordan Rose9fe09f32013-03-09 00:59:10 +0000539 if (!isKnownDeallocObjCMethodName(Call))
540 return;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000541
Jordan Rose9fe09f32013-03-09 00:59:10 +0000542 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
543 if (!*FreeWhenDone)
544 return;
545
546 bool ReleasedAllocatedMemory;
547 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
548 Call.getOriginExpr(), C.getState(),
549 /*Hold=*/true, ReleasedAllocatedMemory,
550 /*RetNullOnFailure=*/true);
551
552 C.addTransition(State);
Anna Zaks5b7aa342012-06-22 02:04:31 +0000553}
554
Anna Zaks87cb5be2012-02-22 19:24:52 +0000555ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
556 const CallExpr *CE,
557 const OwnershipAttr* Att) {
Sean Huntcf807c42010-08-18 23:23:40 +0000558 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000559 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000560
Sean Huntcf807c42010-08-18 23:23:40 +0000561 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000562 if (I != E) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000563 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000564 }
Anna Zaks87cb5be2012-02-22 19:24:52 +0000565 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000566}
567
Anna Zaksb319e022012-02-08 20:13:28 +0000568ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000569 const CallExpr *CE,
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000570 SVal Size, SVal Init,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000571 ProgramStateRef state) {
Anna Zakse17fdb22012-06-07 03:57:32 +0000572
573 // Bind the return value to the symbolic value from the heap region.
574 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
575 // side effects other than what we model here.
Ted Kremenek66c486f2012-08-22 06:26:15 +0000576 unsigned Count = C.blockCount();
Anna Zakse17fdb22012-06-07 03:57:32 +0000577 SValBuilder &svalBuilder = C.getSValBuilder();
578 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
David Blaikie5251abe2013-02-20 05:52:05 +0000579 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
580 .castAs<DefinedSVal>();
Anna Zakse17fdb22012-06-07 03:57:32 +0000581 state = state->BindExpr(CE, C.getLocationContext(), RetVal);
Zhongxing Xua49c6b72009-12-11 03:09:01 +0000582
Anna Zaksb16ce452012-02-15 00:11:22 +0000583 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000584 if (!RetVal.getAs<Loc>())
Anna Zaksb16ce452012-02-15 00:11:22 +0000585 return 0;
586
Jordy Rose32f26562010-07-04 00:00:41 +0000587 // Fill the region with the initialization value.
Anna Zakse17fdb22012-06-07 03:57:32 +0000588 state = state->bindDefault(RetVal, Init);
Zhongxing Xua5ce9662010-06-01 03:01:33 +0000589
Jordy Rose32f26562010-07-04 00:00:41 +0000590 // Set the region's extent equal to the Size parameter.
Anna Zakse9ef5622012-02-10 01:11:00 +0000591 const SymbolicRegion *R =
Anna Zakse17fdb22012-06-07 03:57:32 +0000592 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
Anna Zaks60a1fa42012-02-22 03:14:20 +0000593 if (!R)
Anna Zakse9ef5622012-02-10 01:11:00 +0000594 return 0;
David Blaikiedc84cd52013-02-20 22:23:23 +0000595 if (Optional<DefinedOrUnknownSVal> DefinedSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000596 Size.getAs<DefinedOrUnknownSVal>()) {
Anna Zaks87cb5be2012-02-22 19:24:52 +0000597 SValBuilder &svalBuilder = C.getSValBuilder();
Anna Zaks60a1fa42012-02-22 03:14:20 +0000598 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
Anna Zaks60a1fa42012-02-22 03:14:20 +0000599 DefinedOrUnknownSVal extentMatchesSize =
David Blaikie5251abe2013-02-20 05:52:05 +0000600 svalBuilder.evalEQ(state, Extent, *DefinedSize);
Anna Zakse9ef5622012-02-10 01:11:00 +0000601
Anna Zaks60a1fa42012-02-22 03:14:20 +0000602 state = state->assume(extentMatchesSize, true);
603 assert(state);
604 }
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000605
Anna Zaks87cb5be2012-02-22 19:24:52 +0000606 return MallocUpdateRefState(C, CE, state);
607}
608
609ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
610 const CallExpr *CE,
611 ProgramStateRef state) {
612 // Get the return value.
613 SVal retVal = state->getSVal(CE, C.getLocationContext());
614
615 // We expect the malloc functions to return a pointer.
David Blaikie5251abe2013-02-20 05:52:05 +0000616 if (!retVal.getAs<Loc>())
Anna Zaks87cb5be2012-02-22 19:24:52 +0000617 return 0;
618
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000619 SymbolRef Sym = retVal.getAsLocSymbol();
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000620 assert(Sym);
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000621
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000622 // Set the symbol's state to Allocated.
Anna Zaks050cdd72012-06-20 20:57:46 +0000623 return state->set<RegionState>(Sym, RefState::getAllocated(CE));
Anna Zaks87cb5be2012-02-22 19:24:52 +0000624
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000625}
626
Anna Zaks87cb5be2012-02-22 19:24:52 +0000627ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
628 const CallExpr *CE,
629 const OwnershipAttr* Att) const {
Sean Huntcf807c42010-08-18 23:23:40 +0000630 if (Att->getModule() != "malloc")
Anna Zaks87cb5be2012-02-22 19:24:52 +0000631 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000632
Anna Zaksb3d72752012-03-01 22:06:06 +0000633 ProgramStateRef State = C.getState();
Anna Zaks55dd9562012-08-24 02:28:20 +0000634 bool ReleasedAllocated = false;
Anna Zaksb3d72752012-03-01 22:06:06 +0000635
Sean Huntcf807c42010-08-18 23:23:40 +0000636 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
637 I != E; ++I) {
Anna Zaksb3d72752012-03-01 22:06:06 +0000638 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
Anna Zaks55dd9562012-08-24 02:28:20 +0000639 Att->getOwnKind() == OwnershipAttr::Holds,
640 ReleasedAllocated);
Anna Zaksb3d72752012-03-01 22:06:06 +0000641 if (StateI)
642 State = StateI;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000643 }
Anna Zaksb3d72752012-03-01 22:06:06 +0000644 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000645}
646
Ted Kremenek8bef8232012-01-26 21:29:00 +0000647ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
Anna Zakse9ef5622012-02-10 01:11:00 +0000648 const CallExpr *CE,
649 ProgramStateRef state,
650 unsigned Num,
Anna Zaks55dd9562012-08-24 02:28:20 +0000651 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000652 bool &ReleasedAllocated,
653 bool ReturnsNullOnFailure) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000654 if (CE->getNumArgs() < (Num + 1))
655 return 0;
656
Anna Zaks4141e4d2012-11-13 03:18:01 +0000657 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
658 ReleasedAllocated, ReturnsNullOnFailure);
659}
660
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000661/// Checks if the previous call to free on the given symbol failed - if free
662/// failed, returns true. Also, returns the corresponding return value symbol.
Benjamin Kramer4d9f4e52012-11-22 15:02:44 +0000663static bool didPreviousFreeFail(ProgramStateRef State,
664 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000665 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000666 if (Ret) {
667 assert(*Ret && "We should not store the null return symbol");
668 ConstraintManager &CMgr = State->getConstraintManager();
669 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000670 RetStatusSymbol = *Ret;
671 return FreeFailed.isConstrainedTrue();
Anna Zaks4141e4d2012-11-13 03:18:01 +0000672 }
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000673 return false;
Anna Zaks5b7aa342012-06-22 02:04:31 +0000674}
675
676ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
677 const Expr *ArgExpr,
678 const Expr *ParentExpr,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000679 ProgramStateRef State,
Anna Zaks55dd9562012-08-24 02:28:20 +0000680 bool Hold,
Anna Zaks4141e4d2012-11-13 03:18:01 +0000681 bool &ReleasedAllocated,
682 bool ReturnsNullOnFailure) const {
Anna Zaks5b7aa342012-06-22 02:04:31 +0000683
Anna Zaks4141e4d2012-11-13 03:18:01 +0000684 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
David Blaikie5251abe2013-02-20 05:52:05 +0000685 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
Anna Zakse9ef5622012-02-10 01:11:00 +0000686 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +0000687 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000688
689 // Check for null dereferences.
David Blaikie5251abe2013-02-20 05:52:05 +0000690 if (!location.getAs<Loc>())
Anna Zaksb319e022012-02-08 20:13:28 +0000691 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000692
Anna Zaksb276bd92012-02-14 00:26:13 +0000693 // The explicit NULL case, no operation is performed.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000694 ProgramStateRef notNullState, nullState;
Anna Zaks4141e4d2012-11-13 03:18:01 +0000695 llvm::tie(notNullState, nullState) = State->assume(location);
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000696 if (nullState && !notNullState)
Anna Zaksb319e022012-02-08 20:13:28 +0000697 return 0;
Ted Kremenekdd0e4902010-07-31 01:52:11 +0000698
Jordy Rose43859f62010-06-07 19:32:37 +0000699 // Unknown values could easily be okay
700 // Undefined values are handled elsewhere
701 if (ArgVal.isUnknownOrUndef())
Anna Zaksb319e022012-02-08 20:13:28 +0000702 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000703
Jordy Rose43859f62010-06-07 19:32:37 +0000704 const MemRegion *R = ArgVal.getAsRegion();
705
706 // Nonlocs can't be freed, of course.
707 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
708 if (!R) {
709 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000710 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000711 }
712
713 R = R->StripCasts();
714
715 // Blocks might show up as heap data, but should not be free()d
716 if (isa<BlockDataRegion>(R)) {
717 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000718 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000719 }
720
721 const MemSpaceRegion *MS = R->getMemorySpace();
722
Anton Yartsevbb369952013-03-13 14:39:10 +0000723 // Parameters, locals, statics, globals, and memory returned by alloca()
724 // shouldn't be freed.
Jordy Rose43859f62010-06-07 19:32:37 +0000725 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
726 // FIXME: at the time this code was written, malloc() regions were
727 // represented by conjured symbols, which are all in UnknownSpaceRegion.
728 // This means that there isn't actually anything from HeapSpaceRegion
729 // that should be freed, even though we allow it here.
730 // Of course, free() can work on memory allocated outside the current
731 // function, so UnknownSpaceRegion is always a possibility.
732 // False negatives are better than false positives.
733
734 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
Anna Zaksb319e022012-02-08 20:13:28 +0000735 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000736 }
Anna Zaks118aa752013-02-07 23:05:47 +0000737
738 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
Jordy Rose43859f62010-06-07 19:32:37 +0000739 // Various cases could lead to non-symbol values here.
740 // For now, ignore them.
Anna Zaks118aa752013-02-07 23:05:47 +0000741 if (!SrBase)
Anna Zaksb319e022012-02-08 20:13:28 +0000742 return 0;
Jordy Rose43859f62010-06-07 19:32:37 +0000743
Anna Zaks118aa752013-02-07 23:05:47 +0000744 SymbolRef SymBase = SrBase->getSymbol();
745 const RefState *RsBase = State->get<RegionState>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000746 SymbolRef PreviousRetStatusSymbol = 0;
Zhongxing Xu7e3cda92010-01-18 03:27:34 +0000747
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000748 // Check double free.
Anna Zaks118aa752013-02-07 23:05:47 +0000749 if (RsBase &&
750 (RsBase->isReleased() || RsBase->isRelinquished()) &&
751 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
Anton Yartsevbb369952013-03-13 14:39:10 +0000752 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
753 SymBase, PreviousRetStatusSymbol);
Anna Zaksb319e022012-02-08 20:13:28 +0000754 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000755 }
756
Anna Zaks118aa752013-02-07 23:05:47 +0000757 // Check if the memory location being freed is the actual location
758 // allocated, or an offset.
759 RegionOffset Offset = R->getAsOffset();
760 if (RsBase && RsBase->isAllocated() &&
761 Offset.isValid() &&
762 !Offset.hasSymbolicOffset() &&
763 Offset.getOffset() != 0) {
764 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange());
765 return 0;
766 }
767
768 ReleasedAllocated = (RsBase != 0);
Anna Zaks55dd9562012-08-24 02:28:20 +0000769
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000770 // Clean out the info on previous call to free return info.
Anna Zaks118aa752013-02-07 23:05:47 +0000771 State = State->remove<FreeReturnValue>(SymBase);
Anna Zaks2ccecfa2012-11-13 19:47:40 +0000772
Anna Zaks4141e4d2012-11-13 03:18:01 +0000773 // Keep track of the return value. If it is NULL, we will know that free
774 // failed.
775 if (ReturnsNullOnFailure) {
776 SVal RetVal = C.getSVal(ParentExpr);
777 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
778 if (RetStatusSymbol) {
Anna Zaks118aa752013-02-07 23:05:47 +0000779 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
780 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
Anna Zaks4141e4d2012-11-13 03:18:01 +0000781 }
782 }
783
Zhongxing Xu589c0f22009-11-12 08:38:56 +0000784 // Normal free.
Anna Zaks118aa752013-02-07 23:05:47 +0000785 if (Hold) {
786 return State->set<RegionState>(SymBase,
787 RefState::getRelinquished(ParentExpr));
788 }
789 return State->set<RegionState>(SymBase, RefState::getReleased(ParentExpr));
Zhongxing Xud9c84c82009-12-12 12:29:38 +0000790}
791
Ted Kremenek9c378f72011-08-12 23:37:29 +0000792bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000793 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +0000794 os << "an integer (" << IntVal->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +0000795 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
Jordy Rose43859f62010-06-07 19:32:37 +0000796 os << "a constant address (" << ConstAddr->getValue() << ")";
David Blaikiedc84cd52013-02-20 22:23:23 +0000797 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
Chris Lattner68106302011-02-17 05:38:27 +0000798 os << "the address of the label '" << Label->getLabel()->getName() << "'";
Jordy Rose43859f62010-06-07 19:32:37 +0000799 else
800 return false;
801
802 return true;
803}
804
Ted Kremenek9c378f72011-08-12 23:37:29 +0000805bool MallocChecker::SummarizeRegion(raw_ostream &os,
Jordy Rose43859f62010-06-07 19:32:37 +0000806 const MemRegion *MR) {
807 switch (MR->getKind()) {
808 case MemRegion::FunctionTextRegionKind: {
Anna Zaks5fc1d0c2012-09-17 19:13:56 +0000809 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
Jordy Rose43859f62010-06-07 19:32:37 +0000810 if (FD)
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000811 os << "the address of the function '" << *FD << '\'';
Jordy Rose43859f62010-06-07 19:32:37 +0000812 else
813 os << "the address of a function";
814 return true;
815 }
816 case MemRegion::BlockTextRegionKind:
817 os << "block text";
818 return true;
819 case MemRegion::BlockDataRegionKind:
820 // FIXME: where the block came from?
821 os << "a block";
822 return true;
823 default: {
824 const MemSpaceRegion *MS = MR->getMemorySpace();
825
Anna Zakseb31a762012-01-04 23:54:01 +0000826 if (isa<StackLocalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000827 const VarRegion *VR = dyn_cast<VarRegion>(MR);
828 const VarDecl *VD;
829 if (VR)
830 VD = VR->getDecl();
831 else
832 VD = NULL;
833
834 if (VD)
835 os << "the address of the local variable '" << VD->getName() << "'";
836 else
837 os << "the address of a local stack variable";
838 return true;
839 }
Anna Zakseb31a762012-01-04 23:54:01 +0000840
841 if (isa<StackArgumentsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000842 const VarRegion *VR = dyn_cast<VarRegion>(MR);
843 const VarDecl *VD;
844 if (VR)
845 VD = VR->getDecl();
846 else
847 VD = NULL;
848
849 if (VD)
850 os << "the address of the parameter '" << VD->getName() << "'";
851 else
852 os << "the address of a parameter";
853 return true;
854 }
Anna Zakseb31a762012-01-04 23:54:01 +0000855
856 if (isa<GlobalsSpaceRegion>(MS)) {
Jordy Rose43859f62010-06-07 19:32:37 +0000857 const VarRegion *VR = dyn_cast<VarRegion>(MR);
858 const VarDecl *VD;
859 if (VR)
860 VD = VR->getDecl();
861 else
862 VD = NULL;
863
864 if (VD) {
865 if (VD->isStaticLocal())
866 os << "the address of the static variable '" << VD->getName() << "'";
867 else
868 os << "the address of the global variable '" << VD->getName() << "'";
869 } else
870 os << "the address of a global variable";
871 return true;
872 }
Anna Zakseb31a762012-01-04 23:54:01 +0000873
874 return false;
Jordy Rose43859f62010-06-07 19:32:37 +0000875 }
876 }
877}
878
879void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
Anton Yartsevbb369952013-03-13 14:39:10 +0000880 SourceRange Range) const {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000881 if (ExplodedNode *N = C.generateSink()) {
Jordy Rose43859f62010-06-07 19:32:37 +0000882 if (!BT_BadFree)
Anna Zaksfebdc322012-02-16 22:26:12 +0000883 BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
Jordy Rose43859f62010-06-07 19:32:37 +0000884
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000885 SmallString<100> buf;
Jordy Rose43859f62010-06-07 19:32:37 +0000886 llvm::raw_svector_ostream os(buf);
887
888 const MemRegion *MR = ArgVal.getAsRegion();
889 if (MR) {
890 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
891 MR = ER->getSuperRegion();
892
893 // Special case for alloca()
894 if (isa<AllocaRegion>(MR))
895 os << "Argument to free() was allocated by alloca(), not malloc()";
896 else {
897 os << "Argument to free() is ";
898 if (SummarizeRegion(os, MR))
899 os << ", which is not memory allocated by malloc()";
900 else
901 os << "not memory allocated by malloc()";
902 }
903 } else {
904 os << "Argument to free() is ";
905 if (SummarizeValue(os, ArgVal))
906 os << ", which is not memory allocated by malloc()";
907 else
908 os << "not memory allocated by malloc()";
909 }
910
Anna Zakse172e8b2011-08-17 23:00:25 +0000911 BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
Ted Kremenek76aadc32012-03-09 01:13:14 +0000912 R->markInteresting(MR);
Anton Yartsevbb369952013-03-13 14:39:10 +0000913 R->addRange(Range);
Jordan Rose785950e2012-11-02 01:53:40 +0000914 C.emitReport(R);
Jordy Rose43859f62010-06-07 19:32:37 +0000915 }
916}
917
Anna Zaks118aa752013-02-07 23:05:47 +0000918void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
919 SourceRange Range) const {
920 ExplodedNode *N = C.generateSink();
921 if (N == NULL)
922 return;
923
924 if (!BT_OffsetFree)
925 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
926
927 SmallString<100> buf;
928 llvm::raw_svector_ostream os(buf);
929
930 const MemRegion *MR = ArgVal.getAsRegion();
931 assert(MR && "Only MemRegion based symbols can have offset free errors");
932
933 RegionOffset Offset = MR->getAsOffset();
934 assert((Offset.isValid() &&
935 !Offset.hasSymbolicOffset() &&
936 Offset.getOffset() != 0) &&
937 "Only symbols with a valid offset can have offset free errors");
938
939 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
940
941 os << "Argument to free() is offset by "
942 << offsetBytes
943 << " "
944 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
945 << " from the start of memory allocated by malloc()";
946
947 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
948 R->markInteresting(MR->getBaseRegion());
949 R->addRange(Range);
950 C.emitReport(R);
951}
952
Anton Yartsevbb369952013-03-13 14:39:10 +0000953void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
954 SymbolRef Sym) const {
955
956 if (ExplodedNode *N = C.generateSink()) {
957 if (!BT_UseFree)
958 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
959
960 BugReport *R = new BugReport(*BT_UseFree,
961 "Use of memory after it is freed", N);
962
963 R->markInteresting(Sym);
964 R->addRange(Range);
965 R->addVisitor(new MallocBugVisitor(Sym));
966 C.emitReport(R);
967 }
968}
969
970void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
971 bool Released, SymbolRef Sym,
972 bool Interesting) const {
973
974 if (ExplodedNode *N = C.generateSink()) {
975 if (!BT_DoubleFree)
976 BT_DoubleFree.reset(new BugType("Double free", "Memory Error"));
977
978 BugReport *R = new BugReport(*BT_DoubleFree,
979 (Released ? "Attempt to free released memory"
980 : "Attempt to free non-owned memory"),
981 N);
982 R->addRange(Range);
983 if (Interesting)
984 R->markInteresting(Sym);
985 R->addVisitor(new MallocBugVisitor(Sym));
986 C.emitReport(R);
987 }
988}
989
Anna Zaks87cb5be2012-02-22 19:24:52 +0000990ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
991 const CallExpr *CE,
992 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000993 if (CE->getNumArgs() < 2)
994 return 0;
995
Ted Kremenek8bef8232012-01-26 21:29:00 +0000996 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000997 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000998 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +0000999 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001000 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001001 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001002 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001003
Ted Kremenek846eabd2010-12-01 21:28:31 +00001004 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001005
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001006 DefinedOrUnknownSVal PtrEQ =
1007 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001008
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001009 // Get the size argument. If there is no size arg then give up.
1010 const Expr *Arg1 = CE->getArg(1);
1011 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001012 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001013
1014 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +00001015 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001016 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001017 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001018 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001019
1020 // Compare the size argument to 0.
1021 DefinedOrUnknownSVal SizeZero =
1022 svalBuilder.evalEQ(state, Arg1Val,
1023 svalBuilder.makeIntValWithPtrWidth(0, false));
1024
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001025 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1026 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
1027 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1028 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
1029 // We only assume exceptional states if they are definitely true; if the
1030 // state is under-constrained, assume regular realloc behavior.
1031 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1032 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1033
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001034 // If the ptr is NULL and the size is not 0, the call is equivalent to
1035 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001036 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +00001037 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001038 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001039 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001040 }
1041
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001042 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001043 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001044
Anna Zaks30838b92012-02-13 20:57:07 +00001045 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001046 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001047 SymbolRef FromPtr = arg0Val.getAsSymbol();
1048 SVal RetVal = state->getSVal(CE, LCtx);
1049 SymbolRef ToPtr = RetVal.getAsSymbol();
1050 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001051 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001052
Anna Zaks55dd9562012-08-24 02:28:20 +00001053 bool ReleasedAllocated = false;
1054
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001055 // If the size is 0, free the memory.
1056 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001057 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1058 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001059 // The semantics of the return value are:
1060 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001061 // to free() is returned. We just free the input pointer and do not add
1062 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001063 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001064 }
1065
1066 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001067 if (ProgramStateRef stateFree =
1068 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1069
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001070 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1071 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001072 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001073 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001074
Anna Zaks9dc298b2012-09-12 22:57:34 +00001075 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1076 if (FreesOnFail)
1077 Kind = RPIsFreeOnFailure;
1078 else if (!ReleasedAllocated)
1079 Kind = RPDoNotTrackAfterFailure;
1080
Anna Zaks55dd9562012-08-24 02:28:20 +00001081 // Record the info about the reallocated symbol so that we could properly
1082 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001083 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001084 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001085 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001086 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001087 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001088 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001089 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001090}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001091
Anna Zaks87cb5be2012-02-22 19:24:52 +00001092ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001093 if (CE->getNumArgs() < 2)
1094 return 0;
1095
Ted Kremenek8bef8232012-01-26 21:29:00 +00001096 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001097 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001098 const LocationContext *LCtx = C.getLocationContext();
1099 SVal count = state->getSVal(CE->getArg(0), LCtx);
1100 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001101 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1102 svalBuilder.getContext().getSizeType());
1103 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001104
Anna Zaks87cb5be2012-02-22 19:24:52 +00001105 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001106}
1107
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001108LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001109MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1110 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001111 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001112 // Walk the ExplodedGraph backwards and find the first node that referred to
1113 // the tracked symbol.
1114 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001115 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001116
1117 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001118 ProgramStateRef State = N->getState();
1119 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001120 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001121
1122 // Find the most recent expression bound to the symbol in the current
1123 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001124 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001125 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1126 SVal Val = State->getSVal(MR);
1127 if (Val.getAsLocSymbol() == Sym)
1128 ReferenceRegion = MR;
1129 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001130 }
1131
Anna Zaks7752d292012-02-27 23:40:55 +00001132 // Allocation node, is the last node in the current context in which the
1133 // symbol was tracked.
1134 if (N->getLocationContext() == LeakContext)
1135 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001136 N = N->pred_empty() ? NULL : *(N->pred_begin());
1137 }
1138
Anna Zaks97bfb552013-01-08 00:25:29 +00001139 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001140}
1141
Anna Zaksda046772012-02-11 21:02:40 +00001142void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1143 CheckerContext &C) const {
1144 assert(N);
1145 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001146 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001147 // Leaks should not be reported if they are post-dominated by a sink:
1148 // (1) Sinks are higher importance bugs.
1149 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1150 // with __noreturn functions such as assert() or exit(). We choose not
1151 // to report leaks on such paths.
1152 BT_Leak->setSuppressOnSink(true);
1153 }
1154
Anna Zaksca8e36e2012-02-23 21:38:21 +00001155 // Most bug reports are cached at the location where they occurred.
1156 // With leaks, we want to unique them by the location where they were
1157 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001158 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001159 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001160 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001161 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1162
1163 ProgramPoint P = AllocNode->getLocation();
1164 const Stmt *AllocationStmt = 0;
David Blaikie7a95de62013-02-21 22:23:56 +00001165 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001166 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001167 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001168 AllocationStmt = SP->getStmt();
1169 if (AllocationStmt)
1170 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1171 C.getSourceManager(),
1172 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001173
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001174 SmallString<200> buf;
1175 llvm::raw_svector_ostream os(buf);
1176 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001177 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001178 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001179 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001180 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001181 }
1182
Anna Zaks97bfb552013-01-08 00:25:29 +00001183 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1184 LocUsedForUniqueing,
1185 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001186 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001187 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001188 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001189}
1190
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001191void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1192 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001193{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001194 if (!SymReaper.hasDeadSymbols())
1195 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001196
Ted Kremenek8bef8232012-01-26 21:29:00 +00001197 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001198 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001199 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001200
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001201 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001202 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1203 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001204 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001205 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001206 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001207 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001208
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001209 }
1210 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001211
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001212 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001213 ReallocPairsTy RP = state->get<ReallocPairs>();
1214 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001215 if (SymReaper.isDead(I->first) ||
1216 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001217 state = state->remove<ReallocPairs>(I->first);
1218 }
1219 }
1220
Anna Zaks4141e4d2012-11-13 03:18:01 +00001221 // Cleanup the FreeReturnValue Map.
1222 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1223 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1224 if (SymReaper.isDead(I->first) ||
1225 SymReaper.isDead(I->second)) {
1226 state = state->remove<FreeReturnValue>(I->first);
1227 }
1228 }
1229
Anna Zaksca8e36e2012-02-23 21:38:21 +00001230 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001231 ExplodedNode *N = C.getPredecessor();
1232 if (!Errors.empty()) {
1233 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1234 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001235 for (SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001236 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001237 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001238 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001239 }
Anna Zaks54458702012-10-29 22:51:54 +00001240
Anna Zaksca8e36e2012-02-23 21:38:21 +00001241 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001242}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001243
Anna Zaks66c40402012-02-14 21:55:24 +00001244void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001245 // We will check for double free in the post visit.
1246 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001247 return;
1248
1249 // Check use after free, when a freed pointer is passed to a call.
1250 ProgramStateRef State = C.getState();
1251 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1252 E = CE->arg_end(); I != E; ++I) {
1253 const Expr *A = *I;
1254 if (A->getType().getTypePtr()->isAnyPointerType()) {
Anton Yartsevbb369952013-03-13 14:39:10 +00001255 SymbolRef Sym = C.getSVal(A).getAsSymbol();
Anna Zaks66c40402012-02-14 21:55:24 +00001256 if (!Sym)
1257 continue;
1258 if (checkUseAfterFree(Sym, C, A))
1259 return;
1260 }
1261 }
1262}
1263
Anna Zaks91c2a112012-02-08 23:16:56 +00001264void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1265 const Expr *E = S->getRetValue();
1266 if (!E)
1267 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001268
1269 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001270 ProgramStateRef State = C.getState();
1271 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001272 SymbolRef Sym = RetVal.getAsSymbol();
1273 if (!Sym)
1274 // If we are returning a field of the allocated struct or an array element,
1275 // the callee could still free the memory.
1276 // TODO: This logic should be a part of generic symbol escape callback.
1277 if (const MemRegion *MR = RetVal.getAsRegion())
1278 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1279 if (const SymbolicRegion *BMR =
1280 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1281 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001282
Anna Zaks0860cd02012-02-11 21:44:39 +00001283 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001284 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001285 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001286}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001287
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001288// TODO: Blocks should be either inlined or should call invalidate regions
1289// upon invocation. After that's in place, special casing here will not be
1290// needed.
1291void MallocChecker::checkPostStmt(const BlockExpr *BE,
1292 CheckerContext &C) const {
1293
1294 // Scan the BlockDecRefExprs for any object the retain count checker
1295 // may be tracking.
1296 if (!BE->getBlockDecl()->hasCaptures())
1297 return;
1298
1299 ProgramStateRef state = C.getState();
1300 const BlockDataRegion *R =
1301 cast<BlockDataRegion>(state->getSVal(BE,
1302 C.getLocationContext()).getAsRegion());
1303
1304 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1305 E = R->referenced_vars_end();
1306
1307 if (I == E)
1308 return;
1309
1310 SmallVector<const MemRegion*, 10> Regions;
1311 const LocationContext *LC = C.getLocationContext();
1312 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1313
1314 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001315 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001316 if (VR->getSuperRegion() == R) {
1317 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1318 }
1319 Regions.push_back(VR);
1320 }
1321
1322 state =
1323 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1324 Regions.data() + Regions.size()).getState();
1325 C.addTransition(state);
1326}
1327
Anna Zaks14345182012-05-18 01:16:10 +00001328bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001329 assert(Sym);
1330 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001331 return (RS && RS->isReleased());
1332}
1333
1334bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1335 const Stmt *S) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001336
Anton Yartsevbb369952013-03-13 14:39:10 +00001337 if (isReleased(Sym, C)) {
1338 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1339 return true;
Anna Zaks91c2a112012-02-08 23:16:56 +00001340 }
Anton Yartsevbb369952013-03-13 14:39:10 +00001341
Anna Zaks91c2a112012-02-08 23:16:56 +00001342 return false;
1343}
1344
Zhongxing Xuc8023782010-03-10 04:58:55 +00001345// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001346void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1347 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001348 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001349 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001350 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001351}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001352
Anna Zaks4fb54872012-02-11 21:02:35 +00001353// If a symbolic region is assumed to NULL (or another constant), stop tracking
1354// it - assuming that allocation failed on this path.
1355ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1356 SVal Cond,
1357 bool Assumption) const {
1358 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001359 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001360 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001361 ConstraintManager &CMgr = state->getConstraintManager();
1362 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1363 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001364 state = state->remove<RegionState>(I.getKey());
1365 }
1366
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001367 // Realloc returns 0 when reallocation fails, which means that we should
1368 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001369 ReallocPairsTy RP = state->get<ReallocPairs>();
1370 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001371 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001372 ConstraintManager &CMgr = state->getConstraintManager();
1373 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001374 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001375 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001376
Anna Zaks9dc298b2012-09-12 22:57:34 +00001377 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1378 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1379 if (RS->isReleased()) {
1380 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001381 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001382 RefState::getAllocated(RS->getStmt()));
1383 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1384 state = state->remove<RegionState>(ReallocSym);
1385 else
1386 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001387 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001388 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001389 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001390 }
1391
Anna Zaks4fb54872012-02-11 21:02:35 +00001392 return state;
1393}
1394
Jordan Rose9fe09f32013-03-09 00:59:10 +00001395bool MallocChecker::doesNotFreeMemOrInteresting(const CallEvent *Call,
1396 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001397 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001398
1399 // For now, assume that any C++ call can free memory.
1400 // TODO: If we want to be more optimistic here, we'll need to make sure that
1401 // regions escape to C++ containers. They seem to do that even now, but for
1402 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001403 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001404 return false;
1405
Jordan Rose740d4902012-07-02 19:27:35 +00001406 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001407 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001408 // If it's not a framework call, or if it takes a callback, assume it
1409 // can free memory.
1410 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001411 return false;
1412
Jordan Rose9fe09f32013-03-09 00:59:10 +00001413 // If it's a method we know about, handle it explicitly post-call.
1414 // This should happen before the "freeWhenDone" check below.
1415 if (isKnownDeallocObjCMethodName(*Msg))
1416 return true;
Anna Zaks52a04812012-06-20 23:35:57 +00001417
Jordan Rose9fe09f32013-03-09 00:59:10 +00001418 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1419 // about, we can't be sure that the object will use free() to deallocate the
1420 // memory, so we can't model it explicitly. The best we can do is use it to
1421 // decide whether the pointer escapes.
1422 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
1423 return !*FreeWhenDone;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001424
Jordan Rose9fe09f32013-03-09 00:59:10 +00001425 // If the first selector piece ends with "NoCopy", and there is no
1426 // "freeWhenDone" parameter set to zero, we know ownership is being
1427 // transferred. Again, though, we can't be sure that the object will use
1428 // free() to deallocate the memory, so we can't model it explicitly.
1429 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose740d4902012-07-02 19:27:35 +00001430 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001431 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001432
Anna Zaks5f757682012-06-19 05:10:32 +00001433 // If the first selector starts with addPointer, insertPointer,
1434 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1435 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001436 // that the pointers get freed by following the container itself.
1437 if (FirstSlot.startswith("addPointer") ||
1438 FirstSlot.startswith("insertPointer") ||
1439 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001440 return false;
1441 }
1442
Jordan Rose740d4902012-07-02 19:27:35 +00001443 // Otherwise, assume that the method does not free memory.
1444 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001445 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001446 }
1447
Jordan Rose740d4902012-07-02 19:27:35 +00001448 // At this point the only thing left to handle is straight function calls.
1449 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1450 if (!FD)
1451 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001452
Jordan Rose740d4902012-07-02 19:27:35 +00001453 ASTContext &ASTC = State->getStateManager().getContext();
1454
1455 // If it's one of the allocation functions we can reason about, we model
1456 // its behavior explicitly.
1457 if (isMemFunction(FD, ASTC))
1458 return true;
1459
1460 // If it's not a system call, assume it frees memory.
1461 if (!Call->isInSystemHeader())
1462 return false;
1463
1464 // White list the system functions whose arguments escape.
1465 const IdentifierInfo *II = FD->getIdentifier();
1466 if (!II)
1467 return false;
1468 StringRef FName = II->getName();
1469
Jordan Rose740d4902012-07-02 19:27:35 +00001470 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001471 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001472 if (FName.endswith("NoCopy")) {
1473 // Look for the deallocator argument. We know that the memory ownership
1474 // is not transferred only if the deallocator argument is
1475 // 'kCFAllocatorNull'.
1476 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1477 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1478 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1479 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1480 if (DeallocatorName == "kCFAllocatorNull")
1481 return true;
1482 }
1483 }
1484 return false;
1485 }
1486
Jordan Rose740d4902012-07-02 19:27:35 +00001487 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001488 // 'closefn' is specified (and if that function does free memory),
1489 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001490 // Currently, we do not inspect the 'closefn' function (PR12101).
1491 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001492 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1493 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001494
1495 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1496 // these leaks might be intentional when setting the buffer for stdio.
1497 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1498 if (FName == "setbuf" || FName =="setbuffer" ||
1499 FName == "setlinebuf" || FName == "setvbuf") {
1500 if (Call->getNumArgs() >= 1) {
1501 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1502 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1503 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1504 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1505 return false;
1506 }
1507 }
1508
1509 // A bunch of other functions which either take ownership of a pointer or
1510 // wrap the result up in a struct or object, meaning it can be freed later.
1511 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1512 // but the Malloc checker cannot differentiate between them. The right way
1513 // of doing this would be to implement a pointer escapes callback.
1514 if (FName == "CGBitmapContextCreate" ||
1515 FName == "CGBitmapContextCreateWithData" ||
1516 FName == "CVPixelBufferCreateWithBytes" ||
1517 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1518 FName == "OSAtomicEnqueue") {
1519 return false;
1520 }
1521
Jordan Rose85d7e012012-07-02 19:27:51 +00001522 // Handle cases where we know a buffer's /address/ can escape.
1523 // Note that the above checks handle some special cases where we know that
1524 // even though the address escapes, it's still our responsibility to free the
1525 // buffer.
1526 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001527 return false;
1528
1529 // Otherwise, assume that the function does not free memory.
1530 // Most system calls do not free the memory.
1531 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001532}
1533
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001534ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1535 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00001536 const CallEvent *Call,
1537 PointerEscapeKind Kind) const {
Jordan Rose9fe09f32013-03-09 00:59:10 +00001538 // If we know that the call does not free memory, or we want to process the
1539 // call later, keep tracking the top level arguments.
Anna Zaks233e26a2013-02-07 23:05:43 +00001540 if ((Kind == PSK_DirectEscapeOnCall ||
1541 Kind == PSK_IndirectEscapeOnCall) &&
Jordan Rose9fe09f32013-03-09 00:59:10 +00001542 doesNotFreeMemOrInteresting(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001543 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00001544 }
Anna Zaks66c40402012-02-14 21:55:24 +00001545
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001546 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
1547 E = Escaped.end();
1548 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001549 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001550
Anna Zaks5b7aa342012-06-22 02:04:31 +00001551 if (const RefState *RS = State->get<RegionState>(sym)) {
1552 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001553 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001554 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001555 }
Anna Zaks66c40402012-02-14 21:55:24 +00001556 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001557}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001558
Jordy Rose393f98b2012-03-18 07:43:35 +00001559static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1560 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001561 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1562 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001563
Jordan Rose166d5022012-11-02 01:54:06 +00001564 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001565 I != E; ++I) {
1566 SymbolRef sym = I.getKey();
1567 if (!currMap.lookup(sym))
1568 return sym;
1569 }
1570
1571 return NULL;
1572}
1573
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001574PathDiagnosticPiece *
1575MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1576 const ExplodedNode *PrevN,
1577 BugReporterContext &BRC,
1578 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001579 ProgramStateRef state = N->getState();
1580 ProgramStateRef statePrev = PrevN->getState();
1581
1582 const RefState *RS = state->get<RegionState>(Sym);
1583 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001584 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001585 return 0;
1586
Anna Zaksfe571602012-02-16 22:26:07 +00001587 const Stmt *S = 0;
1588 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001589 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001590
1591 // Retrieve the associated statement.
1592 ProgramPoint ProgLoc = N->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00001593 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001594 S = SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +00001595 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001596 S = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001597 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremeneka4a17592013-01-04 19:04:36 +00001598 // If an assumption was made on a branch, it should be caught
1599 // here by looking at the state transition.
1600 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00001601 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00001602
Anna Zaksfe571602012-02-16 22:26:07 +00001603 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001604 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001605
Jordan Rose28038f32012-07-10 22:07:42 +00001606 // FIXME: We will eventually need to handle non-statement-based events
1607 // (__attribute__((cleanup))).
1608
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001609 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001610 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001611 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001612 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001613 StackHint = new StackHintGeneratorForSymbol(Sym,
1614 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001615 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001616 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001617 StackHint = new StackHintGeneratorForSymbol(Sym,
1618 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001619 } else if (isRelinquished(RS, RSPrev, S)) {
1620 Msg = "Memory ownership is transfered";
1621 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001622 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001623 Mode = ReallocationFailed;
1624 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001625 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001626 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001627
Jordy Roseb000fb52012-03-24 03:15:09 +00001628 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1629 // Is it possible to fail two reallocs WITHOUT testing in between?
1630 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1631 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001632 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001633 FailedReallocSymbol = sym;
1634 }
Anna Zaksfe571602012-02-16 22:26:07 +00001635 }
1636
1637 // We are in a special mode if a reallocation failed later in the path.
1638 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001639 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001640
Jordy Roseb000fb52012-03-24 03:15:09 +00001641 // Is this is the first appearance of the reallocated symbol?
1642 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001643 // We're at the reallocation point.
1644 Msg = "Attempt to reallocate memory";
1645 StackHint = new StackHintGeneratorForSymbol(Sym,
1646 "Returned reallocated memory");
1647 FailedReallocSymbol = NULL;
1648 Mode = Normal;
1649 }
Anna Zaksfe571602012-02-16 22:26:07 +00001650 }
1651
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001652 if (!Msg)
1653 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001654 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001655
1656 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001657 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001658 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001659 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001660}
1661
Anna Zaks93c5a242012-05-02 00:05:20 +00001662void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1663 const char *NL, const char *Sep) const {
1664
1665 RegionStateTy RS = State->get<RegionState>();
1666
Ted Kremenekc37fad62013-01-03 01:30:12 +00001667 if (!RS.isEmpty()) {
1668 Out << Sep << "MallocChecker:" << NL;
1669 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1670 I.getKey()->dumpToStream(Out);
1671 Out << " : ";
1672 I.getData().dump(Out);
1673 Out << NL;
1674 }
1675 }
Anna Zaks93c5a242012-05-02 00:05:20 +00001676}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001677
Anna Zaks231361a2012-02-08 23:16:52 +00001678#define REGISTER_CHECKER(name) \
1679void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001680 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001681 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001682}
Anna Zaks231361a2012-02-08 23:16:52 +00001683
1684REGISTER_CHECKER(MallocPessimistic)
1685REGISTER_CHECKER(MallocOptimistic)