BasicObjCFoundationChecks.cpp 44 KB

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