blob: e88322ddf58e057e0b70d5514f7f7ff6f5dedf76 [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,
Anton Yartsev3258d4b2013-03-13 17:07:32 +0000239 SymbolRef Sym, SymbolRef PrevSym) 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,
Anton Yartsev3258d4b2013-03-13 17:07:32 +0000972 SymbolRef PrevSym) const {
Anton Yartsevbb369952013-03-13 14:39:10 +0000973
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);
Anton Yartsev3258d4b2013-03-13 17:07:32 +0000983 R->markInteresting(Sym);
984 if (PrevSym)
985 R->markInteresting(PrevSym);
Anton Yartsevbb369952013-03-13 14:39:10 +0000986 R->addVisitor(new MallocBugVisitor(Sym));
987 C.emitReport(R);
988 }
989}
990
Anna Zaks87cb5be2012-02-22 19:24:52 +0000991ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
992 const CallExpr *CE,
993 bool FreesOnFail) const {
Anna Zaks259052d2012-04-10 23:41:11 +0000994 if (CE->getNumArgs() < 2)
995 return 0;
996
Ted Kremenek8bef8232012-01-26 21:29:00 +0000997 ProgramStateRef state = C.getState();
Ted Kremenekc8413fd2010-12-02 07:49:45 +0000998 const Expr *arg0Expr = CE->getArg(0);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000999 const LocationContext *LCtx = C.getLocationContext();
Anna Zakse9ef5622012-02-10 01:11:00 +00001000 SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001001 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001002 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001003 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001004
Ted Kremenek846eabd2010-12-01 21:28:31 +00001005 SValBuilder &svalBuilder = C.getSValBuilder();
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001006
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001007 DefinedOrUnknownSVal PtrEQ =
1008 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001009
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001010 // Get the size argument. If there is no size arg then give up.
1011 const Expr *Arg1 = CE->getArg(1);
1012 if (!Arg1)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001013 return 0;
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001014
1015 // Get the value of the size argument.
Anna Zakse9ef5622012-02-10 01:11:00 +00001016 SVal Arg1ValG = state->getSVal(Arg1, LCtx);
David Blaikie5251abe2013-02-20 05:52:05 +00001017 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
Anna Zaks87cb5be2012-02-22 19:24:52 +00001018 return 0;
David Blaikie5251abe2013-02-20 05:52:05 +00001019 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001020
1021 // Compare the size argument to 0.
1022 DefinedOrUnknownSVal SizeZero =
1023 svalBuilder.evalEQ(state, Arg1Val,
1024 svalBuilder.makeIntValWithPtrWidth(0, false));
1025
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001026 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1027 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
1028 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1029 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
1030 // We only assume exceptional states if they are definitely true; if the
1031 // state is under-constrained, assume regular realloc behavior.
1032 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1033 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1034
Lenny Maiorani4d8d8032011-04-27 14:49:29 +00001035 // If the ptr is NULL and the size is not 0, the call is equivalent to
1036 // malloc(size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001037 if ( PrtIsNull && !SizeIsZero) {
Anna Zaks87cb5be2012-02-22 19:24:52 +00001038 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001039 UndefinedVal(), StatePtrIsNull);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001040 return stateMalloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001041 }
1042
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001043 if (PrtIsNull && SizeIsZero)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001044 return 0;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001045
Anna Zaks30838b92012-02-13 20:57:07 +00001046 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001047 assert(!PrtIsNull);
Anna Zaks30838b92012-02-13 20:57:07 +00001048 SymbolRef FromPtr = arg0Val.getAsSymbol();
1049 SVal RetVal = state->getSVal(CE, LCtx);
1050 SymbolRef ToPtr = RetVal.getAsSymbol();
1051 if (!FromPtr || !ToPtr)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001052 return 0;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001053
Anna Zaks55dd9562012-08-24 02:28:20 +00001054 bool ReleasedAllocated = false;
1055
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001056 // If the size is 0, free the memory.
1057 if (SizeIsZero)
Anna Zaks55dd9562012-08-24 02:28:20 +00001058 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1059 false, ReleasedAllocated)){
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001060 // The semantics of the return value are:
1061 // If size was equal to 0, either NULL or a pointer suitable to be passed
Anna Zaksede875b2012-08-03 18:30:18 +00001062 // to free() is returned. We just free the input pointer and do not add
1063 // any constrains on the output pointer.
Anna Zaks87cb5be2012-02-22 19:24:52 +00001064 return stateFree;
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001065 }
1066
1067 // Default behavior.
Anna Zaks55dd9562012-08-24 02:28:20 +00001068 if (ProgramStateRef stateFree =
1069 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1070
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001071 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1072 UnknownVal(), stateFree);
Anna Zaks30838b92012-02-13 20:57:07 +00001073 if (!stateRealloc)
Anna Zaks87cb5be2012-02-22 19:24:52 +00001074 return 0;
Anna Zaks55dd9562012-08-24 02:28:20 +00001075
Anna Zaks9dc298b2012-09-12 22:57:34 +00001076 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1077 if (FreesOnFail)
1078 Kind = RPIsFreeOnFailure;
1079 else if (!ReleasedAllocated)
1080 Kind = RPDoNotTrackAfterFailure;
1081
Anna Zaks55dd9562012-08-24 02:28:20 +00001082 // Record the info about the reallocated symbol so that we could properly
1083 // process failed reallocation.
Anna Zaks40add292012-02-15 00:11:25 +00001084 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001085 ReallocPair(FromPtr, Kind));
Anna Zaks55dd9562012-08-24 02:28:20 +00001086 // The reallocated symbol should stay alive for as long as the new symbol.
Anna Zaksb276bd92012-02-14 00:26:13 +00001087 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
Anna Zaks87cb5be2012-02-22 19:24:52 +00001088 return stateRealloc;
Zhongxing Xud9c84c82009-12-12 12:29:38 +00001089 }
Anna Zaks87cb5be2012-02-22 19:24:52 +00001090 return 0;
Zhongxing Xu589c0f22009-11-12 08:38:56 +00001091}
Zhongxing Xu7b760962009-11-13 07:25:27 +00001092
Anna Zaks87cb5be2012-02-22 19:24:52 +00001093ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
Anna Zaks259052d2012-04-10 23:41:11 +00001094 if (CE->getNumArgs() < 2)
1095 return 0;
1096
Ted Kremenek8bef8232012-01-26 21:29:00 +00001097 ProgramStateRef state = C.getState();
Ted Kremenek846eabd2010-12-01 21:28:31 +00001098 SValBuilder &svalBuilder = C.getSValBuilder();
Ted Kremenek5eca4822012-01-06 22:09:28 +00001099 const LocationContext *LCtx = C.getLocationContext();
1100 SVal count = state->getSVal(CE->getArg(0), LCtx);
1101 SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001102 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1103 svalBuilder.getContext().getSizeType());
1104 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001105
Anna Zaks87cb5be2012-02-22 19:24:52 +00001106 return MallocMemAux(C, CE, TotalSize, zeroVal, state);
Zhongxing Xua5ce9662010-06-01 03:01:33 +00001107}
1108
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001109LeakInfo
Anna Zaksca8e36e2012-02-23 21:38:21 +00001110MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1111 CheckerContext &C) const {
Anna Zaks7752d292012-02-27 23:40:55 +00001112 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksca8e36e2012-02-23 21:38:21 +00001113 // Walk the ExplodedGraph backwards and find the first node that referred to
1114 // the tracked symbol.
1115 const ExplodedNode *AllocNode = N;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001116 const MemRegion *ReferenceRegion = 0;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001117
1118 while (N) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001119 ProgramStateRef State = N->getState();
1120 if (!State->get<RegionState>(Sym))
Anna Zaksca8e36e2012-02-23 21:38:21 +00001121 break;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001122
1123 // Find the most recent expression bound to the symbol in the current
1124 // context.
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001125 if (!ReferenceRegion) {
Benjamin Kramer850f1b12012-03-21 21:03:48 +00001126 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1127 SVal Val = State->getSVal(MR);
1128 if (Val.getAsLocSymbol() == Sym)
1129 ReferenceRegion = MR;
1130 }
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001131 }
1132
Anna Zaks7752d292012-02-27 23:40:55 +00001133 // Allocation node, is the last node in the current context in which the
1134 // symbol was tracked.
1135 if (N->getLocationContext() == LeakContext)
1136 AllocNode = N;
Anna Zaksca8e36e2012-02-23 21:38:21 +00001137 N = N->pred_empty() ? NULL : *(N->pred_begin());
1138 }
1139
Anna Zaks97bfb552013-01-08 00:25:29 +00001140 return LeakInfo(AllocNode, ReferenceRegion);
Anna Zaksca8e36e2012-02-23 21:38:21 +00001141}
1142
Anna Zaksda046772012-02-11 21:02:40 +00001143void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1144 CheckerContext &C) const {
1145 assert(N);
1146 if (!BT_Leak) {
Anna Zaksfebdc322012-02-16 22:26:12 +00001147 BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
Anna Zaksda046772012-02-11 21:02:40 +00001148 // Leaks should not be reported if they are post-dominated by a sink:
1149 // (1) Sinks are higher importance bugs.
1150 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1151 // with __noreturn functions such as assert() or exit(). We choose not
1152 // to report leaks on such paths.
1153 BT_Leak->setSuppressOnSink(true);
1154 }
1155
Anna Zaksca8e36e2012-02-23 21:38:21 +00001156 // Most bug reports are cached at the location where they occurred.
1157 // With leaks, we want to unique them by the location where they were
1158 // allocated, and only report a single path.
Anna Zaks7752d292012-02-27 23:40:55 +00001159 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +00001160 const ExplodedNode *AllocNode = 0;
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001161 const MemRegion *Region = 0;
Anna Zaks97bfb552013-01-08 00:25:29 +00001162 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1163
1164 ProgramPoint P = AllocNode->getLocation();
1165 const Stmt *AllocationStmt = 0;
David Blaikie7a95de62013-02-21 22:23:56 +00001166 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001167 AllocationStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001168 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
Anna Zaks97bfb552013-01-08 00:25:29 +00001169 AllocationStmt = SP->getStmt();
1170 if (AllocationStmt)
1171 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1172 C.getSourceManager(),
1173 AllocNode->getLocationContext());
Anna Zaksca8e36e2012-02-23 21:38:21 +00001174
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001175 SmallString<200> buf;
1176 llvm::raw_svector_ostream os(buf);
1177 os << "Memory is never released; potential leak";
Jordan Rose919e8a12012-08-08 18:23:36 +00001178 if (Region && Region->canPrintPretty()) {
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001179 os << " of memory pointed to by '";
Jordan Rose919e8a12012-08-08 18:23:36 +00001180 Region->printPretty(os);
Jordan Rose0d53ab42012-08-08 18:23:31 +00001181 os << '\'';
Anna Zaks3d7c44e2012-03-21 19:45:08 +00001182 }
1183
Anna Zaks97bfb552013-01-08 00:25:29 +00001184 BugReport *R = new BugReport(*BT_Leak, os.str(), N,
1185 LocUsedForUniqueing,
1186 AllocNode->getLocationContext()->getDecl());
Ted Kremenek76aadc32012-03-09 01:13:14 +00001187 R->markInteresting(Sym);
Anna Zaks88feba02012-05-10 01:37:40 +00001188 R->addVisitor(new MallocBugVisitor(Sym, true));
Jordan Rose785950e2012-11-02 01:53:40 +00001189 C.emitReport(R);
Anna Zaksda046772012-02-11 21:02:40 +00001190}
1191
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001192void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1193 CheckerContext &C) const
Ted Kremenekc8413fd2010-12-02 07:49:45 +00001194{
Zhongxing Xu173ff562010-08-15 08:19:57 +00001195 if (!SymReaper.hasDeadSymbols())
1196 return;
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001197
Ted Kremenek8bef8232012-01-26 21:29:00 +00001198 ProgramStateRef state = C.getState();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001199 RegionStateTy RS = state->get<RegionState>();
Jordy Rose90760142010-08-18 04:33:47 +00001200 RegionStateTy::Factory &F = state->get_context<RegionState>();
Zhongxing Xu173ff562010-08-15 08:19:57 +00001201
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001202 SmallVector<SymbolRef, 2> Errors;
Zhongxing Xu173ff562010-08-15 08:19:57 +00001203 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1204 if (SymReaper.isDead(I->first)) {
Anna Zaks54458702012-10-29 22:51:54 +00001205 if (I->second.isAllocated())
Anna Zaksf8c17b72012-02-09 06:48:19 +00001206 Errors.push_back(I->first);
Jordy Rose90760142010-08-18 04:33:47 +00001207 // Remove the dead symbol from the map.
Ted Kremenek3baf6722010-11-24 00:54:37 +00001208 RS = F.remove(RS, I->first);
Ted Kremenek217470e2011-07-28 23:07:51 +00001209
Zhongxing Xufc7ac8f2009-11-13 07:48:11 +00001210 }
1211 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001212
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001213 // Cleanup the Realloc Pairs Map.
Jordan Rose166d5022012-11-02 01:54:06 +00001214 ReallocPairsTy RP = state->get<ReallocPairs>();
1215 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Anna Zaks40add292012-02-15 00:11:25 +00001216 if (SymReaper.isDead(I->first) ||
1217 SymReaper.isDead(I->second.ReallocatedSym)) {
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001218 state = state->remove<ReallocPairs>(I->first);
1219 }
1220 }
1221
Anna Zaks4141e4d2012-11-13 03:18:01 +00001222 // Cleanup the FreeReturnValue Map.
1223 FreeReturnValueTy FR = state->get<FreeReturnValue>();
1224 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1225 if (SymReaper.isDead(I->first) ||
1226 SymReaper.isDead(I->second)) {
1227 state = state->remove<FreeReturnValue>(I->first);
1228 }
1229 }
1230
Anna Zaksca8e36e2012-02-23 21:38:21 +00001231 // Generate leak node.
Anna Zaks54458702012-10-29 22:51:54 +00001232 ExplodedNode *N = C.getPredecessor();
1233 if (!Errors.empty()) {
1234 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
1235 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001236 for (SmallVector<SymbolRef, 2>::iterator
Anna Zaks54458702012-10-29 22:51:54 +00001237 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
Anna Zaksda046772012-02-11 21:02:40 +00001238 reportLeak(*I, N, C);
Anna Zaksf8c17b72012-02-09 06:48:19 +00001239 }
Ted Kremenek217470e2011-07-28 23:07:51 +00001240 }
Anna Zaks54458702012-10-29 22:51:54 +00001241
Anna Zaksca8e36e2012-02-23 21:38:21 +00001242 C.addTransition(state->set<RegionState>(RS), N);
Zhongxing Xu7b760962009-11-13 07:25:27 +00001243}
Zhongxing Xu243fde92009-11-17 07:54:15 +00001244
Anna Zaks66c40402012-02-14 21:55:24 +00001245void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
Anna Zaks14345182012-05-18 01:16:10 +00001246 // We will check for double free in the post visit.
1247 if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
Anna Zaks66c40402012-02-14 21:55:24 +00001248 return;
1249
1250 // Check use after free, when a freed pointer is passed to a call.
1251 ProgramStateRef State = C.getState();
1252 for (CallExpr::const_arg_iterator I = CE->arg_begin(),
1253 E = CE->arg_end(); I != E; ++I) {
1254 const Expr *A = *I;
1255 if (A->getType().getTypePtr()->isAnyPointerType()) {
Anton Yartsevbb369952013-03-13 14:39:10 +00001256 SymbolRef Sym = C.getSVal(A).getAsSymbol();
Anna Zaks66c40402012-02-14 21:55:24 +00001257 if (!Sym)
1258 continue;
1259 if (checkUseAfterFree(Sym, C, A))
1260 return;
1261 }
1262 }
1263}
1264
Anna Zaks91c2a112012-02-08 23:16:56 +00001265void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1266 const Expr *E = S->getRetValue();
1267 if (!E)
1268 return;
Anna Zaks0860cd02012-02-11 21:44:39 +00001269
1270 // Check if we are returning a symbol.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001271 ProgramStateRef State = C.getState();
1272 SVal RetVal = State->getSVal(E, C.getLocationContext());
Anna Zaksd9ab7bb2012-02-22 02:36:01 +00001273 SymbolRef Sym = RetVal.getAsSymbol();
1274 if (!Sym)
1275 // If we are returning a field of the allocated struct or an array element,
1276 // the callee could still free the memory.
1277 // TODO: This logic should be a part of generic symbol escape callback.
1278 if (const MemRegion *MR = RetVal.getAsRegion())
1279 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1280 if (const SymbolicRegion *BMR =
1281 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
1282 Sym = BMR->getSymbol();
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001283
Anna Zaks0860cd02012-02-11 21:44:39 +00001284 // Check if we are returning freed memory.
Jordan Rose0d53ab42012-08-08 18:23:31 +00001285 if (Sym)
Jordan Rose65d4bd62012-11-15 19:11:33 +00001286 checkUseAfterFree(Sym, C, E);
Zhongxing Xu4985e3e2009-11-17 08:58:18 +00001287}
Zhongxing Xub94b81a2009-12-31 06:13:07 +00001288
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001289// TODO: Blocks should be either inlined or should call invalidate regions
1290// upon invocation. After that's in place, special casing here will not be
1291// needed.
1292void MallocChecker::checkPostStmt(const BlockExpr *BE,
1293 CheckerContext &C) const {
1294
1295 // Scan the BlockDecRefExprs for any object the retain count checker
1296 // may be tracking.
1297 if (!BE->getBlockDecl()->hasCaptures())
1298 return;
1299
1300 ProgramStateRef state = C.getState();
1301 const BlockDataRegion *R =
1302 cast<BlockDataRegion>(state->getSVal(BE,
1303 C.getLocationContext()).getAsRegion());
1304
1305 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
1306 E = R->referenced_vars_end();
1307
1308 if (I == E)
1309 return;
1310
1311 SmallVector<const MemRegion*, 10> Regions;
1312 const LocationContext *LC = C.getLocationContext();
1313 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
1314
1315 for ( ; I != E; ++I) {
Ted Kremeneke3ce2c12012-12-06 07:17:20 +00001316 const VarRegion *VR = I.getCapturedRegion();
Anna Zaksf5aa3f52012-03-22 00:57:20 +00001317 if (VR->getSuperRegion() == R) {
1318 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
1319 }
1320 Regions.push_back(VR);
1321 }
1322
1323 state =
1324 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
1325 Regions.data() + Regions.size()).getState();
1326 C.addTransition(state);
1327}
1328
Anna Zaks14345182012-05-18 01:16:10 +00001329bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001330 assert(Sym);
1331 const RefState *RS = C.getState()->get<RegionState>(Sym);
Anna Zaks14345182012-05-18 01:16:10 +00001332 return (RS && RS->isReleased());
1333}
1334
1335bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
1336 const Stmt *S) const {
Anna Zaks91c2a112012-02-08 23:16:56 +00001337
Anton Yartsevbb369952013-03-13 14:39:10 +00001338 if (isReleased(Sym, C)) {
1339 ReportUseAfterFree(C, S->getSourceRange(), Sym);
1340 return true;
Anna Zaks91c2a112012-02-08 23:16:56 +00001341 }
Anton Yartsevbb369952013-03-13 14:39:10 +00001342
Anna Zaks91c2a112012-02-08 23:16:56 +00001343 return false;
1344}
1345
Zhongxing Xuc8023782010-03-10 04:58:55 +00001346// Check if the location is a freed symbolic region.
Anna Zaks390909c2011-10-06 00:43:15 +00001347void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
1348 CheckerContext &C) const {
Zhongxing Xuc8023782010-03-10 04:58:55 +00001349 SymbolRef Sym = l.getLocSymbolInBase();
Anna Zaks91c2a112012-02-08 23:16:56 +00001350 if (Sym)
Anna Zaks14345182012-05-18 01:16:10 +00001351 checkUseAfterFree(Sym, C, S);
Zhongxing Xuc8023782010-03-10 04:58:55 +00001352}
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001353
Anna Zaks4fb54872012-02-11 21:02:35 +00001354// If a symbolic region is assumed to NULL (or another constant), stop tracking
1355// it - assuming that allocation failed on this path.
1356ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
1357 SVal Cond,
1358 bool Assumption) const {
1359 RegionStateTy RS = state->get<RegionState>();
Anna Zaks4fb54872012-02-11 21:02:35 +00001360 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001361 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001362 ConstraintManager &CMgr = state->getConstraintManager();
1363 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
1364 if (AllocFailed.isConstrainedTrue())
Anna Zaks4fb54872012-02-11 21:02:35 +00001365 state = state->remove<RegionState>(I.getKey());
1366 }
1367
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001368 // Realloc returns 0 when reallocation fails, which means that we should
1369 // restore the state of the pointer being reallocated.
Jordan Rose166d5022012-11-02 01:54:06 +00001370 ReallocPairsTy RP = state->get<ReallocPairs>();
1371 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
Ted Kremenek47cbd0f2012-09-07 22:31:01 +00001372 // If the symbol is assumed to be NULL, remove it from consideration.
Jordan Roseec8d4202012-11-01 00:18:27 +00001373 ConstraintManager &CMgr = state->getConstraintManager();
1374 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
Jordan Rose79a29eb2012-11-01 00:25:15 +00001375 if (!AllocFailed.isConstrainedTrue())
Anna Zaks9dc298b2012-09-12 22:57:34 +00001376 continue;
Jordan Roseec8d4202012-11-01 00:18:27 +00001377
Anna Zaks9dc298b2012-09-12 22:57:34 +00001378 SymbolRef ReallocSym = I.getData().ReallocatedSym;
1379 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
1380 if (RS->isReleased()) {
1381 if (I.getData().Kind == RPToBeFreedAfterFailure)
Anna Zaks40add292012-02-15 00:11:25 +00001382 state = state->set<RegionState>(ReallocSym,
Anna Zaks9dc298b2012-09-12 22:57:34 +00001383 RefState::getAllocated(RS->getStmt()));
1384 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
1385 state = state->remove<RegionState>(ReallocSym);
1386 else
1387 assert(I.getData().Kind == RPIsFreeOnFailure);
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001388 }
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001389 }
Anna Zaks9dc298b2012-09-12 22:57:34 +00001390 state = state->remove<ReallocPairs>(I.getKey());
Anna Zaksc8bb3be2012-02-13 18:05:39 +00001391 }
1392
Anna Zaks4fb54872012-02-11 21:02:35 +00001393 return state;
1394}
1395
Jordan Rose9fe09f32013-03-09 00:59:10 +00001396bool MallocChecker::doesNotFreeMemOrInteresting(const CallEvent *Call,
1397 ProgramStateRef State) const {
Jordan Rose85d7e012012-07-02 19:27:51 +00001398 assert(Call);
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001399
1400 // For now, assume that any C++ call can free memory.
1401 // TODO: If we want to be more optimistic here, we'll need to make sure that
1402 // regions escape to C++ containers. They seem to do that even now, but for
1403 // mysterious reasons.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001404 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001405 return false;
1406
Jordan Rose740d4902012-07-02 19:27:35 +00001407 // Check Objective-C messages by selector name.
Jordan Rosecde8cdb2012-07-02 19:27:56 +00001408 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
Jordan Rose85d7e012012-07-02 19:27:51 +00001409 // If it's not a framework call, or if it takes a callback, assume it
1410 // can free memory.
1411 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
Anna Zaks07d39a42012-02-28 01:54:22 +00001412 return false;
1413
Jordan Rose9fe09f32013-03-09 00:59:10 +00001414 // If it's a method we know about, handle it explicitly post-call.
1415 // This should happen before the "freeWhenDone" check below.
1416 if (isKnownDeallocObjCMethodName(*Msg))
1417 return true;
Anna Zaks52a04812012-06-20 23:35:57 +00001418
Jordan Rose9fe09f32013-03-09 00:59:10 +00001419 // If there's a "freeWhenDone" parameter, but the method isn't one we know
1420 // about, we can't be sure that the object will use free() to deallocate the
1421 // memory, so we can't model it explicitly. The best we can do is use it to
1422 // decide whether the pointer escapes.
1423 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
1424 return !*FreeWhenDone;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001425
Jordan Rose9fe09f32013-03-09 00:59:10 +00001426 // If the first selector piece ends with "NoCopy", and there is no
1427 // "freeWhenDone" parameter set to zero, we know ownership is being
1428 // transferred. Again, though, we can't be sure that the object will use
1429 // free() to deallocate the memory, so we can't model it explicitly.
1430 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
Jordan Rose740d4902012-07-02 19:27:35 +00001431 if (FirstSlot.endswith("NoCopy"))
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001432 return false;
Anna Zaksfb7f76f2012-03-05 17:42:10 +00001433
Anna Zaks5f757682012-06-19 05:10:32 +00001434 // If the first selector starts with addPointer, insertPointer,
1435 // or replacePointer, assume we are dealing with NSPointerArray or similar.
1436 // This is similar to C++ containers (vector); we still might want to check
Jordan Rose740d4902012-07-02 19:27:35 +00001437 // that the pointers get freed by following the container itself.
1438 if (FirstSlot.startswith("addPointer") ||
1439 FirstSlot.startswith("insertPointer") ||
1440 FirstSlot.startswith("replacePointer")) {
Anna Zaks5f757682012-06-19 05:10:32 +00001441 return false;
1442 }
1443
Jordan Rose740d4902012-07-02 19:27:35 +00001444 // Otherwise, assume that the method does not free memory.
1445 // Most framework methods do not free memory.
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001446 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001447 }
1448
Jordan Rose740d4902012-07-02 19:27:35 +00001449 // At this point the only thing left to handle is straight function calls.
1450 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
1451 if (!FD)
1452 return false;
Anna Zaks3cd89ad2012-02-24 23:56:53 +00001453
Jordan Rose740d4902012-07-02 19:27:35 +00001454 ASTContext &ASTC = State->getStateManager().getContext();
1455
1456 // If it's one of the allocation functions we can reason about, we model
1457 // its behavior explicitly.
1458 if (isMemFunction(FD, ASTC))
1459 return true;
1460
1461 // If it's not a system call, assume it frees memory.
1462 if (!Call->isInSystemHeader())
1463 return false;
1464
1465 // White list the system functions whose arguments escape.
1466 const IdentifierInfo *II = FD->getIdentifier();
1467 if (!II)
1468 return false;
1469 StringRef FName = II->getName();
1470
Jordan Rose740d4902012-07-02 19:27:35 +00001471 // White list the 'XXXNoCopy' CoreFoundation functions.
Jordan Rose85d7e012012-07-02 19:27:51 +00001472 // We specifically check these before
Jordan Rose740d4902012-07-02 19:27:35 +00001473 if (FName.endswith("NoCopy")) {
1474 // Look for the deallocator argument. We know that the memory ownership
1475 // is not transferred only if the deallocator argument is
1476 // 'kCFAllocatorNull'.
1477 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
1478 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
1479 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
1480 StringRef DeallocatorName = DE->getFoundDecl()->getName();
1481 if (DeallocatorName == "kCFAllocatorNull")
1482 return true;
1483 }
1484 }
1485 return false;
1486 }
1487
Jordan Rose740d4902012-07-02 19:27:35 +00001488 // Associating streams with malloced buffers. The pointer can escape if
Jordan Rose85d7e012012-07-02 19:27:51 +00001489 // 'closefn' is specified (and if that function does free memory),
1490 // but it will not if closefn is not specified.
Jordan Rose740d4902012-07-02 19:27:35 +00001491 // Currently, we do not inspect the 'closefn' function (PR12101).
1492 if (FName == "funopen")
Jordan Rose85d7e012012-07-02 19:27:51 +00001493 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
1494 return true;
Jordan Rose740d4902012-07-02 19:27:35 +00001495
1496 // Do not warn on pointers passed to 'setbuf' when used with std streams,
1497 // these leaks might be intentional when setting the buffer for stdio.
1498 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
1499 if (FName == "setbuf" || FName =="setbuffer" ||
1500 FName == "setlinebuf" || FName == "setvbuf") {
1501 if (Call->getNumArgs() >= 1) {
1502 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
1503 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
1504 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
1505 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
1506 return false;
1507 }
1508 }
1509
1510 // A bunch of other functions which either take ownership of a pointer or
1511 // wrap the result up in a struct or object, meaning it can be freed later.
1512 // (See RetainCountChecker.) Not all the parameters here are invalidated,
1513 // but the Malloc checker cannot differentiate between them. The right way
1514 // of doing this would be to implement a pointer escapes callback.
1515 if (FName == "CGBitmapContextCreate" ||
1516 FName == "CGBitmapContextCreateWithData" ||
1517 FName == "CVPixelBufferCreateWithBytes" ||
1518 FName == "CVPixelBufferCreateWithPlanarBytes" ||
1519 FName == "OSAtomicEnqueue") {
1520 return false;
1521 }
1522
Jordan Rose85d7e012012-07-02 19:27:51 +00001523 // Handle cases where we know a buffer's /address/ can escape.
1524 // Note that the above checks handle some special cases where we know that
1525 // even though the address escapes, it's still our responsibility to free the
1526 // buffer.
1527 if (Call->argumentsMayEscape())
Jordan Rose740d4902012-07-02 19:27:35 +00001528 return false;
1529
1530 // Otherwise, assume that the function does not free memory.
1531 // Most system calls do not free the memory.
1532 return true;
Anna Zaks66c40402012-02-14 21:55:24 +00001533}
1534
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001535ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
1536 const InvalidatedSymbols &Escaped,
Anna Zaks233e26a2013-02-07 23:05:43 +00001537 const CallEvent *Call,
1538 PointerEscapeKind Kind) const {
Jordan Rose9fe09f32013-03-09 00:59:10 +00001539 // If we know that the call does not free memory, or we want to process the
1540 // call later, keep tracking the top level arguments.
Anna Zaks233e26a2013-02-07 23:05:43 +00001541 if ((Kind == PSK_DirectEscapeOnCall ||
1542 Kind == PSK_IndirectEscapeOnCall) &&
Jordan Rose9fe09f32013-03-09 00:59:10 +00001543 doesNotFreeMemOrInteresting(Call, State)) {
Anna Zaks66c40402012-02-14 21:55:24 +00001544 return State;
Anna Zaks233e26a2013-02-07 23:05:43 +00001545 }
Anna Zaks66c40402012-02-14 21:55:24 +00001546
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001547 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
1548 E = Escaped.end();
1549 I != E; ++I) {
Anna Zaks4fb54872012-02-11 21:02:35 +00001550 SymbolRef sym = *I;
Anna Zaksbf53dfa2012-12-20 00:38:25 +00001551
Anna Zaks5b7aa342012-06-22 02:04:31 +00001552 if (const RefState *RS = State->get<RegionState>(sym)) {
1553 if (RS->isAllocated())
Anna Zaks431e35c2012-08-09 00:42:24 +00001554 State = State->remove<RegionState>(sym);
Anna Zaks5b7aa342012-06-22 02:04:31 +00001555 }
Anna Zaks4fb54872012-02-11 21:02:35 +00001556 }
Anna Zaks66c40402012-02-14 21:55:24 +00001557 return State;
Ted Kremenekdd0e4902010-07-31 01:52:11 +00001558}
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001559
Jordy Rose393f98b2012-03-18 07:43:35 +00001560static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
1561 ProgramStateRef prevState) {
Jordan Rose166d5022012-11-02 01:54:06 +00001562 ReallocPairsTy currMap = currState->get<ReallocPairs>();
1563 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
Jordy Rose393f98b2012-03-18 07:43:35 +00001564
Jordan Rose166d5022012-11-02 01:54:06 +00001565 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
Jordy Rose393f98b2012-03-18 07:43:35 +00001566 I != E; ++I) {
1567 SymbolRef sym = I.getKey();
1568 if (!currMap.lookup(sym))
1569 return sym;
1570 }
1571
1572 return NULL;
1573}
1574
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001575PathDiagnosticPiece *
1576MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
1577 const ExplodedNode *PrevN,
1578 BugReporterContext &BRC,
1579 BugReport &BR) {
Jordy Rose393f98b2012-03-18 07:43:35 +00001580 ProgramStateRef state = N->getState();
1581 ProgramStateRef statePrev = PrevN->getState();
1582
1583 const RefState *RS = state->get<RegionState>(Sym);
1584 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
Anna Zaksede875b2012-08-03 18:30:18 +00001585 if (!RS)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001586 return 0;
1587
Anna Zaksfe571602012-02-16 22:26:07 +00001588 const Stmt *S = 0;
1589 const char *Msg = 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001590 StackHintGeneratorForSymbol *StackHint = 0;
Anna Zaksfe571602012-02-16 22:26:07 +00001591
1592 // Retrieve the associated statement.
1593 ProgramPoint ProgLoc = N->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +00001594 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001595 S = SP->getStmt();
David Blaikie7a95de62013-02-21 22:23:56 +00001596 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
Jordan Rose852aa0d2012-07-10 22:07:52 +00001597 S = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +00001598 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
Ted Kremeneka4a17592013-01-04 19:04:36 +00001599 // If an assumption was made on a branch, it should be caught
1600 // here by looking at the state transition.
1601 S = Edge->getSrc()->getTerminator();
Anna Zaksfe571602012-02-16 22:26:07 +00001602 }
Ted Kremeneka4a17592013-01-04 19:04:36 +00001603
Anna Zaksfe571602012-02-16 22:26:07 +00001604 if (!S)
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001605 return 0;
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001606
Jordan Rose28038f32012-07-10 22:07:42 +00001607 // FIXME: We will eventually need to handle non-statement-based events
1608 // (__attribute__((cleanup))).
1609
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001610 // Find out if this is an interesting point and what is the kind.
Anna Zaksfe571602012-02-16 22:26:07 +00001611 if (Mode == Normal) {
Anna Zaks368a0d52012-03-15 21:13:02 +00001612 if (isAllocated(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001613 Msg = "Memory is allocated";
Anna Zaksfbd58742012-03-16 23:44:28 +00001614 StackHint = new StackHintGeneratorForSymbol(Sym,
1615 "Returned allocated memory");
Anna Zaks368a0d52012-03-15 21:13:02 +00001616 } else if (isReleased(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001617 Msg = "Memory is released";
Anna Zaksfbd58742012-03-16 23:44:28 +00001618 StackHint = new StackHintGeneratorForSymbol(Sym,
1619 "Returned released memory");
Anna Zaks5b7aa342012-06-22 02:04:31 +00001620 } else if (isRelinquished(RS, RSPrev, S)) {
1621 Msg = "Memory ownership is transfered";
1622 StackHint = new StackHintGeneratorForSymbol(Sym, "");
Anna Zaks368a0d52012-03-15 21:13:02 +00001623 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
Anna Zaksfe571602012-02-16 22:26:07 +00001624 Mode = ReallocationFailed;
1625 Msg = "Reallocation failed";
Anna Zaks56a938f2012-03-16 23:24:20 +00001626 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
Anna Zaksfbd58742012-03-16 23:44:28 +00001627 "Reallocation failed");
Jordy Rose393f98b2012-03-18 07:43:35 +00001628
Jordy Roseb000fb52012-03-24 03:15:09 +00001629 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
1630 // Is it possible to fail two reallocs WITHOUT testing in between?
1631 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
1632 "We only support one failed realloc at a time.");
Jordy Rose393f98b2012-03-18 07:43:35 +00001633 BR.markInteresting(sym);
Jordy Roseb000fb52012-03-24 03:15:09 +00001634 FailedReallocSymbol = sym;
1635 }
Anna Zaksfe571602012-02-16 22:26:07 +00001636 }
1637
1638 // We are in a special mode if a reallocation failed later in the path.
1639 } else if (Mode == ReallocationFailed) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001640 assert(FailedReallocSymbol && "No symbol to look for.");
Anna Zaksfe571602012-02-16 22:26:07 +00001641
Jordy Roseb000fb52012-03-24 03:15:09 +00001642 // Is this is the first appearance of the reallocated symbol?
1643 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
Jordy Roseb000fb52012-03-24 03:15:09 +00001644 // We're at the reallocation point.
1645 Msg = "Attempt to reallocate memory";
1646 StackHint = new StackHintGeneratorForSymbol(Sym,
1647 "Returned reallocated memory");
1648 FailedReallocSymbol = NULL;
1649 Mode = Normal;
1650 }
Anna Zaksfe571602012-02-16 22:26:07 +00001651 }
1652
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001653 if (!Msg)
1654 return 0;
Anna Zaks56a938f2012-03-16 23:24:20 +00001655 assert(StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001656
1657 // Generate the extra diagnostic.
Anna Zaksfe571602012-02-16 22:26:07 +00001658 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001659 N->getLocationContext());
Anna Zaks56a938f2012-03-16 23:24:20 +00001660 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001661}
1662
Anna Zaks93c5a242012-05-02 00:05:20 +00001663void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
1664 const char *NL, const char *Sep) const {
1665
1666 RegionStateTy RS = State->get<RegionState>();
1667
Ted Kremenekc37fad62013-01-03 01:30:12 +00001668 if (!RS.isEmpty()) {
1669 Out << Sep << "MallocChecker:" << NL;
1670 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1671 I.getKey()->dumpToStream(Out);
1672 Out << " : ";
1673 I.getData().dump(Out);
1674 Out << NL;
1675 }
1676 }
Anna Zaks93c5a242012-05-02 00:05:20 +00001677}
Anna Zaksff3b9fd2012-02-09 06:25:51 +00001678
Anna Zaks231361a2012-02-08 23:16:52 +00001679#define REGISTER_CHECKER(name) \
1680void ento::register##name(CheckerManager &mgr) {\
Anna Zaksf0dfc9c2012-02-17 22:35:31 +00001681 registerCStringCheckerBasic(mgr); \
Anna Zaks231361a2012-02-08 23:16:52 +00001682 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
Argyrios Kyrtzidis312dbec2011-02-28 01:26:35 +00001683}
Anna Zaks231361a2012-02-08 23:16:52 +00001684
1685REGISTER_CHECKER(MallocPessimistic)
1686REGISTER_CHECKER(MallocOptimistic)