RetainCountChecker.cpp 50 KB

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