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 // FIXME (rdar://7937506): In the case of:
40 // Have an extra PathDiagnosticPiece in the path that says "called [super init],
41 // but didn't assign the result to self."
43 //===----------------------------------------------------------------------===//
45 // FIXME: Somehow stick the link to Apple's documentation about initializing
46 // objects in the diagnostics.
47 // http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocAllocInit.html
49 #include "ClangSACheckers.h"
50 #include "clang/StaticAnalyzer/Core/Checker.h"
51 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
52 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
53 #include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h"
54 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
55 #include "clang/AST/ParentMap.h"
57 using namespace clang;
60 static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
61 static bool isInitializationMethod(const ObjCMethodDecl *MD);
62 static bool isInitMessage(const ObjCMessage &msg);
63 static bool isSelfVar(SVal location, CheckerContext &C);
66 class ObjCSelfInitChecker : public Checker<
67 check::PostObjCMessage,
68 check::PostStmt<ObjCIvarRefExpr>,
69 check::PreStmt<ReturnStmt>,
70 check::PreStmt<CallExpr>,
71 check::PostStmt<CallExpr>,
74 void checkPostObjCMessage(ObjCMessage msg, CheckerContext &C) const;
75 void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
76 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
77 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
78 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
79 void checkLocation(SVal location, bool isLoad, CheckerContext &C) const;
81 } // end anonymous namespace
85 class InitSelfBug : public BugType {
86 const std::string desc;
88 InitSelfBug() : BugType("missing \"self = [(super or self) init...]\"",
89 "missing \"self = [(super or self) init...]\"") {}
92 } // end anonymous namespace
96 /// \brief No flag set.
98 /// \brief Value came from 'self'.
100 /// \brief Value came from the result of an initializer (e.g. [super init]).
101 SelfFlag_InitRes = 0x2
105 typedef llvm::ImmutableMap<SymbolRef, unsigned> SelfFlag;
106 namespace { struct CalledInit {}; }
107 namespace { struct PreCallSelfFlags {}; }
112 struct GRStateTrait<SelfFlag> : public GRStatePartialTrait<SelfFlag> {
113 static void* GDMIndex() { static int index = 0; return &index; }
116 struct GRStateTrait<CalledInit> : public GRStatePartialTrait<bool> {
117 static void *GDMIndex() { static int index = 0; return &index; }
120 /// \brief A call receiving a reference to 'self' invalidates the object that
121 /// 'self' contains. This keeps the "self flags" assigned to the 'self'
122 /// object before the call so we can assign them to the new object that 'self'
123 /// points to after the call.
125 struct GRStateTrait<PreCallSelfFlags> : public GRStatePartialTrait<unsigned> {
126 static void *GDMIndex() { static int index = 0; return &index; }
131 static SelfFlagEnum getSelfFlags(SVal val, const GRState *state) {
132 if (SymbolRef sym = val.getAsSymbol())
133 if (const unsigned *attachedFlags = state->get<SelfFlag>(sym))
134 return (SelfFlagEnum)*attachedFlags;
135 return SelfFlag_None;
138 static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
139 return getSelfFlags(val, C.getState());
142 static void addSelfFlag(const GRState *state, SVal val,
143 SelfFlagEnum flag, CheckerContext &C) {
144 // We tag the symbol that the SVal wraps.
145 if (SymbolRef sym = val.getAsSymbol())
146 C.addTransition(state->set<SelfFlag>(sym, getSelfFlags(val, C) | flag));
149 static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
150 return getSelfFlags(val, C) & flag;
153 /// \brief Returns true of the value of the expression is the object that 'self'
154 /// points to and is an object that did not come from the result of calling
156 static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
157 SVal exprVal = C.getState()->getSVal(E);
158 if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
159 return false; // value did not come from 'self'.
160 if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
161 return false; // 'self' is properly initialized.
166 static void checkForInvalidSelf(const Expr *E, CheckerContext &C,
167 const char *errorStr) {
171 if (!C.getState()->get<CalledInit>())
174 if (!isInvalidSelf(E, C))
177 // Generate an error node.
178 ExplodedNode *N = C.generateSink();
182 EnhancedBugReport *report =
183 new EnhancedBugReport(*new InitSelfBug(), errorStr, N);
184 C.EmitReport(report);
187 void ObjCSelfInitChecker::checkPostObjCMessage(ObjCMessage msg,
188 CheckerContext &C) const {
189 // When encountering a message that does initialization (init rule),
190 // tag the return value so that we know later on that if self has this value
191 // then it is properly initialized.
193 // FIXME: A callback should disable checkers at the start of functions.
194 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
195 C.getCurrentAnalysisContext()->getDecl())))
198 if (isInitMessage(msg)) {
199 // Tag the return value as the result of an initializer.
200 const GRState *state = C.getState();
202 // FIXME this really should be context sensitive, where we record
203 // the current stack frame (for IPA). Also, we need to clean this
204 // value out when we return from this method.
205 state = state->set<CalledInit>(true);
207 SVal V = state->getSVal(msg.getOriginExpr());
208 addSelfFlag(state, V, SelfFlag_InitRes, C);
212 // We don't check for an invalid 'self' in an obj-c message expression to cut
213 // down false positives where logging functions get information from self
214 // (like its class) or doing "invalidation" on self when the initialization
218 void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E,
219 CheckerContext &C) const {
220 // FIXME: A callback should disable checkers at the start of functions.
221 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
222 C.getCurrentAnalysisContext()->getDecl())))
225 checkForInvalidSelf(E->getBase(), C,
226 "Instance variable used while 'self' is not set to the result of "
227 "'[(super or self) init...]'");
230 void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S,
231 CheckerContext &C) const {
232 // FIXME: A callback should disable checkers at the start of functions.
233 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
234 C.getCurrentAnalysisContext()->getDecl())))
237 checkForInvalidSelf(S->getRetValue(), C,
238 "Returning 'self' while it is not set to the result of "
239 "'[(super or self) init...]'");
242 // When a call receives a reference to 'self', [Pre/Post]VisitGenericCall pass
243 // the SelfFlags from the object 'self' point to before the call, to the new
244 // object after the call. This is to avoid invalidation of 'self' by logging
246 // Another common pattern in classes with multiple initializers is to put the
247 // subclass's common initialization bits into a static function that receives
248 // the value of 'self', e.g:
250 // if (!(self = [super init]))
252 // if (!(self = _commonInit(self)))
255 // Until we can use inter-procedural analysis, in such a call, transfer the
256 // SelfFlags to the result of the call.
258 void ObjCSelfInitChecker::checkPreStmt(const CallExpr *CE,
259 CheckerContext &C) const {
260 const GRState *state = C.getState();
261 for (CallExpr::const_arg_iterator
262 I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) {
263 SVal argV = state->getSVal(*I);
264 if (isSelfVar(argV, C)) {
265 unsigned selfFlags = getSelfFlags(state->getSVal(cast<Loc>(argV)), C);
266 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
268 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
269 unsigned selfFlags = getSelfFlags(argV, C);
270 C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
276 void ObjCSelfInitChecker::checkPostStmt(const CallExpr *CE,
277 CheckerContext &C) const {
278 const GRState *state = C.getState();
279 for (CallExpr::const_arg_iterator
280 I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) {
281 SVal argV = state->getSVal(*I);
282 if (isSelfVar(argV, C)) {
283 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
284 state = state->remove<PreCallSelfFlags>();
285 addSelfFlag(state, state->getSVal(cast<Loc>(argV)), prevFlags, C);
287 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
288 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
289 state = state->remove<PreCallSelfFlags>();
290 addSelfFlag(state, state->getSVal(CE), prevFlags, C);
296 void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad,
297 CheckerContext &C) const {
298 // Tag the result of a load from 'self' so that we can easily know that the
299 // value is the object that 'self' points to.
300 const GRState *state = C.getState();
301 if (isSelfVar(location, C))
302 addSelfFlag(state, state->getSVal(cast<Loc>(location)), SelfFlag_Self, C);
305 // FIXME: A callback should disable checkers at the start of functions.
306 static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
310 const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
313 if (!isInitializationMethod(MD))
316 // self = [super init] applies only to NSObject subclasses.
317 // For instance, NSProxy doesn't implement -init.
318 ASTContext& Ctx = MD->getASTContext();
319 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
320 ObjCInterfaceDecl* ID = MD->getClassInterface()->getSuperClass();
321 for ( ; ID ; ID = ID->getSuperClass()) {
322 IdentifierInfo *II = ID->getIdentifier();
324 if (II == NSObjectII)
333 /// \brief Returns true if the location is 'self'.
334 static bool isSelfVar(SVal location, CheckerContext &C) {
335 AnalysisContext *analCtx = C.getCurrentAnalysisContext();
336 if (!analCtx->getSelfDecl())
338 if (!isa<loc::MemRegionVal>(location))
341 loc::MemRegionVal MRV = cast<loc::MemRegionVal>(location);
342 if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.getRegion()))
343 return (DR->getDecl() == analCtx->getSelfDecl());
348 static bool isInitializationMethod(const ObjCMethodDecl *MD) {
349 return MD->getMethodFamily() == OMF_init;
352 static bool isInitMessage(const ObjCMessage &msg) {
353 return msg.getMethodFamily() == OMF_init;
356 //===----------------------------------------------------------------------===//
358 //===----------------------------------------------------------------------===//
360 void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
361 mgr.registerChecker<ObjCSelfInitChecker>();