BasicObjCFoundationChecks.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  1. //== BasicObjCFoundationChecks.cpp - Simple Apple-Foundation checks -*- 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 BasicObjCFoundationChecks, a class that encapsulates
  10. // a set of simple checks to run on Objective-C code using Apple's Foundation
  11. // classes.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/DeclObjC.h"
  16. #include "clang/AST/Expr.h"
  17. #include "clang/AST/ExprObjC.h"
  18. #include "clang/AST/StmtObjC.h"
  19. #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
  20. #include "clang/Analysis/SelectorExtras.h"
  21. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  22. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  23. #include "clang/StaticAnalyzer/Core/Checker.h"
  24. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  25. #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
  26. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  27. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  28. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  29. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  30. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  31. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  32. #include "llvm/ADT/SmallString.h"
  33. #include "llvm/ADT/StringMap.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include <optional>
  36. using namespace clang;
  37. using namespace ento;
  38. using namespace llvm;
  39. namespace {
  40. class APIMisuse : public BugType {
  41. public:
  42. APIMisuse(const CheckerBase *checker, const char *name)
  43. : BugType(checker, name, "API Misuse (Apple)") {}
  44. };
  45. } // end anonymous namespace
  46. //===----------------------------------------------------------------------===//
  47. // Utility functions.
  48. //===----------------------------------------------------------------------===//
  49. static StringRef GetReceiverInterfaceName(const ObjCMethodCall &msg) {
  50. if (const ObjCInterfaceDecl *ID = msg.getReceiverInterface())
  51. return ID->getIdentifier()->getName();
  52. return StringRef();
  53. }
  54. enum FoundationClass {
  55. FC_None,
  56. FC_NSArray,
  57. FC_NSDictionary,
  58. FC_NSEnumerator,
  59. FC_NSNull,
  60. FC_NSOrderedSet,
  61. FC_NSSet,
  62. FC_NSString
  63. };
  64. static FoundationClass findKnownClass(const ObjCInterfaceDecl *ID,
  65. bool IncludeSuperclasses = true) {
  66. static llvm::StringMap<FoundationClass> Classes;
  67. if (Classes.empty()) {
  68. Classes["NSArray"] = FC_NSArray;
  69. Classes["NSDictionary"] = FC_NSDictionary;
  70. Classes["NSEnumerator"] = FC_NSEnumerator;
  71. Classes["NSNull"] = FC_NSNull;
  72. Classes["NSOrderedSet"] = FC_NSOrderedSet;
  73. Classes["NSSet"] = FC_NSSet;
  74. Classes["NSString"] = FC_NSString;
  75. }
  76. // FIXME: Should we cache this at all?
  77. FoundationClass result = Classes.lookup(ID->getIdentifier()->getName());
  78. if (result == FC_None && IncludeSuperclasses)
  79. if (const ObjCInterfaceDecl *Super = ID->getSuperClass())
  80. return findKnownClass(Super);
  81. return result;
  82. }
  83. //===----------------------------------------------------------------------===//
  84. // NilArgChecker - Check for prohibited nil arguments to ObjC method calls.
  85. //===----------------------------------------------------------------------===//
  86. namespace {
  87. class NilArgChecker : public Checker<check::PreObjCMessage,
  88. check::PostStmt<ObjCDictionaryLiteral>,
  89. check::PostStmt<ObjCArrayLiteral> > {
  90. mutable std::unique_ptr<APIMisuse> BT;
  91. mutable llvm::SmallDenseMap<Selector, unsigned, 16> StringSelectors;
  92. mutable Selector ArrayWithObjectSel;
  93. mutable Selector AddObjectSel;
  94. mutable Selector InsertObjectAtIndexSel;
  95. mutable Selector ReplaceObjectAtIndexWithObjectSel;
  96. mutable Selector SetObjectAtIndexedSubscriptSel;
  97. mutable Selector ArrayByAddingObjectSel;
  98. mutable Selector DictionaryWithObjectForKeySel;
  99. mutable Selector SetObjectForKeySel;
  100. mutable Selector SetObjectForKeyedSubscriptSel;
  101. mutable Selector RemoveObjectForKeySel;
  102. void warnIfNilExpr(const Expr *E,
  103. const char *Msg,
  104. CheckerContext &C) const;
  105. void warnIfNilArg(CheckerContext &C,
  106. const ObjCMethodCall &msg, unsigned Arg,
  107. FoundationClass Class,
  108. bool CanBeSubscript = false) const;
  109. void generateBugReport(ExplodedNode *N,
  110. StringRef Msg,
  111. SourceRange Range,
  112. const Expr *Expr,
  113. CheckerContext &C) const;
  114. public:
  115. void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
  116. void checkPostStmt(const ObjCDictionaryLiteral *DL,
  117. CheckerContext &C) const;
  118. void checkPostStmt(const ObjCArrayLiteral *AL,
  119. CheckerContext &C) const;
  120. };
  121. } // end anonymous namespace
  122. void NilArgChecker::warnIfNilExpr(const Expr *E,
  123. const char *Msg,
  124. CheckerContext &C) const {
  125. ProgramStateRef State = C.getState();
  126. if (State->isNull(C.getSVal(E)).isConstrainedTrue()) {
  127. if (ExplodedNode *N = C.generateErrorNode()) {
  128. generateBugReport(N, Msg, E->getSourceRange(), E, C);
  129. }
  130. }
  131. }
  132. void NilArgChecker::warnIfNilArg(CheckerContext &C,
  133. const ObjCMethodCall &msg,
  134. unsigned int Arg,
  135. FoundationClass Class,
  136. bool CanBeSubscript) const {
  137. // Check if the argument is nil.
  138. ProgramStateRef State = C.getState();
  139. if (!State->isNull(msg.getArgSVal(Arg)).isConstrainedTrue())
  140. return;
  141. // NOTE: We cannot throw non-fatal errors from warnIfNilExpr,
  142. // because it's called multiple times from some callers, so it'd cause
  143. // an unwanted state split if two or more non-fatal errors are thrown
  144. // within the same checker callback. For now we don't want to, but
  145. // it'll need to be fixed if we ever want to.
  146. if (ExplodedNode *N = C.generateErrorNode()) {
  147. SmallString<128> sbuf;
  148. llvm::raw_svector_ostream os(sbuf);
  149. if (CanBeSubscript && msg.getMessageKind() == OCM_Subscript) {
  150. if (Class == FC_NSArray) {
  151. os << "Array element cannot be nil";
  152. } else if (Class == FC_NSDictionary) {
  153. if (Arg == 0) {
  154. os << "Value stored into '";
  155. os << GetReceiverInterfaceName(msg) << "' cannot be nil";
  156. } else {
  157. assert(Arg == 1);
  158. os << "'"<< GetReceiverInterfaceName(msg) << "' key cannot be nil";
  159. }
  160. } else
  161. llvm_unreachable("Missing foundation class for the subscript expr");
  162. } else {
  163. if (Class == FC_NSDictionary) {
  164. if (Arg == 0)
  165. os << "Value argument ";
  166. else {
  167. assert(Arg == 1);
  168. os << "Key argument ";
  169. }
  170. os << "to '";
  171. msg.getSelector().print(os);
  172. os << "' cannot be nil";
  173. } else {
  174. os << "Argument to '" << GetReceiverInterfaceName(msg) << "' method '";
  175. msg.getSelector().print(os);
  176. os << "' cannot be nil";
  177. }
  178. }
  179. generateBugReport(N, os.str(), msg.getArgSourceRange(Arg),
  180. msg.getArgExpr(Arg), C);
  181. }
  182. }
  183. void NilArgChecker::generateBugReport(ExplodedNode *N,
  184. StringRef Msg,
  185. SourceRange Range,
  186. const Expr *E,
  187. CheckerContext &C) const {
  188. if (!BT)
  189. BT.reset(new APIMisuse(this, "nil argument"));
  190. auto R = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
  191. R->addRange(Range);
  192. bugreporter::trackExpressionValue(N, E, *R);
  193. C.emitReport(std::move(R));
  194. }
  195. void NilArgChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
  196. CheckerContext &C) const {
  197. const ObjCInterfaceDecl *ID = msg.getReceiverInterface();
  198. if (!ID)
  199. return;
  200. FoundationClass Class = findKnownClass(ID);
  201. static const unsigned InvalidArgIndex = UINT_MAX;
  202. unsigned Arg = InvalidArgIndex;
  203. bool CanBeSubscript = false;
  204. if (Class == FC_NSString) {
  205. Selector S = msg.getSelector();
  206. if (S.isUnarySelector())
  207. return;
  208. if (StringSelectors.empty()) {
  209. ASTContext &Ctx = C.getASTContext();
  210. Selector Sels[] = {
  211. getKeywordSelector(Ctx, "caseInsensitiveCompare"),
  212. getKeywordSelector(Ctx, "compare"),
  213. getKeywordSelector(Ctx, "compare", "options"),
  214. getKeywordSelector(Ctx, "compare", "options", "range"),
  215. getKeywordSelector(Ctx, "compare", "options", "range", "locale"),
  216. getKeywordSelector(Ctx, "componentsSeparatedByCharactersInSet"),
  217. getKeywordSelector(Ctx, "initWithFormat"),
  218. getKeywordSelector(Ctx, "localizedCaseInsensitiveCompare"),
  219. getKeywordSelector(Ctx, "localizedCompare"),
  220. getKeywordSelector(Ctx, "localizedStandardCompare"),
  221. };
  222. for (Selector KnownSel : Sels)
  223. StringSelectors[KnownSel] = 0;
  224. }
  225. auto I = StringSelectors.find(S);
  226. if (I == StringSelectors.end())
  227. return;
  228. Arg = I->second;
  229. } else if (Class == FC_NSArray) {
  230. Selector S = msg.getSelector();
  231. if (S.isUnarySelector())
  232. return;
  233. if (ArrayWithObjectSel.isNull()) {
  234. ASTContext &Ctx = C.getASTContext();
  235. ArrayWithObjectSel = getKeywordSelector(Ctx, "arrayWithObject");
  236. AddObjectSel = getKeywordSelector(Ctx, "addObject");
  237. InsertObjectAtIndexSel =
  238. getKeywordSelector(Ctx, "insertObject", "atIndex");
  239. ReplaceObjectAtIndexWithObjectSel =
  240. getKeywordSelector(Ctx, "replaceObjectAtIndex", "withObject");
  241. SetObjectAtIndexedSubscriptSel =
  242. getKeywordSelector(Ctx, "setObject", "atIndexedSubscript");
  243. ArrayByAddingObjectSel = getKeywordSelector(Ctx, "arrayByAddingObject");
  244. }
  245. if (S == ArrayWithObjectSel || S == AddObjectSel ||
  246. S == InsertObjectAtIndexSel || S == ArrayByAddingObjectSel) {
  247. Arg = 0;
  248. } else if (S == SetObjectAtIndexedSubscriptSel) {
  249. Arg = 0;
  250. CanBeSubscript = true;
  251. } else if (S == ReplaceObjectAtIndexWithObjectSel) {
  252. Arg = 1;
  253. }
  254. } else if (Class == FC_NSDictionary) {
  255. Selector S = msg.getSelector();
  256. if (S.isUnarySelector())
  257. return;
  258. if (DictionaryWithObjectForKeySel.isNull()) {
  259. ASTContext &Ctx = C.getASTContext();
  260. DictionaryWithObjectForKeySel =
  261. getKeywordSelector(Ctx, "dictionaryWithObject", "forKey");
  262. SetObjectForKeySel = getKeywordSelector(Ctx, "setObject", "forKey");
  263. SetObjectForKeyedSubscriptSel =
  264. getKeywordSelector(Ctx, "setObject", "forKeyedSubscript");
  265. RemoveObjectForKeySel = getKeywordSelector(Ctx, "removeObjectForKey");
  266. }
  267. if (S == DictionaryWithObjectForKeySel || S == SetObjectForKeySel) {
  268. Arg = 0;
  269. warnIfNilArg(C, msg, /* Arg */1, Class);
  270. } else if (S == SetObjectForKeyedSubscriptSel) {
  271. CanBeSubscript = true;
  272. Arg = 1;
  273. } else if (S == RemoveObjectForKeySel) {
  274. Arg = 0;
  275. }
  276. }
  277. // If argument is '0', report a warning.
  278. if ((Arg != InvalidArgIndex))
  279. warnIfNilArg(C, msg, Arg, Class, CanBeSubscript);
  280. }
  281. void NilArgChecker::checkPostStmt(const ObjCArrayLiteral *AL,
  282. CheckerContext &C) const {
  283. unsigned NumOfElements = AL->getNumElements();
  284. for (unsigned i = 0; i < NumOfElements; ++i) {
  285. warnIfNilExpr(AL->getElement(i), "Array element cannot be nil", C);
  286. }
  287. }
  288. void NilArgChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
  289. CheckerContext &C) const {
  290. unsigned NumOfElements = DL->getNumElements();
  291. for (unsigned i = 0; i < NumOfElements; ++i) {
  292. ObjCDictionaryElement Element = DL->getKeyValueElement(i);
  293. warnIfNilExpr(Element.Key, "Dictionary key cannot be nil", C);
  294. warnIfNilExpr(Element.Value, "Dictionary value cannot be nil", C);
  295. }
  296. }
  297. //===----------------------------------------------------------------------===//
  298. // Checking for mismatched types passed to CFNumberCreate/CFNumberGetValue.
  299. //===----------------------------------------------------------------------===//
  300. namespace {
  301. class CFNumberChecker : public Checker< check::PreStmt<CallExpr> > {
  302. mutable std::unique_ptr<APIMisuse> BT;
  303. mutable IdentifierInfo *ICreate, *IGetValue;
  304. public:
  305. CFNumberChecker() : ICreate(nullptr), IGetValue(nullptr) {}
  306. void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
  307. };
  308. } // end anonymous namespace
  309. enum CFNumberType {
  310. kCFNumberSInt8Type = 1,
  311. kCFNumberSInt16Type = 2,
  312. kCFNumberSInt32Type = 3,
  313. kCFNumberSInt64Type = 4,
  314. kCFNumberFloat32Type = 5,
  315. kCFNumberFloat64Type = 6,
  316. kCFNumberCharType = 7,
  317. kCFNumberShortType = 8,
  318. kCFNumberIntType = 9,
  319. kCFNumberLongType = 10,
  320. kCFNumberLongLongType = 11,
  321. kCFNumberFloatType = 12,
  322. kCFNumberDoubleType = 13,
  323. kCFNumberCFIndexType = 14,
  324. kCFNumberNSIntegerType = 15,
  325. kCFNumberCGFloatType = 16
  326. };
  327. static std::optional<uint64_t> GetCFNumberSize(ASTContext &Ctx, uint64_t i) {
  328. static const unsigned char FixedSize[] = { 8, 16, 32, 64, 32, 64 };
  329. if (i < kCFNumberCharType)
  330. return FixedSize[i-1];
  331. QualType T;
  332. switch (i) {
  333. case kCFNumberCharType: T = Ctx.CharTy; break;
  334. case kCFNumberShortType: T = Ctx.ShortTy; break;
  335. case kCFNumberIntType: T = Ctx.IntTy; break;
  336. case kCFNumberLongType: T = Ctx.LongTy; break;
  337. case kCFNumberLongLongType: T = Ctx.LongLongTy; break;
  338. case kCFNumberFloatType: T = Ctx.FloatTy; break;
  339. case kCFNumberDoubleType: T = Ctx.DoubleTy; break;
  340. case kCFNumberCFIndexType:
  341. case kCFNumberNSIntegerType:
  342. case kCFNumberCGFloatType:
  343. // FIXME: We need a way to map from names to Type*.
  344. default:
  345. return std::nullopt;
  346. }
  347. return Ctx.getTypeSize(T);
  348. }
  349. #if 0
  350. static const char* GetCFNumberTypeStr(uint64_t i) {
  351. static const char* Names[] = {
  352. "kCFNumberSInt8Type",
  353. "kCFNumberSInt16Type",
  354. "kCFNumberSInt32Type",
  355. "kCFNumberSInt64Type",
  356. "kCFNumberFloat32Type",
  357. "kCFNumberFloat64Type",
  358. "kCFNumberCharType",
  359. "kCFNumberShortType",
  360. "kCFNumberIntType",
  361. "kCFNumberLongType",
  362. "kCFNumberLongLongType",
  363. "kCFNumberFloatType",
  364. "kCFNumberDoubleType",
  365. "kCFNumberCFIndexType",
  366. "kCFNumberNSIntegerType",
  367. "kCFNumberCGFloatType"
  368. };
  369. return i <= kCFNumberCGFloatType ? Names[i-1] : "Invalid CFNumberType";
  370. }
  371. #endif
  372. void CFNumberChecker::checkPreStmt(const CallExpr *CE,
  373. CheckerContext &C) const {
  374. ProgramStateRef state = C.getState();
  375. const FunctionDecl *FD = C.getCalleeDecl(CE);
  376. if (!FD)
  377. return;
  378. ASTContext &Ctx = C.getASTContext();
  379. if (!ICreate) {
  380. ICreate = &Ctx.Idents.get("CFNumberCreate");
  381. IGetValue = &Ctx.Idents.get("CFNumberGetValue");
  382. }
  383. if (!(FD->getIdentifier() == ICreate || FD->getIdentifier() == IGetValue) ||
  384. CE->getNumArgs() != 3)
  385. return;
  386. // Get the value of the "theType" argument.
  387. SVal TheTypeVal = C.getSVal(CE->getArg(1));
  388. // FIXME: We really should allow ranges of valid theType values, and
  389. // bifurcate the state appropriately.
  390. std::optional<nonloc::ConcreteInt> V =
  391. dyn_cast<nonloc::ConcreteInt>(TheTypeVal);
  392. if (!V)
  393. return;
  394. uint64_t NumberKind = V->getValue().getLimitedValue();
  395. std::optional<uint64_t> OptCFNumberSize = GetCFNumberSize(Ctx, NumberKind);
  396. // FIXME: In some cases we can emit an error.
  397. if (!OptCFNumberSize)
  398. return;
  399. uint64_t CFNumberSize = *OptCFNumberSize;
  400. // Look at the value of the integer being passed by reference. Essentially
  401. // we want to catch cases where the value passed in is not equal to the
  402. // size of the type being created.
  403. SVal TheValueExpr = C.getSVal(CE->getArg(2));
  404. // FIXME: Eventually we should handle arbitrary locations. We can do this
  405. // by having an enhanced memory model that does low-level typing.
  406. std::optional<loc::MemRegionVal> LV = TheValueExpr.getAs<loc::MemRegionVal>();
  407. if (!LV)
  408. return;
  409. const TypedValueRegion* R = dyn_cast<TypedValueRegion>(LV->stripCasts());
  410. if (!R)
  411. return;
  412. QualType T = Ctx.getCanonicalType(R->getValueType());
  413. // FIXME: If the pointee isn't an integer type, should we flag a warning?
  414. // People can do weird stuff with pointers.
  415. if (!T->isIntegralOrEnumerationType())
  416. return;
  417. uint64_t PrimitiveTypeSize = Ctx.getTypeSize(T);
  418. if (PrimitiveTypeSize == CFNumberSize)
  419. return;
  420. // FIXME: We can actually create an abstract "CFNumber" object that has
  421. // the bits initialized to the provided values.
  422. ExplodedNode *N = C.generateNonFatalErrorNode();
  423. if (N) {
  424. SmallString<128> sbuf;
  425. llvm::raw_svector_ostream os(sbuf);
  426. bool isCreate = (FD->getIdentifier() == ICreate);
  427. if (isCreate) {
  428. os << (PrimitiveTypeSize == 8 ? "An " : "A ")
  429. << PrimitiveTypeSize << "-bit integer is used to initialize a "
  430. << "CFNumber object that represents "
  431. << (CFNumberSize == 8 ? "an " : "a ")
  432. << CFNumberSize << "-bit integer; ";
  433. } else {
  434. os << "A CFNumber object that represents "
  435. << (CFNumberSize == 8 ? "an " : "a ")
  436. << CFNumberSize << "-bit integer is used to initialize "
  437. << (PrimitiveTypeSize == 8 ? "an " : "a ")
  438. << PrimitiveTypeSize << "-bit integer; ";
  439. }
  440. if (PrimitiveTypeSize < CFNumberSize)
  441. os << (CFNumberSize - PrimitiveTypeSize)
  442. << " bits of the CFNumber value will "
  443. << (isCreate ? "be garbage." : "overwrite adjacent storage.");
  444. else
  445. os << (PrimitiveTypeSize - CFNumberSize)
  446. << " bits of the integer value will be "
  447. << (isCreate ? "lost." : "garbage.");
  448. if (!BT)
  449. BT.reset(new APIMisuse(this, "Bad use of CFNumber APIs"));
  450. auto report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
  451. report->addRange(CE->getArg(2)->getSourceRange());
  452. C.emitReport(std::move(report));
  453. }
  454. }
  455. //===----------------------------------------------------------------------===//
  456. // CFRetain/CFRelease/CFMakeCollectable/CFAutorelease checking for null arguments.
  457. //===----------------------------------------------------------------------===//
  458. namespace {
  459. class CFRetainReleaseChecker : public Checker<check::PreCall> {
  460. mutable APIMisuse BT{this, "null passed to CF memory management function"};
  461. const CallDescriptionSet ModelledCalls = {
  462. {{"CFRetain"}, 1},
  463. {{"CFRelease"}, 1},
  464. {{"CFMakeCollectable"}, 1},
  465. {{"CFAutorelease"}, 1},
  466. };
  467. public:
  468. void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
  469. };
  470. } // end anonymous namespace
  471. void CFRetainReleaseChecker::checkPreCall(const CallEvent &Call,
  472. CheckerContext &C) const {
  473. // TODO: Make this check part of CallDescription.
  474. if (!Call.isGlobalCFunction())
  475. return;
  476. // Check if we called CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
  477. if (!ModelledCalls.contains(Call))
  478. return;
  479. // Get the argument's value.
  480. SVal ArgVal = Call.getArgSVal(0);
  481. std::optional<DefinedSVal> DefArgVal = ArgVal.getAs<DefinedSVal>();
  482. if (!DefArgVal)
  483. return;
  484. // Is it null?
  485. ProgramStateRef state = C.getState();
  486. ProgramStateRef stateNonNull, stateNull;
  487. std::tie(stateNonNull, stateNull) = state->assume(*DefArgVal);
  488. if (!stateNonNull) {
  489. ExplodedNode *N = C.generateErrorNode(stateNull);
  490. if (!N)
  491. return;
  492. SmallString<64> Str;
  493. raw_svector_ostream OS(Str);
  494. OS << "Null pointer argument in call to "
  495. << cast<FunctionDecl>(Call.getDecl())->getName();
  496. auto report = std::make_unique<PathSensitiveBugReport>(BT, OS.str(), N);
  497. report->addRange(Call.getArgSourceRange(0));
  498. bugreporter::trackExpressionValue(N, Call.getArgExpr(0), *report);
  499. C.emitReport(std::move(report));
  500. return;
  501. }
  502. // From here on, we know the argument is non-null.
  503. C.addTransition(stateNonNull);
  504. }
  505. //===----------------------------------------------------------------------===//
  506. // Check for sending 'retain', 'release', or 'autorelease' directly to a Class.
  507. //===----------------------------------------------------------------------===//
  508. namespace {
  509. class ClassReleaseChecker : public Checker<check::PreObjCMessage> {
  510. mutable Selector releaseS;
  511. mutable Selector retainS;
  512. mutable Selector autoreleaseS;
  513. mutable Selector drainS;
  514. mutable std::unique_ptr<BugType> BT;
  515. public:
  516. void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
  517. };
  518. } // end anonymous namespace
  519. void ClassReleaseChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
  520. CheckerContext &C) const {
  521. if (!BT) {
  522. BT.reset(new APIMisuse(
  523. this, "message incorrectly sent to class instead of class instance"));
  524. ASTContext &Ctx = C.getASTContext();
  525. releaseS = GetNullarySelector("release", Ctx);
  526. retainS = GetNullarySelector("retain", Ctx);
  527. autoreleaseS = GetNullarySelector("autorelease", Ctx);
  528. drainS = GetNullarySelector("drain", Ctx);
  529. }
  530. if (msg.isInstanceMessage())
  531. return;
  532. const ObjCInterfaceDecl *Class = msg.getReceiverInterface();
  533. assert(Class);
  534. Selector S = msg.getSelector();
  535. if (!(S == releaseS || S == retainS || S == autoreleaseS || S == drainS))
  536. return;
  537. if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
  538. SmallString<200> buf;
  539. llvm::raw_svector_ostream os(buf);
  540. os << "The '";
  541. S.print(os);
  542. os << "' message should be sent to instances "
  543. "of class '" << Class->getName()
  544. << "' and not the class directly";
  545. auto report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
  546. report->addRange(msg.getSourceRange());
  547. C.emitReport(std::move(report));
  548. }
  549. }
  550. //===----------------------------------------------------------------------===//
  551. // Check for passing non-Objective-C types to variadic methods that expect
  552. // only Objective-C types.
  553. //===----------------------------------------------------------------------===//
  554. namespace {
  555. class VariadicMethodTypeChecker : public Checker<check::PreObjCMessage> {
  556. mutable Selector arrayWithObjectsS;
  557. mutable Selector dictionaryWithObjectsAndKeysS;
  558. mutable Selector setWithObjectsS;
  559. mutable Selector orderedSetWithObjectsS;
  560. mutable Selector initWithObjectsS;
  561. mutable Selector initWithObjectsAndKeysS;
  562. mutable std::unique_ptr<BugType> BT;
  563. bool isVariadicMessage(const ObjCMethodCall &msg) const;
  564. public:
  565. void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
  566. };
  567. } // end anonymous namespace
  568. /// isVariadicMessage - Returns whether the given message is a variadic message,
  569. /// where all arguments must be Objective-C types.
  570. bool
  571. VariadicMethodTypeChecker::isVariadicMessage(const ObjCMethodCall &msg) const {
  572. const ObjCMethodDecl *MD = msg.getDecl();
  573. if (!MD || !MD->isVariadic() || isa<ObjCProtocolDecl>(MD->getDeclContext()))
  574. return false;
  575. Selector S = msg.getSelector();
  576. if (msg.isInstanceMessage()) {
  577. // FIXME: Ideally we'd look at the receiver interface here, but that's not
  578. // useful for init, because alloc returns 'id'. In theory, this could lead
  579. // to false positives, for example if there existed a class that had an
  580. // initWithObjects: implementation that does accept non-Objective-C pointer
  581. // types, but the chance of that happening is pretty small compared to the
  582. // gains that this analysis gives.
  583. const ObjCInterfaceDecl *Class = MD->getClassInterface();
  584. switch (findKnownClass(Class)) {
  585. case FC_NSArray:
  586. case FC_NSOrderedSet:
  587. case FC_NSSet:
  588. return S == initWithObjectsS;
  589. case FC_NSDictionary:
  590. return S == initWithObjectsAndKeysS;
  591. default:
  592. return false;
  593. }
  594. } else {
  595. const ObjCInterfaceDecl *Class = msg.getReceiverInterface();
  596. switch (findKnownClass(Class)) {
  597. case FC_NSArray:
  598. return S == arrayWithObjectsS;
  599. case FC_NSOrderedSet:
  600. return S == orderedSetWithObjectsS;
  601. case FC_NSSet:
  602. return S == setWithObjectsS;
  603. case FC_NSDictionary:
  604. return S == dictionaryWithObjectsAndKeysS;
  605. default:
  606. return false;
  607. }
  608. }
  609. }
  610. void VariadicMethodTypeChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
  611. CheckerContext &C) const {
  612. if (!BT) {
  613. BT.reset(new APIMisuse(this,
  614. "Arguments passed to variadic method aren't all "
  615. "Objective-C pointer types"));
  616. ASTContext &Ctx = C.getASTContext();
  617. arrayWithObjectsS = GetUnarySelector("arrayWithObjects", Ctx);
  618. dictionaryWithObjectsAndKeysS =
  619. GetUnarySelector("dictionaryWithObjectsAndKeys", Ctx);
  620. setWithObjectsS = GetUnarySelector("setWithObjects", Ctx);
  621. orderedSetWithObjectsS = GetUnarySelector("orderedSetWithObjects", Ctx);
  622. initWithObjectsS = GetUnarySelector("initWithObjects", Ctx);
  623. initWithObjectsAndKeysS = GetUnarySelector("initWithObjectsAndKeys", Ctx);
  624. }
  625. if (!isVariadicMessage(msg))
  626. return;
  627. // We are not interested in the selector arguments since they have
  628. // well-defined types, so the compiler will issue a warning for them.
  629. unsigned variadicArgsBegin = msg.getSelector().getNumArgs();
  630. // We're not interested in the last argument since it has to be nil or the
  631. // compiler would have issued a warning for it elsewhere.
  632. unsigned variadicArgsEnd = msg.getNumArgs() - 1;
  633. if (variadicArgsEnd <= variadicArgsBegin)
  634. return;
  635. // Verify that all arguments have Objective-C types.
  636. std::optional<ExplodedNode *> errorNode;
  637. for (unsigned I = variadicArgsBegin; I != variadicArgsEnd; ++I) {
  638. QualType ArgTy = msg.getArgExpr(I)->getType();
  639. if (ArgTy->isObjCObjectPointerType())
  640. continue;
  641. // Block pointers are treaded as Objective-C pointers.
  642. if (ArgTy->isBlockPointerType())
  643. continue;
  644. // Ignore pointer constants.
  645. if (isa<loc::ConcreteInt>(msg.getArgSVal(I)))
  646. continue;
  647. // Ignore pointer types annotated with 'NSObject' attribute.
  648. if (C.getASTContext().isObjCNSObjectType(ArgTy))
  649. continue;
  650. // Ignore CF references, which can be toll-free bridged.
  651. if (coreFoundation::isCFObjectRef(ArgTy))
  652. continue;
  653. // Generate only one error node to use for all bug reports.
  654. if (!errorNode)
  655. errorNode = C.generateNonFatalErrorNode();
  656. if (!*errorNode)
  657. continue;
  658. SmallString<128> sbuf;
  659. llvm::raw_svector_ostream os(sbuf);
  660. StringRef TypeName = GetReceiverInterfaceName(msg);
  661. if (!TypeName.empty())
  662. os << "Argument to '" << TypeName << "' method '";
  663. else
  664. os << "Argument to method '";
  665. msg.getSelector().print(os);
  666. os << "' should be an Objective-C pointer type, not '";
  667. ArgTy.print(os, C.getLangOpts());
  668. os << "'";
  669. auto R =
  670. std::make_unique<PathSensitiveBugReport>(*BT, os.str(), *errorNode);
  671. R->addRange(msg.getArgSourceRange(I));
  672. C.emitReport(std::move(R));
  673. }
  674. }
  675. //===----------------------------------------------------------------------===//
  676. // Improves the modeling of loops over Cocoa collections.
  677. //===----------------------------------------------------------------------===//
  678. // The map from container symbol to the container count symbol.
  679. // We currently will remember the last container count symbol encountered.
  680. REGISTER_MAP_WITH_PROGRAMSTATE(ContainerCountMap, SymbolRef, SymbolRef)
  681. REGISTER_MAP_WITH_PROGRAMSTATE(ContainerNonEmptyMap, SymbolRef, bool)
  682. namespace {
  683. class ObjCLoopChecker
  684. : public Checker<check::PostStmt<ObjCForCollectionStmt>,
  685. check::PostObjCMessage,
  686. check::DeadSymbols,
  687. check::PointerEscape > {
  688. mutable IdentifierInfo *CountSelectorII;
  689. bool isCollectionCountMethod(const ObjCMethodCall &M,
  690. CheckerContext &C) const;
  691. public:
  692. ObjCLoopChecker() : CountSelectorII(nullptr) {}
  693. void checkPostStmt(const ObjCForCollectionStmt *FCS, CheckerContext &C) const;
  694. void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
  695. void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
  696. ProgramStateRef checkPointerEscape(ProgramStateRef State,
  697. const InvalidatedSymbols &Escaped,
  698. const CallEvent *Call,
  699. PointerEscapeKind Kind) const;
  700. };
  701. } // end anonymous namespace
  702. static bool isKnownNonNilCollectionType(QualType T) {
  703. const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
  704. if (!PT)
  705. return false;
  706. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  707. if (!ID)
  708. return false;
  709. switch (findKnownClass(ID)) {
  710. case FC_NSArray:
  711. case FC_NSDictionary:
  712. case FC_NSEnumerator:
  713. case FC_NSOrderedSet:
  714. case FC_NSSet:
  715. return true;
  716. default:
  717. return false;
  718. }
  719. }
  720. /// Assumes that the collection is non-nil.
  721. ///
  722. /// If the collection is known to be nil, returns NULL to indicate an infeasible
  723. /// path.
  724. static ProgramStateRef checkCollectionNonNil(CheckerContext &C,
  725. ProgramStateRef State,
  726. const ObjCForCollectionStmt *FCS) {
  727. if (!State)
  728. return nullptr;
  729. SVal CollectionVal = C.getSVal(FCS->getCollection());
  730. std::optional<DefinedSVal> KnownCollection =
  731. CollectionVal.getAs<DefinedSVal>();
  732. if (!KnownCollection)
  733. return State;
  734. ProgramStateRef StNonNil, StNil;
  735. std::tie(StNonNil, StNil) = State->assume(*KnownCollection);
  736. if (StNil && !StNonNil) {
  737. // The collection is nil. This path is infeasible.
  738. return nullptr;
  739. }
  740. return StNonNil;
  741. }
  742. /// Assumes that the collection elements are non-nil.
  743. ///
  744. /// This only applies if the collection is one of those known not to contain
  745. /// nil values.
  746. static ProgramStateRef checkElementNonNil(CheckerContext &C,
  747. ProgramStateRef State,
  748. const ObjCForCollectionStmt *FCS) {
  749. if (!State)
  750. return nullptr;
  751. // See if the collection is one where we /know/ the elements are non-nil.
  752. if (!isKnownNonNilCollectionType(FCS->getCollection()->getType()))
  753. return State;
  754. const LocationContext *LCtx = C.getLocationContext();
  755. const Stmt *Element = FCS->getElement();
  756. // FIXME: Copied from ExprEngineObjC.
  757. std::optional<Loc> ElementLoc;
  758. if (const DeclStmt *DS = dyn_cast<DeclStmt>(Element)) {
  759. const VarDecl *ElemDecl = cast<VarDecl>(DS->getSingleDecl());
  760. assert(ElemDecl->getInit() == nullptr);
  761. ElementLoc = State->getLValue(ElemDecl, LCtx);
  762. } else {
  763. ElementLoc = State->getSVal(Element, LCtx).getAs<Loc>();
  764. }
  765. if (!ElementLoc)
  766. return State;
  767. // Go ahead and assume the value is non-nil.
  768. SVal Val = State->getSVal(*ElementLoc);
  769. return State->assume(cast<DefinedOrUnknownSVal>(Val), true);
  770. }
  771. /// Returns NULL state if the collection is known to contain elements
  772. /// (or is known not to contain elements if the Assumption parameter is false.)
  773. static ProgramStateRef
  774. assumeCollectionNonEmpty(CheckerContext &C, ProgramStateRef State,
  775. SymbolRef CollectionS, bool Assumption) {
  776. if (!State || !CollectionS)
  777. return State;
  778. const SymbolRef *CountS = State->get<ContainerCountMap>(CollectionS);
  779. if (!CountS) {
  780. const bool *KnownNonEmpty = State->get<ContainerNonEmptyMap>(CollectionS);
  781. if (!KnownNonEmpty)
  782. return State->set<ContainerNonEmptyMap>(CollectionS, Assumption);
  783. return (Assumption == *KnownNonEmpty) ? State : nullptr;
  784. }
  785. SValBuilder &SvalBuilder = C.getSValBuilder();
  786. SVal CountGreaterThanZeroVal =
  787. SvalBuilder.evalBinOp(State, BO_GT,
  788. nonloc::SymbolVal(*CountS),
  789. SvalBuilder.makeIntVal(0, (*CountS)->getType()),
  790. SvalBuilder.getConditionType());
  791. std::optional<DefinedSVal> CountGreaterThanZero =
  792. CountGreaterThanZeroVal.getAs<DefinedSVal>();
  793. if (!CountGreaterThanZero) {
  794. // The SValBuilder cannot construct a valid SVal for this condition.
  795. // This means we cannot properly reason about it.
  796. return State;
  797. }
  798. return State->assume(*CountGreaterThanZero, Assumption);
  799. }
  800. static ProgramStateRef
  801. assumeCollectionNonEmpty(CheckerContext &C, ProgramStateRef State,
  802. const ObjCForCollectionStmt *FCS,
  803. bool Assumption) {
  804. if (!State)
  805. return nullptr;
  806. SymbolRef CollectionS = C.getSVal(FCS->getCollection()).getAsSymbol();
  807. return assumeCollectionNonEmpty(C, State, CollectionS, Assumption);
  808. }
  809. /// If the fist block edge is a back edge, we are reentering the loop.
  810. static bool alreadyExecutedAtLeastOneLoopIteration(const ExplodedNode *N,
  811. const ObjCForCollectionStmt *FCS) {
  812. if (!N)
  813. return false;
  814. ProgramPoint P = N->getLocation();
  815. if (std::optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
  816. return BE->getSrc()->getLoopTarget() == FCS;
  817. }
  818. // Keep looking for a block edge.
  819. for (ExplodedNode::const_pred_iterator I = N->pred_begin(),
  820. E = N->pred_end(); I != E; ++I) {
  821. if (alreadyExecutedAtLeastOneLoopIteration(*I, FCS))
  822. return true;
  823. }
  824. return false;
  825. }
  826. void ObjCLoopChecker::checkPostStmt(const ObjCForCollectionStmt *FCS,
  827. CheckerContext &C) const {
  828. ProgramStateRef State = C.getState();
  829. // Check if this is the branch for the end of the loop.
  830. if (!ExprEngine::hasMoreIteration(State, FCS, C.getLocationContext())) {
  831. if (!alreadyExecutedAtLeastOneLoopIteration(C.getPredecessor(), FCS))
  832. State = assumeCollectionNonEmpty(C, State, FCS, /*Assumption*/false);
  833. // Otherwise, this is a branch that goes through the loop body.
  834. } else {
  835. State = checkCollectionNonNil(C, State, FCS);
  836. State = checkElementNonNil(C, State, FCS);
  837. State = assumeCollectionNonEmpty(C, State, FCS, /*Assumption*/true);
  838. }
  839. if (!State)
  840. C.generateSink(C.getState(), C.getPredecessor());
  841. else if (State != C.getState())
  842. C.addTransition(State);
  843. }
  844. bool ObjCLoopChecker::isCollectionCountMethod(const ObjCMethodCall &M,
  845. CheckerContext &C) const {
  846. Selector S = M.getSelector();
  847. // Initialize the identifiers on first use.
  848. if (!CountSelectorII)
  849. CountSelectorII = &C.getASTContext().Idents.get("count");
  850. // If the method returns collection count, record the value.
  851. return S.isUnarySelector() &&
  852. (S.getIdentifierInfoForSlot(0) == CountSelectorII);
  853. }
  854. void ObjCLoopChecker::checkPostObjCMessage(const ObjCMethodCall &M,
  855. CheckerContext &C) const {
  856. if (!M.isInstanceMessage())
  857. return;
  858. const ObjCInterfaceDecl *ClassID = M.getReceiverInterface();
  859. if (!ClassID)
  860. return;
  861. FoundationClass Class = findKnownClass(ClassID);
  862. if (Class != FC_NSDictionary &&
  863. Class != FC_NSArray &&
  864. Class != FC_NSSet &&
  865. Class != FC_NSOrderedSet)
  866. return;
  867. SymbolRef ContainerS = M.getReceiverSVal().getAsSymbol();
  868. if (!ContainerS)
  869. return;
  870. // If we are processing a call to "count", get the symbolic value returned by
  871. // a call to "count" and add it to the map.
  872. if (!isCollectionCountMethod(M, C))
  873. return;
  874. const Expr *MsgExpr = M.getOriginExpr();
  875. SymbolRef CountS = C.getSVal(MsgExpr).getAsSymbol();
  876. if (CountS) {
  877. ProgramStateRef State = C.getState();
  878. C.getSymbolManager().addSymbolDependency(ContainerS, CountS);
  879. State = State->set<ContainerCountMap>(ContainerS, CountS);
  880. if (const bool *NonEmpty = State->get<ContainerNonEmptyMap>(ContainerS)) {
  881. State = State->remove<ContainerNonEmptyMap>(ContainerS);
  882. State = assumeCollectionNonEmpty(C, State, ContainerS, *NonEmpty);
  883. }
  884. C.addTransition(State);
  885. }
  886. }
  887. static SymbolRef getMethodReceiverIfKnownImmutable(const CallEvent *Call) {
  888. const ObjCMethodCall *Message = dyn_cast_or_null<ObjCMethodCall>(Call);
  889. if (!Message)
  890. return nullptr;
  891. const ObjCMethodDecl *MD = Message->getDecl();
  892. if (!MD)
  893. return nullptr;
  894. const ObjCInterfaceDecl *StaticClass;
  895. if (isa<ObjCProtocolDecl>(MD->getDeclContext())) {
  896. // We can't find out where the method was declared without doing more work.
  897. // Instead, see if the receiver is statically typed as a known immutable
  898. // collection.
  899. StaticClass = Message->getOriginExpr()->getReceiverInterface();
  900. } else {
  901. StaticClass = MD->getClassInterface();
  902. }
  903. if (!StaticClass)
  904. return nullptr;
  905. switch (findKnownClass(StaticClass, /*IncludeSuper=*/false)) {
  906. case FC_None:
  907. return nullptr;
  908. case FC_NSArray:
  909. case FC_NSDictionary:
  910. case FC_NSEnumerator:
  911. case FC_NSNull:
  912. case FC_NSOrderedSet:
  913. case FC_NSSet:
  914. case FC_NSString:
  915. break;
  916. }
  917. return Message->getReceiverSVal().getAsSymbol();
  918. }
  919. ProgramStateRef
  920. ObjCLoopChecker::checkPointerEscape(ProgramStateRef State,
  921. const InvalidatedSymbols &Escaped,
  922. const CallEvent *Call,
  923. PointerEscapeKind Kind) const {
  924. SymbolRef ImmutableReceiver = getMethodReceiverIfKnownImmutable(Call);
  925. // Remove the invalidated symbols from the collection count map.
  926. for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
  927. E = Escaped.end();
  928. I != E; ++I) {
  929. SymbolRef Sym = *I;
  930. // Don't invalidate this symbol's count if we know the method being called
  931. // is declared on an immutable class. This isn't completely correct if the
  932. // receiver is also passed as an argument, but in most uses of NSArray,
  933. // NSDictionary, etc. this isn't likely to happen in a dangerous way.
  934. if (Sym == ImmutableReceiver)
  935. continue;
  936. // The symbol escaped. Pessimistically, assume that the count could have
  937. // changed.
  938. State = State->remove<ContainerCountMap>(Sym);
  939. State = State->remove<ContainerNonEmptyMap>(Sym);
  940. }
  941. return State;
  942. }
  943. void ObjCLoopChecker::checkDeadSymbols(SymbolReaper &SymReaper,
  944. CheckerContext &C) const {
  945. ProgramStateRef State = C.getState();
  946. // Remove the dead symbols from the collection count map.
  947. ContainerCountMapTy Tracked = State->get<ContainerCountMap>();
  948. for (ContainerCountMapTy::iterator I = Tracked.begin(),
  949. E = Tracked.end(); I != E; ++I) {
  950. SymbolRef Sym = I->first;
  951. if (SymReaper.isDead(Sym)) {
  952. State = State->remove<ContainerCountMap>(Sym);
  953. State = State->remove<ContainerNonEmptyMap>(Sym);
  954. }
  955. }
  956. C.addTransition(State);
  957. }
  958. namespace {
  959. /// \class ObjCNonNilReturnValueChecker
  960. /// The checker restricts the return values of APIs known to
  961. /// never (or almost never) return 'nil'.
  962. class ObjCNonNilReturnValueChecker
  963. : public Checker<check::PostObjCMessage,
  964. check::PostStmt<ObjCArrayLiteral>,
  965. check::PostStmt<ObjCDictionaryLiteral>,
  966. check::PostStmt<ObjCBoxedExpr> > {
  967. mutable bool Initialized;
  968. mutable Selector ObjectAtIndex;
  969. mutable Selector ObjectAtIndexedSubscript;
  970. mutable Selector NullSelector;
  971. public:
  972. ObjCNonNilReturnValueChecker() : Initialized(false) {}
  973. ProgramStateRef assumeExprIsNonNull(const Expr *NonNullExpr,
  974. ProgramStateRef State,
  975. CheckerContext &C) const;
  976. void assumeExprIsNonNull(const Expr *E, CheckerContext &C) const {
  977. C.addTransition(assumeExprIsNonNull(E, C.getState(), C));
  978. }
  979. void checkPostStmt(const ObjCArrayLiteral *E, CheckerContext &C) const {
  980. assumeExprIsNonNull(E, C);
  981. }
  982. void checkPostStmt(const ObjCDictionaryLiteral *E, CheckerContext &C) const {
  983. assumeExprIsNonNull(E, C);
  984. }
  985. void checkPostStmt(const ObjCBoxedExpr *E, CheckerContext &C) const {
  986. assumeExprIsNonNull(E, C);
  987. }
  988. void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
  989. };
  990. } // end anonymous namespace
  991. ProgramStateRef
  992. ObjCNonNilReturnValueChecker::assumeExprIsNonNull(const Expr *NonNullExpr,
  993. ProgramStateRef State,
  994. CheckerContext &C) const {
  995. SVal Val = C.getSVal(NonNullExpr);
  996. if (std::optional<DefinedOrUnknownSVal> DV =
  997. Val.getAs<DefinedOrUnknownSVal>())
  998. return State->assume(*DV, true);
  999. return State;
  1000. }
  1001. void ObjCNonNilReturnValueChecker::checkPostObjCMessage(const ObjCMethodCall &M,
  1002. CheckerContext &C)
  1003. const {
  1004. ProgramStateRef State = C.getState();
  1005. if (!Initialized) {
  1006. ASTContext &Ctx = C.getASTContext();
  1007. ObjectAtIndex = GetUnarySelector("objectAtIndex", Ctx);
  1008. ObjectAtIndexedSubscript = GetUnarySelector("objectAtIndexedSubscript", Ctx);
  1009. NullSelector = GetNullarySelector("null", Ctx);
  1010. }
  1011. // Check the receiver type.
  1012. if (const ObjCInterfaceDecl *Interface = M.getReceiverInterface()) {
  1013. // Assume that object returned from '[self init]' or '[super init]' is not
  1014. // 'nil' if we are processing an inlined function/method.
  1015. //
  1016. // A defensive callee will (and should) check if the object returned by
  1017. // '[super init]' is 'nil' before doing it's own initialization. However,
  1018. // since 'nil' is rarely returned in practice, we should not warn when the
  1019. // caller to the defensive constructor uses the object in contexts where
  1020. // 'nil' is not accepted.
  1021. if (!C.inTopFrame() && M.getDecl() &&
  1022. M.getDecl()->getMethodFamily() == OMF_init &&
  1023. M.isReceiverSelfOrSuper()) {
  1024. State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
  1025. }
  1026. FoundationClass Cl = findKnownClass(Interface);
  1027. // Objects returned from
  1028. // [NSArray|NSOrderedSet]::[ObjectAtIndex|ObjectAtIndexedSubscript]
  1029. // are never 'nil'.
  1030. if (Cl == FC_NSArray || Cl == FC_NSOrderedSet) {
  1031. Selector Sel = M.getSelector();
  1032. if (Sel == ObjectAtIndex || Sel == ObjectAtIndexedSubscript) {
  1033. // Go ahead and assume the value is non-nil.
  1034. State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
  1035. }
  1036. }
  1037. // Objects returned from [NSNull null] are not nil.
  1038. if (Cl == FC_NSNull) {
  1039. if (M.getSelector() == NullSelector) {
  1040. // Go ahead and assume the value is non-nil.
  1041. State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
  1042. }
  1043. }
  1044. }
  1045. C.addTransition(State);
  1046. }
  1047. //===----------------------------------------------------------------------===//
  1048. // Check registration.
  1049. //===----------------------------------------------------------------------===//
  1050. void ento::registerNilArgChecker(CheckerManager &mgr) {
  1051. mgr.registerChecker<NilArgChecker>();
  1052. }
  1053. bool ento::shouldRegisterNilArgChecker(const CheckerManager &mgr) {
  1054. return true;
  1055. }
  1056. void ento::registerCFNumberChecker(CheckerManager &mgr) {
  1057. mgr.registerChecker<CFNumberChecker>();
  1058. }
  1059. bool ento::shouldRegisterCFNumberChecker(const CheckerManager &mgr) {
  1060. return true;
  1061. }
  1062. void ento::registerCFRetainReleaseChecker(CheckerManager &mgr) {
  1063. mgr.registerChecker<CFRetainReleaseChecker>();
  1064. }
  1065. bool ento::shouldRegisterCFRetainReleaseChecker(const CheckerManager &mgr) {
  1066. return true;
  1067. }
  1068. void ento::registerClassReleaseChecker(CheckerManager &mgr) {
  1069. mgr.registerChecker<ClassReleaseChecker>();
  1070. }
  1071. bool ento::shouldRegisterClassReleaseChecker(const CheckerManager &mgr) {
  1072. return true;
  1073. }
  1074. void ento::registerVariadicMethodTypeChecker(CheckerManager &mgr) {
  1075. mgr.registerChecker<VariadicMethodTypeChecker>();
  1076. }
  1077. bool ento::shouldRegisterVariadicMethodTypeChecker(const CheckerManager &mgr) {
  1078. return true;
  1079. }
  1080. void ento::registerObjCLoopChecker(CheckerManager &mgr) {
  1081. mgr.registerChecker<ObjCLoopChecker>();
  1082. }
  1083. bool ento::shouldRegisterObjCLoopChecker(const CheckerManager &mgr) {
  1084. return true;
  1085. }
  1086. void ento::registerObjCNonNilReturnValueChecker(CheckerManager &mgr) {
  1087. mgr.registerChecker<ObjCNonNilReturnValueChecker>();
  1088. }
  1089. bool ento::shouldRegisterObjCNonNilReturnValueChecker(const CheckerManager &mgr) {
  1090. return true;
  1091. }