Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 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 wih 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 | |
Argyrios Kyrtzidis | 04291a7 | 2011-02-08 22:30:02 +0000 | [diff] [blame] | 49 | #include "InternalChecks.h" |
Ted Kremenek | 9b66371 | 2011-02-10 01:03:03 +0000 | [diff] [blame] | 50 | #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerVisitor.h" |
| 51 | #include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h" |
| 52 | #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 53 | #include "clang/Analysis/DomainSpecific/CocoaConventions.h" |
| 54 | #include "clang/AST/ParentMap.h" |
| 55 | |
| 56 | using namespace clang; |
| 57 | using namespace ento; |
| 58 | |
| 59 | static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND); |
| 60 | static bool isInitializationMethod(const ObjCMethodDecl *MD); |
Argyrios Kyrtzidis | 432424d | 2011-01-25 00:03:53 +0000 | [diff] [blame] | 61 | static bool isInitMessage(const ObjCMessage &msg); |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 62 | static bool isSelfVar(SVal location, CheckerContext &C); |
| 63 | |
| 64 | namespace { |
| 65 | enum SelfFlagEnum { |
| 66 | /// \brief No flag set. |
| 67 | SelfFlag_None = 0x0, |
| 68 | /// \brief Value came from 'self'. |
| 69 | SelfFlag_Self = 0x1, |
| 70 | /// \brief Value came from the result of an initializer (e.g. [super init]). |
| 71 | SelfFlag_InitRes = 0x2 |
| 72 | }; |
| 73 | } |
| 74 | |
| 75 | namespace { |
| 76 | class ObjCSelfInitChecker : public CheckerVisitor<ObjCSelfInitChecker> { |
| 77 | /// \brief A call receiving a reference to 'self' invalidates the object that |
| 78 | /// 'self' contains. This field keeps the "self flags" assigned to the 'self' |
| 79 | /// object before the call and assign them to the new object that 'self' |
| 80 | /// points to after the call. |
| 81 | SelfFlagEnum preCallSelfFlags; |
| 82 | |
| 83 | public: |
| 84 | static void *getTag() { static int tag = 0; return &tag; } |
Argyrios Kyrtzidis | 432424d | 2011-01-25 00:03:53 +0000 | [diff] [blame] | 85 | void postVisitObjCMessage(CheckerContext &C, ObjCMessage msg); |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 86 | void PostVisitObjCIvarRefExpr(CheckerContext &C, const ObjCIvarRefExpr *E); |
| 87 | void PreVisitReturnStmt(CheckerContext &C, const ReturnStmt *S); |
| 88 | void PreVisitGenericCall(CheckerContext &C, const CallExpr *CE); |
| 89 | void PostVisitGenericCall(CheckerContext &C, const CallExpr *CE); |
| 90 | virtual void visitLocation(CheckerContext &C, const Stmt *S, SVal location, |
| 91 | bool isLoad); |
| 92 | }; |
| 93 | } // end anonymous namespace |
| 94 | |
| 95 | void ento::registerObjCSelfInitChecker(ExprEngine &Eng) { |
| 96 | if (Eng.getContext().getLangOptions().ObjC1) |
| 97 | Eng.registerCheck(new ObjCSelfInitChecker()); |
| 98 | } |
| 99 | |
| 100 | namespace { |
| 101 | |
| 102 | class InitSelfBug : public BugType { |
| 103 | const std::string desc; |
| 104 | public: |
Argyrios Kyrtzidis | 4717f16 | 2011-01-26 01:26:41 +0000 | [diff] [blame] | 105 | InitSelfBug() : BugType("missing \"self = [(super or self) init...]\"", |
| 106 | "missing \"self = [(super or self) init...]\"") {} |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 107 | }; |
| 108 | |
| 109 | } // end anonymous namespace |
| 110 | |
| 111 | typedef llvm::ImmutableMap<SymbolRef, unsigned> SelfFlag; |
Ted Kremenek | b715a7c | 2011-02-12 03:03:54 +0000 | [diff] [blame^] | 112 | namespace { struct CalledInit {}; } |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 113 | |
| 114 | namespace clang { |
| 115 | namespace ento { |
| 116 | template<> |
| 117 | struct GRStateTrait<SelfFlag> : public GRStatePartialTrait<SelfFlag> { |
| 118 | static void* GDMIndex() { |
| 119 | static int index = 0; |
| 120 | return &index; |
| 121 | } |
| 122 | }; |
Ted Kremenek | b715a7c | 2011-02-12 03:03:54 +0000 | [diff] [blame^] | 123 | template <> |
| 124 | struct GRStateTrait<CalledInit> : public GRStatePartialTrait<bool> { |
| 125 | static void *GDMIndex() { static int index = 0; return &index; } |
| 126 | }; |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 127 | } |
| 128 | } |
| 129 | |
| 130 | static SelfFlagEnum getSelfFlags(SVal val, const GRState *state) { |
| 131 | if (SymbolRef sym = val.getAsSymbol()) |
| 132 | if (const unsigned *attachedFlags = state->get<SelfFlag>(sym)) |
| 133 | return (SelfFlagEnum)*attachedFlags; |
| 134 | return SelfFlag_None; |
| 135 | } |
| 136 | |
| 137 | static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) { |
| 138 | return getSelfFlags(val, C.getState()); |
| 139 | } |
| 140 | |
Ted Kremenek | b715a7c | 2011-02-12 03:03:54 +0000 | [diff] [blame^] | 141 | static void addSelfFlag(const GRState *state, SVal val, |
| 142 | SelfFlagEnum flag, CheckerContext &C) { |
Argyrios Kyrtzidis | 0ca1040 | 2011-02-05 05:54:53 +0000 | [diff] [blame] | 143 | // We tag the symbol that the SVal wraps. |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 144 | if (SymbolRef sym = val.getAsSymbol()) |
| 145 | C.addTransition(state->set<SelfFlag>(sym, getSelfFlags(val, C) | flag)); |
| 146 | } |
| 147 | |
| 148 | static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) { |
| 149 | return getSelfFlags(val, C) & flag; |
| 150 | } |
| 151 | |
| 152 | /// \brief Returns true of the value of the expression is the object that 'self' |
| 153 | /// points to and is an object that did not come from the result of calling |
| 154 | /// an initializer. |
| 155 | static bool isInvalidSelf(const Expr *E, CheckerContext &C) { |
| 156 | SVal exprVal = C.getState()->getSVal(E); |
| 157 | if (!hasSelfFlag(exprVal, SelfFlag_Self, C)) |
| 158 | return false; // value did not come from 'self'. |
| 159 | if (hasSelfFlag(exprVal, SelfFlag_InitRes, C)) |
| 160 | return false; // 'self' is properly initialized. |
| 161 | |
| 162 | return true; |
| 163 | } |
| 164 | |
| 165 | static void checkForInvalidSelf(const Expr *E, CheckerContext &C, |
| 166 | const char *errorStr) { |
| 167 | if (!E) |
| 168 | return; |
Ted Kremenek | b715a7c | 2011-02-12 03:03:54 +0000 | [diff] [blame^] | 169 | |
| 170 | if (!C.getState()->get<CalledInit>()) |
| 171 | return; |
| 172 | |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 173 | if (!isInvalidSelf(E, C)) |
| 174 | return; |
Ted Kremenek | b715a7c | 2011-02-12 03:03:54 +0000 | [diff] [blame^] | 175 | |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 176 | // Generate an error node. |
| 177 | ExplodedNode *N = C.generateSink(); |
| 178 | if (!N) |
| 179 | return; |
| 180 | |
| 181 | EnhancedBugReport *report = |
| 182 | new EnhancedBugReport(*new InitSelfBug(), errorStr, N); |
| 183 | C.EmitReport(report); |
| 184 | } |
| 185 | |
Argyrios Kyrtzidis | 432424d | 2011-01-25 00:03:53 +0000 | [diff] [blame] | 186 | void ObjCSelfInitChecker::postVisitObjCMessage(CheckerContext &C, |
| 187 | ObjCMessage msg) { |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 188 | // When encountering a message that does initialization (init rule), |
| 189 | // tag the return value so that we know later on that if self has this value |
| 190 | // then it is properly initialized. |
| 191 | |
| 192 | // FIXME: A callback should disable checkers at the start of functions. |
| 193 | if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>( |
| 194 | C.getCurrentAnalysisContext()->getDecl()))) |
| 195 | return; |
| 196 | |
Argyrios Kyrtzidis | 432424d | 2011-01-25 00:03:53 +0000 | [diff] [blame] | 197 | if (isInitMessage(msg)) { |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 198 | // Tag the return value as the result of an initializer. |
| 199 | const GRState *state = C.getState(); |
Ted Kremenek | b715a7c | 2011-02-12 03:03:54 +0000 | [diff] [blame^] | 200 | |
| 201 | // FIXME this really should be context sensitive, where we record |
| 202 | // the current stack frame (for IPA). Also, we need to clean this |
| 203 | // value out when we return from this method. |
| 204 | state = state->set<CalledInit>(true); |
| 205 | |
Argyrios Kyrtzidis | 432424d | 2011-01-25 00:03:53 +0000 | [diff] [blame] | 206 | SVal V = state->getSVal(msg.getOriginExpr()); |
Ted Kremenek | b715a7c | 2011-02-12 03:03:54 +0000 | [diff] [blame^] | 207 | addSelfFlag(state, V, SelfFlag_InitRes, C); |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 208 | return; |
| 209 | } |
| 210 | |
| 211 | // We don't check for an invalid 'self' in an obj-c message expression to cut |
| 212 | // down false positives where logging functions get information from self |
| 213 | // (like its class) or doing "invalidation" on self when the initialization |
| 214 | // fails. |
| 215 | } |
| 216 | |
| 217 | void ObjCSelfInitChecker::PostVisitObjCIvarRefExpr(CheckerContext &C, |
| 218 | const ObjCIvarRefExpr *E) { |
| 219 | // FIXME: A callback should disable checkers at the start of functions. |
| 220 | if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>( |
| 221 | C.getCurrentAnalysisContext()->getDecl()))) |
| 222 | return; |
| 223 | |
| 224 | checkForInvalidSelf(E->getBase(), C, |
Argyrios Kyrtzidis | be29d8d | 2011-02-01 19:32:55 +0000 | [diff] [blame] | 225 | "Instance variable used while 'self' is not set to the result of " |
Argyrios Kyrtzidis | 4717f16 | 2011-01-26 01:26:41 +0000 | [diff] [blame] | 226 | "'[(super or self) init...]'"); |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 227 | } |
| 228 | |
| 229 | void ObjCSelfInitChecker::PreVisitReturnStmt(CheckerContext &C, |
| 230 | const ReturnStmt *S) { |
| 231 | // FIXME: A callback should disable checkers at the start of functions. |
| 232 | if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>( |
| 233 | C.getCurrentAnalysisContext()->getDecl()))) |
| 234 | return; |
| 235 | |
| 236 | checkForInvalidSelf(S->getRetValue(), C, |
Argyrios Kyrtzidis | 63eeade | 2011-02-01 20:33:05 +0000 | [diff] [blame] | 237 | "Returning 'self' while it is not set to the result of " |
Argyrios Kyrtzidis | 4717f16 | 2011-01-26 01:26:41 +0000 | [diff] [blame] | 238 | "'[(super or self) init...]'"); |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 239 | } |
| 240 | |
| 241 | // When a call receives a reference to 'self', [Pre/Post]VisitGenericCall pass |
| 242 | // the SelfFlags from the object 'self' point to before the call, to the new |
Argyrios Kyrtzidis | 0ca1040 | 2011-02-05 05:54:53 +0000 | [diff] [blame] | 243 | // object after the call. This is to avoid invalidation of 'self' by logging |
| 244 | // functions. |
| 245 | // Another common pattern in classes with multiple initializers is to put the |
| 246 | // subclass's common initialization bits into a static function that receives |
| 247 | // the value of 'self', e.g: |
| 248 | // @code |
| 249 | // if (!(self = [super init])) |
| 250 | // return nil; |
| 251 | // if (!(self = _commonInit(self))) |
| 252 | // return nil; |
| 253 | // @endcode |
| 254 | // Until we can use inter-procedural analysis, in such a call, transfer the |
| 255 | // SelfFlags to the result of the call. |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 256 | |
| 257 | void ObjCSelfInitChecker::PreVisitGenericCall(CheckerContext &C, |
| 258 | const CallExpr *CE) { |
| 259 | const GRState *state = C.getState(); |
| 260 | for (CallExpr::const_arg_iterator |
| 261 | I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) { |
| 262 | SVal argV = state->getSVal(*I); |
| 263 | if (isSelfVar(argV, C)) { |
| 264 | preCallSelfFlags = getSelfFlags(state->getSVal(cast<Loc>(argV)), C); |
| 265 | return; |
Argyrios Kyrtzidis | 0ca1040 | 2011-02-05 05:54:53 +0000 | [diff] [blame] | 266 | } else if (hasSelfFlag(argV, SelfFlag_Self, C)) { |
| 267 | preCallSelfFlags = getSelfFlags(argV, C); |
| 268 | return; |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 269 | } |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | void ObjCSelfInitChecker::PostVisitGenericCall(CheckerContext &C, |
| 274 | const CallExpr *CE) { |
| 275 | const GRState *state = C.getState(); |
| 276 | for (CallExpr::const_arg_iterator |
| 277 | I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) { |
| 278 | SVal argV = state->getSVal(*I); |
| 279 | if (isSelfVar(argV, C)) { |
Ted Kremenek | b715a7c | 2011-02-12 03:03:54 +0000 | [diff] [blame^] | 280 | addSelfFlag(state, state->getSVal(cast<Loc>(argV)), preCallSelfFlags, C); |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 281 | return; |
Argyrios Kyrtzidis | 0ca1040 | 2011-02-05 05:54:53 +0000 | [diff] [blame] | 282 | } else if (hasSelfFlag(argV, SelfFlag_Self, C)) { |
Ted Kremenek | b715a7c | 2011-02-12 03:03:54 +0000 | [diff] [blame^] | 283 | addSelfFlag(state, state->getSVal(CE), preCallSelfFlags, C); |
Argyrios Kyrtzidis | 0ca1040 | 2011-02-05 05:54:53 +0000 | [diff] [blame] | 284 | return; |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 285 | } |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | void ObjCSelfInitChecker::visitLocation(CheckerContext &C, const Stmt *S, |
| 290 | SVal location, bool isLoad) { |
| 291 | // Tag the result of a load from 'self' so that we can easily know that the |
| 292 | // value is the object that 'self' points to. |
| 293 | const GRState *state = C.getState(); |
| 294 | if (isSelfVar(location, C)) |
Ted Kremenek | b715a7c | 2011-02-12 03:03:54 +0000 | [diff] [blame^] | 295 | addSelfFlag(state, state->getSVal(cast<Loc>(location)), SelfFlag_Self, C); |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 296 | } |
| 297 | |
| 298 | // FIXME: A callback should disable checkers at the start of functions. |
| 299 | static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) { |
| 300 | if (!ND) |
| 301 | return false; |
| 302 | |
| 303 | const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND); |
| 304 | if (!MD) |
| 305 | return false; |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 306 | if (!isInitializationMethod(MD)) |
| 307 | return false; |
| 308 | |
Argyrios Kyrtzidis | eaf969b | 2011-01-25 23:54:44 +0000 | [diff] [blame] | 309 | // self = [super init] applies only to NSObject subclasses. |
| 310 | // For instance, NSProxy doesn't implement -init. |
| 311 | ASTContext& Ctx = MD->getASTContext(); |
| 312 | IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject"); |
| 313 | ObjCInterfaceDecl* ID = MD->getClassInterface()->getSuperClass(); |
| 314 | for ( ; ID ; ID = ID->getSuperClass()) { |
| 315 | IdentifierInfo *II = ID->getIdentifier(); |
| 316 | |
| 317 | if (II == NSObjectII) |
| 318 | break; |
| 319 | } |
| 320 | if (!ID) |
| 321 | return false; |
| 322 | |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 323 | return true; |
| 324 | } |
| 325 | |
| 326 | /// \brief Returns true if the location is 'self'. |
| 327 | static bool isSelfVar(SVal location, CheckerContext &C) { |
| 328 | AnalysisContext *analCtx = C.getCurrentAnalysisContext(); |
| 329 | if (!analCtx->getSelfDecl()) |
| 330 | return false; |
| 331 | if (!isa<loc::MemRegionVal>(location)) |
| 332 | return false; |
| 333 | |
| 334 | loc::MemRegionVal MRV = cast<loc::MemRegionVal>(location); |
| 335 | if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.getRegion())) |
| 336 | return (DR->getDecl() == analCtx->getSelfDecl()); |
| 337 | |
| 338 | return false; |
| 339 | } |
| 340 | |
| 341 | static bool isInitializationMethod(const ObjCMethodDecl *MD) { |
| 342 | // Init methods with prefix like '-(id)_init' are private and the requirements |
| 343 | // are less strict so we don't check those. |
| 344 | return MD->isInstanceMethod() && |
| 345 | cocoa::deriveNamingConvention(MD->getSelector(), |
| 346 | /*ignorePrefix=*/false) == cocoa::InitRule; |
| 347 | } |
| 348 | |
Argyrios Kyrtzidis | 432424d | 2011-01-25 00:03:53 +0000 | [diff] [blame] | 349 | static bool isInitMessage(const ObjCMessage &msg) { |
| 350 | return cocoa::deriveNamingConvention(msg.getSelector()) == cocoa::InitRule; |
Argyrios Kyrtzidis | d7a31ba | 2011-01-11 19:45:25 +0000 | [diff] [blame] | 351 | } |