ObjCSelfInitChecker.cpp revision 5eca482fe895ea57bc82410222e6426c09e63284
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 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. 18// 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]). 22// 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. 27// 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. 32// 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. 36// 37// FIXME (rdar://7937506): In the case of: 38// [super init]; 39// return self; 40// Have an extra PathDiagnosticPiece in the path that says "called [super init], 41// but didn't assign the result to self." 42 43//===----------------------------------------------------------------------===// 44 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 48 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/ProgramStateTrait.h" 54#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h" 55#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 56#include "clang/AST/ParentMap.h" 57 58using namespace clang; 59using namespace ento; 60 61static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND); 62static bool isInitializationMethod(const ObjCMethodDecl *MD); 63static bool isInitMessage(const ObjCMessage &msg); 64static bool isSelfVar(SVal location, CheckerContext &C); 65 66namespace { 67class ObjCSelfInitChecker : public Checker< 68 check::PostObjCMessage, 69 check::PostStmt<ObjCIvarRefExpr>, 70 check::PreStmt<ReturnStmt>, 71 check::PreStmt<CallExpr>, 72 check::PostStmt<CallExpr>, 73 check::Location > { 74public: 75 void checkPostObjCMessage(ObjCMessage msg, CheckerContext &C) const; 76 void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const; 77 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const; 78 void checkPreStmt(const CallExpr *CE, CheckerContext &C) const; 79 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const; 80 void checkLocation(SVal location, bool isLoad, const Stmt *S, 81 CheckerContext &C) const; 82}; 83} // end anonymous namespace 84 85namespace { 86 87class InitSelfBug : public BugType { 88 const std::string desc; 89public: 90 InitSelfBug() : BugType("missing \"self = [(super or self) init...]\"", 91 "missing \"self = [(super or self) init...]\"") {} 92}; 93 94} // end anonymous namespace 95 96namespace { 97enum SelfFlagEnum { 98 /// \brief No flag set. 99 SelfFlag_None = 0x0, 100 /// \brief Value came from 'self'. 101 SelfFlag_Self = 0x1, 102 /// \brief Value came from the result of an initializer (e.g. [super init]). 103 SelfFlag_InitRes = 0x2 104}; 105} 106 107typedef llvm::ImmutableMap<SymbolRef, unsigned> SelfFlag; 108namespace { struct CalledInit {}; } 109namespace { struct PreCallSelfFlags {}; } 110 111namespace clang { 112namespace ento { 113 template<> 114 struct ProgramStateTrait<SelfFlag> : public ProgramStatePartialTrait<SelfFlag> { 115 static void *GDMIndex() { static int index = 0; return &index; } 116 }; 117 template <> 118 struct ProgramStateTrait<CalledInit> : public ProgramStatePartialTrait<bool> { 119 static void *GDMIndex() { static int index = 0; return &index; } 120 }; 121 122 /// \brief A call receiving a reference to 'self' invalidates the object that 123 /// 'self' contains. This keeps the "self flags" assigned to the 'self' 124 /// object before the call so we can assign them to the new object that 'self' 125 /// points to after the call. 126 template <> 127 struct ProgramStateTrait<PreCallSelfFlags> : public ProgramStatePartialTrait<unsigned> { 128 static void *GDMIndex() { static int index = 0; return &index; } 129 }; 130} 131} 132 133static SelfFlagEnum getSelfFlags(SVal val, const ProgramState *state) { 134 if (SymbolRef sym = val.getAsSymbol()) 135 if (const unsigned *attachedFlags = state->get<SelfFlag>(sym)) 136 return (SelfFlagEnum)*attachedFlags; 137 return SelfFlag_None; 138} 139 140static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) { 141 return getSelfFlags(val, C.getState()); 142} 143 144static void addSelfFlag(const ProgramState *state, SVal val, 145 SelfFlagEnum flag, CheckerContext &C) { 146 // We tag the symbol that the SVal wraps. 147 if (SymbolRef sym = val.getAsSymbol()) 148 C.addTransition(state->set<SelfFlag>(sym, getSelfFlags(val, C) | flag)); 149} 150 151static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) { 152 return getSelfFlags(val, C) & flag; 153} 154 155/// \brief Returns true of the value of the expression is the object that 'self' 156/// points to and is an object that did not come from the result of calling 157/// an initializer. 158static bool isInvalidSelf(const Expr *E, CheckerContext &C) { 159 SVal exprVal = C.getState()->getSVal(E, C.getLocationContext()); 160 if (!hasSelfFlag(exprVal, SelfFlag_Self, C)) 161 return false; // value did not come from 'self'. 162 if (hasSelfFlag(exprVal, SelfFlag_InitRes, C)) 163 return false; // 'self' is properly initialized. 164 165 return true; 166} 167 168static void checkForInvalidSelf(const Expr *E, CheckerContext &C, 169 const char *errorStr) { 170 if (!E) 171 return; 172 173 if (!C.getState()->get<CalledInit>()) 174 return; 175 176 if (!isInvalidSelf(E, C)) 177 return; 178 179 // Generate an error node. 180 ExplodedNode *N = C.generateSink(); 181 if (!N) 182 return; 183 184 BugReport *report = 185 new BugReport(*new InitSelfBug(), errorStr, N); 186 C.EmitReport(report); 187} 188 189void ObjCSelfInitChecker::checkPostObjCMessage(ObjCMessage msg, 190 CheckerContext &C) const { 191 // When encountering a message that does initialization (init rule), 192 // tag the return value so that we know later on that if self has this value 193 // then it is properly initialized. 194 195 // FIXME: A callback should disable checkers at the start of functions. 196 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>( 197 C.getCurrentAnalysisDeclContext()->getDecl()))) 198 return; 199 200 if (isInitMessage(msg)) { 201 // Tag the return value as the result of an initializer. 202 const ProgramState *state = C.getState(); 203 204 // FIXME this really should be context sensitive, where we record 205 // the current stack frame (for IPA). Also, we need to clean this 206 // value out when we return from this method. 207 state = state->set<CalledInit>(true); 208 209 SVal V = state->getSVal(msg.getOriginExpr(), C.getLocationContext()); 210 addSelfFlag(state, V, SelfFlag_InitRes, C); 211 return; 212 } 213 214 // We don't check for an invalid 'self' in an obj-c message expression to cut 215 // down false positives where logging functions get information from self 216 // (like its class) or doing "invalidation" on self when the initialization 217 // fails. 218} 219 220void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E, 221 CheckerContext &C) const { 222 // FIXME: A callback should disable checkers at the start of functions. 223 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>( 224 C.getCurrentAnalysisDeclContext()->getDecl()))) 225 return; 226 227 checkForInvalidSelf(E->getBase(), C, 228 "Instance variable used while 'self' is not set to the result of " 229 "'[(super or self) init...]'"); 230} 231 232void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S, 233 CheckerContext &C) const { 234 // FIXME: A callback should disable checkers at the start of functions. 235 if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>( 236 C.getCurrentAnalysisDeclContext()->getDecl()))) 237 return; 238 239 checkForInvalidSelf(S->getRetValue(), C, 240 "Returning 'self' while it is not set to the result of " 241 "'[(super or self) init...]'"); 242} 243 244// When a call receives a reference to 'self', [Pre/Post]VisitGenericCall pass 245// the SelfFlags from the object 'self' point to before the call, to the new 246// object after the call. This is to avoid invalidation of 'self' by logging 247// functions. 248// Another common pattern in classes with multiple initializers is to put the 249// subclass's common initialization bits into a static function that receives 250// the value of 'self', e.g: 251// @code 252// if (!(self = [super init])) 253// return nil; 254// if (!(self = _commonInit(self))) 255// return nil; 256// @endcode 257// Until we can use inter-procedural analysis, in such a call, transfer the 258// SelfFlags to the result of the call. 259 260void ObjCSelfInitChecker::checkPreStmt(const CallExpr *CE, 261 CheckerContext &C) const { 262 const ProgramState *state = C.getState(); 263 for (CallExpr::const_arg_iterator 264 I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) { 265 SVal argV = state->getSVal(*I, C.getLocationContext()); 266 if (isSelfVar(argV, C)) { 267 unsigned selfFlags = getSelfFlags(state->getSVal(cast<Loc>(argV)), C); 268 C.addTransition(state->set<PreCallSelfFlags>(selfFlags)); 269 return; 270 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) { 271 unsigned selfFlags = getSelfFlags(argV, C); 272 C.addTransition(state->set<PreCallSelfFlags>(selfFlags)); 273 return; 274 } 275 } 276} 277 278void ObjCSelfInitChecker::checkPostStmt(const CallExpr *CE, 279 CheckerContext &C) const { 280 const ProgramState *state = C.getState(); 281 const LocationContext *LCtx = C.getLocationContext(); 282 for (CallExpr::const_arg_iterator 283 I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) { 284 SVal argV = state->getSVal(*I, LCtx); 285 if (isSelfVar(argV, C)) { 286 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>(); 287 state = state->remove<PreCallSelfFlags>(); 288 addSelfFlag(state, state->getSVal(cast<Loc>(argV)), prevFlags, C); 289 return; 290 } else if (hasSelfFlag(argV, SelfFlag_Self, C)) { 291 SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>(); 292 state = state->remove<PreCallSelfFlags>(); 293 addSelfFlag(state, state->getSVal(CE, LCtx), prevFlags, C); 294 return; 295 } 296 } 297} 298 299void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad, 300 const Stmt *S, 301 CheckerContext &C) const { 302 // Tag the result of a load from 'self' so that we can easily know that the 303 // value is the object that 'self' points to. 304 const ProgramState *state = C.getState(); 305 if (isSelfVar(location, C)) 306 addSelfFlag(state, state->getSVal(cast<Loc>(location)), SelfFlag_Self, C); 307} 308 309// FIXME: A callback should disable checkers at the start of functions. 310static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) { 311 if (!ND) 312 return false; 313 314 const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND); 315 if (!MD) 316 return false; 317 if (!isInitializationMethod(MD)) 318 return false; 319 320 // self = [super init] applies only to NSObject subclasses. 321 // For instance, NSProxy doesn't implement -init. 322 ASTContext &Ctx = MD->getASTContext(); 323 IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject"); 324 ObjCInterfaceDecl *ID = MD->getClassInterface()->getSuperClass(); 325 for ( ; ID ; ID = ID->getSuperClass()) { 326 IdentifierInfo *II = ID->getIdentifier(); 327 328 if (II == NSObjectII) 329 break; 330 } 331 if (!ID) 332 return false; 333 334 return true; 335} 336 337/// \brief Returns true if the location is 'self'. 338static bool isSelfVar(SVal location, CheckerContext &C) { 339 AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext(); 340 if (!analCtx->getSelfDecl()) 341 return false; 342 if (!isa<loc::MemRegionVal>(location)) 343 return false; 344 345 loc::MemRegionVal MRV = cast<loc::MemRegionVal>(location); 346 if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.getRegion())) 347 return (DR->getDecl() == analCtx->getSelfDecl()); 348 349 return false; 350} 351 352static bool isInitializationMethod(const ObjCMethodDecl *MD) { 353 return MD->getMethodFamily() == OMF_init; 354} 355 356static bool isInitMessage(const ObjCMessage &msg) { 357 return msg.getMethodFamily() == OMF_init; 358} 359 360//===----------------------------------------------------------------------===// 361// Registration. 362//===----------------------------------------------------------------------===// 363 364void ento::registerObjCSelfInitChecker(CheckerManager &mgr) { 365 mgr.registerChecker<ObjCSelfInitChecker>(); 366} 367