clang API Documentation

ObjCSelfInitChecker.cpp
Go to the documentation of this file.
00001 //== ObjCSelfInitChecker.cpp - Checker for 'self' initialization -*- C++ -*--=//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This defines ObjCSelfInitChecker, a builtin check that checks for uses of
00011 // 'self' before proper initialization.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 // This checks initialization methods to verify that they assign 'self' to the
00016 // result of an initialization call (e.g. [super init], or [self initWith..])
00017 // before using 'self' or any instance variable.
00018 //
00019 // To perform the required checking, values are tagged with flags that indicate
00020 // 1) if the object is the one pointed to by 'self', and 2) if the object
00021 // is the result of an initializer (e.g. [super init]).
00022 //
00023 // Uses of an object that is true for 1) but not 2) trigger a diagnostic.
00024 // The uses that are currently checked are:
00025 //  - Using instance variables.
00026 //  - Returning the object.
00027 //
00028 // Note that we don't check for an invalid 'self' that is the receiver of an
00029 // obj-c message expression to cut down false positives where logging functions
00030 // get information from self (like its class) or doing "invalidation" on self
00031 // when the initialization fails.
00032 //
00033 // Because the object that 'self' points to gets invalidated when a call
00034 // receives a reference to 'self', the checker keeps track and passes the flags
00035 // for 1) and 2) to the new object that 'self' points to after the call.
00036 //
00037 //===----------------------------------------------------------------------===//
00038 
00039 #include "ClangSACheckers.h"
00040 #include "clang/AST/ParentMap.h"
00041 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
00042 #include "clang/StaticAnalyzer/Core/Checker.h"
00043 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
00044 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
00045 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
00046 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
00047 #include "llvm/Support/raw_ostream.h"
00048 
00049 using namespace clang;
00050 using namespace ento;
00051 
00052 static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND);
00053 static bool isInitializationMethod(const ObjCMethodDecl *MD);
00054 static bool isInitMessage(const ObjCMethodCall &Msg);
00055 static bool isSelfVar(SVal location, CheckerContext &C);
00056 
00057 namespace {
00058 class ObjCSelfInitChecker : public Checker<  check::PostObjCMessage,
00059                                              check::PostStmt<ObjCIvarRefExpr>,
00060                                              check::PreStmt<ReturnStmt>,
00061                                              check::PreCall,
00062                                              check::PostCall,
00063                                              check::Location,
00064                                              check::Bind > {
00065   mutable std::unique_ptr<BugType> BT;
00066 
00067   void checkForInvalidSelf(const Expr *E, CheckerContext &C,
00068                            const char *errorStr) const;
00069 
00070 public:
00071   ObjCSelfInitChecker() {}
00072   void checkPostObjCMessage(const ObjCMethodCall &Msg, CheckerContext &C) const;
00073   void checkPostStmt(const ObjCIvarRefExpr *E, CheckerContext &C) const;
00074   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
00075   void checkLocation(SVal location, bool isLoad, const Stmt *S,
00076                      CheckerContext &C) const;
00077   void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
00078 
00079   void checkPreCall(const CallEvent &CE, CheckerContext &C) const;
00080   void checkPostCall(const CallEvent &CE, CheckerContext &C) const;
00081 
00082   void printState(raw_ostream &Out, ProgramStateRef State,
00083                   const char *NL, const char *Sep) const override;
00084 };
00085 } // end anonymous namespace
00086 
00087 namespace {
00088 enum SelfFlagEnum {
00089   /// \brief No flag set.
00090   SelfFlag_None = 0x0,
00091   /// \brief Value came from 'self'.
00092   SelfFlag_Self    = 0x1,
00093   /// \brief Value came from the result of an initializer (e.g. [super init]).
00094   SelfFlag_InitRes = 0x2
00095 };
00096 }
00097 
00098 REGISTER_MAP_WITH_PROGRAMSTATE(SelfFlag, SymbolRef, unsigned)
00099 REGISTER_TRAIT_WITH_PROGRAMSTATE(CalledInit, bool)
00100 
00101 /// \brief A call receiving a reference to 'self' invalidates the object that
00102 /// 'self' contains. This keeps the "self flags" assigned to the 'self'
00103 /// object before the call so we can assign them to the new object that 'self'
00104 /// points to after the call.
00105 REGISTER_TRAIT_WITH_PROGRAMSTATE(PreCallSelfFlags, unsigned)
00106 
00107 static SelfFlagEnum getSelfFlags(SVal val, ProgramStateRef state) {
00108   if (SymbolRef sym = val.getAsSymbol())
00109     if (const unsigned *attachedFlags = state->get<SelfFlag>(sym))
00110       return (SelfFlagEnum)*attachedFlags;
00111   return SelfFlag_None;
00112 }
00113 
00114 static SelfFlagEnum getSelfFlags(SVal val, CheckerContext &C) {
00115   return getSelfFlags(val, C.getState());
00116 }
00117 
00118 static void addSelfFlag(ProgramStateRef state, SVal val,
00119                         SelfFlagEnum flag, CheckerContext &C) {
00120   // We tag the symbol that the SVal wraps.
00121   if (SymbolRef sym = val.getAsSymbol()) {
00122     state = state->set<SelfFlag>(sym, getSelfFlags(val, state) | flag);
00123     C.addTransition(state);
00124   }
00125 }
00126 
00127 static bool hasSelfFlag(SVal val, SelfFlagEnum flag, CheckerContext &C) {
00128   return getSelfFlags(val, C) & flag;
00129 }
00130 
00131 /// \brief Returns true of the value of the expression is the object that 'self'
00132 /// points to and is an object that did not come from the result of calling
00133 /// an initializer.
00134 static bool isInvalidSelf(const Expr *E, CheckerContext &C) {
00135   SVal exprVal = C.getState()->getSVal(E, C.getLocationContext());
00136   if (!hasSelfFlag(exprVal, SelfFlag_Self, C))
00137     return false; // value did not come from 'self'.
00138   if (hasSelfFlag(exprVal, SelfFlag_InitRes, C))
00139     return false; // 'self' is properly initialized.
00140 
00141   return true;
00142 }
00143 
00144 void ObjCSelfInitChecker::checkForInvalidSelf(const Expr *E, CheckerContext &C,
00145                                               const char *errorStr) const {
00146   if (!E)
00147     return;
00148   
00149   if (!C.getState()->get<CalledInit>())
00150     return;
00151   
00152   if (!isInvalidSelf(E, C))
00153     return;
00154   
00155   // Generate an error node.
00156   ExplodedNode *N = C.generateSink();
00157   if (!N)
00158     return;
00159 
00160   if (!BT)
00161     BT.reset(new BugType(this, "Missing \"self = [(super or self) init...]\"",
00162                          categories::CoreFoundationObjectiveC));
00163   BugReport *report = new BugReport(*BT, errorStr, N);
00164   C.emitReport(report);
00165 }
00166 
00167 void ObjCSelfInitChecker::checkPostObjCMessage(const ObjCMethodCall &Msg,
00168                                                CheckerContext &C) const {
00169   // When encountering a message that does initialization (init rule),
00170   // tag the return value so that we know later on that if self has this value
00171   // then it is properly initialized.
00172 
00173   // FIXME: A callback should disable checkers at the start of functions.
00174   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
00175                                 C.getCurrentAnalysisDeclContext()->getDecl())))
00176     return;
00177 
00178   if (isInitMessage(Msg)) {
00179     // Tag the return value as the result of an initializer.
00180     ProgramStateRef state = C.getState();
00181     
00182     // FIXME this really should be context sensitive, where we record
00183     // the current stack frame (for IPA).  Also, we need to clean this
00184     // value out when we return from this method.
00185     state = state->set<CalledInit>(true);
00186     
00187     SVal V = state->getSVal(Msg.getOriginExpr(), C.getLocationContext());
00188     addSelfFlag(state, V, SelfFlag_InitRes, C);
00189     return;
00190   }
00191 
00192   // We don't check for an invalid 'self' in an obj-c message expression to cut
00193   // down false positives where logging functions get information from self
00194   // (like its class) or doing "invalidation" on self when the initialization
00195   // fails.
00196 }
00197 
00198 void ObjCSelfInitChecker::checkPostStmt(const ObjCIvarRefExpr *E,
00199                                         CheckerContext &C) const {
00200   // FIXME: A callback should disable checkers at the start of functions.
00201   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
00202                                  C.getCurrentAnalysisDeclContext()->getDecl())))
00203     return;
00204 
00205   checkForInvalidSelf(
00206       E->getBase(), C,
00207       "Instance variable used while 'self' is not set to the result of "
00208       "'[(super or self) init...]'");
00209 }
00210 
00211 void ObjCSelfInitChecker::checkPreStmt(const ReturnStmt *S,
00212                                        CheckerContext &C) const {
00213   // FIXME: A callback should disable checkers at the start of functions.
00214   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
00215                                  C.getCurrentAnalysisDeclContext()->getDecl())))
00216     return;
00217 
00218   checkForInvalidSelf(S->getRetValue(), C,
00219                       "Returning 'self' while it is not set to the result of "
00220                       "'[(super or self) init...]'");
00221 }
00222 
00223 // When a call receives a reference to 'self', [Pre/Post]Call pass
00224 // the SelfFlags from the object 'self' points to before the call to the new
00225 // object after the call. This is to avoid invalidation of 'self' by logging
00226 // functions.
00227 // Another common pattern in classes with multiple initializers is to put the
00228 // subclass's common initialization bits into a static function that receives
00229 // the value of 'self', e.g:
00230 // @code
00231 //   if (!(self = [super init]))
00232 //     return nil;
00233 //   if (!(self = _commonInit(self)))
00234 //     return nil;
00235 // @endcode
00236 // Until we can use inter-procedural analysis, in such a call, transfer the
00237 // SelfFlags to the result of the call.
00238 
00239 void ObjCSelfInitChecker::checkPreCall(const CallEvent &CE,
00240                                        CheckerContext &C) const {
00241   // FIXME: A callback should disable checkers at the start of functions.
00242   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
00243                                  C.getCurrentAnalysisDeclContext()->getDecl())))
00244     return;
00245 
00246   ProgramStateRef state = C.getState();
00247   unsigned NumArgs = CE.getNumArgs();
00248   // If we passed 'self' as and argument to the call, record it in the state
00249   // to be propagated after the call.
00250   // Note, we could have just given up, but try to be more optimistic here and
00251   // assume that the functions are going to continue initialization or will not
00252   // modify self.
00253   for (unsigned i = 0; i < NumArgs; ++i) {
00254     SVal argV = CE.getArgSVal(i);
00255     if (isSelfVar(argV, C)) {
00256       unsigned selfFlags = getSelfFlags(state->getSVal(argV.castAs<Loc>()), C);
00257       C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
00258       return;
00259     } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
00260       unsigned selfFlags = getSelfFlags(argV, C);
00261       C.addTransition(state->set<PreCallSelfFlags>(selfFlags));
00262       return;
00263     }
00264   }
00265 }
00266 
00267 void ObjCSelfInitChecker::checkPostCall(const CallEvent &CE,
00268                                         CheckerContext &C) const {
00269   // FIXME: A callback should disable checkers at the start of functions.
00270   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
00271                                  C.getCurrentAnalysisDeclContext()->getDecl())))
00272     return;
00273 
00274   ProgramStateRef state = C.getState();
00275   SelfFlagEnum prevFlags = (SelfFlagEnum)state->get<PreCallSelfFlags>();
00276   if (!prevFlags)
00277     return;
00278   state = state->remove<PreCallSelfFlags>();
00279 
00280   unsigned NumArgs = CE.getNumArgs();
00281   for (unsigned i = 0; i < NumArgs; ++i) {
00282     SVal argV = CE.getArgSVal(i);
00283     if (isSelfVar(argV, C)) {
00284       // If the address of 'self' is being passed to the call, assume that the
00285       // 'self' after the call will have the same flags.
00286       // EX: log(&self)
00287       addSelfFlag(state, state->getSVal(argV.castAs<Loc>()), prevFlags, C);
00288       return;
00289     } else if (hasSelfFlag(argV, SelfFlag_Self, C)) {
00290       // If 'self' is passed to the call by value, assume that the function
00291       // returns 'self'. So assign the flags, which were set on 'self' to the
00292       // return value.
00293       // EX: self = performMoreInitialization(self)
00294       addSelfFlag(state, CE.getReturnValue(), prevFlags, C);
00295       return;
00296     }
00297   }
00298 
00299   C.addTransition(state);
00300 }
00301 
00302 void ObjCSelfInitChecker::checkLocation(SVal location, bool isLoad,
00303                                         const Stmt *S,
00304                                         CheckerContext &C) const {
00305   if (!shouldRunOnFunctionOrMethod(dyn_cast<NamedDecl>(
00306         C.getCurrentAnalysisDeclContext()->getDecl())))
00307     return;
00308 
00309   // Tag the result of a load from 'self' so that we can easily know that the
00310   // value is the object that 'self' points to.
00311   ProgramStateRef state = C.getState();
00312   if (isSelfVar(location, C))
00313     addSelfFlag(state, state->getSVal(location.castAs<Loc>()), SelfFlag_Self,
00314                 C);
00315 }
00316 
00317 
00318 void ObjCSelfInitChecker::checkBind(SVal loc, SVal val, const Stmt *S,
00319                                     CheckerContext &C) const {
00320   // Allow assignment of anything to self. Self is a local variable in the
00321   // initializer, so it is legal to assign anything to it, like results of
00322   // static functions/method calls. After self is assigned something we cannot 
00323   // reason about, stop enforcing the rules.
00324   // (Only continue checking if the assigned value should be treated as self.)
00325   if ((isSelfVar(loc, C)) &&
00326       !hasSelfFlag(val, SelfFlag_InitRes, C) &&
00327       !hasSelfFlag(val, SelfFlag_Self, C) &&
00328       !isSelfVar(val, C)) {
00329 
00330     // Stop tracking the checker-specific state in the state.
00331     ProgramStateRef State = C.getState();
00332     State = State->remove<CalledInit>();
00333     if (SymbolRef sym = loc.getAsSymbol())
00334       State = State->remove<SelfFlag>(sym);
00335     C.addTransition(State);
00336   }
00337 }
00338 
00339 void ObjCSelfInitChecker::printState(raw_ostream &Out, ProgramStateRef State,
00340                                      const char *NL, const char *Sep) const {
00341   SelfFlagTy FlagMap = State->get<SelfFlag>();
00342   bool DidCallInit = State->get<CalledInit>();
00343   SelfFlagEnum PreCallFlags = (SelfFlagEnum)State->get<PreCallSelfFlags>();
00344 
00345   if (FlagMap.isEmpty() && !DidCallInit && !PreCallFlags)
00346     return;
00347 
00348   Out << Sep << NL << *this << " :" << NL;
00349 
00350   if (DidCallInit)
00351     Out << "  An init method has been called." << NL;
00352 
00353   if (PreCallFlags != SelfFlag_None) {
00354     if (PreCallFlags & SelfFlag_Self) {
00355       Out << "  An argument of the current call came from the 'self' variable."
00356           << NL;
00357     }
00358     if (PreCallFlags & SelfFlag_InitRes) {
00359       Out << "  An argument of the current call came from an init method."
00360           << NL;
00361     }
00362   }
00363 
00364   Out << NL;
00365   for (SelfFlagTy::iterator I = FlagMap.begin(), E = FlagMap.end();
00366        I != E; ++I) {
00367     Out << I->first << " : ";
00368 
00369     if (I->second == SelfFlag_None)
00370       Out << "none";
00371 
00372     if (I->second & SelfFlag_Self)
00373       Out << "self variable";
00374 
00375     if (I->second & SelfFlag_InitRes) {
00376       if (I->second != SelfFlag_InitRes)
00377         Out << " | ";
00378       Out << "result of init method";
00379     }
00380 
00381     Out << NL;
00382   }
00383 }
00384 
00385 
00386 // FIXME: A callback should disable checkers at the start of functions.
00387 static bool shouldRunOnFunctionOrMethod(const NamedDecl *ND) {
00388   if (!ND)
00389     return false;
00390 
00391   const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND);
00392   if (!MD)
00393     return false;
00394   if (!isInitializationMethod(MD))
00395     return false;
00396 
00397   // self = [super init] applies only to NSObject subclasses.
00398   // For instance, NSProxy doesn't implement -init.
00399   ASTContext &Ctx = MD->getASTContext();
00400   IdentifierInfo* NSObjectII = &Ctx.Idents.get("NSObject");
00401   ObjCInterfaceDecl *ID = MD->getClassInterface()->getSuperClass();
00402   for ( ; ID ; ID = ID->getSuperClass()) {
00403     IdentifierInfo *II = ID->getIdentifier();
00404 
00405     if (II == NSObjectII)
00406       break;
00407   }
00408   if (!ID)
00409     return false;
00410 
00411   return true;
00412 }
00413 
00414 /// \brief Returns true if the location is 'self'.
00415 static bool isSelfVar(SVal location, CheckerContext &C) {
00416   AnalysisDeclContext *analCtx = C.getCurrentAnalysisDeclContext(); 
00417   if (!analCtx->getSelfDecl())
00418     return false;
00419   if (!location.getAs<loc::MemRegionVal>())
00420     return false;
00421 
00422   loc::MemRegionVal MRV = location.castAs<loc::MemRegionVal>();
00423   if (const DeclRegion *DR = dyn_cast<DeclRegion>(MRV.stripCasts()))
00424     return (DR->getDecl() == analCtx->getSelfDecl());
00425 
00426   return false;
00427 }
00428 
00429 static bool isInitializationMethod(const ObjCMethodDecl *MD) {
00430   return MD->getMethodFamily() == OMF_init;
00431 }
00432 
00433 static bool isInitMessage(const ObjCMethodCall &Call) {
00434   return Call.getMethodFamily() == OMF_init;
00435 }
00436 
00437 //===----------------------------------------------------------------------===//
00438 // Registration.
00439 //===----------------------------------------------------------------------===//
00440 
00441 void ento::registerObjCSelfInitChecker(CheckerManager &mgr) {
00442   mgr.registerChecker<ObjCSelfInitChecker>();
00443 }