CheckObjCDealloc.cpp 38 KB

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