RetainCountChecker.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547
  1. //==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- 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 file defines the methods for RetainCountChecker, which implements
  10. // a reference count checker for Core Foundation and Cocoa on (Mac OS X).
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "RetainCountChecker.h"
  14. #include "clang/StaticAnalyzer/Core/Checker.h"
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  16. #include <optional>
  17. using namespace clang;
  18. using namespace ento;
  19. using namespace retaincountchecker;
  20. REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
  21. namespace clang {
  22. namespace ento {
  23. namespace retaincountchecker {
  24. const RefVal *getRefBinding(ProgramStateRef State, SymbolRef Sym) {
  25. return State->get<RefBindings>(Sym);
  26. }
  27. } // end namespace retaincountchecker
  28. } // end namespace ento
  29. } // end namespace clang
  30. static ProgramStateRef setRefBinding(ProgramStateRef State, SymbolRef Sym,
  31. RefVal Val) {
  32. assert(Sym != nullptr);
  33. return State->set<RefBindings>(Sym, Val);
  34. }
  35. static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
  36. return State->remove<RefBindings>(Sym);
  37. }
  38. void RefVal::print(raw_ostream &Out) const {
  39. if (!T.isNull())
  40. Out << "Tracked " << T << " | ";
  41. switch (getKind()) {
  42. default: llvm_unreachable("Invalid RefVal kind");
  43. case Owned: {
  44. Out << "Owned";
  45. unsigned cnt = getCount();
  46. if (cnt) Out << " (+ " << cnt << ")";
  47. break;
  48. }
  49. case NotOwned: {
  50. Out << "NotOwned";
  51. unsigned cnt = getCount();
  52. if (cnt) Out << " (+ " << cnt << ")";
  53. break;
  54. }
  55. case ReturnedOwned: {
  56. Out << "ReturnedOwned";
  57. unsigned cnt = getCount();
  58. if (cnt) Out << " (+ " << cnt << ")";
  59. break;
  60. }
  61. case ReturnedNotOwned: {
  62. Out << "ReturnedNotOwned";
  63. unsigned cnt = getCount();
  64. if (cnt) Out << " (+ " << cnt << ")";
  65. break;
  66. }
  67. case Released:
  68. Out << "Released";
  69. break;
  70. case ErrorDeallocNotOwned:
  71. Out << "-dealloc (not-owned)";
  72. break;
  73. case ErrorLeak:
  74. Out << "Leaked";
  75. break;
  76. case ErrorLeakReturned:
  77. Out << "Leaked (Bad naming)";
  78. break;
  79. case ErrorUseAfterRelease:
  80. Out << "Use-After-Release [ERROR]";
  81. break;
  82. case ErrorReleaseNotOwned:
  83. Out << "Release of Not-Owned [ERROR]";
  84. break;
  85. case RefVal::ErrorOverAutorelease:
  86. Out << "Over-autoreleased";
  87. break;
  88. case RefVal::ErrorReturnedNotOwned:
  89. Out << "Non-owned object returned instead of owned";
  90. break;
  91. }
  92. switch (getIvarAccessHistory()) {
  93. case IvarAccessHistory::None:
  94. break;
  95. case IvarAccessHistory::AccessedDirectly:
  96. Out << " [direct ivar access]";
  97. break;
  98. case IvarAccessHistory::ReleasedAfterDirectAccess:
  99. Out << " [released after direct ivar access]";
  100. }
  101. if (ACnt) {
  102. Out << " [autorelease -" << ACnt << ']';
  103. }
  104. }
  105. namespace {
  106. class StopTrackingCallback final : public SymbolVisitor {
  107. ProgramStateRef state;
  108. public:
  109. StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
  110. ProgramStateRef getState() const { return state; }
  111. bool VisitSymbol(SymbolRef sym) override {
  112. state = removeRefBinding(state, sym);
  113. return true;
  114. }
  115. };
  116. } // end anonymous namespace
  117. //===----------------------------------------------------------------------===//
  118. // Handle statements that may have an effect on refcounts.
  119. //===----------------------------------------------------------------------===//
  120. void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
  121. CheckerContext &C) const {
  122. // Scan the BlockDecRefExprs for any object the retain count checker
  123. // may be tracking.
  124. if (!BE->getBlockDecl()->hasCaptures())
  125. return;
  126. ProgramStateRef state = C.getState();
  127. auto *R = cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
  128. BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
  129. E = R->referenced_vars_end();
  130. if (I == E)
  131. return;
  132. // FIXME: For now we invalidate the tracking of all symbols passed to blocks
  133. // via captured variables, even though captured variables result in a copy
  134. // and in implicit increment/decrement of a retain count.
  135. SmallVector<const MemRegion*, 10> Regions;
  136. const LocationContext *LC = C.getLocationContext();
  137. MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
  138. for ( ; I != E; ++I) {
  139. const VarRegion *VR = I.getCapturedRegion();
  140. if (VR->getSuperRegion() == R) {
  141. VR = MemMgr.getVarRegion(VR->getDecl(), LC);
  142. }
  143. Regions.push_back(VR);
  144. }
  145. state = state->scanReachableSymbols<StopTrackingCallback>(Regions).getState();
  146. C.addTransition(state);
  147. }
  148. void RetainCountChecker::checkPostStmt(const CastExpr *CE,
  149. CheckerContext &C) const {
  150. const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
  151. if (!BE)
  152. return;
  153. QualType QT = CE->getType();
  154. ObjKind K;
  155. if (QT->isObjCObjectPointerType()) {
  156. K = ObjKind::ObjC;
  157. } else {
  158. K = ObjKind::CF;
  159. }
  160. ArgEffect AE = ArgEffect(IncRef, K);
  161. switch (BE->getBridgeKind()) {
  162. case OBC_Bridge:
  163. // Do nothing.
  164. return;
  165. case OBC_BridgeRetained:
  166. AE = AE.withKind(IncRef);
  167. break;
  168. case OBC_BridgeTransfer:
  169. AE = AE.withKind(DecRefBridgedTransferred);
  170. break;
  171. }
  172. ProgramStateRef state = C.getState();
  173. SymbolRef Sym = C.getSVal(CE).getAsLocSymbol();
  174. if (!Sym)
  175. return;
  176. const RefVal* T = getRefBinding(state, Sym);
  177. if (!T)
  178. return;
  179. RefVal::Kind hasErr = (RefVal::Kind) 0;
  180. state = updateSymbol(state, Sym, *T, AE, hasErr, C);
  181. if (hasErr) {
  182. // FIXME: If we get an error during a bridge cast, should we report it?
  183. return;
  184. }
  185. C.addTransition(state);
  186. }
  187. void RetainCountChecker::processObjCLiterals(CheckerContext &C,
  188. const Expr *Ex) const {
  189. ProgramStateRef state = C.getState();
  190. const ExplodedNode *pred = C.getPredecessor();
  191. for (const Stmt *Child : Ex->children()) {
  192. SVal V = pred->getSVal(Child);
  193. if (SymbolRef sym = V.getAsSymbol())
  194. if (const RefVal* T = getRefBinding(state, sym)) {
  195. RefVal::Kind hasErr = (RefVal::Kind) 0;
  196. state = updateSymbol(state, sym, *T,
  197. ArgEffect(MayEscape, ObjKind::ObjC), hasErr, C);
  198. if (hasErr) {
  199. processNonLeakError(state, Child->getSourceRange(), hasErr, sym, C);
  200. return;
  201. }
  202. }
  203. }
  204. // Return the object as autoreleased.
  205. // RetEffect RE = RetEffect::MakeNotOwned(ObjKind::ObjC);
  206. if (SymbolRef sym =
  207. state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
  208. QualType ResultTy = Ex->getType();
  209. state = setRefBinding(state, sym,
  210. RefVal::makeNotOwned(ObjKind::ObjC, ResultTy));
  211. }
  212. C.addTransition(state);
  213. }
  214. void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
  215. CheckerContext &C) const {
  216. // Apply the 'MayEscape' to all values.
  217. processObjCLiterals(C, AL);
  218. }
  219. void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
  220. CheckerContext &C) const {
  221. // Apply the 'MayEscape' to all keys and values.
  222. processObjCLiterals(C, DL);
  223. }
  224. void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
  225. CheckerContext &C) const {
  226. const ExplodedNode *Pred = C.getPredecessor();
  227. ProgramStateRef State = Pred->getState();
  228. if (SymbolRef Sym = Pred->getSVal(Ex).getAsSymbol()) {
  229. QualType ResultTy = Ex->getType();
  230. State = setRefBinding(State, Sym,
  231. RefVal::makeNotOwned(ObjKind::ObjC, ResultTy));
  232. }
  233. C.addTransition(State);
  234. }
  235. void RetainCountChecker::checkPostStmt(const ObjCIvarRefExpr *IRE,
  236. CheckerContext &C) const {
  237. std::optional<Loc> IVarLoc = C.getSVal(IRE).getAs<Loc>();
  238. if (!IVarLoc)
  239. return;
  240. ProgramStateRef State = C.getState();
  241. SymbolRef Sym = State->getSVal(*IVarLoc).getAsSymbol();
  242. if (!Sym || !isa_and_nonnull<ObjCIvarRegion>(Sym->getOriginRegion()))
  243. return;
  244. // Accessing an ivar directly is unusual. If we've done that, be more
  245. // forgiving about what the surrounding code is allowed to do.
  246. QualType Ty = Sym->getType();
  247. ObjKind Kind;
  248. if (Ty->isObjCRetainableType())
  249. Kind = ObjKind::ObjC;
  250. else if (coreFoundation::isCFObjectRef(Ty))
  251. Kind = ObjKind::CF;
  252. else
  253. return;
  254. // If the value is already known to be nil, don't bother tracking it.
  255. ConstraintManager &CMgr = State->getConstraintManager();
  256. if (CMgr.isNull(State, Sym).isConstrainedTrue())
  257. return;
  258. if (const RefVal *RV = getRefBinding(State, Sym)) {
  259. // If we've seen this symbol before, or we're only seeing it now because
  260. // of something the analyzer has synthesized, don't do anything.
  261. if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None ||
  262. isSynthesizedAccessor(C.getStackFrame())) {
  263. return;
  264. }
  265. // Note that this value has been loaded from an ivar.
  266. C.addTransition(setRefBinding(State, Sym, RV->withIvarAccess()));
  267. return;
  268. }
  269. RefVal PlusZero = RefVal::makeNotOwned(Kind, Ty);
  270. // In a synthesized accessor, the effective retain count is +0.
  271. if (isSynthesizedAccessor(C.getStackFrame())) {
  272. C.addTransition(setRefBinding(State, Sym, PlusZero));
  273. return;
  274. }
  275. State = setRefBinding(State, Sym, PlusZero.withIvarAccess());
  276. C.addTransition(State);
  277. }
  278. static bool isReceiverUnconsumedSelf(const CallEvent &Call) {
  279. if (const auto *MC = dyn_cast<ObjCMethodCall>(&Call)) {
  280. // Check if the message is not consumed, we know it will not be used in
  281. // an assignment, ex: "self = [super init]".
  282. return MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper() &&
  283. !Call.getLocationContext()
  284. ->getAnalysisDeclContext()
  285. ->getParentMap()
  286. .isConsumedExpr(Call.getOriginExpr());
  287. }
  288. return false;
  289. }
  290. const static RetainSummary *getSummary(RetainSummaryManager &Summaries,
  291. const CallEvent &Call,
  292. QualType ReceiverType) {
  293. const Expr *CE = Call.getOriginExpr();
  294. AnyCall C =
  295. CE ? *AnyCall::forExpr(CE)
  296. : AnyCall(cast<CXXDestructorDecl>(Call.getDecl()));
  297. return Summaries.getSummary(C, Call.hasNonZeroCallbackArg(),
  298. isReceiverUnconsumedSelf(Call), ReceiverType);
  299. }
  300. void RetainCountChecker::checkPostCall(const CallEvent &Call,
  301. CheckerContext &C) const {
  302. RetainSummaryManager &Summaries = getSummaryManager(C);
  303. // Leave null if no receiver.
  304. QualType ReceiverType;
  305. if (const auto *MC = dyn_cast<ObjCMethodCall>(&Call)) {
  306. if (MC->isInstanceMessage()) {
  307. SVal ReceiverV = MC->getReceiverSVal();
  308. if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
  309. if (const RefVal *T = getRefBinding(C.getState(), Sym))
  310. ReceiverType = T->getType();
  311. }
  312. }
  313. const RetainSummary *Summ = getSummary(Summaries, Call, ReceiverType);
  314. if (C.wasInlined) {
  315. processSummaryOfInlined(*Summ, Call, C);
  316. return;
  317. }
  318. checkSummary(*Summ, Call, C);
  319. }
  320. /// GetReturnType - Used to get the return type of a message expression or
  321. /// function call with the intention of affixing that type to a tracked symbol.
  322. /// While the return type can be queried directly from RetEx, when
  323. /// invoking class methods we augment to the return type to be that of
  324. /// a pointer to the class (as opposed it just being id).
  325. // FIXME: We may be able to do this with related result types instead.
  326. // This function is probably overestimating.
  327. static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
  328. QualType RetTy = RetE->getType();
  329. // If RetE is not a message expression just return its type.
  330. // If RetE is a message expression, return its types if it is something
  331. /// more specific than id.
  332. if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
  333. if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
  334. if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
  335. PT->isObjCClassType()) {
  336. // At this point we know the return type of the message expression is
  337. // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
  338. // is a call to a class method whose type we can resolve. In such
  339. // cases, promote the return type to XXX* (where XXX is the class).
  340. const ObjCInterfaceDecl *D = ME->getReceiverInterface();
  341. return !D ? RetTy :
  342. Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
  343. }
  344. return RetTy;
  345. }
  346. static std::optional<RefVal> refValFromRetEffect(RetEffect RE,
  347. QualType ResultTy) {
  348. if (RE.isOwned()) {
  349. return RefVal::makeOwned(RE.getObjKind(), ResultTy);
  350. } else if (RE.notOwned()) {
  351. return RefVal::makeNotOwned(RE.getObjKind(), ResultTy);
  352. }
  353. return std::nullopt;
  354. }
  355. static bool isPointerToObject(QualType QT) {
  356. QualType PT = QT->getPointeeType();
  357. if (!PT.isNull())
  358. if (PT->getAsCXXRecordDecl())
  359. return true;
  360. return false;
  361. }
  362. /// Whether the tracked value should be escaped on a given call.
  363. /// OSObjects are escaped when passed to void * / etc.
  364. static bool shouldEscapeOSArgumentOnCall(const CallEvent &CE, unsigned ArgIdx,
  365. const RefVal *TrackedValue) {
  366. if (TrackedValue->getObjKind() != ObjKind::OS)
  367. return false;
  368. if (ArgIdx >= CE.parameters().size())
  369. return false;
  370. return !isPointerToObject(CE.parameters()[ArgIdx]->getType());
  371. }
  372. // We don't always get the exact modeling of the function with regards to the
  373. // retain count checker even when the function is inlined. For example, we need
  374. // to stop tracking the symbols which were marked with StopTrackingHard.
  375. void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
  376. const CallEvent &CallOrMsg,
  377. CheckerContext &C) const {
  378. ProgramStateRef state = C.getState();
  379. // Evaluate the effect of the arguments.
  380. for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
  381. SVal V = CallOrMsg.getArgSVal(idx);
  382. if (SymbolRef Sym = V.getAsLocSymbol()) {
  383. bool ShouldRemoveBinding = Summ.getArg(idx).getKind() == StopTrackingHard;
  384. if (const RefVal *T = getRefBinding(state, Sym))
  385. if (shouldEscapeOSArgumentOnCall(CallOrMsg, idx, T))
  386. ShouldRemoveBinding = true;
  387. if (ShouldRemoveBinding)
  388. state = removeRefBinding(state, Sym);
  389. }
  390. }
  391. // Evaluate the effect on the message receiver.
  392. if (const auto *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg)) {
  393. if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
  394. if (Summ.getReceiverEffect().getKind() == StopTrackingHard) {
  395. state = removeRefBinding(state, Sym);
  396. }
  397. }
  398. }
  399. // Consult the summary for the return value.
  400. RetEffect RE = Summ.getRetEffect();
  401. if (SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol()) {
  402. if (RE.getKind() == RetEffect::NoRetHard)
  403. state = removeRefBinding(state, Sym);
  404. }
  405. C.addTransition(state);
  406. }
  407. static bool isSmartPtrField(const MemRegion *MR) {
  408. const auto *TR = dyn_cast<TypedValueRegion>(
  409. cast<SubRegion>(MR)->getSuperRegion());
  410. return TR && RetainSummaryManager::isKnownSmartPointer(TR->getValueType());
  411. }
  412. /// A value escapes in these possible cases:
  413. ///
  414. /// - binding to something that is not a memory region.
  415. /// - binding to a memregion that does not have stack storage
  416. /// - binding to a variable that has a destructor attached using CleanupAttr
  417. ///
  418. /// We do not currently model what happens when a symbol is
  419. /// assigned to a struct field, unless it is a known smart pointer
  420. /// implementation, about which we know that it is inlined.
  421. /// FIXME: This could definitely be improved upon.
  422. static bool shouldEscapeRegion(const MemRegion *R) {
  423. if (isSmartPtrField(R))
  424. return false;
  425. const auto *VR = dyn_cast<VarRegion>(R);
  426. if (!R->hasStackStorage() || !VR)
  427. return true;
  428. const VarDecl *VD = VR->getDecl();
  429. if (!VD->hasAttr<CleanupAttr>())
  430. return false; // CleanupAttr attaches destructors, which cause escaping.
  431. return true;
  432. }
  433. static SmallVector<ProgramStateRef, 2>
  434. updateOutParameters(ProgramStateRef State, const RetainSummary &Summ,
  435. const CallEvent &CE) {
  436. SVal L = CE.getReturnValue();
  437. // Splitting is required to support out parameters,
  438. // as out parameters might be created only on the "success" branch.
  439. // We want to avoid eagerly splitting unless out parameters are actually
  440. // needed.
  441. bool SplitNecessary = false;
  442. for (auto &P : Summ.getArgEffects())
  443. if (P.second.getKind() == RetainedOutParameterOnNonZero ||
  444. P.second.getKind() == RetainedOutParameterOnZero)
  445. SplitNecessary = true;
  446. ProgramStateRef AssumeNonZeroReturn = State;
  447. ProgramStateRef AssumeZeroReturn = State;
  448. if (SplitNecessary) {
  449. if (!CE.getResultType()->isScalarType()) {
  450. // Structures cannot be assumed. This probably deserves
  451. // a compiler warning for invalid annotations.
  452. return {State};
  453. }
  454. if (auto DL = L.getAs<DefinedOrUnknownSVal>()) {
  455. AssumeNonZeroReturn = AssumeNonZeroReturn->assume(*DL, true);
  456. AssumeZeroReturn = AssumeZeroReturn->assume(*DL, false);
  457. }
  458. }
  459. for (unsigned idx = 0, e = CE.getNumArgs(); idx != e; ++idx) {
  460. SVal ArgVal = CE.getArgSVal(idx);
  461. ArgEffect AE = Summ.getArg(idx);
  462. auto *ArgRegion = dyn_cast_or_null<TypedValueRegion>(ArgVal.getAsRegion());
  463. if (!ArgRegion)
  464. continue;
  465. QualType PointeeTy = ArgRegion->getValueType();
  466. SVal PointeeVal = State->getSVal(ArgRegion);
  467. SymbolRef Pointee = PointeeVal.getAsLocSymbol();
  468. if (!Pointee)
  469. continue;
  470. if (shouldEscapeRegion(ArgRegion))
  471. continue;
  472. auto makeNotOwnedParameter = [&](ProgramStateRef St) {
  473. return setRefBinding(St, Pointee,
  474. RefVal::makeNotOwned(AE.getObjKind(), PointeeTy));
  475. };
  476. auto makeOwnedParameter = [&](ProgramStateRef St) {
  477. return setRefBinding(St, Pointee,
  478. RefVal::makeOwned(ObjKind::OS, PointeeTy));
  479. };
  480. switch (AE.getKind()) {
  481. case UnretainedOutParameter:
  482. AssumeNonZeroReturn = makeNotOwnedParameter(AssumeNonZeroReturn);
  483. AssumeZeroReturn = makeNotOwnedParameter(AssumeZeroReturn);
  484. break;
  485. case RetainedOutParameter:
  486. AssumeNonZeroReturn = makeOwnedParameter(AssumeNonZeroReturn);
  487. AssumeZeroReturn = makeOwnedParameter(AssumeZeroReturn);
  488. break;
  489. case RetainedOutParameterOnNonZero:
  490. AssumeNonZeroReturn = makeOwnedParameter(AssumeNonZeroReturn);
  491. break;
  492. case RetainedOutParameterOnZero:
  493. AssumeZeroReturn = makeOwnedParameter(AssumeZeroReturn);
  494. break;
  495. default:
  496. break;
  497. }
  498. }
  499. if (SplitNecessary) {
  500. return {AssumeNonZeroReturn, AssumeZeroReturn};
  501. } else {
  502. assert(AssumeZeroReturn == AssumeNonZeroReturn);
  503. return {AssumeZeroReturn};
  504. }
  505. }
  506. void RetainCountChecker::checkSummary(const RetainSummary &Summ,
  507. const CallEvent &CallOrMsg,
  508. CheckerContext &C) const {
  509. ProgramStateRef state = C.getState();
  510. // Evaluate the effect of the arguments.
  511. RefVal::Kind hasErr = (RefVal::Kind) 0;
  512. SourceRange ErrorRange;
  513. SymbolRef ErrorSym = nullptr;
  514. // Helper tag for providing diagnostics: indicate whether dealloc was sent
  515. // at this location.
  516. bool DeallocSent = false;
  517. for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
  518. SVal V = CallOrMsg.getArgSVal(idx);
  519. ArgEffect Effect = Summ.getArg(idx);
  520. if (SymbolRef Sym = V.getAsLocSymbol()) {
  521. if (const RefVal *T = getRefBinding(state, Sym)) {
  522. if (shouldEscapeOSArgumentOnCall(CallOrMsg, idx, T))
  523. Effect = ArgEffect(StopTrackingHard, ObjKind::OS);
  524. state = updateSymbol(state, Sym, *T, Effect, hasErr, C);
  525. if (hasErr) {
  526. ErrorRange = CallOrMsg.getArgSourceRange(idx);
  527. ErrorSym = Sym;
  528. break;
  529. } else if (Effect.getKind() == Dealloc) {
  530. DeallocSent = true;
  531. }
  532. }
  533. }
  534. }
  535. // Evaluate the effect on the message receiver / `this` argument.
  536. bool ReceiverIsTracked = false;
  537. if (!hasErr) {
  538. if (const auto *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg)) {
  539. if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
  540. if (const RefVal *T = getRefBinding(state, Sym)) {
  541. ReceiverIsTracked = true;
  542. state = updateSymbol(state, Sym, *T,
  543. Summ.getReceiverEffect(), hasErr, C);
  544. if (hasErr) {
  545. ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
  546. ErrorSym = Sym;
  547. } else if (Summ.getReceiverEffect().getKind() == Dealloc) {
  548. DeallocSent = true;
  549. }
  550. }
  551. }
  552. } else if (const auto *MCall = dyn_cast<CXXMemberCall>(&CallOrMsg)) {
  553. if (SymbolRef Sym = MCall->getCXXThisVal().getAsLocSymbol()) {
  554. if (const RefVal *T = getRefBinding(state, Sym)) {
  555. state = updateSymbol(state, Sym, *T, Summ.getThisEffect(),
  556. hasErr, C);
  557. if (hasErr) {
  558. ErrorRange = MCall->getOriginExpr()->getSourceRange();
  559. ErrorSym = Sym;
  560. }
  561. }
  562. }
  563. }
  564. }
  565. // Process any errors.
  566. if (hasErr) {
  567. processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
  568. return;
  569. }
  570. // Consult the summary for the return value.
  571. RetEffect RE = Summ.getRetEffect();
  572. if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
  573. if (ReceiverIsTracked)
  574. RE = getSummaryManager(C).getObjAllocRetEffect();
  575. else
  576. RE = RetEffect::MakeNoRet();
  577. }
  578. if (SymbolRef Sym = CallOrMsg.getReturnValue().getAsSymbol()) {
  579. QualType ResultTy = CallOrMsg.getResultType();
  580. if (RE.notOwned()) {
  581. const Expr *Ex = CallOrMsg.getOriginExpr();
  582. assert(Ex);
  583. ResultTy = GetReturnType(Ex, C.getASTContext());
  584. }
  585. if (std::optional<RefVal> updatedRefVal = refValFromRetEffect(RE, ResultTy))
  586. state = setRefBinding(state, Sym, *updatedRefVal);
  587. }
  588. SmallVector<ProgramStateRef, 2> Out =
  589. updateOutParameters(state, Summ, CallOrMsg);
  590. for (ProgramStateRef St : Out) {
  591. if (DeallocSent) {
  592. C.addTransition(St, C.getPredecessor(), &getDeallocSentTag());
  593. } else {
  594. C.addTransition(St);
  595. }
  596. }
  597. }
  598. ProgramStateRef RetainCountChecker::updateSymbol(ProgramStateRef state,
  599. SymbolRef sym, RefVal V,
  600. ArgEffect AE,
  601. RefVal::Kind &hasErr,
  602. CheckerContext &C) const {
  603. bool IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
  604. if (AE.getObjKind() == ObjKind::ObjC && IgnoreRetainMsg) {
  605. switch (AE.getKind()) {
  606. default:
  607. break;
  608. case IncRef:
  609. AE = AE.withKind(DoNothing);
  610. break;
  611. case DecRef:
  612. AE = AE.withKind(DoNothing);
  613. break;
  614. case DecRefAndStopTrackingHard:
  615. AE = AE.withKind(StopTracking);
  616. break;
  617. }
  618. }
  619. // Handle all use-after-releases.
  620. if (V.getKind() == RefVal::Released) {
  621. V = V ^ RefVal::ErrorUseAfterRelease;
  622. hasErr = V.getKind();
  623. return setRefBinding(state, sym, V);
  624. }
  625. switch (AE.getKind()) {
  626. case UnretainedOutParameter:
  627. case RetainedOutParameter:
  628. case RetainedOutParameterOnZero:
  629. case RetainedOutParameterOnNonZero:
  630. llvm_unreachable("Applies to pointer-to-pointer parameters, which should "
  631. "not have ref state.");
  632. case Dealloc: // NB. we only need to add a note in a non-error case.
  633. switch (V.getKind()) {
  634. default:
  635. llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
  636. case RefVal::Owned:
  637. // The object immediately transitions to the released state.
  638. V = V ^ RefVal::Released;
  639. V.clearCounts();
  640. return setRefBinding(state, sym, V);
  641. case RefVal::NotOwned:
  642. V = V ^ RefVal::ErrorDeallocNotOwned;
  643. hasErr = V.getKind();
  644. break;
  645. }
  646. break;
  647. case MayEscape:
  648. if (V.getKind() == RefVal::Owned) {
  649. V = V ^ RefVal::NotOwned;
  650. break;
  651. }
  652. [[fallthrough]];
  653. case DoNothing:
  654. return state;
  655. case Autorelease:
  656. // Update the autorelease counts.
  657. V = V.autorelease();
  658. break;
  659. case StopTracking:
  660. case StopTrackingHard:
  661. return removeRefBinding(state, sym);
  662. case IncRef:
  663. switch (V.getKind()) {
  664. default:
  665. llvm_unreachable("Invalid RefVal state for a retain.");
  666. case RefVal::Owned:
  667. case RefVal::NotOwned:
  668. V = V + 1;
  669. break;
  670. }
  671. break;
  672. case DecRef:
  673. case DecRefBridgedTransferred:
  674. case DecRefAndStopTrackingHard:
  675. switch (V.getKind()) {
  676. default:
  677. // case 'RefVal::Released' handled above.
  678. llvm_unreachable("Invalid RefVal state for a release.");
  679. case RefVal::Owned:
  680. assert(V.getCount() > 0);
  681. if (V.getCount() == 1) {
  682. if (AE.getKind() == DecRefBridgedTransferred ||
  683. V.getIvarAccessHistory() ==
  684. RefVal::IvarAccessHistory::AccessedDirectly)
  685. V = V ^ RefVal::NotOwned;
  686. else
  687. V = V ^ RefVal::Released;
  688. } else if (AE.getKind() == DecRefAndStopTrackingHard) {
  689. return removeRefBinding(state, sym);
  690. }
  691. V = V - 1;
  692. break;
  693. case RefVal::NotOwned:
  694. if (V.getCount() > 0) {
  695. if (AE.getKind() == DecRefAndStopTrackingHard)
  696. return removeRefBinding(state, sym);
  697. V = V - 1;
  698. } else if (V.getIvarAccessHistory() ==
  699. RefVal::IvarAccessHistory::AccessedDirectly) {
  700. // Assume that the instance variable was holding on the object at
  701. // +1, and we just didn't know.
  702. if (AE.getKind() == DecRefAndStopTrackingHard)
  703. return removeRefBinding(state, sym);
  704. V = V.releaseViaIvar() ^ RefVal::Released;
  705. } else {
  706. V = V ^ RefVal::ErrorReleaseNotOwned;
  707. hasErr = V.getKind();
  708. }
  709. break;
  710. }
  711. break;
  712. }
  713. return setRefBinding(state, sym, V);
  714. }
  715. const RefCountBug &
  716. RetainCountChecker::errorKindToBugKind(RefVal::Kind ErrorKind,
  717. SymbolRef Sym) const {
  718. switch (ErrorKind) {
  719. case RefVal::ErrorUseAfterRelease:
  720. return *UseAfterRelease;
  721. case RefVal::ErrorReleaseNotOwned:
  722. return *ReleaseNotOwned;
  723. case RefVal::ErrorDeallocNotOwned:
  724. if (Sym->getType()->getPointeeCXXRecordDecl())
  725. return *FreeNotOwned;
  726. return *DeallocNotOwned;
  727. default:
  728. llvm_unreachable("Unhandled error.");
  729. }
  730. }
  731. void RetainCountChecker::processNonLeakError(ProgramStateRef St,
  732. SourceRange ErrorRange,
  733. RefVal::Kind ErrorKind,
  734. SymbolRef Sym,
  735. CheckerContext &C) const {
  736. // HACK: Ignore retain-count issues on values accessed through ivars,
  737. // because of cases like this:
  738. // [_contentView retain];
  739. // [_contentView removeFromSuperview];
  740. // [self addSubview:_contentView]; // invalidates 'self'
  741. // [_contentView release];
  742. if (const RefVal *RV = getRefBinding(St, Sym))
  743. if (RV->getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
  744. return;
  745. ExplodedNode *N = C.generateErrorNode(St);
  746. if (!N)
  747. return;
  748. auto report = std::make_unique<RefCountReport>(
  749. errorKindToBugKind(ErrorKind, Sym),
  750. C.getASTContext().getLangOpts(), N, Sym);
  751. report->addRange(ErrorRange);
  752. C.emitReport(std::move(report));
  753. }
  754. //===----------------------------------------------------------------------===//
  755. // Handle the return values of retain-count-related functions.
  756. //===----------------------------------------------------------------------===//
  757. bool RetainCountChecker::evalCall(const CallEvent &Call,
  758. CheckerContext &C) const {
  759. ProgramStateRef state = C.getState();
  760. const auto *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
  761. if (!FD)
  762. return false;
  763. const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
  764. if (!CE)
  765. return false;
  766. RetainSummaryManager &SmrMgr = getSummaryManager(C);
  767. QualType ResultTy = Call.getResultType();
  768. // See if the function has 'rc_ownership_trusted_implementation'
  769. // annotate attribute. If it does, we will not inline it.
  770. bool hasTrustedImplementationAnnotation = false;
  771. const LocationContext *LCtx = C.getLocationContext();
  772. using BehaviorSummary = RetainSummaryManager::BehaviorSummary;
  773. std::optional<BehaviorSummary> BSmr =
  774. SmrMgr.canEval(CE, FD, hasTrustedImplementationAnnotation);
  775. // See if it's one of the specific functions we know how to eval.
  776. if (!BSmr)
  777. return false;
  778. // Bind the return value.
  779. if (BSmr == BehaviorSummary::Identity ||
  780. BSmr == BehaviorSummary::IdentityOrZero ||
  781. BSmr == BehaviorSummary::IdentityThis) {
  782. const Expr *BindReturnTo =
  783. (BSmr == BehaviorSummary::IdentityThis)
  784. ? cast<CXXMemberCallExpr>(CE)->getImplicitObjectArgument()
  785. : CE->getArg(0);
  786. SVal RetVal = state->getSVal(BindReturnTo, LCtx);
  787. // If the receiver is unknown or the function has
  788. // 'rc_ownership_trusted_implementation' annotate attribute, conjure a
  789. // return value.
  790. // FIXME: this branch is very strange.
  791. if (RetVal.isUnknown() ||
  792. (hasTrustedImplementationAnnotation && !ResultTy.isNull())) {
  793. SValBuilder &SVB = C.getSValBuilder();
  794. RetVal =
  795. SVB.conjureSymbolVal(nullptr, CE, LCtx, ResultTy, C.blockCount());
  796. }
  797. // Bind the value.
  798. state = state->BindExpr(CE, LCtx, RetVal, /*Invalidate=*/false);
  799. if (BSmr == BehaviorSummary::IdentityOrZero) {
  800. // Add a branch where the output is zero.
  801. ProgramStateRef NullOutputState = C.getState();
  802. // Assume that output is zero on the other branch.
  803. NullOutputState = NullOutputState->BindExpr(
  804. CE, LCtx, C.getSValBuilder().makeNullWithType(ResultTy),
  805. /*Invalidate=*/false);
  806. C.addTransition(NullOutputState, &getCastFailTag());
  807. // And on the original branch assume that both input and
  808. // output are non-zero.
  809. if (auto L = RetVal.getAs<DefinedOrUnknownSVal>())
  810. state = state->assume(*L, /*assumption=*/true);
  811. }
  812. }
  813. C.addTransition(state);
  814. return true;
  815. }
  816. ExplodedNode * RetainCountChecker::processReturn(const ReturnStmt *S,
  817. CheckerContext &C) const {
  818. ExplodedNode *Pred = C.getPredecessor();
  819. // Only adjust the reference count if this is the top-level call frame,
  820. // and not the result of inlining. In the future, we should do
  821. // better checking even for inlined calls, and see if they match
  822. // with their expected semantics (e.g., the method should return a retained
  823. // object, etc.).
  824. if (!C.inTopFrame())
  825. return Pred;
  826. if (!S)
  827. return Pred;
  828. const Expr *RetE = S->getRetValue();
  829. if (!RetE)
  830. return Pred;
  831. ProgramStateRef state = C.getState();
  832. // We need to dig down to the symbolic base here because various
  833. // custom allocators do sometimes return the symbol with an offset.
  834. SymbolRef Sym = state->getSValAsScalarOrLoc(RetE, C.getLocationContext())
  835. .getAsLocSymbol(/*IncludeBaseRegions=*/true);
  836. if (!Sym)
  837. return Pred;
  838. // Get the reference count binding (if any).
  839. const RefVal *T = getRefBinding(state, Sym);
  840. if (!T)
  841. return Pred;
  842. // Change the reference count.
  843. RefVal X = *T;
  844. switch (X.getKind()) {
  845. case RefVal::Owned: {
  846. unsigned cnt = X.getCount();
  847. assert(cnt > 0);
  848. X.setCount(cnt - 1);
  849. X = X ^ RefVal::ReturnedOwned;
  850. break;
  851. }
  852. case RefVal::NotOwned: {
  853. unsigned cnt = X.getCount();
  854. if (cnt) {
  855. X.setCount(cnt - 1);
  856. X = X ^ RefVal::ReturnedOwned;
  857. } else {
  858. X = X ^ RefVal::ReturnedNotOwned;
  859. }
  860. break;
  861. }
  862. default:
  863. return Pred;
  864. }
  865. // Update the binding.
  866. state = setRefBinding(state, Sym, X);
  867. Pred = C.addTransition(state);
  868. // At this point we have updated the state properly.
  869. // Everything after this is merely checking to see if the return value has
  870. // been over- or under-retained.
  871. // Did we cache out?
  872. if (!Pred)
  873. return nullptr;
  874. // Update the autorelease counts.
  875. static CheckerProgramPointTag AutoreleaseTag(this, "Autorelease");
  876. state = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag, C, Sym, X, S);
  877. // Have we generated a sink node?
  878. if (!state)
  879. return nullptr;
  880. // Get the updated binding.
  881. T = getRefBinding(state, Sym);
  882. assert(T);
  883. X = *T;
  884. // Consult the summary of the enclosing method.
  885. RetainSummaryManager &Summaries = getSummaryManager(C);
  886. const Decl *CD = &Pred->getCodeDecl();
  887. RetEffect RE = RetEffect::MakeNoRet();
  888. // FIXME: What is the convention for blocks? Is there one?
  889. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
  890. const RetainSummary *Summ = Summaries.getSummary(AnyCall(MD));
  891. RE = Summ->getRetEffect();
  892. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
  893. if (!isa<CXXMethodDecl>(FD)) {
  894. const RetainSummary *Summ = Summaries.getSummary(AnyCall(FD));
  895. RE = Summ->getRetEffect();
  896. }
  897. }
  898. return checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
  899. }
  900. ExplodedNode * RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
  901. CheckerContext &C,
  902. ExplodedNode *Pred,
  903. RetEffect RE, RefVal X,
  904. SymbolRef Sym,
  905. ProgramStateRef state) const {
  906. // HACK: Ignore retain-count issues on values accessed through ivars,
  907. // because of cases like this:
  908. // [_contentView retain];
  909. // [_contentView removeFromSuperview];
  910. // [self addSubview:_contentView]; // invalidates 'self'
  911. // [_contentView release];
  912. if (X.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
  913. return Pred;
  914. // Any leaks or other errors?
  915. if (X.isReturnedOwned() && X.getCount() == 0) {
  916. if (RE.getKind() != RetEffect::NoRet) {
  917. if (!RE.isOwned()) {
  918. // The returning type is a CF, we expect the enclosing method should
  919. // return ownership.
  920. X = X ^ RefVal::ErrorLeakReturned;
  921. // Generate an error node.
  922. state = setRefBinding(state, Sym, X);
  923. static CheckerProgramPointTag ReturnOwnLeakTag(this, "ReturnsOwnLeak");
  924. ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
  925. if (N) {
  926. const LangOptions &LOpts = C.getASTContext().getLangOpts();
  927. auto R =
  928. std::make_unique<RefLeakReport>(*LeakAtReturn, LOpts, N, Sym, C);
  929. C.emitReport(std::move(R));
  930. }
  931. return N;
  932. }
  933. }
  934. } else if (X.isReturnedNotOwned()) {
  935. if (RE.isOwned()) {
  936. if (X.getIvarAccessHistory() ==
  937. RefVal::IvarAccessHistory::AccessedDirectly) {
  938. // Assume the method was trying to transfer a +1 reference from a
  939. // strong ivar to the caller.
  940. state = setRefBinding(state, Sym,
  941. X.releaseViaIvar() ^ RefVal::ReturnedOwned);
  942. } else {
  943. // Trying to return a not owned object to a caller expecting an
  944. // owned object.
  945. state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
  946. static CheckerProgramPointTag
  947. ReturnNotOwnedTag(this, "ReturnNotOwnedForOwned");
  948. ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
  949. if (N) {
  950. auto R = std::make_unique<RefCountReport>(
  951. *ReturnNotOwnedForOwned, C.getASTContext().getLangOpts(), N, Sym);
  952. C.emitReport(std::move(R));
  953. }
  954. return N;
  955. }
  956. }
  957. }
  958. return Pred;
  959. }
  960. //===----------------------------------------------------------------------===//
  961. // Check various ways a symbol can be invalidated.
  962. //===----------------------------------------------------------------------===//
  963. void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
  964. CheckerContext &C) const {
  965. ProgramStateRef state = C.getState();
  966. const MemRegion *MR = loc.getAsRegion();
  967. // Find all symbols referenced by 'val' that we are tracking
  968. // and stop tracking them.
  969. if (MR && shouldEscapeRegion(MR)) {
  970. state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
  971. C.addTransition(state);
  972. }
  973. }
  974. ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
  975. SVal Cond,
  976. bool Assumption) const {
  977. // FIXME: We may add to the interface of evalAssume the list of symbols
  978. // whose assumptions have changed. For now we just iterate through the
  979. // bindings and check if any of the tracked symbols are NULL. This isn't
  980. // too bad since the number of symbols we will track in practice are
  981. // probably small and evalAssume is only called at branches and a few
  982. // other places.
  983. RefBindingsTy B = state->get<RefBindings>();
  984. if (B.isEmpty())
  985. return state;
  986. bool changed = false;
  987. RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
  988. ConstraintManager &CMgr = state->getConstraintManager();
  989. for (auto &I : B) {
  990. // Check if the symbol is null stop tracking the symbol.
  991. ConditionTruthVal AllocFailed = CMgr.isNull(state, I.first);
  992. if (AllocFailed.isConstrainedTrue()) {
  993. changed = true;
  994. B = RefBFactory.remove(B, I.first);
  995. }
  996. }
  997. if (changed)
  998. state = state->set<RefBindings>(B);
  999. return state;
  1000. }
  1001. ProgramStateRef RetainCountChecker::checkRegionChanges(
  1002. ProgramStateRef state, const InvalidatedSymbols *invalidated,
  1003. ArrayRef<const MemRegion *> ExplicitRegions,
  1004. ArrayRef<const MemRegion *> Regions, const LocationContext *LCtx,
  1005. const CallEvent *Call) const {
  1006. if (!invalidated)
  1007. return state;
  1008. llvm::SmallPtrSet<SymbolRef, 8> AllowedSymbols;
  1009. for (const MemRegion *I : ExplicitRegions)
  1010. if (const SymbolicRegion *SR = I->StripCasts()->getAs<SymbolicRegion>())
  1011. AllowedSymbols.insert(SR->getSymbol());
  1012. for (SymbolRef sym : *invalidated) {
  1013. if (AllowedSymbols.count(sym))
  1014. continue;
  1015. // Remove any existing reference-count binding.
  1016. state = removeRefBinding(state, sym);
  1017. }
  1018. return state;
  1019. }
  1020. ProgramStateRef
  1021. RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
  1022. ExplodedNode *Pred,
  1023. const ProgramPointTag *Tag,
  1024. CheckerContext &Ctx,
  1025. SymbolRef Sym,
  1026. RefVal V,
  1027. const ReturnStmt *S) const {
  1028. unsigned ACnt = V.getAutoreleaseCount();
  1029. // No autorelease counts? Nothing to be done.
  1030. if (!ACnt)
  1031. return state;
  1032. unsigned Cnt = V.getCount();
  1033. // FIXME: Handle sending 'autorelease' to already released object.
  1034. if (V.getKind() == RefVal::ReturnedOwned)
  1035. ++Cnt;
  1036. // If we would over-release here, but we know the value came from an ivar,
  1037. // assume it was a strong ivar that's just been relinquished.
  1038. if (ACnt > Cnt &&
  1039. V.getIvarAccessHistory() == RefVal::IvarAccessHistory::AccessedDirectly) {
  1040. V = V.releaseViaIvar();
  1041. --ACnt;
  1042. }
  1043. if (ACnt <= Cnt) {
  1044. if (ACnt == Cnt) {
  1045. V.clearCounts();
  1046. if (V.getKind() == RefVal::ReturnedOwned) {
  1047. V = V ^ RefVal::ReturnedNotOwned;
  1048. } else {
  1049. V = V ^ RefVal::NotOwned;
  1050. }
  1051. } else {
  1052. V.setCount(V.getCount() - ACnt);
  1053. V.setAutoreleaseCount(0);
  1054. }
  1055. return setRefBinding(state, Sym, V);
  1056. }
  1057. // HACK: Ignore retain-count issues on values accessed through ivars,
  1058. // because of cases like this:
  1059. // [_contentView retain];
  1060. // [_contentView removeFromSuperview];
  1061. // [self addSubview:_contentView]; // invalidates 'self'
  1062. // [_contentView release];
  1063. if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
  1064. return state;
  1065. // Woah! More autorelease counts then retain counts left.
  1066. // Emit hard error.
  1067. V = V ^ RefVal::ErrorOverAutorelease;
  1068. state = setRefBinding(state, Sym, V);
  1069. ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
  1070. if (N) {
  1071. SmallString<128> sbuf;
  1072. llvm::raw_svector_ostream os(sbuf);
  1073. os << "Object was autoreleased ";
  1074. if (V.getAutoreleaseCount() > 1)
  1075. os << V.getAutoreleaseCount() << " times but the object ";
  1076. else
  1077. os << "but ";
  1078. os << "has a +" << V.getCount() << " retain count";
  1079. const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
  1080. auto R = std::make_unique<RefCountReport>(*OverAutorelease, LOpts, N, Sym,
  1081. os.str());
  1082. Ctx.emitReport(std::move(R));
  1083. }
  1084. return nullptr;
  1085. }
  1086. ProgramStateRef
  1087. RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
  1088. SymbolRef sid, RefVal V,
  1089. SmallVectorImpl<SymbolRef> &Leaked) const {
  1090. bool hasLeak;
  1091. // HACK: Ignore retain-count issues on values accessed through ivars,
  1092. // because of cases like this:
  1093. // [_contentView retain];
  1094. // [_contentView removeFromSuperview];
  1095. // [self addSubview:_contentView]; // invalidates 'self'
  1096. // [_contentView release];
  1097. if (V.getIvarAccessHistory() != RefVal::IvarAccessHistory::None)
  1098. hasLeak = false;
  1099. else if (V.isOwned())
  1100. hasLeak = true;
  1101. else if (V.isNotOwned() || V.isReturnedOwned())
  1102. hasLeak = (V.getCount() > 0);
  1103. else
  1104. hasLeak = false;
  1105. if (!hasLeak)
  1106. return removeRefBinding(state, sid);
  1107. Leaked.push_back(sid);
  1108. return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
  1109. }
  1110. ExplodedNode *
  1111. RetainCountChecker::processLeaks(ProgramStateRef state,
  1112. SmallVectorImpl<SymbolRef> &Leaked,
  1113. CheckerContext &Ctx,
  1114. ExplodedNode *Pred) const {
  1115. // Generate an intermediate node representing the leak point.
  1116. ExplodedNode *N = Ctx.addTransition(state, Pred);
  1117. const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
  1118. if (N) {
  1119. for (SymbolRef L : Leaked) {
  1120. const RefCountBug &BT = Pred ? *LeakWithinFunction : *LeakAtReturn;
  1121. Ctx.emitReport(std::make_unique<RefLeakReport>(BT, LOpts, N, L, Ctx));
  1122. }
  1123. }
  1124. return N;
  1125. }
  1126. void RetainCountChecker::checkBeginFunction(CheckerContext &Ctx) const {
  1127. if (!Ctx.inTopFrame())
  1128. return;
  1129. RetainSummaryManager &SmrMgr = getSummaryManager(Ctx);
  1130. const LocationContext *LCtx = Ctx.getLocationContext();
  1131. const Decl *D = LCtx->getDecl();
  1132. std::optional<AnyCall> C = AnyCall::forDecl(D);
  1133. if (!C || SmrMgr.isTrustedReferenceCountImplementation(D))
  1134. return;
  1135. ProgramStateRef state = Ctx.getState();
  1136. const RetainSummary *FunctionSummary = SmrMgr.getSummary(*C);
  1137. ArgEffects CalleeSideArgEffects = FunctionSummary->getArgEffects();
  1138. for (unsigned idx = 0, e = C->param_size(); idx != e; ++idx) {
  1139. const ParmVarDecl *Param = C->parameters()[idx];
  1140. SymbolRef Sym = state->getSVal(state->getRegion(Param, LCtx)).getAsSymbol();
  1141. QualType Ty = Param->getType();
  1142. const ArgEffect *AE = CalleeSideArgEffects.lookup(idx);
  1143. if (AE) {
  1144. ObjKind K = AE->getObjKind();
  1145. if (K == ObjKind::Generalized || K == ObjKind::OS ||
  1146. (TrackNSCFStartParam && (K == ObjKind::ObjC || K == ObjKind::CF))) {
  1147. RefVal NewVal = AE->getKind() == DecRef ? RefVal::makeOwned(K, Ty)
  1148. : RefVal::makeNotOwned(K, Ty);
  1149. state = setRefBinding(state, Sym, NewVal);
  1150. }
  1151. }
  1152. }
  1153. Ctx.addTransition(state);
  1154. }
  1155. void RetainCountChecker::checkEndFunction(const ReturnStmt *RS,
  1156. CheckerContext &Ctx) const {
  1157. ExplodedNode *Pred = processReturn(RS, Ctx);
  1158. // Created state cached out.
  1159. if (!Pred) {
  1160. return;
  1161. }
  1162. ProgramStateRef state = Pred->getState();
  1163. RefBindingsTy B = state->get<RefBindings>();
  1164. // Don't process anything within synthesized bodies.
  1165. const LocationContext *LCtx = Pred->getLocationContext();
  1166. if (LCtx->getAnalysisDeclContext()->isBodyAutosynthesized()) {
  1167. assert(!LCtx->inTopFrame());
  1168. return;
  1169. }
  1170. for (auto &I : B) {
  1171. state = handleAutoreleaseCounts(state, Pred, /*Tag=*/nullptr, Ctx,
  1172. I.first, I.second);
  1173. if (!state)
  1174. return;
  1175. }
  1176. // If the current LocationContext has a parent, don't check for leaks.
  1177. // We will do that later.
  1178. // FIXME: we should instead check for imbalances of the retain/releases,
  1179. // and suggest annotations.
  1180. if (LCtx->getParent())
  1181. return;
  1182. B = state->get<RefBindings>();
  1183. SmallVector<SymbolRef, 10> Leaked;
  1184. for (auto &I : B)
  1185. state = handleSymbolDeath(state, I.first, I.second, Leaked);
  1186. processLeaks(state, Leaked, Ctx, Pred);
  1187. }
  1188. void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
  1189. CheckerContext &C) const {
  1190. ExplodedNode *Pred = C.getPredecessor();
  1191. ProgramStateRef state = C.getState();
  1192. SmallVector<SymbolRef, 10> Leaked;
  1193. // Update counts from autorelease pools
  1194. for (const auto &I: state->get<RefBindings>()) {
  1195. SymbolRef Sym = I.first;
  1196. if (SymReaper.isDead(Sym)) {
  1197. static CheckerProgramPointTag Tag(this, "DeadSymbolAutorelease");
  1198. const RefVal &V = I.second;
  1199. state = handleAutoreleaseCounts(state, Pred, &Tag, C, Sym, V);
  1200. if (!state)
  1201. return;
  1202. // Fetch the new reference count from the state, and use it to handle
  1203. // this symbol.
  1204. state = handleSymbolDeath(state, Sym, *getRefBinding(state, Sym), Leaked);
  1205. }
  1206. }
  1207. if (Leaked.empty()) {
  1208. C.addTransition(state);
  1209. return;
  1210. }
  1211. Pred = processLeaks(state, Leaked, C, Pred);
  1212. // Did we cache out?
  1213. if (!Pred)
  1214. return;
  1215. // Now generate a new node that nukes the old bindings.
  1216. // The only bindings left at this point are the leaked symbols.
  1217. RefBindingsTy::Factory &F = state->get_context<RefBindings>();
  1218. RefBindingsTy B = state->get<RefBindings>();
  1219. for (SymbolRef L : Leaked)
  1220. B = F.remove(B, L);
  1221. state = state->set<RefBindings>(B);
  1222. C.addTransition(state, Pred);
  1223. }
  1224. void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
  1225. const char *NL, const char *Sep) const {
  1226. RefBindingsTy B = State->get<RefBindings>();
  1227. if (B.isEmpty())
  1228. return;
  1229. Out << Sep << NL;
  1230. for (auto &I : B) {
  1231. Out << I.first << " : ";
  1232. I.second.print(Out);
  1233. Out << NL;
  1234. }
  1235. }
  1236. //===----------------------------------------------------------------------===//
  1237. // Checker registration.
  1238. //===----------------------------------------------------------------------===//
  1239. std::unique_ptr<CheckerProgramPointTag> RetainCountChecker::DeallocSentTag;
  1240. std::unique_ptr<CheckerProgramPointTag> RetainCountChecker::CastFailTag;
  1241. void ento::registerRetainCountBase(CheckerManager &Mgr) {
  1242. auto *Chk = Mgr.registerChecker<RetainCountChecker>();
  1243. Chk->DeallocSentTag =
  1244. std::make_unique<CheckerProgramPointTag>(Chk, "DeallocSent");
  1245. Chk->CastFailTag =
  1246. std::make_unique<CheckerProgramPointTag>(Chk, "DynamicCastFail");
  1247. }
  1248. bool ento::shouldRegisterRetainCountBase(const CheckerManager &mgr) {
  1249. return true;
  1250. }
  1251. void ento::registerRetainCountChecker(CheckerManager &Mgr) {
  1252. auto *Chk = Mgr.getChecker<RetainCountChecker>();
  1253. Chk->TrackObjCAndCFObjects = true;
  1254. Chk->TrackNSCFStartParam = Mgr.getAnalyzerOptions().getCheckerBooleanOption(
  1255. Mgr.getCurrentCheckerName(), "TrackNSCFStartParam");
  1256. #define INIT_BUGTYPE(KIND) \
  1257. Chk->KIND = std::make_unique<RefCountBug>(Mgr.getCurrentCheckerName(), \
  1258. RefCountBug::KIND);
  1259. // TODO: Ideally, we should have a checker for each of these bug types.
  1260. INIT_BUGTYPE(UseAfterRelease)
  1261. INIT_BUGTYPE(ReleaseNotOwned)
  1262. INIT_BUGTYPE(DeallocNotOwned)
  1263. INIT_BUGTYPE(FreeNotOwned)
  1264. INIT_BUGTYPE(OverAutorelease)
  1265. INIT_BUGTYPE(ReturnNotOwnedForOwned)
  1266. INIT_BUGTYPE(LeakWithinFunction)
  1267. INIT_BUGTYPE(LeakAtReturn)
  1268. #undef INIT_BUGTYPE
  1269. }
  1270. bool ento::shouldRegisterRetainCountChecker(const CheckerManager &mgr) {
  1271. return true;
  1272. }
  1273. void ento::registerOSObjectRetainCountChecker(CheckerManager &Mgr) {
  1274. auto *Chk = Mgr.getChecker<RetainCountChecker>();
  1275. Chk->TrackOSObjects = true;
  1276. // FIXME: We want bug reports to always have the same checker name associated
  1277. // with them, yet here, if RetainCountChecker is disabled but
  1278. // OSObjectRetainCountChecker is enabled, the checker names will be different.
  1279. // This hack will make it so that the checker name depends on which checker is
  1280. // enabled rather than on the registration order.
  1281. // For the most part, we want **non-hidden checkers** to be associated with
  1282. // diagnostics, and **hidden checker options** with the fine-tuning of
  1283. // modeling. Following this logic, OSObjectRetainCountChecker should be the
  1284. // latter, but we can't just remove it for backward compatibility reasons.
  1285. #define LAZY_INIT_BUGTYPE(KIND) \
  1286. if (!Chk->KIND) \
  1287. Chk->KIND = std::make_unique<RefCountBug>(Mgr.getCurrentCheckerName(), \
  1288. RefCountBug::KIND);
  1289. LAZY_INIT_BUGTYPE(UseAfterRelease)
  1290. LAZY_INIT_BUGTYPE(ReleaseNotOwned)
  1291. LAZY_INIT_BUGTYPE(DeallocNotOwned)
  1292. LAZY_INIT_BUGTYPE(FreeNotOwned)
  1293. LAZY_INIT_BUGTYPE(OverAutorelease)
  1294. LAZY_INIT_BUGTYPE(ReturnNotOwnedForOwned)
  1295. LAZY_INIT_BUGTYPE(LeakWithinFunction)
  1296. LAZY_INIT_BUGTYPE(LeakAtReturn)
  1297. #undef LAZY_INIT_BUGTYPE
  1298. }
  1299. bool ento::shouldRegisterOSObjectRetainCountChecker(const CheckerManager &mgr) {
  1300. return true;
  1301. }