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