BasicObjCFoundationChecks.cpp 44 KB

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