1 //== ObjCSelfInitChecker.cpp - Checker for 'self' initialization -*- C++ -*--=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines ObjCSelfInitChecker, a builtin check that checks for uses of
11 // 'self' before proper initialization.
13 //===----------------------------------------------------------------------===//
15 // This checks initialization methods to verify that they assign 'self' to the
16 // result of an initialization call (e.g. [super init], or [self initWith..])
17 // before using 'self' or any instance variable.
19 // To perform the required checking, values are tagged with flags that indicate
20 // 1) if the object is the one pointed to by 'self', and 2) if the object
21 // is the result of an initializer (e.g. [super init]).
23 // Uses of an object that is true for 1) but not 2) trigger a diagnostic.
24 // The uses that are currently checked are:
25 // - Using instance variables.
26 // - Returning the object.
28 // Note that we don't check for an invalid 'self' that is the receiver of an
29 // obj-c message expression to cut down false positives where logging functions
30 // get information from self (like its class) or doing "invalidation" on self
31 // when the initialization fails.
33 // Because the object that 'self' points to gets invalidated when a call
34 // receives a reference to 'self', the checker keeps track and passes the flags
35 // for 1) and 2) to the new object that 'self' points to after the call.
37 //===----------------------------------------------------------------------===//
39 #include "ClangSACheckers.h"
40 #include "clang/AST/ParentMap.h"
41 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
42 #include "clang/StaticAnalyzer/Core/Checker.h"
43 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
44 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
45 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
46 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
47 #include "llvm/Support/raw_ostream.h"
49 using namespace clang;
52 static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
53 static bool isInitializationMethod(const ObjCMethodDecl *MD);
54 static bool isInitMessage(const ObjCMethodCall &Msg);
55 static bool isSelfVar(SVal location, CheckerContext &C);
58 class ObjCSelfInitChecker : public Checker< check::PostObjCMessage,
59 check::PostStmt<ObjCIvarRefExpr>,
60 check::PreStmt<ReturnStmt>,
65 mutable std::unique_ptr<BugType> BT;
67 void checkForInvalidSelf(const Expr *E, CheckerContext &C,
68 const char *errorStr) const;
71 ObjCSelfInitChecker() {}
72 void checkPostObjCMessage(const ObjCMethodCall &Msg, CheckerContext &C) const;
73 void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
74 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
75 void checkLocation(SVal location, bool isLoad, const Stmt *S,
76 CheckerContext &C) const;
77 void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
79 void checkPreCall(const CallEvent &CE, CheckerContext &C) const;
80 void checkPostCall(const CallEvent &CE, CheckerContext &C) const;
82 void printState(raw_ostream &Out, ProgramStateRef State,
83 const char *NL, const char *Sep) const override;
85 } // end anonymous namespace
89 /// \brief No flag set.
91 /// \brief Value came from 'self'.
93 /// \brief Value came from the result of an initializer (e.g. [super init]).
94 SelfFlag_InitRes = 0x2
98 REGISTER_MAP_WITH_PROGRAMSTATE(SelfFlag, SymbolRef, unsigned)
99 REGISTER_TRAIT_WITH_PROGRAMSTATE(CalledInit, bool)
101 /// \brief A call receiving a reference to 'self' invalidates the object that
102 /// 'self' contains. This keeps the "self flags" assigned to the 'self'
103 /// object before the call so we can assign them to the new object that 'self'
104 /// points to after the call.
105 REGISTER_TRAIT_WITH_PROGRAMSTATE(PreCallSelfFlags, unsigned)
107 static SelfFlagEnum getSelfFlags(SVal val, ProgramStateRef state) {
108 if (SymbolRef sym = val.getAsSymbol())
109 if (const unsigned *attachedFlags = state->get<SelfFlag>(sym))
110 return (SelfFlagEnum)*attachedFlags;
111 return SelfFlag_None;
114 static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
115 return getSelfFlags(val, C.getState());
118 static void addSelfFlag(ProgramStateRef state, SVal val,
119 SelfFlagEnum flag, CheckerContext &C) {
120 // We tag the symbol that the SVal wraps.
121 if (SymbolRef sym = val.getAsSymbol()) {
122 state = state->set<SelfFlag>(sym, getSelfFlags(val, state) | flag);
123 C.addTransition(state);
127 static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
128 return getSelfFlags(val, C) & flag;
131 /// \brief Returns true of the value of the expression is the object that 'self'
132 /// points to and is an object that did not come from the result of calling
134 static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
135 SVal exprVal = C.getState()->getSVal(E, C.getLocationContext());
136 if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
137 return false; // value did not come from 'self'.
138 if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
139 return false; // 'self' is properly initialized.
144 void ObjCSelfInitChecker::checkForInvalidSelf(const Expr *E, CheckerContext &C,
145 const char *errorStr) const {
149 if (!C.getState()->get<CalledInit>())
152 if (!isInvalidSelf(E, C))
155 // Generate an error node.
156 ExplodedNode *N = C.generateSink();
161 BT.reset(new BugType(this, "Missing \"self = [(super or self) init...]\"",
162 categories::CoreFoundationObjectiveC));
163 BugReport *report = new BugReport(*BT, errorStr, N);
164 C.emitReport(report);
167 void ObjCSelfInitChecker::checkPostObjCMessage(const ObjCMethodCall &Msg,
168 CheckerContext &C) const {
169 // When encountering a message that does initialization (init rule),
170 // tag the return value so that we know later on that if self has this value
171 // then it is properly initialized.
173 // FIXME: A callback should disable checkers at the start of functions.
174 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
175 C.getCurrentAnalysisDeclContext()->getDecl())))
178 if (isInitMessage(Msg)) {
179 // Tag the return value as the result of an initializer.
180 ProgramStateRef state = C.getState();
182 // FIXME this really should be context sensitive, where we record
183 // the current stack frame (for IPA). Also, we need to clean this
184 // value out when we return from this method.
185 state = state->set<CalledInit>(true);
187 SVal V = state->getSVal(Msg.getOriginExpr(), C.getLocationContext());
188 addSelfFlag(state, V, SelfFlag_InitRes, C);
192 // We don't check for an invalid 'self' in an obj-c message expression to cut
193 // down false positives where logging functions get information from self
194 // (like its class) or doing "invalidation" on self when the initialization
198 void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E,
199 CheckerContext &C) const {
200 // FIXME: A callback should disable checkers at the start of functions.
201 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
202 C.getCurrentAnalysisDeclContext()->getDecl())))
207 "Instance variable used while 'self' is not set to the result of "
208 "'[(super or self) init...]'");
211 void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S,
212 CheckerContext &C) const {
213 // FIXME: A callback should disable checkers at the start of functions.
214 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
215 C.getCurrentAnalysisDeclContext()->getDecl())))
218 checkForInvalidSelf(S->getRetValue(), C,
219 "Returning 'self' while it is not set to the result of "
220 "'[(super or self) init...]'");
223 // When a call receives a reference to 'self', [Pre/Post]Call pass
224 // the SelfFlags from the object 'self' points to before the call to the new
225 // object after the call. This is to avoid invalidation of 'self' by logging
227 // Another common pattern in classes with multiple initializers is to put the
228 // subclass's common initialization bits into a static function that receives
229 // the value of 'self', e.g:
231 // if (!(self = [super init]))
233 // if (!(self = _commonInit(self)))
236 // Until we can use inter-procedural analysis, in such a call, transfer the
237 // SelfFlags to the result of the call.
239 void ObjCSelfInitChecker::checkPreCall(const CallEvent &CE,
240 CheckerContext &C) const {
241 // FIXME: A callback should disable checkers at the start of functions.
242 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
243 C.getCurrentAnalysisDeclContext()->getDecl())))
246 ProgramStateRef state = C.getState();
247 unsigned NumArgs = CE.getNumArgs();
248 // If we passed 'self' as and argument to the call, record it in the state
249 // to be propagated after the call.
250 // Note, we could have just given up, but try to be more optimistic here and
251 // assume that the functions are going to continue initialization or will not
253 for (unsigned i = 0; i < NumArgs; ++i) {
254 SVal argV = CE.getArgSVal(i);
255 if (isSelfVar(argV, C)) {
256 unsigned selfFlags = getSelfFlags(state->getSVal(argV.castAs<Loc>()), C);
257 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
259 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
260 unsigned selfFlags = getSelfFlags(argV, C);
261 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
267 void ObjCSelfInitChecker::checkPostCall(const CallEvent &CE,
268 CheckerContext &C) const {
269 // FIXME: A callback should disable checkers at the start of functions.
270 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
271 C.getCurrentAnalysisDeclContext()->getDecl())))
274 ProgramStateRef state = C.getState();
275 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
278 state = state->remove<PreCallSelfFlags>();
280 unsigned NumArgs = CE.getNumArgs();
281 for (unsigned i = 0; i < NumArgs; ++i) {
282 SVal argV = CE.getArgSVal(i);
283 if (isSelfVar(argV, C)) {
284 // If the address of 'self' is being passed to the call, assume that the
285 // 'self' after the call will have the same flags.
287 addSelfFlag(state, state->getSVal(argV.castAs<Loc>()), prevFlags, C);
289 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
290 // If 'self' is passed to the call by value, assume that the function
291 // returns 'self'. So assign the flags, which were set on 'self' to the
293 // EX: self = performMoreInitialization(self)
294 addSelfFlag(state, CE.getReturnValue(), prevFlags, C);
299 C.addTransition(state);
302 void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad,
304 CheckerContext &C) const {
305 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
306 C.getCurrentAnalysisDeclContext()->getDecl())))
309 // Tag the result of a load from 'self' so that we can easily know that the
310 // value is the object that 'self' points to.
311 ProgramStateRef state = C.getState();
312 if (isSelfVar(location, C))
313 addSelfFlag(state, state->getSVal(location.castAs<Loc>()), SelfFlag_Self,
318 void ObjCSelfInitChecker::checkBind(SVal loc, SVal val, const Stmt *S,
319 CheckerContext &C) const {
320 // Allow assignment of anything to self. Self is a local variable in the
321 // initializer, so it is legal to assign anything to it, like results of
322 // static functions/method calls. After self is assigned something we cannot
323 // reason about, stop enforcing the rules.
324 // (Only continue checking if the assigned value should be treated as self.)
325 if ((isSelfVar(loc, C)) &&
326 !hasSelfFlag(val, SelfFlag_InitRes, C) &&
327 !hasSelfFlag(val, SelfFlag_Self, C) &&
328 !isSelfVar(val, C)) {
330 // Stop tracking the checker-specific state in the state.
331 ProgramStateRef State = C.getState();
332 State = State->remove<CalledInit>();
333 if (SymbolRef sym = loc.getAsSymbol())
334 State = State->remove<SelfFlag>(sym);
335 C.addTransition(State);
339 void ObjCSelfInitChecker::printState(raw_ostream &Out, ProgramStateRef State,
340 const char *NL, const char *Sep) const {
341 SelfFlagTy FlagMap = State->get<SelfFlag>();
342 bool DidCallInit = State->get<CalledInit>();
343 SelfFlagEnum PreCallFlags = (SelfFlagEnum)State->get<PreCallSelfFlags>();
345 if (FlagMap.isEmpty() && !DidCallInit && !PreCallFlags)
348 Out << Sep << NL << *this << " :" << NL;
351 Out << " An init method has been called." << NL;
353 if (PreCallFlags != SelfFlag_None) {
354 if (PreCallFlags & SelfFlag_Self) {
355 Out << " An argument of the current call came from the 'self' variable."
358 if (PreCallFlags & SelfFlag_InitRes) {
359 Out << " An argument of the current call came from an init method."
365 for (SelfFlagTy::iterator I = FlagMap.begin(), E = FlagMap.end();
367 Out << I->first << " : ";
369 if (I->second == SelfFlag_None)
372 if (I->second & SelfFlag_Self)
373 Out << "self variable";
375 if (I->second & SelfFlag_InitRes) {
376 if (I->second != SelfFlag_InitRes)
378 Out << "result of init method";
386 // FIXME: A callback should disable checkers at the start of functions.
387 static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
391 const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
394 if (!isInitializationMethod(MD))
397 // self = [super init] applies only to NSObject subclasses.
398 // For instance, NSProxy doesn't implement -init.
399 ASTContext &Ctx = MD->getASTContext();
400 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
401 ObjCInterfaceDecl *ID = MD->getClassInterface()->getSuperClass();
402 for ( ; ID ; ID = ID->getSuperClass()) {
403 IdentifierInfo *II = ID->getIdentifier();
405 if (II == NSObjectII)
414 /// \brief Returns true if the location is 'self'.
415 static bool isSelfVar(SVal location, CheckerContext &C) {
416 AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext();
417 if (!analCtx->getSelfDecl())
419 if (!location.getAs<loc::MemRegionVal>())
422 loc::MemRegionVal MRV = location.castAs<loc::MemRegionVal>();
423 if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.stripCasts()))
424 return (DR->getDecl() == analCtx->getSelfDecl());
429 static bool isInitializationMethod(const ObjCMethodDecl *MD) {
430 return MD->getMethodFamily() == OMF_init;
433 static bool isInitMessage(const ObjCMethodCall &Call) {
434 return Call.getMethodFamily() == OMF_init;
437 //===----------------------------------------------------------------------===//
439 //===----------------------------------------------------------------------===//
441 void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
442 mgr.registerChecker<ObjCSelfInitChecker>();