ObjCSelfInitChecker.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. //== ObjCSelfInitChecker.cpp - Checker for 'self' initialization -*- C++ -*--=//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This defines ObjCSelfInitChecker, a builtin check that checks for uses of
  10. // 'self' before proper initialization.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. // This checks initialization methods to verify that they assign 'self' to the
  14. // result of an initialization call (e.g. [super init], or [self initWith..])
  15. // before using 'self' or any instance variable.
  16. //
  17. // To perform the required checking, values are tagged with flags that indicate
  18. // 1) if the object is the one pointed to by 'self', and 2) if the object
  19. // is the result of an initializer (e.g. [super init]).
  20. //
  21. // Uses of an object that is true for 1) but not 2) trigger a diagnostic.
  22. // The uses that are currently checked are:
  23. // - Using instance variables.
  24. // - Returning the object.
  25. //
  26. // Note that we don't check for an invalid 'self' that is the receiver of an
  27. // obj-c message expression to cut down false positives where logging functions
  28. // get information from self (like its class) or doing "invalidation" on self
  29. // when the initialization fails.
  30. //
  31. // Because the object that 'self' points to gets invalidated when a call
  32. // receives a reference to 'self', the checker keeps track and passes the flags
  33. // for 1) and 2) to the new object that 'self' points to after the call.
  34. //
  35. //===----------------------------------------------------------------------===//
  36. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  37. #include "clang/AST/ParentMap.h"
  38. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  39. #include "clang/StaticAnalyzer/Core/Checker.h"
  40. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  41. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  42. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  43. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  44. #include "llvm/Support/raw_ostream.h"
  45. using namespace clang;
  46. using namespace ento;
  47. static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
  48. static bool isInitializationMethod(const ObjCMethodDecl *MD);
  49. static bool isInitMessage(const ObjCMethodCall &Msg);
  50. static bool isSelfVar(SVal location, CheckerContext &C);
  51. namespace {
  52. class ObjCSelfInitChecker : public Checker< check::PostObjCMessage,
  53. check::PostStmt<ObjCIvarRefExpr>,
  54. check::PreStmt<ReturnStmt>,
  55. check::PreCall,
  56. check::PostCall,
  57. check::Location,
  58. check::Bind > {
  59. mutable std::unique_ptr<BugType> BT;
  60. void checkForInvalidSelf(const Expr *E, CheckerContext &C,
  61. const char *errorStr) const;
  62. public:
  63. ObjCSelfInitChecker() {}
  64. void checkPostObjCMessage(const ObjCMethodCall &Msg, CheckerContext &C) const;
  65. void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
  66. void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
  67. void checkLocation(SVal location, bool isLoad, const Stmt *S,
  68. CheckerContext &C) const;
  69. void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
  70. void checkPreCall(const CallEvent &CE, CheckerContext &C) const;
  71. void checkPostCall(const CallEvent &CE, CheckerContext &C) const;
  72. void printState(raw_ostream &Out, ProgramStateRef State,
  73. const char *NL, const char *Sep) const override;
  74. };
  75. } // end anonymous namespace
  76. namespace {
  77. enum SelfFlagEnum {
  78. /// No flag set.
  79. SelfFlag_None = 0x0,
  80. /// Value came from 'self'.
  81. SelfFlag_Self = 0x1,
  82. /// Value came from the result of an initializer (e.g. [super init]).
  83. SelfFlag_InitRes = 0x2
  84. };
  85. }
  86. REGISTER_MAP_WITH_PROGRAMSTATE(SelfFlag, SymbolRef, SelfFlagEnum)
  87. REGISTER_TRAIT_WITH_PROGRAMSTATE(CalledInit, bool)
  88. /// A call receiving a reference to 'self' invalidates the object that
  89. /// 'self' contains. This keeps the "self flags" assigned to the 'self'
  90. /// object before the call so we can assign them to the new object that 'self'
  91. /// points to after the call.
  92. REGISTER_TRAIT_WITH_PROGRAMSTATE(PreCallSelfFlags, SelfFlagEnum)
  93. static SelfFlagEnum getSelfFlags(SVal val, ProgramStateRef state) {
  94. if (SymbolRef sym = val.getAsSymbol())
  95. if (const SelfFlagEnum *attachedFlags = state->get<SelfFlag>(sym))
  96. return *attachedFlags;
  97. return SelfFlag_None;
  98. }
  99. static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
  100. return getSelfFlags(val, C.getState());
  101. }
  102. static void addSelfFlag(ProgramStateRef state, SVal val,
  103. SelfFlagEnum flag, CheckerContext &C) {
  104. // We tag the symbol that the SVal wraps.
  105. if (SymbolRef sym = val.getAsSymbol()) {
  106. state = state->set<SelfFlag>(sym,
  107. SelfFlagEnum(getSelfFlags(val, state) | flag));
  108. C.addTransition(state);
  109. }
  110. }
  111. static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
  112. return getSelfFlags(val, C) & flag;
  113. }
  114. /// Returns true of the value of the expression is the object that 'self'
  115. /// points to and is an object that did not come from the result of calling
  116. /// an initializer.
  117. static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
  118. SVal exprVal = C.getSVal(E);
  119. if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
  120. return false; // value did not come from 'self'.
  121. if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
  122. return false; // 'self' is properly initialized.
  123. return true;
  124. }
  125. void ObjCSelfInitChecker::checkForInvalidSelf(const Expr *E, CheckerContext &C,
  126. const char *errorStr) const {
  127. if (!E)
  128. return;
  129. if (!C.getState()->get<CalledInit>())
  130. return;
  131. if (!isInvalidSelf(E, C))
  132. return;
  133. // Generate an error node.
  134. ExplodedNode *N = C.generateErrorNode();
  135. if (!N)
  136. return;
  137. if (!BT)
  138. BT.reset(new BugType(this, "Missing \"self = [(super or self) init...]\"",
  139. categories::CoreFoundationObjectiveC));
  140. C.emitReport(std::make_unique<PathSensitiveBugReport>(*BT, errorStr, N));
  141. }
  142. void ObjCSelfInitChecker::checkPostObjCMessage(const ObjCMethodCall &Msg,
  143. CheckerContext &C) const {
  144. // When encountering a message that does initialization (init rule),
  145. // tag the return value so that we know later on that if self has this value
  146. // then it is properly initialized.
  147. // FIXME: A callback should disable checkers at the start of functions.
  148. if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
  149. C.getCurrentAnalysisDeclContext()->getDecl())))
  150. return;
  151. if (isInitMessage(Msg)) {
  152. // Tag the return value as the result of an initializer.
  153. ProgramStateRef state = C.getState();
  154. // FIXME this really should be context sensitive, where we record
  155. // the current stack frame (for IPA). Also, we need to clean this
  156. // value out when we return from this method.
  157. state = state->set<CalledInit>(true);
  158. SVal V = C.getSVal(Msg.getOriginExpr());
  159. addSelfFlag(state, V, SelfFlag_InitRes, C);
  160. return;
  161. }
  162. // We don't check for an invalid 'self' in an obj-c message expression to cut
  163. // down false positives where logging functions get information from self
  164. // (like its class) or doing "invalidation" on self when the initialization
  165. // fails.
  166. }
  167. void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E,
  168. CheckerContext &C) const {
  169. // FIXME: A callback should disable checkers at the start of functions.
  170. if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
  171. C.getCurrentAnalysisDeclContext()->getDecl())))
  172. return;
  173. checkForInvalidSelf(
  174. E->getBase(), C,
  175. "Instance variable used while 'self' is not set to the result of "
  176. "'[(super or self) init...]'");
  177. }
  178. void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S,
  179. CheckerContext &C) const {
  180. // FIXME: A callback should disable checkers at the start of functions.
  181. if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
  182. C.getCurrentAnalysisDeclContext()->getDecl())))
  183. return;
  184. checkForInvalidSelf(S->getRetValue(), C,
  185. "Returning 'self' while it is not set to the result of "
  186. "'[(super or self) init...]'");
  187. }
  188. // When a call receives a reference to 'self', [Pre/Post]Call pass
  189. // the SelfFlags from the object 'self' points to before the call to the new
  190. // object after the call. This is to avoid invalidation of 'self' by logging
  191. // functions.
  192. // Another common pattern in classes with multiple initializers is to put the
  193. // subclass's common initialization bits into a static function that receives
  194. // the value of 'self', e.g:
  195. // @code
  196. // if (!(self = [super init]))
  197. // return nil;
  198. // if (!(self = _commonInit(self)))
  199. // return nil;
  200. // @endcode
  201. // Until we can use inter-procedural analysis, in such a call, transfer the
  202. // SelfFlags to the result of the call.
  203. void ObjCSelfInitChecker::checkPreCall(const CallEvent &CE,
  204. CheckerContext &C) const {
  205. // FIXME: A callback should disable checkers at the start of functions.
  206. if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
  207. C.getCurrentAnalysisDeclContext()->getDecl())))
  208. return;
  209. ProgramStateRef state = C.getState();
  210. unsigned NumArgs = CE.getNumArgs();
  211. // If we passed 'self' as and argument to the call, record it in the state
  212. // to be propagated after the call.
  213. // Note, we could have just given up, but try to be more optimistic here and
  214. // assume that the functions are going to continue initialization or will not
  215. // modify self.
  216. for (unsigned i = 0; i < NumArgs; ++i) {
  217. SVal argV = CE.getArgSVal(i);
  218. if (isSelfVar(argV, C)) {
  219. SelfFlagEnum selfFlags =
  220. getSelfFlags(state->getSVal(argV.castAs<Loc>()), C);
  221. C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
  222. return;
  223. } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
  224. SelfFlagEnum selfFlags = getSelfFlags(argV, C);
  225. C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
  226. return;
  227. }
  228. }
  229. }
  230. void ObjCSelfInitChecker::checkPostCall(const CallEvent &CE,
  231. CheckerContext &C) const {
  232. // FIXME: A callback should disable checkers at the start of functions.
  233. if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
  234. C.getCurrentAnalysisDeclContext()->getDecl())))
  235. return;
  236. ProgramStateRef state = C.getState();
  237. SelfFlagEnum prevFlags = state->get<PreCallSelfFlags>();
  238. if (!prevFlags)
  239. return;
  240. state = state->remove<PreCallSelfFlags>();
  241. unsigned NumArgs = CE.getNumArgs();
  242. for (unsigned i = 0; i < NumArgs; ++i) {
  243. SVal argV = CE.getArgSVal(i);
  244. if (isSelfVar(argV, C)) {
  245. // If the address of 'self' is being passed to the call, assume that the
  246. // 'self' after the call will have the same flags.
  247. // EX: log(&self)
  248. addSelfFlag(state, state->getSVal(argV.castAs<Loc>()), prevFlags, C);
  249. return;
  250. } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
  251. // If 'self' is passed to the call by value, assume that the function
  252. // returns 'self'. So assign the flags, which were set on 'self' to the
  253. // return value.
  254. // EX: self = performMoreInitialization(self)
  255. addSelfFlag(state, CE.getReturnValue(), prevFlags, C);
  256. return;
  257. }
  258. }
  259. C.addTransition(state);
  260. }
  261. void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad,
  262. const Stmt *S,
  263. CheckerContext &C) const {
  264. if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
  265. C.getCurrentAnalysisDeclContext()->getDecl())))
  266. return;
  267. // Tag the result of a load from 'self' so that we can easily know that the
  268. // value is the object that 'self' points to.
  269. ProgramStateRef state = C.getState();
  270. if (isSelfVar(location, C))
  271. addSelfFlag(state, state->getSVal(location.castAs<Loc>()), SelfFlag_Self,
  272. C);
  273. }
  274. void ObjCSelfInitChecker::checkBind(SVal loc, SVal val, const Stmt *S,
  275. CheckerContext &C) const {
  276. // Allow assignment of anything to self. Self is a local variable in the
  277. // initializer, so it is legal to assign anything to it, like results of
  278. // static functions/method calls. After self is assigned something we cannot
  279. // reason about, stop enforcing the rules.
  280. // (Only continue checking if the assigned value should be treated as self.)
  281. if ((isSelfVar(loc, C)) &&
  282. !hasSelfFlag(val, SelfFlag_InitRes, C) &&
  283. !hasSelfFlag(val, SelfFlag_Self, C) &&
  284. !isSelfVar(val, C)) {
  285. // Stop tracking the checker-specific state in the state.
  286. ProgramStateRef State = C.getState();
  287. State = State->remove<CalledInit>();
  288. if (SymbolRef sym = loc.getAsSymbol())
  289. State = State->remove<SelfFlag>(sym);
  290. C.addTransition(State);
  291. }
  292. }
  293. void ObjCSelfInitChecker::printState(raw_ostream &Out, ProgramStateRef State,
  294. const char *NL, const char *Sep) const {
  295. SelfFlagTy FlagMap = State->get<SelfFlag>();
  296. bool DidCallInit = State->get<CalledInit>();
  297. SelfFlagEnum PreCallFlags = State->get<PreCallSelfFlags>();
  298. if (FlagMap.isEmpty() && !DidCallInit && !PreCallFlags)
  299. return;
  300. Out << Sep << NL << *this << " :" << NL;
  301. if (DidCallInit)
  302. Out << " An init method has been called." << NL;
  303. if (PreCallFlags != SelfFlag_None) {
  304. if (PreCallFlags & SelfFlag_Self) {
  305. Out << " An argument of the current call came from the 'self' variable."
  306. << NL;
  307. }
  308. if (PreCallFlags & SelfFlag_InitRes) {
  309. Out << " An argument of the current call came from an init method."
  310. << NL;
  311. }
  312. }
  313. Out << NL;
  314. for (SelfFlagTy::iterator I = FlagMap.begin(), E = FlagMap.end();
  315. I != E; ++I) {
  316. Out << I->first << " : ";
  317. if (I->second == SelfFlag_None)
  318. Out << "none";
  319. if (I->second & SelfFlag_Self)
  320. Out << "self variable";
  321. if (I->second & SelfFlag_InitRes) {
  322. if (I->second != SelfFlag_InitRes)
  323. Out << " | ";
  324. Out << "result of init method";
  325. }
  326. Out << NL;
  327. }
  328. }
  329. // FIXME: A callback should disable checkers at the start of functions.
  330. static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
  331. if (!ND)
  332. return false;
  333. const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
  334. if (!MD)
  335. return false;
  336. if (!isInitializationMethod(MD))
  337. return false;
  338. // self = [super init] applies only to NSObject subclasses.
  339. // For instance, NSProxy doesn't implement -init.
  340. ASTContext &Ctx = MD->getASTContext();
  341. IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
  342. ObjCInterfaceDecl *ID = MD->getClassInterface()->getSuperClass();
  343. for ( ; ID ; ID = ID->getSuperClass()) {
  344. IdentifierInfo *II = ID->getIdentifier();
  345. if (II == NSObjectII)
  346. break;
  347. }
  348. return ID != nullptr;
  349. }
  350. /// Returns true if the location is 'self'.
  351. static bool isSelfVar(SVal location, CheckerContext &C) {
  352. AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext();
  353. if (!analCtx->getSelfDecl())
  354. return false;
  355. if (!isa<loc::MemRegionVal>(location))
  356. return false;
  357. loc::MemRegionVal MRV = location.castAs<loc::MemRegionVal>();
  358. if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.stripCasts()))
  359. return (DR->getDecl() == analCtx->getSelfDecl());
  360. return false;
  361. }
  362. static bool isInitializationMethod(const ObjCMethodDecl *MD) {
  363. return MD->getMethodFamily() == OMF_init;
  364. }
  365. static bool isInitMessage(const ObjCMethodCall &Call) {
  366. return Call.getMethodFamily() == OMF_init;
  367. }
  368. //===----------------------------------------------------------------------===//
  369. // Registration.
  370. //===----------------------------------------------------------------------===//
  371. void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
  372. mgr.registerChecker<ObjCSelfInitChecker>();
  373. }
  374. bool ento::shouldRegisterObjCSelfInitChecker(const CheckerManager &mgr) {
  375. return true;
  376. }