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. using namespace clang;
  36. using namespace ento;
  37. using namespace llvm;
  38. namespace {
  39. class APIMisuse : public BugType {
  40. public:
  41. APIMisuse(const CheckerBase *checker, const char *name)
  42. : BugType(checker, name, "API Misuse (Apple)") {}
  43. };
  44. } // end anonymous namespace
  45. //===----------------------------------------------------------------------===//
  46. // Utility functions.
  47. //===----------------------------------------------------------------------===//
  48. static StringRef GetReceiverInterfaceName(const ObjCMethodCall &msg) {
  49. if (const ObjCInterfaceDecl *ID = msg.getReceiverInterface())
  50. return ID->getIdentifier()->getName();
  51. return StringRef();
  52. }
  53. enum FoundationClass {
  54. FC_None,
  55. FC_NSArray,
  56. FC_NSDictionary,
  57. FC_NSEnumerator,
  58. FC_NSNull,
  59. FC_NSOrderedSet,
  60. FC_NSSet,
  61. FC_NSString
  62. };
  63. static FoundationClass findKnownClass(const ObjCInterfaceDecl *ID,
  64. bool IncludeSuperclasses = true) {
  65. static llvm::StringMap<FoundationClass> Classes;
  66. if (Classes.empty()) {
  67. Classes["NSArray"] = FC_NSArray;
  68. Classes["NSDictionary"] = FC_NSDictionary;
  69. Classes["NSEnumerator"] = FC_NSEnumerator;
  70. Classes["NSNull"] = FC_NSNull;
  71. Classes["NSOrderedSet"] = FC_NSOrderedSet;
  72. Classes["NSSet"] = FC_NSSet;
  73. Classes["NSString"] = FC_NSString;
  74. }
  75. // FIXME: Should we cache this at all?
  76. FoundationClass result = Classes.lookup(ID->getIdentifier()->getName());
  77. if (result == FC_None && IncludeSuperclasses)
  78. if (const ObjCInterfaceDecl *Super = ID->getSuperClass())
  79. return findKnownClass(Super);
  80. return result;
  81. }
  82. //===----------------------------------------------------------------------===//
  83. // NilArgChecker - Check for prohibited nil arguments to ObjC method calls.
  84. //===----------------------------------------------------------------------===//
  85. namespace {
  86. class NilArgChecker : public Checker<check::PreObjCMessage,
  87. check::PostStmt<ObjCDictionaryLiteral>,
  88. check::PostStmt<ObjCArrayLiteral> > {
  89. mutable std::unique_ptr<APIMisuse> BT;
  90. mutable llvm::SmallDenseMap<Selector, unsigned, 16> StringSelectors;
  91. mutable Selector ArrayWithObjectSel;
  92. mutable Selector AddObjectSel;
  93. mutable Selector InsertObjectAtIndexSel;
  94. mutable Selector ReplaceObjectAtIndexWithObjectSel;
  95. mutable Selector SetObjectAtIndexedSubscriptSel;
  96. mutable Selector ArrayByAddingObjectSel;
  97. mutable Selector DictionaryWithObjectForKeySel;
  98. mutable Selector SetObjectForKeySel;
  99. mutable Selector SetObjectForKeyedSubscriptSel;
  100. mutable Selector RemoveObjectForKeySel;
  101. void warnIfNilExpr(const Expr *E,
  102. const char *Msg,
  103. CheckerContext &C) const;
  104. void warnIfNilArg(CheckerContext &C,
  105. const ObjCMethodCall &msg, unsigned Arg,
  106. FoundationClass Class,
  107. bool CanBeSubscript = false) const;
  108. void generateBugReport(ExplodedNode *N,
  109. StringRef Msg,
  110. SourceRange Range,
  111. const Expr *Expr,
  112. CheckerContext &C) const;
  113. public:
  114. void checkPreObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
  115. void checkPostStmt(const ObjCDictionaryLiteral *DL,
  116. CheckerContext &C) const;
  117. void checkPostStmt(const ObjCArrayLiteral *AL,
  118. CheckerContext &C) const;
  119. };
  120. } // end anonymous namespace
  121. void NilArgChecker::warnIfNilExpr(const Expr *E,
  122. const char *Msg,
  123. CheckerContext &C) const {
  124. ProgramStateRef State = C.getState();
  125. if (State->isNull(C.getSVal(E)).isConstrainedTrue()) {
  126. if (ExplodedNode *N = C.generateErrorNode()) {
  127. generateBugReport(N, Msg, E->getSourceRange(), E, C);
  128. }
  129. }
  130. }
  131. void NilArgChecker::warnIfNilArg(CheckerContext &C,
  132. const ObjCMethodCall &msg,
  133. unsigned int Arg,
  134. FoundationClass Class,
  135. bool CanBeSubscript) const {
  136. // Check if the argument is nil.
  137. ProgramStateRef State = C.getState();
  138. if (!State->isNull(msg.getArgSVal(Arg)).isConstrainedTrue())
  139. return;
  140. // NOTE: We cannot throw non-fatal errors from warnIfNilExpr,
  141. // because it's called multiple times from some callers, so it'd cause
  142. // an unwanted state split if two or more non-fatal errors are thrown
  143. // within the same checker callback. For now we don't want to, but
  144. // it'll need to be fixed if we ever want to.
  145. if (ExplodedNode *N = C.generateErrorNode()) {
  146. SmallString<128> sbuf;
  147. llvm::raw_svector_ostream os(sbuf);
  148. if (CanBeSubscript && msg.getMessageKind() == OCM_Subscript) {
  149. if (Class == FC_NSArray) {
  150. os << "Array element cannot be nil";
  151. } else if (Class == FC_NSDictionary) {
  152. if (Arg == 0) {
  153. os << "Value stored into '";
  154. os << GetReceiverInterfaceName(msg) << "' cannot be nil";
  155. } else {
  156. assert(Arg == 1);
  157. os << "'"<< GetReceiverInterfaceName(msg) << "' key cannot be nil";
  158. }
  159. } else
  160. llvm_unreachable("Missing foundation class for the subscript expr");
  161. } else {
  162. if (Class == FC_NSDictionary) {
  163. if (Arg == 0)
  164. os << "Value argument ";
  165. else {
  166. assert(Arg == 1);
  167. os << "Key argument ";
  168. }
  169. os << "to '";
  170. msg.getSelector().print(os);
  171. os << "' cannot be nil";
  172. } else {
  173. os << "Argument to '" << GetReceiverInterfaceName(msg) << "' method '";
  174. msg.getSelector().print(os);
  175. os << "' cannot be nil";
  176. }
  177. }
  178. generateBugReport(N, os.str(), msg.getArgSourceRange(Arg),
  179. msg.getArgExpr(Arg), C);
  180. }
  181. }
  182. void NilArgChecker::generateBugReport(ExplodedNode *N,
  183. StringRef Msg,
  184. SourceRange Range,
  185. const Expr *E,
  186. CheckerContext &C) const {
  187. if (!BT)
  188. BT.reset(new APIMisuse(this, "nil argument"));
  189. auto R = std::make_unique<PathSensitiveBugReport>(*BT, Msg, N);
  190. R->addRange(Range);
  191. bugreporter::trackExpressionValue(N, E, *R);
  192. C.emitReport(std::move(R));
  193. }
  194. void NilArgChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
  195. CheckerContext &C) const {
  196. const ObjCInterfaceDecl *ID = msg.getReceiverInterface();
  197. if (!ID)
  198. return;
  199. FoundationClass Class = findKnownClass(ID);
  200. static const unsigned InvalidArgIndex = UINT_MAX;
  201. unsigned Arg = InvalidArgIndex;
  202. bool CanBeSubscript = false;
  203. if (Class == FC_NSString) {
  204. Selector S = msg.getSelector();
  205. if (S.isUnarySelector())
  206. return;
  207. if (StringSelectors.empty()) {
  208. ASTContext &Ctx = C.getASTContext();
  209. Selector Sels[] = {
  210. getKeywordSelector(Ctx, "caseInsensitiveCompare"),
  211. getKeywordSelector(Ctx, "compare"),
  212. getKeywordSelector(Ctx, "compare", "options"),
  213. getKeywordSelector(Ctx, "compare", "options", "range"),
  214. getKeywordSelector(Ctx, "compare", "options", "range", "locale"),
  215. getKeywordSelector(Ctx, "componentsSeparatedByCharactersInSet"),
  216. getKeywordSelector(Ctx, "initWithFormat"),
  217. getKeywordSelector(Ctx, "localizedCaseInsensitiveCompare"),
  218. getKeywordSelector(Ctx, "localizedCompare"),
  219. getKeywordSelector(Ctx, "localizedStandardCompare"),
  220. };
  221. for (Selector KnownSel : Sels)
  222. StringSelectors[KnownSel] = 0;
  223. }
  224. auto I = StringSelectors.find(S);
  225. if (I == StringSelectors.end())
  226. return;
  227. Arg = I->second;
  228. } else if (Class == FC_NSArray) {
  229. Selector S = msg.getSelector();
  230. if (S.isUnarySelector())
  231. return;
  232. if (ArrayWithObjectSel.isNull()) {
  233. ASTContext &Ctx = C.getASTContext();
  234. ArrayWithObjectSel = getKeywordSelector(Ctx, "arrayWithObject");
  235. AddObjectSel = getKeywordSelector(Ctx, "addObject");
  236. InsertObjectAtIndexSel =
  237. getKeywordSelector(Ctx, "insertObject", "atIndex");
  238. ReplaceObjectAtIndexWithObjectSel =
  239. getKeywordSelector(Ctx, "replaceObjectAtIndex", "withObject");
  240. SetObjectAtIndexedSubscriptSel =
  241. getKeywordSelector(Ctx, "setObject", "atIndexedSubscript");
  242. ArrayByAddingObjectSel = getKeywordSelector(Ctx, "arrayByAddingObject");
  243. }
  244. if (S == ArrayWithObjectSel || S == AddObjectSel ||
  245. S == InsertObjectAtIndexSel || S == ArrayByAddingObjectSel) {
  246. Arg = 0;
  247. } else if (S == SetObjectAtIndexedSubscriptSel) {
  248. Arg = 0;
  249. CanBeSubscript = true;
  250. } else if (S == ReplaceObjectAtIndexWithObjectSel) {
  251. Arg = 1;
  252. }
  253. } else if (Class == FC_NSDictionary) {
  254. Selector S = msg.getSelector();
  255. if (S.isUnarySelector())
  256. return;
  257. if (DictionaryWithObjectForKeySel.isNull()) {
  258. ASTContext &Ctx = C.getASTContext();
  259. DictionaryWithObjectForKeySel =
  260. getKeywordSelector(Ctx, "dictionaryWithObject", "forKey");
  261. SetObjectForKeySel = getKeywordSelector(Ctx, "setObject", "forKey");
  262. SetObjectForKeyedSubscriptSel =
  263. getKeywordSelector(Ctx, "setObject", "forKeyedSubscript");
  264. RemoveObjectForKeySel = getKeywordSelector(Ctx, "removeObjectForKey");
  265. }
  266. if (S == DictionaryWithObjectForKeySel || S == SetObjectForKeySel) {
  267. Arg = 0;
  268. warnIfNilArg(C, msg, /* Arg */1, Class);
  269. } else if (S == SetObjectForKeyedSubscriptSel) {
  270. CanBeSubscript = true;
  271. Arg = 1;
  272. } else if (S == RemoveObjectForKeySel) {
  273. Arg = 0;
  274. }
  275. }
  276. // If argument is '0', report a warning.
  277. if ((Arg != InvalidArgIndex))
  278. warnIfNilArg(C, msg, Arg, Class, CanBeSubscript);
  279. }
  280. void NilArgChecker::checkPostStmt(const ObjCArrayLiteral *AL,
  281. CheckerContext &C) const {
  282. unsigned NumOfElements = AL->getNumElements();
  283. for (unsigned i = 0; i < NumOfElements; ++i) {
  284. warnIfNilExpr(AL->getElement(i), "Array element cannot be nil", C);
  285. }
  286. }
  287. void NilArgChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
  288. CheckerContext &C) const {
  289. unsigned NumOfElements = DL->getNumElements();
  290. for (unsigned i = 0; i < NumOfElements; ++i) {
  291. ObjCDictionaryElement Element = DL->getKeyValueElement(i);
  292. warnIfNilExpr(Element.Key, "Dictionary key cannot be nil", C);
  293. warnIfNilExpr(Element.Value, "Dictionary value cannot be nil", C);
  294. }
  295. }
  296. //===----------------------------------------------------------------------===//
  297. // Checking for mismatched types passed to CFNumberCreate/CFNumberGetValue.
  298. //===----------------------------------------------------------------------===//
  299. namespace {
  300. class CFNumberChecker : public Checker< check::PreStmt<CallExpr> > {
  301. mutable std::unique_ptr<APIMisuse> BT;
  302. mutable IdentifierInfo *ICreate, *IGetValue;
  303. public:
  304. CFNumberChecker() : ICreate(nullptr), IGetValue(nullptr) {}
  305. void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
  306. private:
  307. void EmitError(const TypedRegion* R, const Expr *Ex,
  308. uint64_t SourceSize, uint64_t TargetSize, uint64_t NumberKind);
  309. };
  310. } // end anonymous namespace
  311. enum CFNumberType {
  312. kCFNumberSInt8Type = 1,
  313. kCFNumberSInt16Type = 2,
  314. kCFNumberSInt32Type = 3,
  315. kCFNumberSInt64Type = 4,
  316. kCFNumberFloat32Type = 5,
  317. kCFNumberFloat64Type = 6,
  318. kCFNumberCharType = 7,
  319. kCFNumberShortType = 8,
  320. kCFNumberIntType = 9,
  321. kCFNumberLongType = 10,
  322. kCFNumberLongLongType = 11,
  323. kCFNumberFloatType = 12,
  324. kCFNumberDoubleType = 13,
  325. kCFNumberCFIndexType = 14,
  326. kCFNumberNSIntegerType = 15,
  327. kCFNumberCGFloatType = 16
  328. };
  329. static Optional<uint64_t> GetCFNumberSize(ASTContext &Ctx, uint64_t i) {
  330. static const unsigned char FixedSize[] = { 8, 16, 32, 64, 32, 64 };
  331. if (i < kCFNumberCharType)
  332. return FixedSize[i-1];
  333. QualType T;
  334. switch (i) {
  335. case kCFNumberCharType: T = Ctx.CharTy; break;
  336. case kCFNumberShortType: T = Ctx.ShortTy; break;
  337. case kCFNumberIntType: T = Ctx.IntTy; break;
  338. case kCFNumberLongType: T = Ctx.LongTy; break;
  339. case kCFNumberLongLongType: T = Ctx.LongLongTy; break;
  340. case kCFNumberFloatType: T = Ctx.FloatTy; break;
  341. case kCFNumberDoubleType: T = Ctx.DoubleTy; break;
  342. case kCFNumberCFIndexType:
  343. case kCFNumberNSIntegerType:
  344. case kCFNumberCGFloatType:
  345. // FIXME: We need a way to map from names to Type*.
  346. default:
  347. return None;
  348. }
  349. return Ctx.getTypeSize(T);
  350. }
  351. #if 0
  352. static const char* GetCFNumberTypeStr(uint64_t i) {
  353. static const char* Names[] = {
  354. "kCFNumberSInt8Type",
  355. "kCFNumberSInt16Type",
  356. "kCFNumberSInt32Type",
  357. "kCFNumberSInt64Type",
  358. "kCFNumberFloat32Type",
  359. "kCFNumberFloat64Type",
  360. "kCFNumberCharType",
  361. "kCFNumberShortType",
  362. "kCFNumberIntType",
  363. "kCFNumberLongType",
  364. "kCFNumberLongLongType",
  365. "kCFNumberFloatType",
  366. "kCFNumberDoubleType",
  367. "kCFNumberCFIndexType",
  368. "kCFNumberNSIntegerType",
  369. "kCFNumberCGFloatType"
  370. };
  371. return i <= kCFNumberCGFloatType ? Names[i-1] : "Invalid CFNumberType";
  372. }
  373. #endif
  374. void CFNumberChecker::checkPreStmt(const CallExpr *CE,
  375. CheckerContext &C) const {
  376. ProgramStateRef state = C.getState();
  377. const FunctionDecl *FD = C.getCalleeDecl(CE);
  378. if (!FD)
  379. return;
  380. ASTContext &Ctx = C.getASTContext();
  381. if (!ICreate) {
  382. ICreate = &Ctx.Idents.get("CFNumberCreate");
  383. IGetValue = &Ctx.Idents.get("CFNumberGetValue");
  384. }
  385. if (!(FD->getIdentifier() == ICreate || FD->getIdentifier() == IGetValue) ||
  386. CE->getNumArgs() != 3)
  387. return;
  388. // Get the value of the "theType" argument.
  389. SVal TheTypeVal = C.getSVal(CE->getArg(1));
  390. // FIXME: We really should allow ranges of valid theType values, and
  391. // bifurcate the state appropriately.
  392. Optional<nonloc::ConcreteInt> V = TheTypeVal.getAs<nonloc::ConcreteInt>();
  393. if (!V)
  394. return;
  395. uint64_t NumberKind = V->getValue().getLimitedValue();
  396. Optional<uint64_t> OptCFNumberSize = GetCFNumberSize(Ctx, NumberKind);
  397. // FIXME: In some cases we can emit an error.
  398. if (!OptCFNumberSize)
  399. return;
  400. uint64_t CFNumberSize = *OptCFNumberSize;
  401. // Look at the value of the integer being passed by reference. Essentially
  402. // we want to catch cases where the value passed in is not equal to the
  403. // size of the type being created.
  404. SVal TheValueExpr = C.getSVal(CE->getArg(2));
  405. // FIXME: Eventually we should handle arbitrary locations. We can do this
  406. // by having an enhanced memory model that does low-level typing.
  407. Optional<loc::MemRegionVal> LV = TheValueExpr.getAs<loc::MemRegionVal>();
  408. if (!LV)
  409. return;
  410. const TypedValueRegion* R = dyn_cast<TypedValueRegion>(LV->stripCasts());
  411. if (!R)
  412. return;
  413. QualType T = Ctx.getCanonicalType(R->getValueType());
  414. // FIXME: If the pointee isn't an integer type, should we flag a warning?
  415. // People can do weird stuff with pointers.
  416. if (!T->isIntegralOrEnumerationType())
  417. return;
  418. uint64_t PrimitiveTypeSize = Ctx.getTypeSize(T);
  419. if (PrimitiveTypeSize == CFNumberSize)
  420. return;
  421. // FIXME: We can actually create an abstract "CFNumber" object that has
  422. // the bits initialized to the provided values.
  423. ExplodedNode *N = C.generateNonFatalErrorNode();
  424. if (N) {
  425. SmallString<128> sbuf;
  426. llvm::raw_svector_ostream os(sbuf);
  427. bool isCreate = (FD->getIdentifier() == ICreate);
  428. if (isCreate) {
  429. os << (PrimitiveTypeSize == 8 ? "An " : "A ")
  430. << PrimitiveTypeSize << "-bit integer is used to initialize a "
  431. << "CFNumber object that represents "
  432. << (CFNumberSize == 8 ? "an " : "a ")
  433. << CFNumberSize << "-bit integer; ";
  434. } else {
  435. os << "A CFNumber object that represents "
  436. << (CFNumberSize == 8 ? "an " : "a ")
  437. << CFNumberSize << "-bit integer is used to initialize "
  438. << (PrimitiveTypeSize == 8 ? "an " : "a ")
  439. << PrimitiveTypeSize << "-bit integer; ";
  440. }
  441. if (PrimitiveTypeSize < CFNumberSize)
  442. os << (CFNumberSize - PrimitiveTypeSize)
  443. << " bits of the CFNumber value will "
  444. << (isCreate ? "be garbage." : "overwrite adjacent storage.");
  445. else
  446. os << (PrimitiveTypeSize - CFNumberSize)
  447. << " bits of the integer value will be "
  448. << (isCreate ? "lost." : "garbage.");
  449. if (!BT)
  450. BT.reset(new APIMisuse(this, "Bad use of CFNumber APIs"));
  451. auto report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
  452. report->addRange(CE->getArg(2)->getSourceRange());
  453. C.emitReport(std::move(report));
  454. }
  455. }
  456. //===----------------------------------------------------------------------===//
  457. // CFRetain/CFRelease/CFMakeCollectable/CFAutorelease checking for null arguments.
  458. //===----------------------------------------------------------------------===//
  459. namespace {
  460. class CFRetainReleaseChecker : public Checker<check::PreCall> {
  461. mutable APIMisuse BT{this, "null passed to CF memory management function"};
  462. const CallDescriptionSet ModelledCalls = {
  463. {"CFRetain", 1},
  464. {"CFRelease", 1},
  465. {"CFMakeCollectable", 1},
  466. {"CFAutorelease", 1},
  467. };
  468. public:
  469. void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
  470. };
  471. } // end anonymous namespace
  472. void CFRetainReleaseChecker::checkPreCall(const CallEvent &Call,
  473. CheckerContext &C) const {
  474. // TODO: Make this check part of CallDescription.
  475. if (!Call.isGlobalCFunction())
  476. return;
  477. // Check if we called CFRetain/CFRelease/CFMakeCollectable/CFAutorelease.
  478. if (!ModelledCalls.contains(Call))
  479. return;
  480. // Get the argument's value.
  481. SVal ArgVal = Call.getArgSVal(0);
  482. Optional<DefinedSVal> DefArgVal = ArgVal.getAs<DefinedSVal>();
  483. if (!DefArgVal)
  484. return;
  485. // Is it null?
  486. ProgramStateRef state = C.getState();
  487. ProgramStateRef stateNonNull, stateNull;
  488. std::tie(stateNonNull, stateNull) = state->assume(*DefArgVal);
  489. if (!stateNonNull) {
  490. ExplodedNode *N = C.generateErrorNode(stateNull);
  491. if (!N)
  492. return;
  493. SmallString<64> Str;
  494. raw_svector_ostream OS(Str);
  495. OS << "Null pointer argument in call to "
  496. << cast<FunctionDecl>(Call.getDecl())->getName();
  497. auto report = std::make_unique<PathSensitiveBugReport>(BT, OS.str(), N);
  498. report->addRange(Call.getArgSourceRange(0));
  499. bugreporter::trackExpressionValue(N, Call.getArgExpr(0), *report);
  500. C.emitReport(std::move(report));
  501. return;
  502. }
  503. // From here on, we know the argument is non-null.
  504. C.addTransition(stateNonNull);
  505. }
  506. //===----------------------------------------------------------------------===//
  507. // Check for sending 'retain', 'release', or 'autorelease' directly to a Class.
  508. //===----------------------------------------------------------------------===//
  509. namespace {
  510. class ClassReleaseChecker : public Checker<check::PreObjCMessage> {
  511. mutable Selector releaseS;
  512. mutable Selector retainS;
  513. mutable Selector autoreleaseS;
  514. mutable Selector drainS;
  515. mutable std::unique_ptr<BugType> BT;
  516. public:
  517. void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
  518. };
  519. } // end anonymous namespace
  520. void ClassReleaseChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
  521. CheckerContext &C) const {
  522. if (!BT) {
  523. BT.reset(new APIMisuse(
  524. this, "message incorrectly sent to class instead of class instance"));
  525. ASTContext &Ctx = C.getASTContext();
  526. releaseS = GetNullarySelector("release", Ctx);
  527. retainS = GetNullarySelector("retain", Ctx);
  528. autoreleaseS = GetNullarySelector("autorelease", Ctx);
  529. drainS = GetNullarySelector("drain", Ctx);
  530. }
  531. if (msg.isInstanceMessage())
  532. return;
  533. const ObjCInterfaceDecl *Class = msg.getReceiverInterface();
  534. assert(Class);
  535. Selector S = msg.getSelector();
  536. if (!(S == releaseS || S == retainS || S == autoreleaseS || S == drainS))
  537. return;
  538. if (ExplodedNode *N = C.generateNonFatalErrorNode()) {
  539. SmallString<200> buf;
  540. llvm::raw_svector_ostream os(buf);
  541. os << "The '";
  542. S.print(os);
  543. os << "' message should be sent to instances "
  544. "of class '" << Class->getName()
  545. << "' and not the class directly";
  546. auto report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
  547. report->addRange(msg.getSourceRange());
  548. C.emitReport(std::move(report));
  549. }
  550. }
  551. //===----------------------------------------------------------------------===//
  552. // Check for passing non-Objective-C types to variadic methods that expect
  553. // only Objective-C types.
  554. //===----------------------------------------------------------------------===//
  555. namespace {
  556. class VariadicMethodTypeChecker : public Checker<check::PreObjCMessage> {
  557. mutable Selector arrayWithObjectsS;
  558. mutable Selector dictionaryWithObjectsAndKeysS;
  559. mutable Selector setWithObjectsS;
  560. mutable Selector orderedSetWithObjectsS;
  561. mutable Selector initWithObjectsS;
  562. mutable Selector initWithObjectsAndKeysS;
  563. mutable std::unique_ptr<BugType> BT;
  564. bool isVariadicMessage(const ObjCMethodCall &msg) const;
  565. public:
  566. void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
  567. };
  568. } // end anonymous namespace
  569. /// isVariadicMessage - Returns whether the given message is a variadic message,
  570. /// where all arguments must be Objective-C types.
  571. bool
  572. VariadicMethodTypeChecker::isVariadicMessage(const ObjCMethodCall &msg) const {
  573. const ObjCMethodDecl *MD = msg.getDecl();
  574. if (!MD || !MD->isVariadic() || isa<ObjCProtocolDecl>(MD->getDeclContext()))
  575. return false;
  576. Selector S = msg.getSelector();
  577. if (msg.isInstanceMessage()) {
  578. // FIXME: Ideally we'd look at the receiver interface here, but that's not
  579. // useful for init, because alloc returns 'id'. In theory, this could lead
  580. // to false positives, for example if there existed a class that had an
  581. // initWithObjects: implementation that does accept non-Objective-C pointer
  582. // types, but the chance of that happening is pretty small compared to the
  583. // gains that this analysis gives.
  584. const ObjCInterfaceDecl *Class = MD->getClassInterface();
  585. switch (findKnownClass(Class)) {
  586. case FC_NSArray:
  587. case FC_NSOrderedSet:
  588. case FC_NSSet:
  589. return S == initWithObjectsS;
  590. case FC_NSDictionary:
  591. return S == initWithObjectsAndKeysS;
  592. default:
  593. return false;
  594. }
  595. } else {
  596. const ObjCInterfaceDecl *Class = msg.getReceiverInterface();
  597. switch (findKnownClass(Class)) {
  598. case FC_NSArray:
  599. return S == arrayWithObjectsS;
  600. case FC_NSOrderedSet:
  601. return S == orderedSetWithObjectsS;
  602. case FC_NSSet:
  603. return S == setWithObjectsS;
  604. case FC_NSDictionary:
  605. return S == dictionaryWithObjectsAndKeysS;
  606. default:
  607. return false;
  608. }
  609. }
  610. }
  611. void VariadicMethodTypeChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
  612. CheckerContext &C) const {
  613. if (!BT) {
  614. BT.reset(new APIMisuse(this,
  615. "Arguments passed to variadic method aren't all "
  616. "Objective-C pointer types"));
  617. ASTContext &Ctx = C.getASTContext();
  618. arrayWithObjectsS = GetUnarySelector("arrayWithObjects", Ctx);
  619. dictionaryWithObjectsAndKeysS =
  620. GetUnarySelector("dictionaryWithObjectsAndKeys", Ctx);
  621. setWithObjectsS = GetUnarySelector("setWithObjects", Ctx);
  622. orderedSetWithObjectsS = GetUnarySelector("orderedSetWithObjects", Ctx);
  623. initWithObjectsS = GetUnarySelector("initWithObjects", Ctx);
  624. initWithObjectsAndKeysS = GetUnarySelector("initWithObjectsAndKeys", Ctx);
  625. }
  626. if (!isVariadicMessage(msg))
  627. return;
  628. // We are not interested in the selector arguments since they have
  629. // well-defined types, so the compiler will issue a warning for them.
  630. unsigned variadicArgsBegin = msg.getSelector().getNumArgs();
  631. // We're not interested in the last argument since it has to be nil or the
  632. // compiler would have issued a warning for it elsewhere.
  633. unsigned variadicArgsEnd = msg.getNumArgs() - 1;
  634. if (variadicArgsEnd <= variadicArgsBegin)
  635. return;
  636. // Verify that all arguments have Objective-C types.
  637. Optional<ExplodedNode*> errorNode;
  638. for (unsigned I = variadicArgsBegin; I != variadicArgsEnd; ++I) {
  639. QualType ArgTy = msg.getArgExpr(I)->getType();
  640. if (ArgTy->isObjCObjectPointerType())
  641. continue;
  642. // Block pointers are treaded as Objective-C pointers.
  643. if (ArgTy->isBlockPointerType())
  644. continue;
  645. // Ignore pointer constants.
  646. if (msg.getArgSVal(I).getAs<loc::ConcreteInt>())
  647. continue;
  648. // Ignore pointer types annotated with 'NSObject' attribute.
  649. if (C.getASTContext().isObjCNSObjectType(ArgTy))
  650. continue;
  651. // Ignore CF references, which can be toll-free bridged.
  652. if (coreFoundation::isCFObjectRef(ArgTy))
  653. continue;
  654. // Generate only one error node to use for all bug reports.
  655. if (!errorNode.hasValue())
  656. errorNode = C.generateNonFatalErrorNode();
  657. if (!errorNode.getValue())
  658. continue;
  659. SmallString<128> sbuf;
  660. llvm::raw_svector_ostream os(sbuf);
  661. StringRef TypeName = GetReceiverInterfaceName(msg);
  662. if (!TypeName.empty())
  663. os << "Argument to '" << TypeName << "' method '";
  664. else
  665. os << "Argument to method '";
  666. msg.getSelector().print(os);
  667. os << "' should be an Objective-C pointer type, not '";
  668. ArgTy.print(os, C.getLangOpts());
  669. os << "'";
  670. auto R = std::make_unique<PathSensitiveBugReport>(*BT, os.str(),
  671. errorNode.getValue());
  672. R->addRange(msg.getArgSourceRange(I));
  673. C.emitReport(std::move(R));
  674. }
  675. }
  676. //===----------------------------------------------------------------------===//
  677. // Improves the modeling of loops over Cocoa collections.
  678. //===----------------------------------------------------------------------===//
  679. // The map from container symbol to the container count symbol.
  680. // We currently will remember the last container count symbol encountered.
  681. REGISTER_MAP_WITH_PROGRAMSTATE(ContainerCountMap, SymbolRef, SymbolRef)
  682. REGISTER_MAP_WITH_PROGRAMSTATE(ContainerNonEmptyMap, SymbolRef, bool)
  683. namespace {
  684. class ObjCLoopChecker
  685. : public Checker<check::PostStmt<ObjCForCollectionStmt>,
  686. check::PostObjCMessage,
  687. check::DeadSymbols,
  688. check::PointerEscape > {
  689. mutable IdentifierInfo *CountSelectorII;
  690. bool isCollectionCountMethod(const ObjCMethodCall &M,
  691. CheckerContext &C) const;
  692. public:
  693. ObjCLoopChecker() : CountSelectorII(nullptr) {}
  694. void checkPostStmt(const ObjCForCollectionStmt *FCS, CheckerContext &C) const;
  695. void checkPostObjCMessage(const ObjCMethodCall &M, CheckerContext &C) const;
  696. void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
  697. ProgramStateRef checkPointerEscape(ProgramStateRef State,
  698. const InvalidatedSymbols &Escaped,
  699. const CallEvent *Call,
  700. PointerEscapeKind Kind) const;
  701. };
  702. } // end anonymous namespace
  703. static bool isKnownNonNilCollectionType(QualType T) {
  704. const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
  705. if (!PT)
  706. return false;
  707. const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
  708. if (!ID)
  709. return false;
  710. switch (findKnownClass(ID)) {
  711. case FC_NSArray:
  712. case FC_NSDictionary:
  713. case FC_NSEnumerator:
  714. case FC_NSOrderedSet:
  715. case FC_NSSet:
  716. return true;
  717. default:
  718. return false;
  719. }
  720. }
  721. /// Assumes that the collection is non-nil.
  722. ///
  723. /// If the collection is known to be nil, returns NULL to indicate an infeasible
  724. /// path.
  725. static ProgramStateRef checkCollectionNonNil(CheckerContext &C,
  726. ProgramStateRef State,
  727. const ObjCForCollectionStmt *FCS) {
  728. if (!State)
  729. return nullptr;
  730. SVal CollectionVal = C.getSVal(FCS->getCollection());
  731. Optional<DefinedSVal> KnownCollection = 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. 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(Val.castAs<DefinedOrUnknownSVal>(), 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. 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 (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 form 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 (Optional<DefinedOrUnknownSVal> DV = Val.getAs<DefinedOrUnknownSVal>())
  997. return State->assume(*DV, true);
  998. return State;
  999. }
  1000. void ObjCNonNilReturnValueChecker::checkPostObjCMessage(const ObjCMethodCall &M,
  1001. CheckerContext &C)
  1002. const {
  1003. ProgramStateRef State = C.getState();
  1004. if (!Initialized) {
  1005. ASTContext &Ctx = C.getASTContext();
  1006. ObjectAtIndex = GetUnarySelector("objectAtIndex", Ctx);
  1007. ObjectAtIndexedSubscript = GetUnarySelector("objectAtIndexedSubscript", Ctx);
  1008. NullSelector = GetNullarySelector("null", Ctx);
  1009. }
  1010. // Check the receiver type.
  1011. if (const ObjCInterfaceDecl *Interface = M.getReceiverInterface()) {
  1012. // Assume that object returned from '[self init]' or '[super init]' is not
  1013. // 'nil' if we are processing an inlined function/method.
  1014. //
  1015. // A defensive callee will (and should) check if the object returned by
  1016. // '[super init]' is 'nil' before doing it's own initialization. However,
  1017. // since 'nil' is rarely returned in practice, we should not warn when the
  1018. // caller to the defensive constructor uses the object in contexts where
  1019. // 'nil' is not accepted.
  1020. if (!C.inTopFrame() && M.getDecl() &&
  1021. M.getDecl()->getMethodFamily() == OMF_init &&
  1022. M.isReceiverSelfOrSuper()) {
  1023. State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
  1024. }
  1025. FoundationClass Cl = findKnownClass(Interface);
  1026. // Objects returned from
  1027. // [NSArray|NSOrderedSet]::[ObjectAtIndex|ObjectAtIndexedSubscript]
  1028. // are never 'nil'.
  1029. if (Cl == FC_NSArray || Cl == FC_NSOrderedSet) {
  1030. Selector Sel = M.getSelector();
  1031. if (Sel == ObjectAtIndex || Sel == ObjectAtIndexedSubscript) {
  1032. // Go ahead and assume the value is non-nil.
  1033. State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
  1034. }
  1035. }
  1036. // Objects returned from [NSNull null] are not nil.
  1037. if (Cl == FC_NSNull) {
  1038. if (M.getSelector() == NullSelector) {
  1039. // Go ahead and assume the value is non-nil.
  1040. State = assumeExprIsNonNull(M.getOriginExpr(), State, C);
  1041. }
  1042. }
  1043. }
  1044. C.addTransition(State);
  1045. }
  1046. //===----------------------------------------------------------------------===//
  1047. // Check registration.
  1048. //===----------------------------------------------------------------------===//
  1049. void ento::registerNilArgChecker(CheckerManager &mgr) {
  1050. mgr.registerChecker<NilArgChecker>();
  1051. }
  1052. bool ento::shouldRegisterNilArgChecker(const CheckerManager &mgr) {
  1053. return true;
  1054. }
  1055. void ento::registerCFNumberChecker(CheckerManager &mgr) {
  1056. mgr.registerChecker<CFNumberChecker>();
  1057. }
  1058. bool ento::shouldRegisterCFNumberChecker(const CheckerManager &mgr) {
  1059. return true;
  1060. }
  1061. void ento::registerCFRetainReleaseChecker(CheckerManager &mgr) {
  1062. mgr.registerChecker<CFRetainReleaseChecker>();
  1063. }
  1064. bool ento::shouldRegisterCFRetainReleaseChecker(const CheckerManager &mgr) {
  1065. return true;
  1066. }
  1067. void ento::registerClassReleaseChecker(CheckerManager &mgr) {
  1068. mgr.registerChecker<ClassReleaseChecker>();
  1069. }
  1070. bool ento::shouldRegisterClassReleaseChecker(const CheckerManager &mgr) {
  1071. return true;
  1072. }
  1073. void ento::registerVariadicMethodTypeChecker(CheckerManager &mgr) {
  1074. mgr.registerChecker<VariadicMethodTypeChecker>();
  1075. }
  1076. bool ento::shouldRegisterVariadicMethodTypeChecker(const CheckerManager &mgr) {
  1077. return true;
  1078. }
  1079. void ento::registerObjCLoopChecker(CheckerManager &mgr) {
  1080. mgr.registerChecker<ObjCLoopChecker>();
  1081. }
  1082. bool ento::shouldRegisterObjCLoopChecker(const CheckerManager &mgr) {
  1083. return true;
  1084. }
  1085. void ento::registerObjCNonNilReturnValueChecker(CheckerManager &mgr) {
  1086. mgr.registerChecker<ObjCNonNilReturnValueChecker>();
  1087. }
  1088. bool ento::shouldRegisterObjCNonNilReturnValueChecker(const CheckerManager &mgr) {
  1089. return true;
  1090. }