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