blob: ddb4a9e36e2d15a90bf44e256bf182f551586dc4 [file] [log] [blame]
George Karpenkov70c2ee32018-08-17 21:41:07 +00001//==--- RetainCountChecker.h - Checks for leaks and other issues -*- 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 the methods for RetainCountChecker, which implements
11// a reference count checker for Core Foundation and Cocoa on (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_LIB_STATICANALYZER_CHECKERS_RETAINCOUNTCHECKER_H
16#define LLVM_CLANG_LIB_STATICANALYZER_CHECKERS_RETAINCOUNTCHECKER_H
17
Kristof Umann76a21502018-12-15 16:23:51 +000018#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
George Karpenkov70c2ee32018-08-17 21:41:07 +000019#include "RetainCountDiagnostics.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/ParentMap.h"
24#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/SourceManager.h"
George Karpenkovefef49c2018-08-21 03:09:02 +000027#include "clang/Analysis/SelectorExtras.h"
George Karpenkov70c2ee32018-08-17 21:41:07 +000028#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
29#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
30#include "clang/StaticAnalyzer/Core/Checker.h"
31#include "clang/StaticAnalyzer/Core/CheckerManager.h"
32#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
33#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
34#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
35#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
George Karpenkovefef49c2018-08-21 03:09:02 +000036#include "clang/StaticAnalyzer/Core/RetainSummaryManager.h"
George Karpenkov70c2ee32018-08-17 21:41:07 +000037#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/FoldingSet.h"
39#include "llvm/ADT/ImmutableList.h"
40#include "llvm/ADT/ImmutableMap.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/StringExtras.h"
44#include <cstdarg>
45#include <utility>
46
George Karpenkov70c2ee32018-08-17 21:41:07 +000047namespace clang {
48namespace ento {
49namespace retaincountchecker {
50
51/// Metadata on reference.
52class RefVal {
53public:
54 enum Kind {
55 Owned = 0, // Owning reference.
56 NotOwned, // Reference is not owned by still valid (not freed).
57 Released, // Object has been released.
58 ReturnedOwned, // Returned object passes ownership to caller.
59 ReturnedNotOwned, // Return object does not pass ownership to caller.
60 ERROR_START,
61 ErrorDeallocNotOwned, // -dealloc called on non-owned object.
62 ErrorUseAfterRelease, // Object used after released.
63 ErrorReleaseNotOwned, // Release of an object that was not owned.
64 ERROR_LEAK_START,
65 ErrorLeak, // A memory leak due to excessive reference counts.
66 ErrorLeakReturned, // A memory leak due to the returning method not having
67 // the correct naming conventions.
68 ErrorOverAutorelease,
69 ErrorReturnedNotOwned
70 };
71
72 /// Tracks how an object referenced by an ivar has been used.
73 ///
74 /// This accounts for us not knowing if an arbitrary ivar is supposed to be
75 /// stored at +0 or +1.
76 enum class IvarAccessHistory {
77 None,
78 AccessedDirectly,
79 ReleasedAfterDirectAccess
80 };
81
82private:
83 /// The number of outstanding retains.
84 unsigned Cnt;
85 /// The number of outstanding autoreleases.
86 unsigned ACnt;
87 /// The (static) type of the object at the time we started tracking it.
88 QualType T;
89
90 /// The current state of the object.
91 ///
92 /// See the RefVal::Kind enum for possible values.
93 unsigned RawKind : 5;
94
George Karpenkov27db3302018-12-07 20:21:51 +000095 /// The kind of object being tracked (CF or ObjC or OSObject), if known.
George Karpenkov70c2ee32018-08-17 21:41:07 +000096 ///
George Karpenkov7e3016d2019-01-10 18:13:46 +000097 /// See the ObjKind enum for possible values.
George Karpenkovab0011e2018-08-23 00:26:59 +000098 unsigned RawObjectKind : 3;
George Karpenkov70c2ee32018-08-17 21:41:07 +000099
100 /// True if the current state and/or retain count may turn out to not be the
101 /// best possible approximation of the reference counting state.
102 ///
103 /// If true, the checker may decide to throw away ("override") this state
104 /// in favor of something else when it sees the object being used in new ways.
105 ///
106 /// This setting should not be propagated to state derived from this state.
107 /// Once we start deriving new states, it would be inconsistent to override
108 /// them.
109 unsigned RawIvarAccessHistory : 2;
110
George Karpenkov7e3016d2019-01-10 18:13:46 +0000111 RefVal(Kind k, ObjKind o, unsigned cnt, unsigned acnt, QualType t,
George Karpenkov70c2ee32018-08-17 21:41:07 +0000112 IvarAccessHistory IvarAccess)
113 : Cnt(cnt), ACnt(acnt), T(t), RawKind(static_cast<unsigned>(k)),
114 RawObjectKind(static_cast<unsigned>(o)),
115 RawIvarAccessHistory(static_cast<unsigned>(IvarAccess)) {
116 assert(getKind() == k && "not enough bits for the kind");
117 assert(getObjKind() == o && "not enough bits for the object kind");
118 assert(getIvarAccessHistory() == IvarAccess && "not enough bits");
119 }
120
121public:
122 Kind getKind() const { return static_cast<Kind>(RawKind); }
123
George Karpenkov7e3016d2019-01-10 18:13:46 +0000124 ObjKind getObjKind() const {
125 return static_cast<ObjKind>(RawObjectKind);
George Karpenkov70c2ee32018-08-17 21:41:07 +0000126 }
127
128 unsigned getCount() const { return Cnt; }
129 unsigned getAutoreleaseCount() const { return ACnt; }
130 unsigned getCombinedCounts() const { return Cnt + ACnt; }
131 void clearCounts() {
132 Cnt = 0;
133 ACnt = 0;
134 }
135 void setCount(unsigned i) {
136 Cnt = i;
137 }
138 void setAutoreleaseCount(unsigned i) {
139 ACnt = i;
140 }
141
142 QualType getType() const { return T; }
143
144 /// Returns what the analyzer knows about direct accesses to a particular
145 /// instance variable.
146 ///
147 /// If the object with this refcount wasn't originally from an Objective-C
148 /// ivar region, this should always return IvarAccessHistory::None.
149 IvarAccessHistory getIvarAccessHistory() const {
150 return static_cast<IvarAccessHistory>(RawIvarAccessHistory);
151 }
152
153 bool isOwned() const {
154 return getKind() == Owned;
155 }
156
157 bool isNotOwned() const {
158 return getKind() == NotOwned;
159 }
160
161 bool isReturnedOwned() const {
162 return getKind() == ReturnedOwned;
163 }
164
165 bool isReturnedNotOwned() const {
166 return getKind() == ReturnedNotOwned;
167 }
168
169 /// Create a state for an object whose lifetime is the responsibility of the
170 /// current function, at least partially.
171 ///
172 /// Most commonly, this is an owned object with a retain count of +1.
George Karpenkov7e3016d2019-01-10 18:13:46 +0000173 static RefVal makeOwned(ObjKind o, QualType t) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000174 return RefVal(Owned, o, /*Count=*/1, 0, t, IvarAccessHistory::None);
175 }
176
177 /// Create a state for an object whose lifetime is not the responsibility of
178 /// the current function.
179 ///
180 /// Most commonly, this is an unowned object with a retain count of +0.
George Karpenkov7e3016d2019-01-10 18:13:46 +0000181 static RefVal makeNotOwned(ObjKind o, QualType t) {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000182 return RefVal(NotOwned, o, /*Count=*/0, 0, t, IvarAccessHistory::None);
183 }
184
185 RefVal operator-(size_t i) const {
186 return RefVal(getKind(), getObjKind(), getCount() - i,
187 getAutoreleaseCount(), getType(), getIvarAccessHistory());
188 }
189
190 RefVal operator+(size_t i) const {
191 return RefVal(getKind(), getObjKind(), getCount() + i,
192 getAutoreleaseCount(), getType(), getIvarAccessHistory());
193 }
194
195 RefVal operator^(Kind k) const {
196 return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
197 getType(), getIvarAccessHistory());
198 }
199
200 RefVal autorelease() const {
201 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
202 getType(), getIvarAccessHistory());
203 }
204
205 RefVal withIvarAccess() const {
206 assert(getIvarAccessHistory() == IvarAccessHistory::None);
207 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount(),
208 getType(), IvarAccessHistory::AccessedDirectly);
209 }
210
211 RefVal releaseViaIvar() const {
212 assert(getIvarAccessHistory() == IvarAccessHistory::AccessedDirectly);
213 return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount(),
214 getType(), IvarAccessHistory::ReleasedAfterDirectAccess);
215 }
216
217 // Comparison, profiling, and pretty-printing.
George Karpenkov70c2ee32018-08-17 21:41:07 +0000218 bool hasSameState(const RefVal &X) const {
219 return getKind() == X.getKind() && Cnt == X.Cnt && ACnt == X.ACnt &&
220 getIvarAccessHistory() == X.getIvarAccessHistory();
221 }
222
223 bool operator==(const RefVal& X) const {
224 return T == X.T && hasSameState(X) && getObjKind() == X.getObjKind();
225 }
226
227 void Profile(llvm::FoldingSetNodeID& ID) const {
228 ID.Add(T);
229 ID.AddInteger(RawKind);
230 ID.AddInteger(Cnt);
231 ID.AddInteger(ACnt);
232 ID.AddInteger(RawObjectKind);
233 ID.AddInteger(RawIvarAccessHistory);
234 }
235
236 void print(raw_ostream &Out) const;
237};
238
239class RetainCountChecker
240 : public Checker< check::Bind,
241 check::DeadSymbols,
George Karpenkov70c2ee32018-08-17 21:41:07 +0000242 check::BeginFunction,
243 check::EndFunction,
244 check::PostStmt<BlockExpr>,
245 check::PostStmt<CastExpr>,
246 check::PostStmt<ObjCArrayLiteral>,
247 check::PostStmt<ObjCDictionaryLiteral>,
248 check::PostStmt<ObjCBoxedExpr>,
249 check::PostStmt<ObjCIvarRefExpr>,
250 check::PostCall,
George Karpenkov70c2ee32018-08-17 21:41:07 +0000251 check::RegionChanges,
252 eval::Assume,
253 eval::Call > {
George Karpenkov2c2d0b62019-01-18 19:24:55 +0000254
255 RefCountBug useAfterRelease{this, RefCountBug::UseAfterRelease};
256 RefCountBug releaseNotOwned{this, RefCountBug::ReleaseNotOwned};
257 RefCountBug deallocNotOwned{this, RefCountBug::DeallocNotOwned};
258 RefCountBug freeNotOwned{this, RefCountBug::FreeNotOwned};
259 RefCountBug overAutorelease{this, RefCountBug::OverAutorelease};
260 RefCountBug returnNotOwnedForOwned{this, RefCountBug::ReturnNotOwnedForOwned};
261 RefCountBug leakWithinFunction{this, RefCountBug::LeakWithinFunction};
262 RefCountBug leakAtReturn{this, RefCountBug::LeakAtReturn};
George Karpenkov70c2ee32018-08-17 21:41:07 +0000263
George Karpenkov70c2ee32018-08-17 21:41:07 +0000264 mutable std::unique_ptr<RetainSummaryManager> Summaries;
Kristof Umannc83b0dd2018-11-02 15:48:10 +0000265public:
George Karpenkov717c4c02019-01-10 18:15:17 +0000266 static constexpr const char *DeallocTagDescription = "DeallocSent";
George Karpenkov27db3302018-12-07 20:21:51 +0000267
268 /// Track Objective-C and CoreFoundation objects.
269 bool TrackObjCAndCFObjects = false;
270
271 /// Track sublcasses of OSObject.
272 bool TrackOSObjects = false;
George Karpenkov70c2ee32018-08-17 21:41:07 +0000273
George Karpenkov2c2d0b62019-01-18 19:24:55 +0000274 RetainCountChecker() {};
George Karpenkov70c2ee32018-08-17 21:41:07 +0000275
276 RetainSummaryManager &getSummaryManager(ASTContext &Ctx) const {
277 // FIXME: We don't support ARC being turned on and off during one analysis.
278 // (nor, for that matter, do we support changing ASTContexts)
279 bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
George Karpenkovab0011e2018-08-23 00:26:59 +0000280 if (!Summaries) {
281 Summaries.reset(new RetainSummaryManager(
George Karpenkov27db3302018-12-07 20:21:51 +0000282 Ctx, ARCEnabled, TrackObjCAndCFObjects, TrackOSObjects));
George Karpenkovab0011e2018-08-23 00:26:59 +0000283 } else {
George Karpenkov70c2ee32018-08-17 21:41:07 +0000284 assert(Summaries->isARCEnabled() == ARCEnabled);
George Karpenkovab0011e2018-08-23 00:26:59 +0000285 }
George Karpenkov70c2ee32018-08-17 21:41:07 +0000286 return *Summaries;
287 }
288
289 RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
290 return getSummaryManager(C.getASTContext());
291 }
292
293 void printState(raw_ostream &Out, ProgramStateRef State,
294 const char *NL, const char *Sep) const override;
295
296 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
297 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
298 void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
299
300 void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
301 void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
302 void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
303
304 void checkPostStmt(const ObjCIvarRefExpr *IRE, CheckerContext &C) const;
305
306 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
307
308 void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
309 CheckerContext &C) const;
310
311 void processSummaryOfInlined(const RetainSummary &Summ,
312 const CallEvent &Call,
313 CheckerContext &C) const;
314
315 bool evalCall(const CallExpr *CE, CheckerContext &C) const;
316
317 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
318 bool Assumption) const;
319
320 ProgramStateRef
321 checkRegionChanges(ProgramStateRef state,
322 const InvalidatedSymbols *invalidated,
323 ArrayRef<const MemRegion *> ExplicitRegions,
324 ArrayRef<const MemRegion *> Regions,
325 const LocationContext* LCtx,
326 const CallEvent *Call) const;
327
George Karpenkov04553e52018-09-21 20:37:20 +0000328 ExplodedNode* checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
George Karpenkov70c2ee32018-08-17 21:41:07 +0000329 ExplodedNode *Pred, RetEffect RE, RefVal X,
330 SymbolRef Sym, ProgramStateRef state) const;
331
332 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
333 void checkBeginFunction(CheckerContext &C) const;
334 void checkEndFunction(const ReturnStmt *RS, CheckerContext &C) const;
335
336 ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
George Karpenkov9cbcc212019-01-10 18:14:12 +0000337 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
George Karpenkov70c2ee32018-08-17 21:41:07 +0000338 CheckerContext &C) const;
339
George Karpenkov2c2d0b62019-01-18 19:24:55 +0000340 const RefCountBug &errorKindToBugKind(RefVal::Kind ErrorKind,
341 SymbolRef Sym) const;
342
George Karpenkov70c2ee32018-08-17 21:41:07 +0000343 void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
344 RefVal::Kind ErrorKind, SymbolRef Sym,
345 CheckerContext &C) const;
346
347 void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
348
George Karpenkov70c2ee32018-08-17 21:41:07 +0000349 ProgramStateRef handleSymbolDeath(ProgramStateRef state,
350 SymbolRef sid, RefVal V,
351 SmallVectorImpl<SymbolRef> &Leaked) const;
352
353 ProgramStateRef
354 handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
355 const ProgramPointTag *Tag, CheckerContext &Ctx,
George Karpenkov04553e52018-09-21 20:37:20 +0000356 SymbolRef Sym,
357 RefVal V,
358 const ReturnStmt *S=nullptr) const;
George Karpenkov70c2ee32018-08-17 21:41:07 +0000359
360 ExplodedNode *processLeaks(ProgramStateRef state,
361 SmallVectorImpl<SymbolRef> &Leaked,
362 CheckerContext &Ctx,
363 ExplodedNode *Pred = nullptr) const;
George Karpenkov04553e52018-09-21 20:37:20 +0000364
365private:
366 /// Perform the necessary checks and state adjustments at the end of the
367 /// function.
368 /// \p S Return statement, may be null.
369 ExplodedNode * processReturn(const ReturnStmt *S, CheckerContext &C) const;
George Karpenkov70c2ee32018-08-17 21:41:07 +0000370};
371
372//===----------------------------------------------------------------------===//
373// RefBindings - State used to track object reference counts.
374//===----------------------------------------------------------------------===//
375
376const RefVal *getRefBinding(ProgramStateRef State, SymbolRef Sym);
377
George Karpenkov70c2ee32018-08-17 21:41:07 +0000378/// Returns true if this stack frame is for an Objective-C method that is a
379/// property getter or setter whose body has been synthesized by the analyzer.
380inline bool isSynthesizedAccessor(const StackFrameContext *SFC) {
381 auto Method = dyn_cast_or_null<ObjCMethodDecl>(SFC->getDecl());
382 if (!Method || !Method->isPropertyAccessor())
383 return false;
384
385 return SFC->getAnalysisDeclContext()->isBodyAutosynthesized();
386}
387
388} // end namespace retaincountchecker
389} // end namespace ento
390} // end namespace clang
391
392#endif