ExprEngineObjC.cpp revision 6c234b1fd1da64a14a77433cb805cb1aa798512a
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/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"
18
19using namespace clang;
20using namespace ento;
21
22void ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *Ex,
23                                          ExplodedNode *Pred,
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);
29
30  ExplodedNodeSet dstIvar;
31  StmtNodeBuilder Bldr(Pred, dstIvar, *currentBuilderContext);
32  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, location));
33
34  // Perform the post-condition check of the ObjCIvarRefExpr and store
35  // the created nodes in 'Dst'.
36  getCheckerManager().runCheckersForPostStmt(Dst, dstIvar, Ex, *this);
37}
38
39void ExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
40                                             ExplodedNode *Pred,
41                                             ExplodedNodeSet &Dst) {
42  getCheckerManager().runCheckersForPreStmt(Dst, Pred, S, *this);
43}
44
45void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
46                                            ExplodedNode *Pred,
47                                            ExplodedNodeSet &Dst) {
48
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:
52  //
53  //  (1) binds the next container value to 'element'.  This creates a new
54  //      node in the ExplodedGraph.
55  //
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.
60  //
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).
69  //
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.
73
74  const Stmt *elem = S->getElement();
75  ProgramStateRef state = Pred->getState();
76  SVal elementV;
77
78  if (const DeclStmt *DS = dyn_cast<DeclStmt>(elem)) {
79    const VarDecl *elemD = cast<VarDecl>(DS->getSingleDecl());
80    assert(elemD->getInit() == 0);
81    elementV = state->getLValue(elemD, Pred->getLocationContext());
82  }
83  else {
84    elementV = state->getSVal(elem, Pred->getLocationContext());
85  }
86
87  ExplodedNodeSet dstLocation;
88  evalLocation(dstLocation, S, elem, Pred, state, elementV, NULL, false);
89
90  ExplodedNodeSet Tmp;
91  StmtNodeBuilder Bldr(Pred, Tmp, *currentBuilderContext);
92
93  for (ExplodedNodeSet::iterator NI = dstLocation.begin(),
94       NE = dstLocation.end(); NI!=NE; ++NI) {
95    Pred = *NI;
96    ProgramStateRef state = Pred->getState();
97    const LocationContext *LCtx = Pred->getLocationContext();
98
99    // Handle the case where the container still has elements.
100    SVal TrueV = svalBuilder.makeTruthVal(1);
101    ProgramStateRef hasElems = state->BindExpr(S, LCtx, TrueV);
102
103    // Handle the case where the container has no elements.
104    SVal FalseV = svalBuilder.makeTruthVal(0);
105    ProgramStateRef noElems = state->BindExpr(S, LCtx, FalseV);
106
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);
119
120        // Bind the location to 'nil' on the false branch.
121        SVal nilV = svalBuilder.makeIntVal(0, T);
122        noElems = noElems->bindLoc(elementV, nilV);
123      }
124
125    // Create the new nodes.
126    Bldr.generateNode(S, Pred, hasElems);
127    Bldr.generateNode(S, Pred, noElems);
128  }
129
130  // Finally, run any custom checkers.
131  // FIXME: Eventually all pre- and post-checks should live in VisitStmt.
132  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
133}
134
135static bool isSubclass(const ObjCInterfaceDecl *Class, IdentifierInfo *II) {
136  if (!Class)
137    return false;
138  if (Class->getIdentifier() == II)
139    return true;
140  return isSubclass(Class->getSuperClass(), II);
141}
142
143void ExprEngine::VisitObjCMessage(const ObjCMessage &msg,
144                                  ExplodedNode *Pred,
145                                  ExplodedNodeSet &Dst) {
146
147  // Handle the previsits checks.
148  ExplodedNodeSet dstPrevisit;
149  getCheckerManager().runCheckersForPreObjCMessage(dstPrevisit, Pred,
150                                                   msg, *this);
151
152  // Proceed with evaluate the message expression.
153  ExplodedNodeSet dstEval;
154  StmtNodeBuilder Bldr(dstPrevisit, dstEval, *currentBuilderContext);
155
156  for (ExplodedNodeSet::iterator DI = dstPrevisit.begin(),
157       DE = dstPrevisit.end(); DI != DE; ++DI) {
158
159    ExplodedNode *Pred = *DI;
160    bool RaisesException = false;
161
162    if (const Expr *Receiver = msg.getInstanceReceiver()) {
163      ProgramStateRef state = Pred->getState();
164      SVal recVal = state->getSVal(Receiver, Pred->getLocationContext());
165      if (!recVal.isUndef()) {
166        // Bifurcate the state into nil and non-nil ones.
167        DefinedOrUnknownSVal receiverVal = cast<DefinedOrUnknownSVal>(recVal);
168
169        ProgramStateRef notNilState, nilState;
170        llvm::tie(notNilState, nilState) = state->assume(receiverVal);
171
172        // There are three cases: can be nil or non-nil, must be nil, must be
173        // non-nil. We ignore must be nil, and merge the rest two into non-nil.
174        if (nilState && !notNilState) {
175          continue;
176        }
177
178        // Check if the "raise" message was sent.
179        assert(notNilState);
180        if (msg.getSelector() == RaiseSel)
181          RaisesException = true;
182
183        // If we raise an exception, for now treat it as a sink.
184        // Eventually we will want to handle exceptions properly.
185        // Dispatch to plug-in transfer function.
186        evalObjCMessage(Bldr, msg, Pred, notNilState, RaisesException);
187      }
188    } else if (const ObjCInterfaceDecl *Iface = msg.getReceiverInterface()) {
189      // Note that this branch also handles messages to super, not just
190      // class methods!
191
192      // Check for special class methods.
193      if (!msg.isInstanceMessage()) {
194        if (!NSExceptionII) {
195          ASTContext &Ctx = getContext();
196          NSExceptionII = &Ctx.Idents.get("NSException");
197        }
198
199        if (isSubclass(Iface, NSExceptionII)) {
200          enum { NUM_RAISE_SELECTORS = 2 };
201
202          // Lazily create a cache of the selectors.
203          if (!NSExceptionInstanceRaiseSelectors) {
204            ASTContext &Ctx = getContext();
205            NSExceptionInstanceRaiseSelectors =
206              new Selector[NUM_RAISE_SELECTORS];
207            SmallVector<IdentifierInfo*, NUM_RAISE_SELECTORS> II;
208            unsigned idx = 0;
209
210            // raise:format:
211            II.push_back(&Ctx.Idents.get("raise"));
212            II.push_back(&Ctx.Idents.get("format"));
213            NSExceptionInstanceRaiseSelectors[idx++] =
214              Ctx.Selectors.getSelector(II.size(), &II[0]);
215
216            // raise:format:arguments:
217            II.push_back(&Ctx.Idents.get("arguments"));
218            NSExceptionInstanceRaiseSelectors[idx++] =
219              Ctx.Selectors.getSelector(II.size(), &II[0]);
220          }
221
222          Selector S = msg.getSelector();
223          for (unsigned i = 0; i < NUM_RAISE_SELECTORS; ++i) {
224            if (S == NSExceptionInstanceRaiseSelectors[i]) {
225              RaisesException = true;
226              break;
227            }
228          }
229        }
230      }
231
232      // If we raise an exception, for now treat it as a sink.
233      // Eventually we will want to handle exceptions properly.
234      // Dispatch to plug-in transfer function.
235      evalObjCMessage(Bldr, msg, Pred, Pred->getState(), RaisesException);
236    }
237  }
238
239  // Finally, perform the post-condition check of the ObjCMessageExpr and store
240  // the created nodes in 'Dst'.
241  getCheckerManager().runCheckersForPostObjCMessage(Dst, dstEval, msg, *this);
242}
243
244void ExprEngine::evalObjCMessage(StmtNodeBuilder &Bldr,
245                                 const ObjCMessage &msg,
246                                 ExplodedNode *Pred,
247                                 ProgramStateRef state,
248                                 bool GenSink) {
249  // First handle the return value.
250  SVal ReturnValue = UnknownVal();
251
252  // Some method families have known return values.
253  switch (msg.getMethodFamily()) {
254  default:
255    break;
256  case OMF_autorelease:
257  case OMF_retain:
258  case OMF_self: {
259    // These methods return their receivers.
260    const Expr *ReceiverE = msg.getInstanceReceiver();
261    if (ReceiverE)
262      ReturnValue = state->getSVal(ReceiverE, Pred->getLocationContext());
263    break;
264  }
265  }
266
267  // If we failed to figure out the return value, use a conjured value instead.
268  if (ReturnValue.isUnknown()) {
269    SValBuilder &SVB = getSValBuilder();
270    QualType ResultTy = msg.getResultType(getContext());
271    unsigned Count = currentBuilderContext->getCurrentBlockCount();
272    const Expr *CurrentE = cast<Expr>(currentStmt);
273    const LocationContext *LCtx = Pred->getLocationContext();
274    ReturnValue = SVB.getConjuredSymbolVal(NULL, CurrentE, LCtx, ResultTy, Count);
275  }
276
277  // Bind the return value.
278  const LocationContext *LCtx = Pred->getLocationContext();
279  state = state->BindExpr(currentStmt, LCtx, ReturnValue);
280
281  // Invalidate the arguments (and the receiver)
282  state = invalidateArguments(state, CallOrObjCMessage(msg, state, LCtx), LCtx);
283
284  // And create the new node.
285  Bldr.generateNode(msg.getMessageExpr(), Pred, state, GenSink);
286  assert(Bldr.hasGeneratedNodes());
287}
288
289