ObjCSelfInitChecker.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. //== ObjCSelfInitChecker.cpp - Checker for 'self' initialization -*- 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 defines ObjCSelfInitChecker, a builtin check that checks for uses of
  11. // 'self' before proper initialization.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. // This checks initialization methods to verify that they assign 'self' to the
  15. // result of an initialization call (e.g. [super init], or [self initWith..])
  16. // before using 'self' or any instance variable.
  17. //
  18. // To perform the required checking, values are tagged with flags that indicate
  19. // 1) if the object is the one pointed to by 'self', and 2) if the object
  20. // is the result of an initializer (e.g. [super init]).
  21. //
  22. // Uses of an object that is true for 1) but not 2) trigger a diagnostic.
  23. // The uses that are currently checked are:
  24. // - Using instance variables.
  25. // - Returning the object.
  26. //
  27. // Note that we don't check for an invalid 'self' that is the receiver of an
  28. // obj-c message expression to cut down false positives where logging functions
  29. // get information from self (like its class) or doing "invalidation" on self
  30. // when the initialization fails.
  31. //
  32. // Because the object that 'self' points to gets invalidated when a call
  33. // receives a reference to 'self', the checker keeps track and passes the flags
  34. // for 1) and 2) to the new object that 'self' points to after the call.
  35. //
  36. //===----------------------------------------------------------------------===//
  37. #include "ClangSACheckers.h"
  38. #include "clang/AST/ParentMap.h"
  39. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  40. #include "clang/StaticAnalyzer/Core/Checker.h"
  41. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  42. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  43. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  44. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. using namespace clang;
  47. using namespace ento;
  48. static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
  49. static bool isInitializationMethod(const ObjCMethodDecl *MD);
  50. static bool isInitMessage(const ObjCMethodCall &Msg);
  51. static bool isSelfVar(SVal location, CheckerContext &C);
  52. namespace {
  53. class ObjCSelfInitChecker : public Checker< check::PostObjCMessage,
  54. check::PostStmt<ObjCIvarRefExpr>,
  55. check::PreStmt<ReturnStmt>,
  56. check::PreCall,
  57. check::PostCall,
  58. check::Location,
  59. check::Bind > {
  60. mutable std::unique_ptr<BugType> BT;
  61. void checkForInvalidSelf(const Expr *E, CheckerContext &C,
  62. const char *errorStr) const;
  63. public:
  64. ObjCSelfInitChecker() {}
  65. void checkPostObjCMessage(const ObjCMethodCall &Msg, CheckerContext &C) const;
  66. void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
  67. void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
  68. void checkLocation(SVal location, bool isLoad, const Stmt *S,
  69. CheckerContext &C) const;
  70. void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
  71. void checkPreCall(const CallEvent &CE, CheckerContext &C) const;
  72. void checkPostCall(const CallEvent &CE, CheckerContext &C) const;
  73. void printState(raw_ostream &Out, ProgramStateRef State,
  74. const char *NL, const char *Sep) const override;
  75. };
  76. } // end anonymous namespace
  77. namespace {
  78. enum SelfFlagEnum {
  79. /// \brief No flag set.
  80. SelfFlag_None = 0x0,
  81. /// \brief Value came from 'self'.
  82. SelfFlag_Self = 0x1,
  83. /// \brief Value came from the result of an initializer (e.g. [super init]).
  84. SelfFlag_InitRes = 0x2
  85. };
  86. }
  87. REGISTER_MAP_WITH_PROGRAMSTATE(SelfFlag, SymbolRef, unsigned)
  88. REGISTER_TRAIT_WITH_PROGRAMSTATE(CalledInit, bool)
  89. /// \brief A call receiving a reference to 'self' invalidates the object that
  90. /// 'self' contains. This keeps the "self flags" assigned to the 'self'
  91. /// object before the call so we can assign them to the new object that 'self'
  92. /// points to after the call.
  93. REGISTER_TRAIT_WITH_PROGRAMSTATE(PreCallSelfFlags, unsigned)
  94. static SelfFlagEnum getSelfFlags(SVal val, ProgramStateRef state) {
  95. if (SymbolRef sym = val.getAsSymbol())
  96. if (const unsigned *attachedFlags = state->get<SelfFlag>(sym))
  97. return (SelfFlagEnum)*attachedFlags;
  98. return SelfFlag_None;
  99. }
  100. static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
  101. return getSelfFlags(val, C.getState());
  102. }
  103. static void addSelfFlag(ProgramStateRef state, SVal val,
  104. SelfFlagEnum flag, CheckerContext &C) {
  105. // We tag the symbol that the SVal wraps.
  106. if (SymbolRef sym = val.getAsSymbol()) {
  107. state = state->set<SelfFlag>(sym, 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. /// \brief 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(llvm::make_unique<BugReport>(*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. unsigned selfFlags = getSelfFlags(state->getSVal(argV.castAs<Loc>()), C);
  220. C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
  221. return;
  222. } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
  223. unsigned selfFlags = getSelfFlags(argV, C);
  224. C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
  225. return;
  226. }
  227. }
  228. }
  229. void ObjCSelfInitChecker::checkPostCall(const CallEvent &CE,
  230. CheckerContext &C) const {
  231. // FIXME: A callback should disable checkers at the start of functions.
  232. if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
  233. C.getCurrentAnalysisDeclContext()->getDecl())))
  234. return;
  235. ProgramStateRef state = C.getState();
  236. SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
  237. if (!prevFlags)
  238. return;
  239. state = state->remove<PreCallSelfFlags>();
  240. unsigned NumArgs = CE.getNumArgs();
  241. for (unsigned i = 0; i < NumArgs; ++i) {
  242. SVal argV = CE.getArgSVal(i);
  243. if (isSelfVar(argV, C)) {
  244. // If the address of 'self' is being passed to the call, assume that the
  245. // 'self' after the call will have the same flags.
  246. // EX: log(&self)
  247. addSelfFlag(state, state->getSVal(argV.castAs<Loc>()), prevFlags, C);
  248. return;
  249. } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
  250. // If 'self' is passed to the call by value, assume that the function
  251. // returns 'self'. So assign the flags, which were set on 'self' to the
  252. // return value.
  253. // EX: self = performMoreInitialization(self)
  254. addSelfFlag(state, CE.getReturnValue(), prevFlags, C);
  255. return;
  256. }
  257. }
  258. C.addTransition(state);
  259. }
  260. void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad,
  261. const Stmt *S,
  262. CheckerContext &C) const {
  263. if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
  264. C.getCurrentAnalysisDeclContext()->getDecl())))
  265. return;
  266. // Tag the result of a load from 'self' so that we can easily know that the
  267. // value is the object that 'self' points to.
  268. ProgramStateRef state = C.getState();
  269. if (isSelfVar(location, C))
  270. addSelfFlag(state, state->getSVal(location.castAs<Loc>()), SelfFlag_Self,
  271. C);
  272. }
  273. void ObjCSelfInitChecker::checkBind(SVal loc, SVal val, const Stmt *S,
  274. CheckerContext &C) const {
  275. // Allow assignment of anything to self. Self is a local variable in the
  276. // initializer, so it is legal to assign anything to it, like results of
  277. // static functions/method calls. After self is assigned something we cannot
  278. // reason about, stop enforcing the rules.
  279. // (Only continue checking if the assigned value should be treated as self.)
  280. if ((isSelfVar(loc, C)) &&
  281. !hasSelfFlag(val, SelfFlag_InitRes, C) &&
  282. !hasSelfFlag(val, SelfFlag_Self, C) &&
  283. !isSelfVar(val, C)) {
  284. // Stop tracking the checker-specific state in the state.
  285. ProgramStateRef State = C.getState();
  286. State = State->remove<CalledInit>();
  287. if (SymbolRef sym = loc.getAsSymbol())
  288. State = State->remove<SelfFlag>(sym);
  289. C.addTransition(State);
  290. }
  291. }
  292. void ObjCSelfInitChecker::printState(raw_ostream &Out, ProgramStateRef State,
  293. const char *NL, const char *Sep) const {
  294. SelfFlagTy FlagMap = State->get<SelfFlag>();
  295. bool DidCallInit = State->get<CalledInit>();
  296. SelfFlagEnum PreCallFlags = (SelfFlagEnum)State->get<PreCallSelfFlags>();
  297. if (FlagMap.isEmpty() && !DidCallInit && !PreCallFlags)
  298. return;
  299. Out << Sep << NL << *this << " :" << NL;
  300. if (DidCallInit)
  301. Out << " An init method has been called." << NL;
  302. if (PreCallFlags != SelfFlag_None) {
  303. if (PreCallFlags & SelfFlag_Self) {
  304. Out << " An argument of the current call came from the 'self' variable."
  305. << NL;
  306. }
  307. if (PreCallFlags & SelfFlag_InitRes) {
  308. Out << " An argument of the current call came from an init method."
  309. << NL;
  310. }
  311. }
  312. Out << NL;
  313. for (SelfFlagTy::iterator I = FlagMap.begin(), E = FlagMap.end();
  314. I != E; ++I) {
  315. Out << I->first << " : ";
  316. if (I->second == SelfFlag_None)
  317. Out << "none";
  318. if (I->second & SelfFlag_Self)
  319. Out << "self variable";
  320. if (I->second & SelfFlag_InitRes) {
  321. if (I->second != SelfFlag_InitRes)
  322. Out << " | ";
  323. Out << "result of init method";
  324. }
  325. Out << NL;
  326. }
  327. }
  328. // FIXME: A callback should disable checkers at the start of functions.
  329. static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
  330. if (!ND)
  331. return false;
  332. const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
  333. if (!MD)
  334. return false;
  335. if (!isInitializationMethod(MD))
  336. return false;
  337. // self = [super init] applies only to NSObject subclasses.
  338. // For instance, NSProxy doesn't implement -init.
  339. ASTContext &Ctx = MD->getASTContext();
  340. IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
  341. ObjCInterfaceDecl *ID = MD->getClassInterface()->getSuperClass();
  342. for ( ; ID ; ID = ID->getSuperClass()) {
  343. IdentifierInfo *II = ID->getIdentifier();
  344. if (II == NSObjectII)
  345. break;
  346. }
  347. return ID != nullptr;
  348. }
  349. /// \brief Returns true if the location is 'self'.
  350. static bool isSelfVar(SVal location, CheckerContext &C) {
  351. AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext();
  352. if (!analCtx->getSelfDecl())
  353. return false;
  354. if (!location.getAs<loc::MemRegionVal>())
  355. return false;
  356. loc::MemRegionVal MRV = location.castAs<loc::MemRegionVal>();
  357. if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.stripCasts()))
  358. return (DR->getDecl() == analCtx->getSelfDecl());
  359. return false;
  360. }
  361. static bool isInitializationMethod(const ObjCMethodDecl *MD) {
  362. return MD->getMethodFamily() == OMF_init;
  363. }
  364. static bool isInitMessage(const ObjCMethodCall &Call) {
  365. return Call.getMethodFamily() == OMF_init;
  366. }
  367. //===----------------------------------------------------------------------===//
  368. // Registration.
  369. //===----------------------------------------------------------------------===//
  370. void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
  371. mgr.registerChecker<ObjCSelfInitChecker>();
  372. }