1 //=-- ExprEngineObjC.cpp - ExprEngine support for Objective-C ---*- 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 file defines ExprEngine's support for Objective-C expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 15 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 16 #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h" 17 18 using namespace clang; 19 using namespace ento; 20 21 void ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *Ex, 22 ExplodedNode *Pred, 23 ExplodedNodeSet &Dst) { 24 const ProgramState *state = Pred->getState(); 25 SVal baseVal = state->getSVal(Ex->getBase()); 26 SVal location = state->getLValue(Ex->getDecl(), baseVal); 27 28 ExplodedNodeSet dstIvar; 29 StmtNodeBuilder Bldr(Pred, dstIvar, *currentBuilderContext); 30 Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, location)); 31 32 // Perform the post-condition check of the ObjCIvarRefExpr and store 33 // the created nodes in 'Dst'. 34 getCheckerManager().runCheckersForPostStmt(Dst, dstIvar, Ex, *this); 35 } 36 37 void ExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, 38 ExplodedNode *Pred, 39 ExplodedNodeSet &Dst) { 40 getCheckerManager().runCheckersForPreStmt(Dst, Pred, S, *this); 41 } 42 43 void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, 44 ExplodedNode *Pred, 45 ExplodedNodeSet &Dst) { 46 47 // ObjCForCollectionStmts are processed in two places. This method 48 // handles the case where an ObjCForCollectionStmt* occurs as one of the 49 // statements within a basic block. This transfer function does two things: 50 // 51 // (1) binds the next container value to 'element'. This creates a new 52 // node in the ExplodedGraph. 53 // 54 // (2) binds the value 0/1 to the ObjCForCollectionStmt* itself, indicating 55 // whether or not the container has any more elements. This value 56 // will be tested in ProcessBranch. We need to explicitly bind 57 // this value because a container can contain nil elements. 58 // 59 // FIXME: Eventually this logic should actually do dispatches to 60 // 'countByEnumeratingWithState:objects:count:' (NSFastEnumeration). 61 // This will require simulating a temporary NSFastEnumerationState, either 62 // through an SVal or through the use of MemRegions. This value can 63 // be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop 64 // terminates we reclaim the temporary (it goes out of scope) and we 65 // we can test if the SVal is 0 or if the MemRegion is null (depending 66 // on what approach we take). 67 // 68 // For now: simulate (1) by assigning either a symbol or nil if the 69 // container is empty. Thus this transfer function will by default 70 // result in state splitting. 71 72 const Stmt *elem = S->getElement(); 73 const ProgramState *state = Pred->getState(); 74 SVal elementV; 75 StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext); 76 77 if (const DeclStmt *DS = dyn_cast<DeclStmt>(elem)) { 78 const VarDecl *elemD = cast<VarDecl>(DS->getSingleDecl()); 79 assert(elemD->getInit() == 0); 80 elementV = state->getLValue(elemD, Pred->getLocationContext()); 81 } 82 else { 83 elementV = state->getSVal(elem); 84 } 85 86 ExplodedNodeSet dstLocation; 87 Bldr.takeNodes(Pred); 88 evalLocation(dstLocation, elem, Pred, state, elementV, NULL, false); 89 Bldr.addNodes(dstLocation); 90 91 for (ExplodedNodeSet::iterator NI = dstLocation.begin(), 92 NE = dstLocation.end(); NI!=NE; ++NI) { 93 Pred = *NI; 94 const ProgramState *state = Pred->getState(); 95 96 // Handle the case where the container still has elements. 97 SVal TrueV = svalBuilder.makeTruthVal(1); 98 const ProgramState *hasElems = state->BindExpr(S, TrueV); 99 100 // Handle the case where the container has no elements. 101 SVal FalseV = svalBuilder.makeTruthVal(0); 102 const ProgramState *noElems = state->BindExpr(S, FalseV); 103 104 if (loc::MemRegionVal *MV = dyn_cast<loc::MemRegionVal>(&elementV)) 105 if (const TypedValueRegion *R = 106 dyn_cast<TypedValueRegion>(MV->getRegion())) { 107 // FIXME: The proper thing to do is to really iterate over the 108 // container. We will do this with dispatch logic to the store. 109 // For now, just 'conjure' up a symbolic value. 110 QualType T = R->getValueType(); 111 assert(Loc::isLocType(T)); 112 unsigned Count = currentBuilderContext->getCurrentBlockCount(); 113 SymbolRef Sym = SymMgr.getConjuredSymbol(elem, T, Count); 114 SVal V = svalBuilder.makeLoc(Sym); 115 hasElems = hasElems->bindLoc(elementV, V); 116 117 // Bind the location to 'nil' on the false branch. 118 SVal nilV = svalBuilder.makeIntVal(0, T); 119 noElems = noElems->bindLoc(elementV, nilV); 120 } 121 122 // Create the new nodes. 123 Bldr.generateNode(S, Pred, hasElems); 124 Bldr.generateNode(S, Pred, noElems); 125 } 126 } 127 128 void ExprEngine::VisitObjCMessage(const ObjCMessage &msg, 129 ExplodedNode *Pred, 130 ExplodedNodeSet &Dst) { 131 132 // Handle the previsits checks. 133 ExplodedNodeSet dstPrevisit; 134 getCheckerManager().runCheckersForPreObjCMessage(dstPrevisit, Pred, 135 msg, *this); 136 137 // Proceed with evaluate the message expression. 138 ExplodedNodeSet dstEval; 139 StmtNodeBuilder Bldr(dstPrevisit, dstEval, *currentBuilderContext); 140 141 for (ExplodedNodeSet::iterator DI = dstPrevisit.begin(), 142 DE = dstPrevisit.end(); DI != DE; ++DI) { 143 144 ExplodedNode *Pred = *DI; 145 bool RaisesException = false; 146 147 if (const Expr *Receiver = msg.getInstanceReceiver()) { 148 const ProgramState *state = Pred->getState(); 149 SVal recVal = state->getSVal(Receiver); 150 if (!recVal.isUndef()) { 151 // Bifurcate the state into nil and non-nil ones. 152 DefinedOrUnknownSVal receiverVal = cast<DefinedOrUnknownSVal>(recVal); 153 154 const ProgramState *notNilState, *nilState; 155 llvm::tie(notNilState, nilState) = state->assume(receiverVal); 156 157 // There are three cases: can be nil or non-nil, must be nil, must be 158 // non-nil. We ignore must be nil, and merge the rest two into non-nil. 159 if (nilState && !notNilState) { 160 continue; 161 } 162 163 // Check if the "raise" message was sent. 164 assert(notNilState); 165 if (msg.getSelector() == RaiseSel) 166 RaisesException = true; 167 168 // If we raise an exception, for now treat it as a sink. 169 // Eventually we will want to handle exceptions properly. 170 // Dispatch to plug-in transfer function. 171 evalObjCMessage(Bldr, msg, Pred, notNilState, RaisesException); 172 } 173 } 174 else if (const ObjCInterfaceDecl *Iface = msg.getReceiverInterface()) { 175 IdentifierInfo* ClsName = Iface->getIdentifier(); 176 Selector S = msg.getSelector(); 177 178 // Check for special instance methods. 179 if (!NSExceptionII) { 180 ASTContext &Ctx = getContext(); 181 NSExceptionII = &Ctx.Idents.get("NSException"); 182 } 183 184 if (ClsName == NSExceptionII) { 185 enum { NUM_RAISE_SELECTORS = 2 }; 186 187 // Lazily create a cache of the selectors. 188 if (!NSExceptionInstanceRaiseSelectors) { 189 ASTContext &Ctx = getContext(); 190 NSExceptionInstanceRaiseSelectors = 191 new Selector[NUM_RAISE_SELECTORS]; 192 SmallVector<IdentifierInfo*, NUM_RAISE_SELECTORS> II; 193 unsigned idx = 0; 194 195 // raise:format: 196 II.push_back(&Ctx.Idents.get("raise")); 197 II.push_back(&Ctx.Idents.get("format")); 198 NSExceptionInstanceRaiseSelectors[idx++] = 199 Ctx.Selectors.getSelector(II.size(), &II[0]); 200 201 // raise:format::arguments: 202 II.push_back(&Ctx.Idents.get("arguments")); 203 NSExceptionInstanceRaiseSelectors[idx++] = 204 Ctx.Selectors.getSelector(II.size(), &II[0]); 205 } 206 207 for (unsigned i = 0; i < NUM_RAISE_SELECTORS; ++i) 208 if (S == NSExceptionInstanceRaiseSelectors[i]) { 209 RaisesException = true; 210 break; 211 } 212 } 213 214 // If we raise an exception, for now treat it as a sink. 215 // Eventually we will want to handle exceptions properly. 216 // Dispatch to plug-in transfer function. 217 evalObjCMessage(Bldr, msg, Pred, Pred->getState(), RaisesException); 218 } 219 } 220 221 // Finally, perform the post-condition check of the ObjCMessageExpr and store 222 // the created nodes in 'Dst'. 223 getCheckerManager().runCheckersForPostObjCMessage(Dst, dstEval, msg, *this); 224 } 225 226 void ExprEngine::evalObjCMessage(StmtNodeBuilder &Bldr, 227 const ObjCMessage &msg, 228 ExplodedNode *Pred, 229 const ProgramState *state, 230 bool GenSink) { 231 // First handle the return value. 232 SVal ReturnValue = UnknownVal(); 233 234 // Some method families have known return values. 235 switch (msg.getMethodFamily()) { 236 default: 237 break; 238 case OMF_autorelease: 239 case OMF_retain: 240 case OMF_self: { 241 // These methods return their receivers. 242 const Expr *ReceiverE = msg.getInstanceReceiver(); 243 if (ReceiverE) 244 ReturnValue = state->getSVal(ReceiverE); 245 break; 246 } 247 } 248 249 // If we failed to figure out the return value, use a conjured value instead. 250 if (ReturnValue.isUnknown()) { 251 SValBuilder &SVB = getSValBuilder(); 252 QualType ResultTy = msg.getResultType(getContext()); 253 unsigned Count = currentBuilderContext->getCurrentBlockCount(); 254 const Expr *CurrentE = cast<Expr>(currentStmt); 255 ReturnValue = SVB.getConjuredSymbolVal(NULL, CurrentE, ResultTy, Count); 256 } 257 258 // Bind the return value. 259 state = state->BindExpr(currentStmt, ReturnValue); 260 261 // Invalidate the arguments (and the receiver) 262 const LocationContext *LC = Pred->getLocationContext(); 263 state = invalidateArguments(state, CallOrObjCMessage(msg, state), LC); 264 265 // And create the new node. 266 Bldr.generateNode(msg.getOriginExpr(), Pred, state, GenSink); 267 assert(Bldr.hasGeneratedNodes()); 268 } 269 270