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