1 //===- ObjCSuperDeallocChecker.cpp - Check correct use of [super dealloc] -===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines ObjCSuperDeallocChecker, a builtin check that warns when
11 // self is used after a call to [super dealloc] in MRR mode.
13 //===----------------------------------------------------------------------===//
15 #include "ClangSACheckers.h"
16 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
17 #include "clang/StaticAnalyzer/Core/Checker.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
23 using namespace clang;
27 class ObjCSuperDeallocChecker
28 : public Checker<check::PostObjCMessage, check::PreObjCMessage,
29 check::PreCall, check::Location> {
31 mutable IdentifierInfo *IIdealloc, *IINSObject;
32 mutable Selector SELdealloc;
34 std::unique_ptr<BugType> DoubleSuperDeallocBugType;
36 void initIdentifierInfoAndSelectors(ASTContext &Ctx) const;
38 bool isSuperDeallocMessage(const ObjCMethodCall &M) const;
41 ObjCSuperDeallocChecker();
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
66 : public BugReporterVisitorImpl<SuperDeallocBRVisitor> {
68 SymbolRef ReceiverSymbol;
72 SuperDeallocBRVisitor(SymbolRef ReceiverSymbol)
73 : ReceiverSymbol(ReceiverSymbol),
76 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *Succ,
77 const ExplodedNode *Pred,
78 BugReporterContext &BRC,
79 BugReport &BR) override;
81 void Profile(llvm::FoldingSetNodeID &ID) const override {
82 ID.Add(ReceiverSymbol);
85 } // End anonymous namespace.
87 void ObjCSuperDeallocChecker::checkPreObjCMessage(const ObjCMethodCall &M,
88 CheckerContext &C) const {
90 ProgramStateRef State = C.getState();
91 SymbolRef ReceiverSymbol = M.getReceiverSVal().getAsSymbol();
92 if (!ReceiverSymbol) {
93 diagnoseCallArguments(M, C);
97 bool AlreadyCalled = State->contains<CalledSuperDealloc>(ReceiverSymbol);
103 if (isSuperDeallocMessage(M)) {
104 Desc = "[super dealloc] should not be called multiple times";
109 reportUseAfterDealloc(ReceiverSymbol, Desc, M.getOriginExpr(), C);
114 void ObjCSuperDeallocChecker::checkPreCall(const CallEvent &Call,
115 CheckerContext &C) const {
116 diagnoseCallArguments(Call, C);
119 void ObjCSuperDeallocChecker::checkPostObjCMessage(const ObjCMethodCall &M,
120 CheckerContext &C) const {
121 // Check for [super dealloc] method call.
122 if (!isSuperDeallocMessage(M))
125 ProgramStateRef State = C.getState();
126 SymbolRef ReceiverSymbol = M.getSelfSVal().getAsSymbol();
127 assert(ReceiverSymbol && "No receiver symbol at call to [super dealloc]?");
129 // We add this transition in checkPostObjCMessage to avoid warning when
130 // we inline a call to [super dealloc] where the inlined call itself
131 // calls [super dealloc].
132 State = State->add<CalledSuperDealloc>(ReceiverSymbol);
133 C.addTransition(State);
136 void ObjCSuperDeallocChecker::checkLocation(SVal L, bool IsLoad, const Stmt *S,
137 CheckerContext &C) const {
138 SymbolRef BaseSym = L.getLocSymbolInBase();
142 ProgramStateRef State = C.getState();
144 if (!State->contains<CalledSuperDealloc>(BaseSym))
147 const MemRegion *R = L.getAsRegion();
151 // Climb the super regions to find the base symbol while recording
152 // the second-to-last region for error reporting.
153 const MemRegion *PriorSubRegion = nullptr;
154 while (const SubRegion *SR = dyn_cast<SubRegion>(R)) {
155 if (const SymbolicRegion *SymR = dyn_cast<SymbolicRegion>(SR)) {
156 BaseSym = SymR->getSymbol();
159 R = SR->getSuperRegion();
164 StringRef Desc = StringRef();
165 auto *IvarRegion = dyn_cast_or_null<ObjCIvarRegion>(PriorSubRegion);
168 llvm::raw_string_ostream OS(Buf);
170 OS << "Use of instance variable '" << *IvarRegion->getDecl() <<
171 "' after 'self' has been deallocated";
175 reportUseAfterDealloc(BaseSym, Desc, S, C);
178 /// Report a use-after-dealloc on Sym. If not empty,
179 /// Desc will be used to describe the error; otherwise,
180 /// a default warning will be used.
181 void ObjCSuperDeallocChecker::reportUseAfterDealloc(SymbolRef Sym,
184 CheckerContext &C) const {
185 // We have a use of self after free.
186 // This likely causes a crash, so stop exploring the
187 // path by generating a sink.
188 ExplodedNode *ErrNode = C.generateErrorNode();
189 // If we've already reached this node on another path, return.
194 Desc = "Use of 'self' after it has been deallocated";
196 // Generate the report.
197 std::unique_ptr<BugReport> BR(
198 new BugReport(*DoubleSuperDeallocBugType, Desc, ErrNode));
199 BR->addRange(S->getSourceRange());
200 BR->addVisitor(llvm::make_unique<SuperDeallocBRVisitor>(Sym));
201 C.emitReport(std::move(BR));
204 /// Diagnose if any of the arguments to CE have already been
206 void ObjCSuperDeallocChecker::diagnoseCallArguments(const CallEvent &CE,
207 CheckerContext &C) const {
208 ProgramStateRef State = C.getState();
209 unsigned ArgCount = CE.getNumArgs();
210 for (unsigned I = 0; I < ArgCount; I++) {
211 SymbolRef Sym = CE.getArgSVal(I).getAsSymbol();
215 if (State->contains<CalledSuperDealloc>(Sym)) {
216 reportUseAfterDealloc(Sym, StringRef(), CE.getArgExpr(I), C);
222 ObjCSuperDeallocChecker::ObjCSuperDeallocChecker()
223 : IIdealloc(nullptr), IINSObject(nullptr) {
225 DoubleSuperDeallocBugType.reset(
226 new BugType(this, "[super dealloc] should not be called more than once",
227 categories::CoreFoundationObjectiveC));
231 ObjCSuperDeallocChecker::initIdentifierInfoAndSelectors(ASTContext &Ctx) const {
235 IIdealloc = &Ctx.Idents.get("dealloc");
236 IINSObject = &Ctx.Idents.get("NSObject");
238 SELdealloc = Ctx.Selectors.getSelector(0, &IIdealloc);
242 ObjCSuperDeallocChecker::isSuperDeallocMessage(const ObjCMethodCall &M) const {
243 if (M.getOriginExpr()->getReceiverKind() != ObjCMessageExpr::SuperInstance)
246 ASTContext &Ctx = M.getState()->getStateManager().getContext();
247 initIdentifierInfoAndSelectors(Ctx);
249 return M.getSelector() == SELdealloc;
252 std::shared_ptr<PathDiagnosticPiece>
253 SuperDeallocBRVisitor::VisitNode(const ExplodedNode *Succ,
254 const ExplodedNode *Pred,
255 BugReporterContext &BRC, BugReport &BR) {
259 ProgramStateRef State = Succ->getState();
262 Succ->getState()->contains<CalledSuperDealloc>(ReceiverSymbol);
264 Pred->getState()->contains<CalledSuperDealloc>(ReceiverSymbol);
266 // Is Succ the node on which the analyzer noted that [super dealloc] was
267 // called on ReceiverSymbol?
268 if (CalledNow && !CalledBefore) {
271 ProgramPoint P = Succ->getLocation();
272 PathDiagnosticLocation L =
273 PathDiagnosticLocation::create(P, BRC.getSourceManager());
275 if (!L.isValid() || !L.asLocation().isValid())
278 return std::make_shared<PathDiagnosticEventPiece>(
279 L, "[super dealloc] called here");
285 //===----------------------------------------------------------------------===//
286 // Checker Registration.
287 //===----------------------------------------------------------------------===//
289 void ento::registerObjCSuperDeallocChecker(CheckerManager &Mgr) {
290 const LangOptions &LangOpts = Mgr.getLangOpts();
291 if (LangOpts.getGC() == LangOptions::GCOnly || LangOpts.ObjCAutoRefCount)
293 Mgr.registerChecker<ObjCSuperDeallocChecker>();