ObjCSelfInitChecker.cpp 15 KB

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