1 //===- ObjCSuperDeallocChecker.cpp - Check correct use of [super dealloc] -===//
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
7 //===----------------------------------------------------------------------===//
9 // This defines ObjCSuperDeallocChecker, a builtin check that warns when
10 // self is used after a call to [super dealloc] in MRR mode.
12 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
16 #include "clang/StaticAnalyzer/Core/Checker.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
22 using namespace clang
;
26 class 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
;
33 const BugType DoubleSuperDeallocBugType
{
34 this, "[super dealloc] should not be called more than once",
35 categories::CoreFoundationObjectiveC
};
37 void initIdentifierInfoAndSelectors(ASTContext
&Ctx
) const;
39 bool isSuperDeallocMessage(const ObjCMethodCall
&M
) const;
42 void checkPostObjCMessage(const ObjCMethodCall
&M
, CheckerContext
&C
) const;
43 void checkPreObjCMessage(const ObjCMethodCall
&M
, CheckerContext
&C
) const;
45 void checkPreCall(const CallEvent
&Call
, CheckerContext
&C
) const;
47 void checkLocation(SVal l
, bool isLoad
, const Stmt
*S
,
48 CheckerContext
&C
) const;
52 void diagnoseCallArguments(const CallEvent
&CE
, CheckerContext
&C
) const;
54 void reportUseAfterDealloc(SymbolRef Sym
, StringRef Desc
, const Stmt
*S
,
55 CheckerContext
&C
) const;
58 } // End anonymous namespace.
60 // Remember whether [super dealloc] has previously been called on the
61 // SymbolRef for the receiver.
62 REGISTER_SET_WITH_PROGRAMSTATE(CalledSuperDealloc
, SymbolRef
)
65 class SuperDeallocBRVisitor final
: public BugReporterVisitor
{
66 SymbolRef ReceiverSymbol
;
70 SuperDeallocBRVisitor(SymbolRef ReceiverSymbol
)
71 : ReceiverSymbol(ReceiverSymbol
), Satisfied(false) {}
73 PathDiagnosticPieceRef
VisitNode(const ExplodedNode
*Succ
,
74 BugReporterContext
&BRC
,
75 PathSensitiveBugReport
&BR
) override
;
77 void Profile(llvm::FoldingSetNodeID
&ID
) const override
{
78 ID
.Add(ReceiverSymbol
);
81 } // End anonymous namespace.
83 void ObjCSuperDeallocChecker::checkPreObjCMessage(const ObjCMethodCall
&M
,
84 CheckerContext
&C
) const {
86 ProgramStateRef State
= C
.getState();
87 SymbolRef ReceiverSymbol
= M
.getReceiverSVal().getAsSymbol();
88 if (!ReceiverSymbol
) {
89 diagnoseCallArguments(M
, C
);
93 bool AlreadyCalled
= State
->contains
<CalledSuperDealloc
>(ReceiverSymbol
);
99 if (isSuperDeallocMessage(M
)) {
100 Desc
= "[super dealloc] should not be called multiple times";
105 reportUseAfterDealloc(ReceiverSymbol
, Desc
, M
.getOriginExpr(), C
);
108 void ObjCSuperDeallocChecker::checkPreCall(const CallEvent
&Call
,
109 CheckerContext
&C
) const {
110 diagnoseCallArguments(Call
, C
);
113 void ObjCSuperDeallocChecker::checkPostObjCMessage(const ObjCMethodCall
&M
,
114 CheckerContext
&C
) const {
115 // Check for [super dealloc] method call.
116 if (!isSuperDeallocMessage(M
))
119 ProgramStateRef State
= C
.getState();
120 const LocationContext
*LC
= C
.getLocationContext();
121 SymbolRef SelfSymbol
= State
->getSelfSVal(LC
).getAsSymbol();
122 assert(SelfSymbol
&& "No receiver symbol at call to [super dealloc]?");
124 // We add this transition in checkPostObjCMessage to avoid warning when
125 // we inline a call to [super dealloc] where the inlined call itself
126 // calls [super dealloc].
127 State
= State
->add
<CalledSuperDealloc
>(SelfSymbol
);
128 C
.addTransition(State
);
131 void ObjCSuperDeallocChecker::checkLocation(SVal L
, bool IsLoad
, const Stmt
*S
,
132 CheckerContext
&C
) const {
133 SymbolRef BaseSym
= L
.getLocSymbolInBase();
137 ProgramStateRef State
= C
.getState();
139 if (!State
->contains
<CalledSuperDealloc
>(BaseSym
))
142 const MemRegion
*R
= L
.getAsRegion();
146 // Climb the super regions to find the base symbol while recording
147 // the second-to-last region for error reporting.
148 const MemRegion
*PriorSubRegion
= nullptr;
149 while (const SubRegion
*SR
= dyn_cast
<SubRegion
>(R
)) {
150 if (const SymbolicRegion
*SymR
= dyn_cast
<SymbolicRegion
>(SR
)) {
151 BaseSym
= SymR
->getSymbol();
154 R
= SR
->getSuperRegion();
159 StringRef Desc
= StringRef();
160 auto *IvarRegion
= dyn_cast_or_null
<ObjCIvarRegion
>(PriorSubRegion
);
163 llvm::raw_string_ostream
OS(Buf
);
165 OS
<< "Use of instance variable '" << *IvarRegion
->getDecl() <<
166 "' after 'self' has been deallocated";
170 reportUseAfterDealloc(BaseSym
, Desc
, S
, C
);
173 /// Report a use-after-dealloc on Sym. If not empty,
174 /// Desc will be used to describe the error; otherwise,
175 /// a default warning will be used.
176 void ObjCSuperDeallocChecker::reportUseAfterDealloc(SymbolRef Sym
,
179 CheckerContext
&C
) const {
180 // We have a use of self after free.
181 // This likely causes a crash, so stop exploring the
182 // path by generating a sink.
183 ExplodedNode
*ErrNode
= C
.generateErrorNode();
184 // If we've already reached this node on another path, return.
189 Desc
= "Use of 'self' after it has been deallocated";
191 // Generate the report.
192 auto BR
= std::make_unique
<PathSensitiveBugReport
>(DoubleSuperDeallocBugType
,
194 BR
->addRange(S
->getSourceRange());
195 BR
->addVisitor(std::make_unique
<SuperDeallocBRVisitor
>(Sym
));
196 C
.emitReport(std::move(BR
));
199 /// Diagnose if any of the arguments to CE have already been
201 void ObjCSuperDeallocChecker::diagnoseCallArguments(const CallEvent
&CE
,
202 CheckerContext
&C
) const {
203 ProgramStateRef State
= C
.getState();
204 unsigned ArgCount
= CE
.getNumArgs();
205 for (unsigned I
= 0; I
< ArgCount
; I
++) {
206 SymbolRef Sym
= CE
.getArgSVal(I
).getAsSymbol();
210 if (State
->contains
<CalledSuperDealloc
>(Sym
)) {
211 reportUseAfterDealloc(Sym
, StringRef(), CE
.getArgExpr(I
), C
);
218 ObjCSuperDeallocChecker::initIdentifierInfoAndSelectors(ASTContext
&Ctx
) const {
222 IIdealloc
= &Ctx
.Idents
.get("dealloc");
223 IINSObject
= &Ctx
.Idents
.get("NSObject");
225 SELdealloc
= Ctx
.Selectors
.getSelector(0, &IIdealloc
);
229 ObjCSuperDeallocChecker::isSuperDeallocMessage(const ObjCMethodCall
&M
) const {
230 if (M
.getOriginExpr()->getReceiverKind() != ObjCMessageExpr::SuperInstance
)
233 ASTContext
&Ctx
= M
.getState()->getStateManager().getContext();
234 initIdentifierInfoAndSelectors(Ctx
);
236 return M
.getSelector() == SELdealloc
;
239 PathDiagnosticPieceRef
240 SuperDeallocBRVisitor::VisitNode(const ExplodedNode
*Succ
,
241 BugReporterContext
&BRC
,
242 PathSensitiveBugReport
&) {
246 ProgramStateRef State
= Succ
->getState();
249 Succ
->getState()->contains
<CalledSuperDealloc
>(ReceiverSymbol
);
251 Succ
->getFirstPred()->getState()->contains
<CalledSuperDealloc
>(
254 // Is Succ the node on which the analyzer noted that [super dealloc] was
255 // called on ReceiverSymbol?
256 if (CalledNow
&& !CalledBefore
) {
259 ProgramPoint P
= Succ
->getLocation();
260 PathDiagnosticLocation L
=
261 PathDiagnosticLocation::create(P
, BRC
.getSourceManager());
263 if (!L
.isValid() || !L
.asLocation().isValid())
266 return std::make_shared
<PathDiagnosticEventPiece
>(
267 L
, "[super dealloc] called here");
273 //===----------------------------------------------------------------------===//
274 // Checker Registration.
275 //===----------------------------------------------------------------------===//
277 void ento::registerObjCSuperDeallocChecker(CheckerManager
&Mgr
) {
278 Mgr
.registerChecker
<ObjCSuperDeallocChecker
>();
281 bool ento::shouldRegisterObjCSuperDeallocChecker(const CheckerManager
&mgr
) {