ExprEngineObjC.cpp revision 234353
1226586Sdim//=-- ExprEngineObjC.cpp - ExprEngine support for Objective-C ---*- C++ -*-===//
2226586Sdim//
3226586Sdim//                     The LLVM Compiler Infrastructure
4226586Sdim//
5226586Sdim// This file is distributed under the University of Illinois Open Source
6226586Sdim// License. See LICENSE.TXT for details.
7226586Sdim//
8226586Sdim//===----------------------------------------------------------------------===//
9226586Sdim//
10226586Sdim//  This file defines ExprEngine's support for Objective-C expressions.
11226586Sdim//
12226586Sdim//===----------------------------------------------------------------------===//
13226586Sdim
14234353Sdim#include "clang/AST/StmtObjC.h"
15226586Sdim#include "clang/StaticAnalyzer/Core/CheckerManager.h"
16226586Sdim#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17226586Sdim#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
18226586Sdim
19226586Sdimusing namespace clang;
20226586Sdimusing namespace ento;
21226586Sdim
22226586Sdimvoid ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *Ex,
23226586Sdim                                          ExplodedNode *Pred,
24226586Sdim                                          ExplodedNodeSet &Dst) {
25234353Sdim  ProgramStateRef state = Pred->getState();
26234353Sdim  const LocationContext *LCtx = Pred->getLocationContext();
27234353Sdim  SVal baseVal = state->getSVal(Ex->getBase(), LCtx);
28226586Sdim  SVal location = state->getLValue(Ex->getDecl(), baseVal);
29226586Sdim
30226586Sdim  ExplodedNodeSet dstIvar;
31234353Sdim  StmtNodeBuilder Bldr(Pred, dstIvar, *currentBuilderContext);
32234353Sdim  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, location));
33226586Sdim
34226586Sdim  // Perform the post-condition check of the ObjCIvarRefExpr and store
35226586Sdim  // the created nodes in 'Dst'.
36226586Sdim  getCheckerManager().runCheckersForPostStmt(Dst, dstIvar, Ex, *this);
37226586Sdim}
38226586Sdim
39226586Sdimvoid ExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
40226586Sdim                                             ExplodedNode *Pred,
41226586Sdim                                             ExplodedNodeSet &Dst) {
42226586Sdim  getCheckerManager().runCheckersForPreStmt(Dst, Pred, S, *this);
43226586Sdim}
44226586Sdim
45226586Sdimvoid ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
46226586Sdim                                            ExplodedNode *Pred,
47226586Sdim                                            ExplodedNodeSet &Dst) {
48226586Sdim
49226586Sdim  // ObjCForCollectionStmts are processed in two places.  This method
50226586Sdim  // handles the case where an ObjCForCollectionStmt* occurs as one of the
51226586Sdim  // statements within a basic block.  This transfer function does two things:
52226586Sdim  //
53226586Sdim  //  (1) binds the next container value to 'element'.  This creates a new
54226586Sdim  //      node in the ExplodedGraph.
55226586Sdim  //
56226586Sdim  //  (2) binds the value 0/1 to the ObjCForCollectionStmt* itself, indicating
57226586Sdim  //      whether or not the container has any more elements.  This value
58226586Sdim  //      will be tested in ProcessBranch.  We need to explicitly bind
59226586Sdim  //      this value because a container can contain nil elements.
60226586Sdim  //
61226586Sdim  // FIXME: Eventually this logic should actually do dispatches to
62226586Sdim  //   'countByEnumeratingWithState:objects:count:' (NSFastEnumeration).
63226586Sdim  //   This will require simulating a temporary NSFastEnumerationState, either
64226586Sdim  //   through an SVal or through the use of MemRegions.  This value can
65226586Sdim  //   be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop
66226586Sdim  //   terminates we reclaim the temporary (it goes out of scope) and we
67226586Sdim  //   we can test if the SVal is 0 or if the MemRegion is null (depending
68226586Sdim  //   on what approach we take).
69226586Sdim  //
70226586Sdim  //  For now: simulate (1) by assigning either a symbol or nil if the
71226586Sdim  //    container is empty.  Thus this transfer function will by default
72226586Sdim  //    result in state splitting.
73234353Sdim
74226586Sdim  const Stmt *elem = S->getElement();
75234353Sdim  ProgramStateRef state = Pred->getState();
76226586Sdim  SVal elementV;
77234353Sdim  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
78226586Sdim
79226586Sdim  if (const DeclStmt *DS = dyn_cast<DeclStmt>(elem)) {
80226586Sdim    const VarDecl *elemD = cast<VarDecl>(DS->getSingleDecl());
81226586Sdim    assert(elemD->getInit() == 0);
82226586Sdim    elementV = state->getLValue(elemD, Pred->getLocationContext());
83226586Sdim  }
84226586Sdim  else {
85234353Sdim    elementV = state->getSVal(elem, Pred->getLocationContext());
86226586Sdim  }
87226586Sdim
88226586Sdim  ExplodedNodeSet dstLocation;
89234353Sdim  Bldr.takeNodes(Pred);
90234353Sdim  evalLocation(dstLocation, S, elem, Pred, state, elementV, NULL, false);
91234353Sdim  Bldr.addNodes(dstLocation);
92226586Sdim
93226586Sdim  for (ExplodedNodeSet::iterator NI = dstLocation.begin(),
94226586Sdim       NE = dstLocation.end(); NI!=NE; ++NI) {
95226586Sdim    Pred = *NI;
96234353Sdim    ProgramStateRef state = Pred->getState();
97234353Sdim    const LocationContext *LCtx = Pred->getLocationContext();
98226586Sdim
99226586Sdim    // Handle the case where the container still has elements.
100226586Sdim    SVal TrueV = svalBuilder.makeTruthVal(1);
101234353Sdim    ProgramStateRef hasElems = state->BindExpr(S, LCtx, TrueV);
102226586Sdim
103226586Sdim    // Handle the case where the container has no elements.
104226586Sdim    SVal FalseV = svalBuilder.makeTruthVal(0);
105234353Sdim    ProgramStateRef noElems = state->BindExpr(S, LCtx, FalseV);
106226586Sdim
107226586Sdim    if (loc::MemRegionVal *MV = dyn_cast<loc::MemRegionVal>(&elementV))
108226586Sdim      if (const TypedValueRegion *R =
109226586Sdim          dyn_cast<TypedValueRegion>(MV->getRegion())) {
110226586Sdim        // FIXME: The proper thing to do is to really iterate over the
111226586Sdim        //  container.  We will do this with dispatch logic to the store.
112226586Sdim        //  For now, just 'conjure' up a symbolic value.
113226586Sdim        QualType T = R->getValueType();
114226586Sdim        assert(Loc::isLocType(T));
115234353Sdim        unsigned Count = currentBuilderContext->getCurrentBlockCount();
116234353Sdim        SymbolRef Sym = SymMgr.getConjuredSymbol(elem, LCtx, T, Count);
117226586Sdim        SVal V = svalBuilder.makeLoc(Sym);
118226586Sdim        hasElems = hasElems->bindLoc(elementV, V);
119226586Sdim
120226586Sdim        // Bind the location to 'nil' on the false branch.
121226586Sdim        SVal nilV = svalBuilder.makeIntVal(0, T);
122226586Sdim        noElems = noElems->bindLoc(elementV, nilV);
123226586Sdim      }
124226586Sdim
125226586Sdim    // Create the new nodes.
126234353Sdim    Bldr.generateNode(S, Pred, hasElems);
127234353Sdim    Bldr.generateNode(S, Pred, noElems);
128226586Sdim  }
129226586Sdim}
130226586Sdim
131226586Sdimvoid ExprEngine::VisitObjCMessage(const ObjCMessage &msg,
132226586Sdim                                  ExplodedNode *Pred,
133226586Sdim                                  ExplodedNodeSet &Dst) {
134226586Sdim
135226586Sdim  // Handle the previsits checks.
136226586Sdim  ExplodedNodeSet dstPrevisit;
137226586Sdim  getCheckerManager().runCheckersForPreObjCMessage(dstPrevisit, Pred,
138226586Sdim                                                   msg, *this);
139226586Sdim
140226586Sdim  // Proceed with evaluate the message expression.
141226586Sdim  ExplodedNodeSet dstEval;
142234353Sdim  StmtNodeBuilder Bldr(dstPrevisit, dstEval, *currentBuilderContext);
143234353Sdim
144226586Sdim  for (ExplodedNodeSet::iterator DI = dstPrevisit.begin(),
145226586Sdim       DE = dstPrevisit.end(); DI != DE; ++DI) {
146226586Sdim
147226586Sdim    ExplodedNode *Pred = *DI;
148226586Sdim    bool RaisesException = false;
149226586Sdim
150226586Sdim    if (const Expr *Receiver = msg.getInstanceReceiver()) {
151234353Sdim      ProgramStateRef state = Pred->getState();
152234353Sdim      SVal recVal = state->getSVal(Receiver, Pred->getLocationContext());
153226586Sdim      if (!recVal.isUndef()) {
154226586Sdim        // Bifurcate the state into nil and non-nil ones.
155226586Sdim        DefinedOrUnknownSVal receiverVal = cast<DefinedOrUnknownSVal>(recVal);
156226586Sdim
157234353Sdim        ProgramStateRef notNilState, nilState;
158226586Sdim        llvm::tie(notNilState, nilState) = state->assume(receiverVal);
159226586Sdim
160226586Sdim        // There are three cases: can be nil or non-nil, must be nil, must be
161226586Sdim        // non-nil. We ignore must be nil, and merge the rest two into non-nil.
162226586Sdim        if (nilState && !notNilState) {
163226586Sdim          continue;
164226586Sdim        }
165226586Sdim
166226586Sdim        // Check if the "raise" message was sent.
167226586Sdim        assert(notNilState);
168226586Sdim        if (msg.getSelector() == RaiseSel)
169226586Sdim          RaisesException = true;
170226586Sdim
171234353Sdim        // If we raise an exception, for now treat it as a sink.
172226586Sdim        // Eventually we will want to handle exceptions properly.
173226586Sdim        // Dispatch to plug-in transfer function.
174234353Sdim        evalObjCMessage(Bldr, msg, Pred, notNilState, RaisesException);
175226586Sdim      }
176226586Sdim    }
177226586Sdim    else if (const ObjCInterfaceDecl *Iface = msg.getReceiverInterface()) {
178226586Sdim      IdentifierInfo* ClsName = Iface->getIdentifier();
179226586Sdim      Selector S = msg.getSelector();
180226586Sdim
181226586Sdim      // Check for special instance methods.
182226586Sdim      if (!NSExceptionII) {
183226586Sdim        ASTContext &Ctx = getContext();
184226586Sdim        NSExceptionII = &Ctx.Idents.get("NSException");
185226586Sdim      }
186226586Sdim
187226586Sdim      if (ClsName == NSExceptionII) {
188226586Sdim        enum { NUM_RAISE_SELECTORS = 2 };
189226586Sdim
190226586Sdim        // Lazily create a cache of the selectors.
191226586Sdim        if (!NSExceptionInstanceRaiseSelectors) {
192226586Sdim          ASTContext &Ctx = getContext();
193226586Sdim          NSExceptionInstanceRaiseSelectors =
194226586Sdim          new Selector[NUM_RAISE_SELECTORS];
195226586Sdim          SmallVector<IdentifierInfo*, NUM_RAISE_SELECTORS> II;
196226586Sdim          unsigned idx = 0;
197226586Sdim
198226586Sdim          // raise:format:
199226586Sdim          II.push_back(&Ctx.Idents.get("raise"));
200226586Sdim          II.push_back(&Ctx.Idents.get("format"));
201226586Sdim          NSExceptionInstanceRaiseSelectors[idx++] =
202226586Sdim          Ctx.Selectors.getSelector(II.size(), &II[0]);
203226586Sdim
204226586Sdim          // raise:format::arguments:
205226586Sdim          II.push_back(&Ctx.Idents.get("arguments"));
206226586Sdim          NSExceptionInstanceRaiseSelectors[idx++] =
207226586Sdim          Ctx.Selectors.getSelector(II.size(), &II[0]);
208226586Sdim        }
209226586Sdim
210226586Sdim        for (unsigned i = 0; i < NUM_RAISE_SELECTORS; ++i)
211226586Sdim          if (S == NSExceptionInstanceRaiseSelectors[i]) {
212226586Sdim            RaisesException = true;
213226586Sdim            break;
214226586Sdim          }
215226586Sdim      }
216226586Sdim
217234353Sdim      // If we raise an exception, for now treat it as a sink.
218226586Sdim      // Eventually we will want to handle exceptions properly.
219226586Sdim      // Dispatch to plug-in transfer function.
220234353Sdim      evalObjCMessage(Bldr, msg, Pred, Pred->getState(), RaisesException);
221226586Sdim    }
222226586Sdim  }
223226586Sdim
224226586Sdim  // Finally, perform the post-condition check of the ObjCMessageExpr and store
225226586Sdim  // the created nodes in 'Dst'.
226226586Sdim  getCheckerManager().runCheckersForPostObjCMessage(Dst, dstEval, msg, *this);
227226586Sdim}
228226586Sdim
229234353Sdimvoid ExprEngine::evalObjCMessage(StmtNodeBuilder &Bldr,
230234353Sdim                                 const ObjCMessage &msg,
231226586Sdim                                 ExplodedNode *Pred,
232234353Sdim                                 ProgramStateRef state,
233234353Sdim                                 bool GenSink) {
234226586Sdim  // First handle the return value.
235226586Sdim  SVal ReturnValue = UnknownVal();
236226586Sdim
237226586Sdim  // Some method families have known return values.
238226586Sdim  switch (msg.getMethodFamily()) {
239226586Sdim  default:
240226586Sdim    break;
241226586Sdim  case OMF_autorelease:
242226586Sdim  case OMF_retain:
243226586Sdim  case OMF_self: {
244226586Sdim    // These methods return their receivers.
245226586Sdim    const Expr *ReceiverE = msg.getInstanceReceiver();
246226586Sdim    if (ReceiverE)
247234353Sdim      ReturnValue = state->getSVal(ReceiverE, Pred->getLocationContext());
248226586Sdim    break;
249226586Sdim  }
250226586Sdim  }
251226586Sdim
252226586Sdim  // If we failed to figure out the return value, use a conjured value instead.
253226586Sdim  if (ReturnValue.isUnknown()) {
254226586Sdim    SValBuilder &SVB = getSValBuilder();
255226586Sdim    QualType ResultTy = msg.getResultType(getContext());
256234353Sdim    unsigned Count = currentBuilderContext->getCurrentBlockCount();
257226586Sdim    const Expr *CurrentE = cast<Expr>(currentStmt);
258234353Sdim    const LocationContext *LCtx = Pred->getLocationContext();
259234353Sdim    ReturnValue = SVB.getConjuredSymbolVal(NULL, CurrentE, LCtx, ResultTy, Count);
260226586Sdim  }
261226586Sdim
262226586Sdim  // Bind the return value.
263234353Sdim  const LocationContext *LCtx = Pred->getLocationContext();
264234353Sdim  state = state->BindExpr(currentStmt, LCtx, ReturnValue);
265226586Sdim
266226586Sdim  // Invalidate the arguments (and the receiver)
267234353Sdim  state = invalidateArguments(state, CallOrObjCMessage(msg, state, LCtx), LCtx);
268226586Sdim
269226586Sdim  // And create the new node.
270234353Sdim  Bldr.generateNode(msg.getMessageExpr(), Pred, state, GenSink);
271234353Sdim  assert(Bldr.hasGeneratedNodes());
272226586Sdim}
273226586Sdim
274