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