ObjCSelfInitChecker.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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, unsigned)
  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, unsigned)
  93. static SelfFlagEnum getSelfFlags(SVal val, ProgramStateRef state) {
  94. if (SymbolRef sym = val.getAsSymbol())
  95. if (const unsigned *attachedFlags = state->get<SelfFlag>(sym))
  96. return (SelfFlagEnum)*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, getSelfFlags(val, state) | flag);
  107. C.addTransition(state);
  108. }
  109. }
  110. static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
  111. return getSelfFlags(val, C) & flag;
  112. }
  113. /// Returns true of the value of the expression is the object that 'self'
  114. /// points to and is an object that did not come from the result of calling
  115. /// an initializer.
  116. static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
  117. SVal exprVal = C.getSVal(E);
  118. if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
  119. return false; // value did not come from 'self'.
  120. if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
  121. return false; // 'self' is properly initialized.
  122. return true;
  123. }
  124. void ObjCSelfInitChecker::checkForInvalidSelf(const Expr *E, CheckerContext &C,
  125. const char *errorStr) const {
  126. if (!E)
  127. return;
  128. if (!C.getState()->get<CalledInit>())
  129. return;
  130. if (!isInvalidSelf(E, C))
  131. return;
  132. // Generate an error node.
  133. ExplodedNode *N = C.generateErrorNode();
  134. if (!N)
  135. return;
  136. if (!BT)
  137. BT.reset(new BugType(this, "Missing \"self = [(super or self) init...]\"",
  138. categories::CoreFoundationObjectiveC));
  139. C.emitReport(std::make_unique<PathSensitiveBugReport>(*BT, errorStr, N));
  140. }
  141. void ObjCSelfInitChecker::checkPostObjCMessage(const ObjCMethodCall &Msg,
  142. CheckerContext &C) const {
  143. // When encountering a message that does initialization (init rule),
  144. // tag the return value so that we know later on that if self has this value
  145. // then it is properly initialized.
  146. // FIXME: A callback should disable checkers at the start of functions.
  147. if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
  148. C.getCurrentAnalysisDeclContext()->getDecl())))
  149. return;
  150. if (isInitMessage(Msg)) {
  151. // Tag the return value as the result of an initializer.
  152. ProgramStateRef state = C.getState();
  153. // FIXME this really should be context sensitive, where we record
  154. // the current stack frame (for IPA). Also, we need to clean this
  155. // value out when we return from this method.
  156. state = state->set<CalledInit>(true);
  157. SVal V = C.getSVal(Msg.getOriginExpr());
  158. addSelfFlag(state, V, SelfFlag_InitRes, C);
  159. return;
  160. }
  161. // We don't check for an invalid 'self' in an obj-c message expression to cut
  162. // down false positives where logging functions get information from self
  163. // (like its class) or doing "invalidation" on self when the initialization
  164. // fails.
  165. }
  166. void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E,
  167. CheckerContext &C) const {
  168. // FIXME: A callback should disable checkers at the start of functions.
  169. if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
  170. C.getCurrentAnalysisDeclContext()->getDecl())))
  171. return;
  172. checkForInvalidSelf(
  173. E->getBase(), C,
  174. "Instance variable used while 'self' is not set to the result of "
  175. "'[(super or self) init...]'");
  176. }
  177. void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S,
  178. CheckerContext &C) const {
  179. // FIXME: A callback should disable checkers at the start of functions.
  180. if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
  181. C.getCurrentAnalysisDeclContext()->getDecl())))
  182. return;
  183. checkForInvalidSelf(S->getRetValue(), C,
  184. "Returning 'self' while it is not set to the result of "
  185. "'[(super or self) init...]'");
  186. }
  187. // When a call receives a reference to 'self', [Pre/Post]Call pass
  188. // the SelfFlags from the object 'self' points to before the call to the new
  189. // object after the call. This is to avoid invalidation of 'self' by logging
  190. // functions.
  191. // Another common pattern in classes with multiple initializers is to put the
  192. // subclass's common initialization bits into a static function that receives
  193. // the value of 'self', e.g:
  194. // @code
  195. // if (!(self = [super init]))
  196. // return nil;
  197. // if (!(self = _commonInit(self)))
  198. // return nil;
  199. // @endcode
  200. // Until we can use inter-procedural analysis, in such a call, transfer the
  201. // SelfFlags to the result of the call.
  202. void ObjCSelfInitChecker::checkPreCall(const CallEvent &CE,
  203. CheckerContext &C) const {
  204. // FIXME: A callback should disable checkers at the start of functions.
  205. if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
  206. C.getCurrentAnalysisDeclContext()->getDecl())))
  207. return;
  208. ProgramStateRef state = C.getState();
  209. unsigned NumArgs = CE.getNumArgs();
  210. // If we passed 'self' as and argument to the call, record it in the state
  211. // to be propagated after the call.
  212. // Note, we could have just given up, but try to be more optimistic here and
  213. // assume that the functions are going to continue initialization or will not
  214. // modify self.
  215. for (unsigned i = 0; i < NumArgs; ++i) {
  216. SVal argV = CE.getArgSVal(i);
  217. if (isSelfVar(argV, C)) {
  218. unsigned selfFlags = getSelfFlags(state->getSVal(argV.castAs<Loc>()), C);
  219. C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
  220. return;
  221. } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
  222. unsigned selfFlags = getSelfFlags(argV, C);
  223. C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
  224. return;
  225. }
  226. }
  227. }
  228. void ObjCSelfInitChecker::checkPostCall(const CallEvent &CE,
  229. CheckerContext &C) const {
  230. // FIXME: A callback should disable checkers at the start of functions.
  231. if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
  232. C.getCurrentAnalysisDeclContext()->getDecl())))
  233. return;
  234. ProgramStateRef state = C.getState();
  235. SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
  236. if (!prevFlags)
  237. return;
  238. state = state->remove<PreCallSelfFlags>();
  239. unsigned NumArgs = CE.getNumArgs();
  240. for (unsigned i = 0; i < NumArgs; ++i) {
  241. SVal argV = CE.getArgSVal(i);
  242. if (isSelfVar(argV, C)) {
  243. // If the address of 'self' is being passed to the call, assume that the
  244. // 'self' after the call will have the same flags.
  245. // EX: log(&self)
  246. addSelfFlag(state, state->getSVal(argV.castAs<Loc>()), prevFlags, C);
  247. return;
  248. } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
  249. // If 'self' is passed to the call by value, assume that the function
  250. // returns 'self'. So assign the flags, which were set on 'self' to the
  251. // return value.
  252. // EX: self = performMoreInitialization(self)
  253. addSelfFlag(state, CE.getReturnValue(), prevFlags, C);
  254. return;
  255. }
  256. }
  257. C.addTransition(state);
  258. }
  259. void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad,
  260. const Stmt *S,
  261. CheckerContext &C) const {
  262. if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
  263. C.getCurrentAnalysisDeclContext()->getDecl())))
  264. return;
  265. // Tag the result of a load from 'self' so that we can easily know that the
  266. // value is the object that 'self' points to.
  267. ProgramStateRef state = C.getState();
  268. if (isSelfVar(location, C))
  269. addSelfFlag(state, state->getSVal(location.castAs<Loc>()), SelfFlag_Self,
  270. C);
  271. }
  272. void ObjCSelfInitChecker::checkBind(SVal loc, SVal val, const Stmt *S,
  273. CheckerContext &C) const {
  274. // Allow assignment of anything to self. Self is a local variable in the
  275. // initializer, so it is legal to assign anything to it, like results of
  276. // static functions/method calls. After self is assigned something we cannot
  277. // reason about, stop enforcing the rules.
  278. // (Only continue checking if the assigned value should be treated as self.)
  279. if ((isSelfVar(loc, C)) &&
  280. !hasSelfFlag(val, SelfFlag_InitRes, C) &&
  281. !hasSelfFlag(val, SelfFlag_Self, C) &&
  282. !isSelfVar(val, C)) {
  283. // Stop tracking the checker-specific state in the state.
  284. ProgramStateRef State = C.getState();
  285. State = State->remove<CalledInit>();
  286. if (SymbolRef sym = loc.getAsSymbol())
  287. State = State->remove<SelfFlag>(sym);
  288. C.addTransition(State);
  289. }
  290. }
  291. void ObjCSelfInitChecker::printState(raw_ostream &Out, ProgramStateRef State,
  292. const char *NL, const char *Sep) const {
  293. SelfFlagTy FlagMap = State->get<SelfFlag>();
  294. bool DidCallInit = State->get<CalledInit>();
  295. SelfFlagEnum PreCallFlags = (SelfFlagEnum)State->get<PreCallSelfFlags>();
  296. if (FlagMap.isEmpty() && !DidCallInit && !PreCallFlags)
  297. return;
  298. Out << Sep << NL << *this << " :" << NL;
  299. if (DidCallInit)
  300. Out << " An init method has been called." << NL;
  301. if (PreCallFlags != SelfFlag_None) {
  302. if (PreCallFlags & SelfFlag_Self) {
  303. Out << " An argument of the current call came from the 'self' variable."
  304. << NL;
  305. }
  306. if (PreCallFlags & SelfFlag_InitRes) {
  307. Out << " An argument of the current call came from an init method."
  308. << NL;
  309. }
  310. }
  311. Out << NL;
  312. for (SelfFlagTy::iterator I = FlagMap.begin(), E = FlagMap.end();
  313. I != E; ++I) {
  314. Out << I->first << " : ";
  315. if (I->second == SelfFlag_None)
  316. Out << "none";
  317. if (I->second & SelfFlag_Self)
  318. Out << "self variable";
  319. if (I->second & SelfFlag_InitRes) {
  320. if (I->second != SelfFlag_InitRes)
  321. Out << " | ";
  322. Out << "result of init method";
  323. }
  324. Out << NL;
  325. }
  326. }
  327. // FIXME: A callback should disable checkers at the start of functions.
  328. static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
  329. if (!ND)
  330. return false;
  331. const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
  332. if (!MD)
  333. return false;
  334. if (!isInitializationMethod(MD))
  335. return false;
  336. // self = [super init] applies only to NSObject subclasses.
  337. // For instance, NSProxy doesn't implement -init.
  338. ASTContext &Ctx = MD->getASTContext();
  339. IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
  340. ObjCInterfaceDecl *ID = MD->getClassInterface()->getSuperClass();
  341. for ( ; ID ; ID = ID->getSuperClass()) {
  342. IdentifierInfo *II = ID->getIdentifier();
  343. if (II == NSObjectII)
  344. break;
  345. }
  346. return ID != nullptr;
  347. }
  348. /// Returns true if the location is 'self'.
  349. static bool isSelfVar(SVal location, CheckerContext &C) {
  350. AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext();
  351. if (!analCtx->getSelfDecl())
  352. return false;
  353. if (!location.getAs<loc::MemRegionVal>())
  354. return false;
  355. loc::MemRegionVal MRV = location.castAs<loc::MemRegionVal>();
  356. if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.stripCasts()))
  357. return (DR->getDecl() == analCtx->getSelfDecl());
  358. return false;
  359. }
  360. static bool isInitializationMethod(const ObjCMethodDecl *MD) {
  361. return MD->getMethodFamily() == OMF_init;
  362. }
  363. static bool isInitMessage(const ObjCMethodCall &Call) {
  364. return Call.getMethodFamily() == OMF_init;
  365. }
  366. //===----------------------------------------------------------------------===//
  367. // Registration.
  368. //===----------------------------------------------------------------------===//
  369. void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
  370. mgr.registerChecker<ObjCSelfInitChecker>();
  371. }
  372. bool ento::shouldRegisterObjCSelfInitChecker(const CheckerManager &mgr) {
  373. return true;
  374. }