clang 23.0.0git
ObjCSuperDeallocChecker.cpp
Go to the documentation of this file.
1//===- ObjCSuperDeallocChecker.cpp - Check correct use of [super dealloc] -===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This defines ObjCSuperDeallocChecker, a builtin check that warns when
10// self is used after a call to [super dealloc] in MRR mode.
11//
12//===----------------------------------------------------------------------===//
13
21
22using namespace clang;
23using namespace ento;
24
25namespace {
26class ObjCSuperDeallocChecker
27 : public Checker<check::PostObjCMessage, check::PreObjCMessage,
28 check::PreCall, check::Location> {
29 mutable const IdentifierInfo *IIdealloc = nullptr;
30 mutable const IdentifierInfo *IINSObject = nullptr;
31 mutable Selector SELdealloc;
32
33 const BugType DoubleSuperDeallocBugType{
34 this, "[super dealloc] should not be called more than once",
36
37 void initIdentifierInfoAndSelectors(const ASTContext &Ctx) const;
38
39 bool isSuperDeallocMessage(const ObjCMethodCall &M) const;
40
41public:
42 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
43 void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
44
45 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
46
47 void checkLocation(SVal l, bool isLoad, const Stmt *S,
48 CheckerContext &C) const;
49
50private:
51
52 void diagnoseCallArguments(const CallEvent &CE, CheckerContext &C) const;
53
54 void reportUseAfterDealloc(SymbolRef Sym, StringRef Desc, const Stmt *S,
55 CheckerContext &C) const;
56};
57
58} // End anonymous namespace.
59
60// Remember whether [super dealloc] has previously been called on the
61// SymbolRef for the receiver.
63
64namespace {
65class SuperDeallocBRVisitor final : public BugReporterVisitor {
66 SymbolRef ReceiverSymbol;
67 bool Satisfied;
68
69public:
70 SuperDeallocBRVisitor(SymbolRef ReceiverSymbol)
71 : ReceiverSymbol(ReceiverSymbol), Satisfied(false) {}
72
73 PathDiagnosticPieceRef VisitNode(const ExplodedNode *Succ,
74 BugReporterContext &BRC,
75 PathSensitiveBugReport &BR) override;
76
77 void Profile(llvm::FoldingSetNodeID &ID) const override {
78 ID.Add(ReceiverSymbol);
79 }
80};
81} // End anonymous namespace.
82
83void ObjCSuperDeallocChecker::checkPreObjCMessage(const ObjCMethodCall &M,
84 CheckerContext &C) const {
85
86 ProgramStateRef State = C.getState();
87 SymbolRef ReceiverSymbol = M.getReceiverSVal().getAsSymbol();
88 if (!ReceiverSymbol) {
89 diagnoseCallArguments(M, C);
90 return;
91 }
92
93 bool AlreadyCalled = State->contains<CalledSuperDealloc>(ReceiverSymbol);
94 if (!AlreadyCalled)
95 return;
96
97 StringRef Desc;
98
99 if (isSuperDeallocMessage(M)) {
100 Desc = "[super dealloc] should not be called multiple times";
101 } else {
102 Desc = StringRef();
103 }
104
105 reportUseAfterDealloc(ReceiverSymbol, Desc, M.getOriginExpr(), C);
106}
107
108void ObjCSuperDeallocChecker::checkPreCall(const CallEvent &Call,
109 CheckerContext &C) const {
110 diagnoseCallArguments(Call, C);
111}
112
113void ObjCSuperDeallocChecker::checkPostObjCMessage(const ObjCMethodCall &M,
114 CheckerContext &C) const {
115 // Check for [super dealloc] method call.
116 if (!isSuperDeallocMessage(M))
117 return;
118
119 ProgramStateRef State = C.getState();
120 SymbolRef SelfSymbol = State->getSelfSVal(C.getStackFrame()).getAsSymbol();
121 assert(SelfSymbol && "No receiver symbol at call to [super dealloc]?");
122
123 // We add this transition in checkPostObjCMessage to avoid warning when
124 // we inline a call to [super dealloc] where the inlined call itself
125 // calls [super dealloc].
126 State = State->add<CalledSuperDealloc>(SelfSymbol);
127 C.addTransition(State);
128}
129
130void ObjCSuperDeallocChecker::checkLocation(SVal L, bool IsLoad, const Stmt *S,
131 CheckerContext &C) const {
132 SymbolRef BaseSym = L.getLocSymbolInBase();
133 if (!BaseSym)
134 return;
135
136 ProgramStateRef State = C.getState();
137
138 if (!State->contains<CalledSuperDealloc>(BaseSym))
139 return;
140
141 const MemRegion *R = L.getAsRegion();
142 if (!R)
143 return;
144
145 // Climb the super regions to find the base symbol while recording
146 // the second-to-last region for error reporting.
147 const MemRegion *PriorSubRegion = nullptr;
148 while (const SubRegion *SR = dyn_cast<SubRegion>(R)) {
149 if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(SR)) {
150 BaseSym = SymR->getSymbol();
151 break;
152 } else {
153 R = SR->getSuperRegion();
154 PriorSubRegion = SR;
155 }
156 }
157
158 StringRef Desc = StringRef();
159 auto *IvarRegion = dyn_cast_or_null<ObjCIvarRegion>(PriorSubRegion);
160
161 std::string Buf;
162 llvm::raw_string_ostream OS(Buf);
163 if (IvarRegion) {
164 OS << "Use of instance variable '" << *IvarRegion->getDecl() <<
165 "' after 'self' has been deallocated";
166 Desc = Buf;
167 }
168
169 reportUseAfterDealloc(BaseSym, Desc, S, C);
170}
171
172/// Report a use-after-dealloc on Sym. If not empty,
173/// Desc will be used to describe the error; otherwise,
174/// a default warning will be used.
175void ObjCSuperDeallocChecker::reportUseAfterDealloc(SymbolRef Sym,
176 StringRef Desc,
177 const Stmt *S,
178 CheckerContext &C) const {
179 // We have a use of self after free.
180 // This likely causes a crash, so stop exploring the
181 // path by generating a sink.
182 ExplodedNode *ErrNode = C.generateErrorNode();
183 // If we've already reached this node on another path, return.
184 if (!ErrNode)
185 return;
186
187 if (Desc.empty())
188 Desc = "Use of 'self' after it has been deallocated";
189
190 // Generate the report.
191 auto BR = std::make_unique<PathSensitiveBugReport>(DoubleSuperDeallocBugType,
192 Desc, ErrNode);
193 BR->addRange(S->getSourceRange());
194 BR->addVisitor(std::make_unique<SuperDeallocBRVisitor>(Sym));
195 C.emitReport(std::move(BR));
196}
197
198/// Diagnose if any of the arguments to CE have already been
199/// dealloc'd.
200void ObjCSuperDeallocChecker::diagnoseCallArguments(const CallEvent &CE,
201 CheckerContext &C) const {
202 ProgramStateRef State = C.getState();
203 unsigned ArgCount = CE.getNumArgs();
204 for (unsigned I = 0; I < ArgCount; I++) {
205 SymbolRef Sym = CE.getArgSVal(I).getAsSymbol();
206 if (!Sym)
207 continue;
208
209 if (State->contains<CalledSuperDealloc>(Sym)) {
210 reportUseAfterDealloc(Sym, StringRef(), CE.getArgExpr(I), C);
211 return;
212 }
213 }
214}
215
216void ObjCSuperDeallocChecker::initIdentifierInfoAndSelectors(
217 const ASTContext &Ctx) const {
218 if (IIdealloc)
219 return;
220
221 IIdealloc = &Ctx.Idents.get("dealloc");
222 IINSObject = &Ctx.Idents.get("NSObject");
223
224 SELdealloc = Ctx.Selectors.getSelector(0, &IIdealloc);
225}
226
227bool
228ObjCSuperDeallocChecker::isSuperDeallocMessage(const ObjCMethodCall &M) const {
230 return false;
231
232 const ASTContext &Ctx = M.getASTContext();
233 initIdentifierInfoAndSelectors(Ctx);
234
235 return M.getSelector() == SELdealloc;
236}
237
239SuperDeallocBRVisitor::VisitNode(const ExplodedNode *Succ,
240 BugReporterContext &BRC,
241 PathSensitiveBugReport &) {
242 if (Satisfied)
243 return nullptr;
244
245 ProgramStateRef State = Succ->getState();
246
247 bool CalledNow =
248 Succ->getState()->contains<CalledSuperDealloc>(ReceiverSymbol);
249 bool CalledBefore =
250 Succ->getFirstPred()->getState()->contains<CalledSuperDealloc>(
251 ReceiverSymbol);
252
253 // Is Succ the node on which the analyzer noted that [super dealloc] was
254 // called on ReceiverSymbol?
255 if (CalledNow && !CalledBefore) {
256 Satisfied = true;
257
258 ProgramPoint P = Succ->getLocation();
259 PathDiagnosticLocation L =
261
262 if (!L.isValid() || !L.asLocation().isValid())
263 return nullptr;
264
265 return std::make_shared<PathDiagnosticEventPiece>(
266 L, "[super dealloc] called here");
267 }
268
269 return nullptr;
270}
271
272//===----------------------------------------------------------------------===//
273// Checker Registration.
274//===----------------------------------------------------------------------===//
275
276void ento::registerObjCSuperDeallocChecker(CheckerManager &Mgr) {
277 Mgr.registerChecker<ObjCSuperDeallocChecker>();
278}
279
280bool ento::shouldRegisterObjCSuperDeallocChecker(const CheckerManager &mgr) {
281 return true;
282}
#define REGISTER_SET_WITH_PROGRAMSTATE(Name, Elem)
Declares an immutable set of type NameTy, suitable for placement into the ProgramState.
IdentifierTable & Idents
Definition ASTContext.h:807
SelectorTable & Selectors
Definition ASTContext.h:808
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
@ SuperInstance
The receiver is the instance of the superclass object.
Definition ExprObjC.h:985
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
Definition ExprObjC.h:1260
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
const SourceManager & getSourceManager() const
BugReporterVisitors are used to add custom diagnostics along a path.
virtual SVal getArgSVal(unsigned Index) const
Returns the value of a given argument at the time of the call.
const ASTContext & getASTContext() const
NOTE: There are plans for refactoring that would eliminate this method.
Definition CallEvent.h:245
virtual const Expr * getArgExpr(unsigned Index) const
Returns the expression associated with a given argument.
Definition CallEvent.h:305
virtual unsigned getNumArgs() const =0
Returns the number of arguments (explicit and implicit).
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:550
const ProgramStateRef & getState() const
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
ExplodedNode * getFirstPred()
Represents any expression that calls an Objective-C method.
Definition CallEvent.h:1251
const ObjCMessageExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
Definition CallEvent.h:1276
SVal getReceiverSVal() const
Returns the value of the receiver at the time of this call.
Selector getSelector() const
Definition CallEvent.h:1298
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
Definition SVals.cpp:103
const MemRegion * getAsRegion() const
Definition SVals.cpp:119
SymbolRef getLocSymbolInBase() const
Get the symbol in the SVal or its base region.
Definition SVals.cpp:79
const char *const CoreFoundationObjectiveC
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:133
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
const Fact * ProgramPoint
A ProgramPoint identifies a location in the CFG by pointing to a specific Fact.
Definition Facts.h:91
The JSON file list parser is used to communicate input to InstallAPI.
#define false
Definition stdbool.h:26