CheckObjCDealloc.cpp 38 KB

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