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