1 //==- CheckObjCDealloc.cpp - Check ObjC -dealloc implementation --*- 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 checker analyzes Objective-C -dealloc methods and their callees
11 // to warn about improper releasing of instance variables that back synthesized
12 // properties. It warns about missing releases in the following cases:
13 // - When a class has a synthesized instance variable for a 'retain' or 'copy'
14 // property and lacks a -dealloc method in its implementation.
15 // - When a class has a synthesized instance variable for a 'retain'/'copy'
16 // property but the ivar is not released in -dealloc by either -release
17 // or by nilling out the property.
18 //
19 // It warns about extra releases in -dealloc (but not in callees) when a
20 // synthesized instance variable is released in the following cases:
21 // - When the property is 'assign' and is not 'readonly'.
22 // - When the property is 'weak'.
23 //
24 // This checker only warns for instance variables synthesized to back
25 // properties. Handling the more general case would require inferring whether
26 // an instance variable is stored retained or not. For synthesized properties,
27 // this is specified in the property declaration itself.
28 //
29 //===----------------------------------------------------------------------===//
30
31 #include "ClangSACheckers.h"
32 #include "clang/AST/Attr.h"
33 #include "clang/AST/DeclObjC.h"
34 #include "clang/AST/Expr.h"
35 #include "clang/AST/ExprObjC.h"
36 #include "clang/Basic/LangOptions.h"
37 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
38 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
39 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
40 #include "clang/StaticAnalyzer/Core/Checker.h"
41 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
42 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
43 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
44 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
45 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
46 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
47 #include "llvm/Support/raw_ostream.h"
48
49 using namespace clang;
50 using namespace ento;
51
52 /// Indicates whether an instance variable is required to be released in
53 /// -dealloc.
54 enum class ReleaseRequirement {
55 /// The instance variable must be released, either by calling
56 /// -release on it directly or by nilling it out with a property setter.
57 MustRelease,
58
59 /// The instance variable must not be directly released with -release.
60 MustNotReleaseDirectly,
61
62 /// The requirement for the instance variable could not be determined.
63 Unknown
64 };
65
66 /// Returns true if the property implementation is synthesized and the
67 /// type of the property is retainable.
isSynthesizedRetainableProperty(const ObjCPropertyImplDecl * I,const ObjCIvarDecl ** ID,const ObjCPropertyDecl ** PD)68 static bool isSynthesizedRetainableProperty(const ObjCPropertyImplDecl *I,
69 const ObjCIvarDecl **ID,
70 const ObjCPropertyDecl **PD) {
71
72 if (I->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize)
73 return false;
74
75 (*ID) = I->getPropertyIvarDecl();
76 if (!(*ID))
77 return false;
78
79 QualType T = (*ID)->getType();
80 if (!T->isObjCRetainableType())
81 return false;
82
83 (*PD) = I->getPropertyDecl();
84 // Shouldn't be able to synthesize a property that doesn't exist.
85 assert(*PD);
86
87 return true;
88 }
89
90 namespace {
91
92 class ObjCDeallocChecker
93 : public Checker<check::ASTDecl<ObjCImplementationDecl>,
94 check::PreObjCMessage, check::PostObjCMessage,
95 check::PreCall,
96 check::BeginFunction, check::EndFunction,
97 eval::Assume,
98 check::PointerEscape,
99 check::PreStmt<ReturnStmt>> {
100
101 mutable IdentifierInfo *NSObjectII, *SenTestCaseII, *XCTestCaseII,
102 *Block_releaseII, *CIFilterII;
103
104 mutable Selector DeallocSel, ReleaseSel;
105
106 std::unique_ptr<BugType> MissingReleaseBugType;
107 std::unique_ptr<BugType> ExtraReleaseBugType;
108 std::unique_ptr<BugType> MistakenDeallocBugType;
109
110 public:
111 ObjCDeallocChecker();
112
113 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
114 BugReporter &BR) const;
115 void checkBeginFunction(CheckerContext &Ctx) const;
116 void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
117 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
118 void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
119
120 ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
121 bool Assumption) const;
122
123 ProgramStateRef checkPointerEscape(ProgramStateRef State,
124 const InvalidatedSymbols &Escaped,
125 const CallEvent *Call,
126 PointerEscapeKind Kind) const;
127 void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
128 void checkEndFunction(CheckerContext &Ctx) const;
129
130 private:
131 void diagnoseMissingReleases(CheckerContext &C) const;
132
133 bool diagnoseExtraRelease(SymbolRef ReleasedValue, const ObjCMethodCall &M,
134 CheckerContext &C) const;
135
136 bool diagnoseMistakenDealloc(SymbolRef DeallocedValue,
137 const ObjCMethodCall &M,
138 CheckerContext &C) const;
139
140 SymbolRef getValueReleasedByNillingOut(const ObjCMethodCall &M,
141 CheckerContext &C) const;
142
143 const ObjCIvarRegion *getIvarRegionForIvarSymbol(SymbolRef IvarSym) const;
144 SymbolRef getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const;
145
146 const ObjCPropertyImplDecl*
147 findPropertyOnDeallocatingInstance(SymbolRef IvarSym,
148 CheckerContext &C) const;
149
150 ReleaseRequirement
151 getDeallocReleaseRequirement(const ObjCPropertyImplDecl *PropImpl) const;
152
153 bool isInInstanceDealloc(const CheckerContext &C, SVal &SelfValOut) const;
154 bool isInInstanceDealloc(const CheckerContext &C, const LocationContext *LCtx,
155 SVal &SelfValOut) const;
156 bool instanceDeallocIsOnStack(const CheckerContext &C,
157 SVal &InstanceValOut) const;
158
159 bool isSuperDeallocMessage(const ObjCMethodCall &M) const;
160
161 const ObjCImplDecl *getContainingObjCImpl(const LocationContext *LCtx) const;
162
163 const ObjCPropertyDecl *
164 findShadowedPropertyDecl(const ObjCPropertyImplDecl *PropImpl) const;
165
166 void transitionToReleaseValue(CheckerContext &C, SymbolRef Value) const;
167 ProgramStateRef removeValueRequiringRelease(ProgramStateRef State,
168 SymbolRef InstanceSym,
169 SymbolRef ValueSym) const;
170
171 void initIdentifierInfoAndSelectors(ASTContext &Ctx) const;
172
173 bool classHasSeparateTeardown(const ObjCInterfaceDecl *ID) const;
174
175 bool isReleasedByCIFilterDealloc(const ObjCPropertyImplDecl *PropImpl) const;
176 };
177 } // End anonymous namespace.
178
179 typedef llvm::ImmutableSet<SymbolRef> SymbolSet;
180
181 /// Maps from the symbol for a class instance to the set of
182 /// symbols remaining that must be released in -dealloc.
183 REGISTER_MAP_WITH_PROGRAMSTATE(UnreleasedIvarMap, SymbolRef, SymbolSet)
184
185 namespace clang {
186 namespace ento {
187 template<> struct ProgramStateTrait<SymbolSet>
188 : public ProgramStatePartialTrait<SymbolSet> {
GDMIndexclang::ento::ProgramStateTrait189 static void *GDMIndex() { static int index = 0; return &index; }
190 };
191 }
192 }
193
194 /// An AST check that diagnose when the class requires a -dealloc method and
195 /// is missing one.
checkASTDecl(const ObjCImplementationDecl * D,AnalysisManager & Mgr,BugReporter & BR) const196 void ObjCDeallocChecker::checkASTDecl(const ObjCImplementationDecl *D,
197 AnalysisManager &Mgr,
198 BugReporter &BR) const {
199 assert(Mgr.getLangOpts().getGC() != LangOptions::GCOnly);
200 assert(!Mgr.getLangOpts().ObjCAutoRefCount);
201 initIdentifierInfoAndSelectors(Mgr.getASTContext());
202
203 const ObjCInterfaceDecl *ID = D->getClassInterface();
204 // If the class is known to have a lifecycle with a separate teardown method
205 // then it may not require a -dealloc method.
206 if (classHasSeparateTeardown(ID))
207 return;
208
209 // Does the class contain any synthesized properties that are retainable?
210 // If not, skip the check entirely.
211 const ObjCPropertyImplDecl *PropImplRequiringRelease = nullptr;
212 bool HasOthers = false;
213 for (const auto *I : D->property_impls()) {
214 if (getDeallocReleaseRequirement(I) == ReleaseRequirement::MustRelease) {
215 if (!PropImplRequiringRelease)
216 PropImplRequiringRelease = I;
217 else {
218 HasOthers = true;
219 break;
220 }
221 }
222 }
223
224 if (!PropImplRequiringRelease)
225 return;
226
227 const ObjCMethodDecl *MD = nullptr;
228
229 // Scan the instance methods for "dealloc".
230 for (const auto *I : D->instance_methods()) {
231 if (I->getSelector() == DeallocSel) {
232 MD = I;
233 break;
234 }
235 }
236
237 if (!MD) { // No dealloc found.
238 const char* Name = "Missing -dealloc";
239
240 std::string Buf;
241 llvm::raw_string_ostream OS(Buf);
242 OS << "'" << *D << "' lacks a 'dealloc' instance method but "
243 << "must release '" << *PropImplRequiringRelease->getPropertyIvarDecl()
244 << "'";
245
246 if (HasOthers)
247 OS << " and others";
248 PathDiagnosticLocation DLoc =
249 PathDiagnosticLocation::createBegin(D, BR.getSourceManager());
250
251 BR.EmitBasicReport(D, this, Name, categories::CoreFoundationObjectiveC,
252 OS.str(), DLoc);
253 return;
254 }
255 }
256
257 /// If this is the beginning of -dealloc, mark the values initially stored in
258 /// instance variables that must be released by the end of -dealloc
259 /// as unreleased in the state.
checkBeginFunction(CheckerContext & C) const260 void ObjCDeallocChecker::checkBeginFunction(
261 CheckerContext &C) const {
262 initIdentifierInfoAndSelectors(C.getASTContext());
263
264 // Only do this if the current method is -dealloc.
265 SVal SelfVal;
266 if (!isInInstanceDealloc(C, SelfVal))
267 return;
268
269 SymbolRef SelfSymbol = SelfVal.getAsSymbol();
270
271 const LocationContext *LCtx = C.getLocationContext();
272 ProgramStateRef InitialState = C.getState();
273
274 ProgramStateRef State = InitialState;
275
276 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
277
278 // Symbols that must be released by the end of the -dealloc;
279 SymbolSet RequiredReleases = F.getEmptySet();
280
281 // If we're an inlined -dealloc, we should add our symbols to the existing
282 // set from our subclass.
283 if (const SymbolSet *CurrSet = State->get<UnreleasedIvarMap>(SelfSymbol))
284 RequiredReleases = *CurrSet;
285
286 for (auto *PropImpl : getContainingObjCImpl(LCtx)->property_impls()) {
287 ReleaseRequirement Requirement = getDeallocReleaseRequirement(PropImpl);
288 if (Requirement != ReleaseRequirement::MustRelease)
289 continue;
290
291 SVal LVal = State->getLValue(PropImpl->getPropertyIvarDecl(), SelfVal);
292 Optional<Loc> LValLoc = LVal.getAs<Loc>();
293 if (!LValLoc)
294 continue;
295
296 SVal InitialVal = State->getSVal(LValLoc.getValue());
297 SymbolRef Symbol = InitialVal.getAsSymbol();
298 if (!Symbol || !isa<SymbolRegionValue>(Symbol))
299 continue;
300
301 // Mark the value as requiring a release.
302 RequiredReleases = F.add(RequiredReleases, Symbol);
303 }
304
305 if (!RequiredReleases.isEmpty()) {
306 State = State->set<UnreleasedIvarMap>(SelfSymbol, RequiredReleases);
307 }
308
309 if (State != InitialState) {
310 C.addTransition(State);
311 }
312 }
313
314 /// Given a symbol for an ivar, return the ivar region it was loaded from.
315 /// Returns nullptr if the instance symbol cannot be found.
316 const ObjCIvarRegion *
getIvarRegionForIvarSymbol(SymbolRef IvarSym) const317 ObjCDeallocChecker::getIvarRegionForIvarSymbol(SymbolRef IvarSym) const {
318 return dyn_cast_or_null<ObjCIvarRegion>(IvarSym->getOriginRegion());
319 }
320
321 /// Given a symbol for an ivar, return a symbol for the instance containing
322 /// the ivar. Returns nullptr if the instance symbol cannot be found.
323 SymbolRef
getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const324 ObjCDeallocChecker::getInstanceSymbolFromIvarSymbol(SymbolRef IvarSym) const {
325
326 const ObjCIvarRegion *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
327 if (!IvarRegion)
328 return nullptr;
329
330 return IvarRegion->getSymbolicBase()->getSymbol();
331 }
332
333 /// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
334 /// a release or a nilling-out property setter.
checkPreObjCMessage(const ObjCMethodCall & M,CheckerContext & C) const335 void ObjCDeallocChecker::checkPreObjCMessage(
336 const ObjCMethodCall &M, CheckerContext &C) const {
337 // Only run if -dealloc is on the stack.
338 SVal DeallocedInstance;
339 if (!instanceDeallocIsOnStack(C, DeallocedInstance))
340 return;
341
342 SymbolRef ReleasedValue = nullptr;
343
344 if (M.getSelector() == ReleaseSel) {
345 ReleasedValue = M.getReceiverSVal().getAsSymbol();
346 } else if (M.getSelector() == DeallocSel && !M.isReceiverSelfOrSuper()) {
347 if (diagnoseMistakenDealloc(M.getReceiverSVal().getAsSymbol(), M, C))
348 return;
349 }
350
351 if (ReleasedValue) {
352 // An instance variable symbol was released with -release:
353 // [_property release];
354 if (diagnoseExtraRelease(ReleasedValue,M, C))
355 return;
356 } else {
357 // An instance variable symbol was released nilling out its property:
358 // self.property = nil;
359 ReleasedValue = getValueReleasedByNillingOut(M, C);
360 }
361
362 if (!ReleasedValue)
363 return;
364
365 transitionToReleaseValue(C, ReleasedValue);
366 }
367
368 /// If we are in -dealloc or -dealloc is on the stack, handle the call if it is
369 /// call to Block_release().
checkPreCall(const CallEvent & Call,CheckerContext & C) const370 void ObjCDeallocChecker::checkPreCall(const CallEvent &Call,
371 CheckerContext &C) const {
372 const IdentifierInfo *II = Call.getCalleeIdentifier();
373 if (II != Block_releaseII)
374 return;
375
376 if (Call.getNumArgs() != 1)
377 return;
378
379 SymbolRef ReleasedValue = Call.getArgSVal(0).getAsSymbol();
380 if (!ReleasedValue)
381 return;
382
383 transitionToReleaseValue(C, ReleasedValue);
384 }
385 /// If the message was a call to '[super dealloc]', diagnose any missing
386 /// releases.
checkPostObjCMessage(const ObjCMethodCall & M,CheckerContext & C) const387 void ObjCDeallocChecker::checkPostObjCMessage(
388 const ObjCMethodCall &M, CheckerContext &C) const {
389 // We perform this check post-message so that if the super -dealloc
390 // calls a helper method and that this class overrides, any ivars released in
391 // the helper method will be recorded before checking.
392 if (isSuperDeallocMessage(M))
393 diagnoseMissingReleases(C);
394 }
395
396 /// Check for missing releases even when -dealloc does not call
397 /// '[super dealloc]'.
checkEndFunction(CheckerContext & C) const398 void ObjCDeallocChecker::checkEndFunction(
399 CheckerContext &C) const {
400 diagnoseMissingReleases(C);
401 }
402
403 /// Check for missing releases on early return.
checkPreStmt(const ReturnStmt * RS,CheckerContext & C) const404 void ObjCDeallocChecker::checkPreStmt(
405 const ReturnStmt *RS, CheckerContext &C) const {
406 diagnoseMissingReleases(C);
407 }
408
409 /// When a symbol is assumed to be nil, remove it from the set of symbols
410 /// require to be nil.
evalAssume(ProgramStateRef State,SVal Cond,bool Assumption) const411 ProgramStateRef ObjCDeallocChecker::evalAssume(ProgramStateRef State, SVal Cond,
412 bool Assumption) const {
413 if (State->get<UnreleasedIvarMap>().isEmpty())
414 return State;
415
416 auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymExpr());
417 if (!CondBSE)
418 return State;
419
420 BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
421 if (Assumption) {
422 if (OpCode != BO_EQ)
423 return State;
424 } else {
425 if (OpCode != BO_NE)
426 return State;
427 }
428
429 SymbolRef NullSymbol = nullptr;
430 if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
431 const llvm::APInt &RHS = SIE->getRHS();
432 if (RHS != 0)
433 return State;
434 NullSymbol = SIE->getLHS();
435 } else if (auto *SIE = dyn_cast<IntSymExpr>(CondBSE)) {
436 const llvm::APInt &LHS = SIE->getLHS();
437 if (LHS != 0)
438 return State;
439 NullSymbol = SIE->getRHS();
440 } else {
441 return State;
442 }
443
444 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(NullSymbol);
445 if (!InstanceSymbol)
446 return State;
447
448 State = removeValueRequiringRelease(State, InstanceSymbol, NullSymbol);
449
450 return State;
451 }
452
453 /// If a symbol escapes conservatively assume unseen code released it.
checkPointerEscape(ProgramStateRef State,const InvalidatedSymbols & Escaped,const CallEvent * Call,PointerEscapeKind Kind) const454 ProgramStateRef ObjCDeallocChecker::checkPointerEscape(
455 ProgramStateRef State, const InvalidatedSymbols &Escaped,
456 const CallEvent *Call, PointerEscapeKind Kind) const {
457
458 if (State->get<UnreleasedIvarMap>().isEmpty())
459 return State;
460
461 // Don't treat calls to '[super dealloc]' as escaping for the purposes
462 // of this checker. Because the checker diagnoses missing releases in the
463 // post-message handler for '[super dealloc], escaping here would cause
464 // the checker to never warn.
465 auto *OMC = dyn_cast_or_null<ObjCMethodCall>(Call);
466 if (OMC && isSuperDeallocMessage(*OMC))
467 return State;
468
469 for (const auto &Sym : Escaped) {
470 if (!Call || (Call && !Call->isInSystemHeader())) {
471 // If Sym is a symbol for an object with instance variables that
472 // must be released, remove these obligations when the object escapes
473 // unless via a call to a system function. System functions are
474 // very unlikely to release instance variables on objects passed to them,
475 // and are frequently called on 'self' in -dealloc (e.g., to remove
476 // observers) -- we want to avoid false negatives from escaping on
477 // them.
478 State = State->remove<UnreleasedIvarMap>(Sym);
479 }
480
481
482 SymbolRef InstanceSymbol = getInstanceSymbolFromIvarSymbol(Sym);
483 if (!InstanceSymbol)
484 continue;
485
486 State = removeValueRequiringRelease(State, InstanceSymbol, Sym);
487 }
488
489 return State;
490 }
491
492 /// Report any unreleased instance variables for the current instance being
493 /// dealloced.
diagnoseMissingReleases(CheckerContext & C) const494 void ObjCDeallocChecker::diagnoseMissingReleases(CheckerContext &C) const {
495 ProgramStateRef State = C.getState();
496
497 SVal SelfVal;
498 if (!isInInstanceDealloc(C, SelfVal))
499 return;
500
501 const MemRegion *SelfRegion = SelfVal.castAs<loc::MemRegionVal>().getRegion();
502 const LocationContext *LCtx = C.getLocationContext();
503
504 ExplodedNode *ErrNode = nullptr;
505
506 SymbolRef SelfSym = SelfVal.getAsSymbol();
507 if (!SelfSym)
508 return;
509
510 const SymbolSet *OldUnreleased = State->get<UnreleasedIvarMap>(SelfSym);
511 if (!OldUnreleased)
512 return;
513
514 SymbolSet NewUnreleased = *OldUnreleased;
515 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
516
517 ProgramStateRef InitialState = State;
518
519 for (auto *IvarSymbol : *OldUnreleased) {
520 const TypedValueRegion *TVR =
521 cast<SymbolRegionValue>(IvarSymbol)->getRegion();
522 const ObjCIvarRegion *IvarRegion = cast<ObjCIvarRegion>(TVR);
523
524 // Don't warn if the ivar is not for this instance.
525 if (SelfRegion != IvarRegion->getSuperRegion())
526 continue;
527
528 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
529 // Prevent an inlined call to -dealloc in a super class from warning
530 // about the values the subclass's -dealloc should release.
531 if (IvarDecl->getContainingInterface() !=
532 cast<ObjCMethodDecl>(LCtx->getDecl())->getClassInterface())
533 continue;
534
535 // Prevents diagnosing multiple times for the same instance variable
536 // at, for example, both a return and at the end of of the function.
537 NewUnreleased = F.remove(NewUnreleased, IvarSymbol);
538
539 if (State->getStateManager()
540 .getConstraintManager()
541 .isNull(State, IvarSymbol)
542 .isConstrainedTrue()) {
543 continue;
544 }
545
546 // A missing release manifests as a leak, so treat as a non-fatal error.
547 if (!ErrNode)
548 ErrNode = C.generateNonFatalErrorNode();
549 // If we've already reached this node on another path, return without
550 // diagnosing.
551 if (!ErrNode)
552 return;
553
554 std::string Buf;
555 llvm::raw_string_ostream OS(Buf);
556
557 const ObjCInterfaceDecl *Interface = IvarDecl->getContainingInterface();
558 // If the class is known to have a lifecycle with teardown that is
559 // separate from -dealloc, do not warn about missing releases. We
560 // suppress here (rather than not tracking for instance variables in
561 // such classes) because these classes are rare.
562 if (classHasSeparateTeardown(Interface))
563 return;
564
565 ObjCImplDecl *ImplDecl = Interface->getImplementation();
566
567 const ObjCPropertyImplDecl *PropImpl =
568 ImplDecl->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
569
570 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
571
572 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Copy ||
573 PropDecl->getSetterKind() == ObjCPropertyDecl::Retain);
574
575 OS << "The '" << *IvarDecl << "' ivar in '" << *ImplDecl
576 << "' was ";
577
578 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Retain)
579 OS << "retained";
580 else
581 OS << "copied";
582
583 OS << " by a synthesized property but not released"
584 " before '[super dealloc]'";
585
586 std::unique_ptr<BugReport> BR(
587 new BugReport(*MissingReleaseBugType, OS.str(), ErrNode));
588
589 C.emitReport(std::move(BR));
590 }
591
592 if (NewUnreleased.isEmpty()) {
593 State = State->remove<UnreleasedIvarMap>(SelfSym);
594 } else {
595 State = State->set<UnreleasedIvarMap>(SelfSym, NewUnreleased);
596 }
597
598 if (ErrNode) {
599 C.addTransition(State, ErrNode);
600 } else if (State != InitialState) {
601 C.addTransition(State);
602 }
603
604 // Make sure that after checking in the top-most frame the list of
605 // tracked ivars is empty. This is intended to detect accidental leaks in
606 // the UnreleasedIvarMap program state.
607 assert(!LCtx->inTopFrame() || State->get<UnreleasedIvarMap>().isEmpty());
608 }
609
610 /// Given a symbol, determine whether the symbol refers to an ivar on
611 /// the top-most deallocating instance. If so, find the property for that
612 /// ivar, if one exists. Otherwise return null.
613 const ObjCPropertyImplDecl *
findPropertyOnDeallocatingInstance(SymbolRef IvarSym,CheckerContext & C) const614 ObjCDeallocChecker::findPropertyOnDeallocatingInstance(
615 SymbolRef IvarSym, CheckerContext &C) const {
616 SVal DeallocedInstance;
617 if (!isInInstanceDealloc(C, DeallocedInstance))
618 return nullptr;
619
620 // Try to get the region from which the ivar value was loaded.
621 auto *IvarRegion = getIvarRegionForIvarSymbol(IvarSym);
622 if (!IvarRegion)
623 return nullptr;
624
625 // Don't try to find the property if the ivar was not loaded from the
626 // given instance.
627 if (DeallocedInstance.castAs<loc::MemRegionVal>().getRegion() !=
628 IvarRegion->getSuperRegion())
629 return nullptr;
630
631 const LocationContext *LCtx = C.getLocationContext();
632 const ObjCIvarDecl *IvarDecl = IvarRegion->getDecl();
633
634 const ObjCImplDecl *Container = getContainingObjCImpl(LCtx);
635 const ObjCPropertyImplDecl *PropImpl =
636 Container->FindPropertyImplIvarDecl(IvarDecl->getIdentifier());
637 return PropImpl;
638 }
639
640 /// Emits a warning if the current context is -dealloc and ReleasedValue
641 /// must not be directly released in a -dealloc. Returns true if a diagnostic
642 /// was emitted.
diagnoseExtraRelease(SymbolRef ReleasedValue,const ObjCMethodCall & M,CheckerContext & C) const643 bool ObjCDeallocChecker::diagnoseExtraRelease(SymbolRef ReleasedValue,
644 const ObjCMethodCall &M,
645 CheckerContext &C) const {
646 // Try to get the region from which the the released value was loaded.
647 // Note that, unlike diagnosing for missing releases, here we don't track
648 // values that must not be released in the state. This is because even if
649 // these values escape, it is still an error under the rules of MRR to
650 // release them in -dealloc.
651 const ObjCPropertyImplDecl *PropImpl =
652 findPropertyOnDeallocatingInstance(ReleasedValue, C);
653
654 if (!PropImpl)
655 return false;
656
657 // If the ivar belongs to a property that must not be released directly
658 // in dealloc, emit a warning.
659 if (getDeallocReleaseRequirement(PropImpl) !=
660 ReleaseRequirement::MustNotReleaseDirectly) {
661 return false;
662 }
663
664 // If the property is readwrite but it shadows a read-only property in its
665 // external interface, treat the property a read-only. If the outside
666 // world cannot write to a property then the internal implementation is free
667 // to make its own convention about whether the value is stored retained
668 // or not. We look up the shadow here rather than in
669 // getDeallocReleaseRequirement() because doing so can be expensive.
670 const ObjCPropertyDecl *PropDecl = findShadowedPropertyDecl(PropImpl);
671 if (PropDecl) {
672 if (PropDecl->isReadOnly())
673 return false;
674 } else {
675 PropDecl = PropImpl->getPropertyDecl();
676 }
677
678 ExplodedNode *ErrNode = C.generateNonFatalErrorNode();
679 if (!ErrNode)
680 return false;
681
682 std::string Buf;
683 llvm::raw_string_ostream OS(Buf);
684
685 assert(PropDecl->getSetterKind() == ObjCPropertyDecl::Weak ||
686 (PropDecl->getSetterKind() == ObjCPropertyDecl::Assign &&
687 !PropDecl->isReadOnly()) ||
688 isReleasedByCIFilterDealloc(PropImpl)
689 );
690
691 const ObjCImplDecl *Container = getContainingObjCImpl(C.getLocationContext());
692 OS << "The '" << *PropImpl->getPropertyIvarDecl()
693 << "' ivar in '" << *Container;
694
695
696 if (isReleasedByCIFilterDealloc(PropImpl)) {
697 OS << "' will be released by '-[CIFilter dealloc]' but also released here";
698 } else {
699 OS << "' was synthesized for ";
700
701 if (PropDecl->getSetterKind() == ObjCPropertyDecl::Weak)
702 OS << "a weak";
703 else
704 OS << "an assign, readwrite";
705
706 OS << " property but was released in 'dealloc'";
707 }
708
709 std::unique_ptr<BugReport> BR(
710 new BugReport(*ExtraReleaseBugType, OS.str(), ErrNode));
711 BR->addRange(M.getOriginExpr()->getSourceRange());
712
713 C.emitReport(std::move(BR));
714
715 return true;
716 }
717
718 /// Emits a warning if the current context is -dealloc and DeallocedValue
719 /// must not be directly dealloced in a -dealloc. Returns true if a diagnostic
720 /// was emitted.
diagnoseMistakenDealloc(SymbolRef DeallocedValue,const ObjCMethodCall & M,CheckerContext & C) const721 bool ObjCDeallocChecker::diagnoseMistakenDealloc(SymbolRef DeallocedValue,
722 const ObjCMethodCall &M,
723 CheckerContext &C) const {
724
725 // Find the property backing the instance variable that M
726 // is dealloc'ing.
727 const ObjCPropertyImplDecl *PropImpl =
728 findPropertyOnDeallocatingInstance(DeallocedValue, C);
729 if (!PropImpl)
730 return false;
731
732 if (getDeallocReleaseRequirement(PropImpl) !=
733 ReleaseRequirement::MustRelease) {
734 return false;
735 }
736
737 ExplodedNode *ErrNode = C.generateErrorNode();
738 if (!ErrNode)
739 return false;
740
741 std::string Buf;
742 llvm::raw_string_ostream OS(Buf);
743
744 OS << "'" << *PropImpl->getPropertyIvarDecl()
745 << "' should be released rather than deallocated";
746
747 std::unique_ptr<BugReport> BR(
748 new BugReport(*MistakenDeallocBugType, OS.str(), ErrNode));
749 BR->addRange(M.getOriginExpr()->getSourceRange());
750
751 C.emitReport(std::move(BR));
752
753 return true;
754 }
755
ObjCDeallocChecker()756 ObjCDeallocChecker::ObjCDeallocChecker()
757 : NSObjectII(nullptr), SenTestCaseII(nullptr), XCTestCaseII(nullptr),
758 CIFilterII(nullptr) {
759
760 MissingReleaseBugType.reset(
761 new BugType(this, "Missing ivar release (leak)",
762 categories::MemoryCoreFoundationObjectiveC));
763
764 ExtraReleaseBugType.reset(
765 new BugType(this, "Extra ivar release",
766 categories::MemoryCoreFoundationObjectiveC));
767
768 MistakenDeallocBugType.reset(
769 new BugType(this, "Mistaken dealloc",
770 categories::MemoryCoreFoundationObjectiveC));
771 }
772
initIdentifierInfoAndSelectors(ASTContext & Ctx) const773 void ObjCDeallocChecker::initIdentifierInfoAndSelectors(
774 ASTContext &Ctx) const {
775 if (NSObjectII)
776 return;
777
778 NSObjectII = &Ctx.Idents.get("NSObject");
779 SenTestCaseII = &Ctx.Idents.get("SenTestCase");
780 XCTestCaseII = &Ctx.Idents.get("XCTestCase");
781 Block_releaseII = &Ctx.Idents.get("_Block_release");
782 CIFilterII = &Ctx.Idents.get("CIFilter");
783
784 IdentifierInfo *DeallocII = &Ctx.Idents.get("dealloc");
785 IdentifierInfo *ReleaseII = &Ctx.Idents.get("release");
786 DeallocSel = Ctx.Selectors.getSelector(0, &DeallocII);
787 ReleaseSel = Ctx.Selectors.getSelector(0, &ReleaseII);
788 }
789
790 /// Returns true if M is a call to '[super dealloc]'.
isSuperDeallocMessage(const ObjCMethodCall & M) const791 bool ObjCDeallocChecker::isSuperDeallocMessage(
792 const ObjCMethodCall &M) const {
793 if (M.getOriginExpr()->getReceiverKind() != ObjCMessageExpr::SuperInstance)
794 return false;
795
796 return M.getSelector() == DeallocSel;
797 }
798
799 /// Returns the ObjCImplDecl containing the method declaration in LCtx.
800 const ObjCImplDecl *
getContainingObjCImpl(const LocationContext * LCtx) const801 ObjCDeallocChecker::getContainingObjCImpl(const LocationContext *LCtx) const {
802 auto *MD = cast<ObjCMethodDecl>(LCtx->getDecl());
803 return cast<ObjCImplDecl>(MD->getDeclContext());
804 }
805
806 /// Returns the property that shadowed by PropImpl if one exists and
807 /// nullptr otherwise.
findShadowedPropertyDecl(const ObjCPropertyImplDecl * PropImpl) const808 const ObjCPropertyDecl *ObjCDeallocChecker::findShadowedPropertyDecl(
809 const ObjCPropertyImplDecl *PropImpl) const {
810 const ObjCPropertyDecl *PropDecl = PropImpl->getPropertyDecl();
811
812 // Only readwrite properties can shadow.
813 if (PropDecl->isReadOnly())
814 return nullptr;
815
816 auto *CatDecl = dyn_cast<ObjCCategoryDecl>(PropDecl->getDeclContext());
817
818 // Only class extensions can contain shadowing properties.
819 if (!CatDecl || !CatDecl->IsClassExtension())
820 return nullptr;
821
822 IdentifierInfo *ID = PropDecl->getIdentifier();
823 DeclContext::lookup_result R = CatDecl->getClassInterface()->lookup(ID);
824 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
825 auto *ShadowedPropDecl = dyn_cast<ObjCPropertyDecl>(*I);
826 if (!ShadowedPropDecl)
827 continue;
828
829 if (ShadowedPropDecl->isInstanceProperty()) {
830 assert(ShadowedPropDecl->isReadOnly());
831 return ShadowedPropDecl;
832 }
833 }
834
835 return nullptr;
836 }
837
838 /// Add a transition noting the release of the given value.
transitionToReleaseValue(CheckerContext & C,SymbolRef Value) const839 void ObjCDeallocChecker::transitionToReleaseValue(CheckerContext &C,
840 SymbolRef Value) const {
841 assert(Value);
842 SymbolRef InstanceSym = getInstanceSymbolFromIvarSymbol(Value);
843 if (!InstanceSym)
844 return;
845 ProgramStateRef InitialState = C.getState();
846
847 ProgramStateRef ReleasedState =
848 removeValueRequiringRelease(InitialState, InstanceSym, Value);
849
850 if (ReleasedState != InitialState) {
851 C.addTransition(ReleasedState);
852 }
853 }
854
855 /// Remove the Value requiring a release from the tracked set for
856 /// Instance and return the resultant state.
removeValueRequiringRelease(ProgramStateRef State,SymbolRef Instance,SymbolRef Value) const857 ProgramStateRef ObjCDeallocChecker::removeValueRequiringRelease(
858 ProgramStateRef State, SymbolRef Instance, SymbolRef Value) const {
859 assert(Instance);
860 assert(Value);
861 const ObjCIvarRegion *RemovedRegion = getIvarRegionForIvarSymbol(Value);
862 if (!RemovedRegion)
863 return State;
864
865 const SymbolSet *Unreleased = State->get<UnreleasedIvarMap>(Instance);
866 if (!Unreleased)
867 return State;
868
869 // Mark the value as no longer requiring a release.
870 SymbolSet::Factory &F = State->getStateManager().get_context<SymbolSet>();
871 SymbolSet NewUnreleased = *Unreleased;
872 for (auto &Sym : *Unreleased) {
873 const ObjCIvarRegion *UnreleasedRegion = getIvarRegionForIvarSymbol(Sym);
874 assert(UnreleasedRegion);
875 if (RemovedRegion->getDecl() == UnreleasedRegion->getDecl()) {
876 NewUnreleased = F.remove(NewUnreleased, Sym);
877 }
878 }
879
880 if (NewUnreleased.isEmpty()) {
881 return State->remove<UnreleasedIvarMap>(Instance);
882 }
883
884 return State->set<UnreleasedIvarMap>(Instance, NewUnreleased);
885 }
886
887 /// Determines whether the instance variable for \p PropImpl must or must not be
888 /// released in -dealloc or whether it cannot be determined.
getDeallocReleaseRequirement(const ObjCPropertyImplDecl * PropImpl) const889 ReleaseRequirement ObjCDeallocChecker::getDeallocReleaseRequirement(
890 const ObjCPropertyImplDecl *PropImpl) const {
891 const ObjCIvarDecl *IvarDecl;
892 const ObjCPropertyDecl *PropDecl;
893 if (!isSynthesizedRetainableProperty(PropImpl, &IvarDecl, &PropDecl))
894 return ReleaseRequirement::Unknown;
895
896 ObjCPropertyDecl::SetterKind SK = PropDecl->getSetterKind();
897
898 switch (SK) {
899 // Retain and copy setters retain/copy their values before storing and so
900 // the value in their instance variables must be released in -dealloc.
901 case ObjCPropertyDecl::Retain:
902 case ObjCPropertyDecl::Copy:
903 if (isReleasedByCIFilterDealloc(PropImpl))
904 return ReleaseRequirement::MustNotReleaseDirectly;
905
906 return ReleaseRequirement::MustRelease;
907
908 case ObjCPropertyDecl::Weak:
909 return ReleaseRequirement::MustNotReleaseDirectly;
910
911 case ObjCPropertyDecl::Assign:
912 // It is common for the ivars for read-only assign properties to
913 // always be stored retained, so their release requirement cannot be
914 // be determined.
915 if (PropDecl->isReadOnly())
916 return ReleaseRequirement::Unknown;
917
918 return ReleaseRequirement::MustNotReleaseDirectly;
919 }
920 llvm_unreachable("Unrecognized setter kind");
921 }
922
923 /// Returns the released value if M is a call a setter that releases
924 /// and nils out its underlying instance variable.
925 SymbolRef
getValueReleasedByNillingOut(const ObjCMethodCall & M,CheckerContext & C) const926 ObjCDeallocChecker::getValueReleasedByNillingOut(const ObjCMethodCall &M,
927 CheckerContext &C) const {
928 SVal ReceiverVal = M.getReceiverSVal();
929 if (!ReceiverVal.isValid())
930 return nullptr;
931
932 if (M.getNumArgs() == 0)
933 return nullptr;
934
935 if (!M.getArgExpr(0)->getType()->isObjCRetainableType())
936 return nullptr;
937
938 // Is the first argument nil?
939 SVal Arg = M.getArgSVal(0);
940 ProgramStateRef notNilState, nilState;
941 std::tie(notNilState, nilState) =
942 M.getState()->assume(Arg.castAs<DefinedOrUnknownSVal>());
943 if (!(nilState && !notNilState))
944 return nullptr;
945
946 const ObjCPropertyDecl *Prop = M.getAccessedProperty();
947 if (!Prop)
948 return nullptr;
949
950 ObjCIvarDecl *PropIvarDecl = Prop->getPropertyIvarDecl();
951 if (!PropIvarDecl)
952 return nullptr;
953
954 ProgramStateRef State = C.getState();
955
956 SVal LVal = State->getLValue(PropIvarDecl, ReceiverVal);
957 Optional<Loc> LValLoc = LVal.getAs<Loc>();
958 if (!LValLoc)
959 return nullptr;
960
961 SVal CurrentValInIvar = State->getSVal(LValLoc.getValue());
962 return CurrentValInIvar.getAsSymbol();
963 }
964
965 /// Returns true if the current context is a call to -dealloc and false
966 /// otherwise. If true, it also sets SelfValOut to the value of
967 /// 'self'.
isInInstanceDealloc(const CheckerContext & C,SVal & SelfValOut) const968 bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
969 SVal &SelfValOut) const {
970 return isInInstanceDealloc(C, C.getLocationContext(), SelfValOut);
971 }
972
973 /// Returns true if LCtx is a call to -dealloc and false
974 /// otherwise. If true, it also sets SelfValOut to the value of
975 /// 'self'.
isInInstanceDealloc(const CheckerContext & C,const LocationContext * LCtx,SVal & SelfValOut) const976 bool ObjCDeallocChecker::isInInstanceDealloc(const CheckerContext &C,
977 const LocationContext *LCtx,
978 SVal &SelfValOut) const {
979 auto *MD = dyn_cast<ObjCMethodDecl>(LCtx->getDecl());
980 if (!MD || !MD->isInstanceMethod() || MD->getSelector() != DeallocSel)
981 return false;
982
983 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
984 assert(SelfDecl && "No self in -dealloc?");
985
986 ProgramStateRef State = C.getState();
987 SelfValOut = State->getSVal(State->getRegion(SelfDecl, LCtx));
988 return true;
989 }
990
991 /// Returns true if there is a call to -dealloc anywhere on the stack and false
992 /// otherwise. If true, it also sets InstanceValOut to the value of
993 /// 'self' in the frame for -dealloc.
instanceDeallocIsOnStack(const CheckerContext & C,SVal & InstanceValOut) const994 bool ObjCDeallocChecker::instanceDeallocIsOnStack(const CheckerContext &C,
995 SVal &InstanceValOut) const {
996 const LocationContext *LCtx = C.getLocationContext();
997
998 while (LCtx) {
999 if (isInInstanceDealloc(C, LCtx, InstanceValOut))
1000 return true;
1001
1002 LCtx = LCtx->getParent();
1003 }
1004
1005 return false;
1006 }
1007
1008 /// Returns true if the ID is a class in which which is known to have
1009 /// a separate teardown lifecycle. In this case, -dealloc warnings
1010 /// about missing releases should be suppressed.
classHasSeparateTeardown(const ObjCInterfaceDecl * ID) const1011 bool ObjCDeallocChecker::classHasSeparateTeardown(
1012 const ObjCInterfaceDecl *ID) const {
1013 // Suppress if the class is not a subclass of NSObject.
1014 for ( ; ID ; ID = ID->getSuperClass()) {
1015 IdentifierInfo *II = ID->getIdentifier();
1016
1017 if (II == NSObjectII)
1018 return false;
1019
1020 // FIXME: For now, ignore classes that subclass SenTestCase and XCTestCase,
1021 // as these don't need to implement -dealloc. They implement tear down in
1022 // another way, which we should try and catch later.
1023 // http://llvm.org/bugs/show_bug.cgi?id=3187
1024 if (II == XCTestCaseII || II == SenTestCaseII)
1025 return true;
1026 }
1027
1028 return true;
1029 }
1030
1031 /// The -dealloc method in CIFilter highly unusual in that is will release
1032 /// instance variables belonging to its *subclasses* if the variable name
1033 /// starts with "input" or backs a property whose name starts with "input".
1034 /// Subclasses should not release these ivars in their own -dealloc method --
1035 /// doing so could result in an over release.
1036 ///
1037 /// This method returns true if the property will be released by
1038 /// -[CIFilter dealloc].
isReleasedByCIFilterDealloc(const ObjCPropertyImplDecl * PropImpl) const1039 bool ObjCDeallocChecker::isReleasedByCIFilterDealloc(
1040 const ObjCPropertyImplDecl *PropImpl) const {
1041 assert(PropImpl->getPropertyIvarDecl());
1042 StringRef PropName = PropImpl->getPropertyDecl()->getName();
1043 StringRef IvarName = PropImpl->getPropertyIvarDecl()->getName();
1044
1045 const char *ReleasePrefix = "input";
1046 if (!(PropName.startswith(ReleasePrefix) ||
1047 IvarName.startswith(ReleasePrefix))) {
1048 return false;
1049 }
1050
1051 const ObjCInterfaceDecl *ID =
1052 PropImpl->getPropertyIvarDecl()->getContainingInterface();
1053 for ( ; ID ; ID = ID->getSuperClass()) {
1054 IdentifierInfo *II = ID->getIdentifier();
1055 if (II == CIFilterII)
1056 return true;
1057 }
1058
1059 return false;
1060 }
1061
registerObjCDeallocChecker(CheckerManager & Mgr)1062 void ento::registerObjCDeallocChecker(CheckerManager &Mgr) {
1063 const LangOptions &LangOpts = Mgr.getLangOpts();
1064 // These checker only makes sense under MRR.
1065 if (LangOpts.getGC() == LangOptions::GCOnly || LangOpts.ObjCAutoRefCount)
1066 return;
1067
1068 Mgr.registerChecker<ObjCDeallocChecker>();
1069 }
1070