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