clang  8.0.0svn
ExprEngineObjC.cpp
Go to the documentation of this file.
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"
18 
19 using namespace clang;
20 using namespace ento;
21 
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, *currBldrCtx);
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 
40  ExplodedNode *Pred,
41  ExplodedNodeSet &Dst) {
42  getCheckerManager().runCheckersForPreStmt(Dst, Pred, S, *this);
43 }
44 
45 /// Generate a node in \p Bldr for an iteration statement using ObjC
46 /// for-loop iterator.
48  ExplodedNodeSet &dstLocation, SValBuilder &svalBuilder,
49  const ObjCForCollectionStmt *S, const Stmt *elem, SVal elementV,
50  SymbolManager &SymMgr, const NodeBuilderContext *currBldrCtx,
51  StmtNodeBuilder &Bldr, bool hasElements) {
52 
53  for (ExplodedNode *Pred : dstLocation) {
54  ProgramStateRef state = Pred->getState();
55  const LocationContext *LCtx = Pred->getLocationContext();
56 
57  SVal hasElementsV = svalBuilder.makeTruthVal(hasElements);
58 
59  // FIXME: S is not an expression. We should not be binding values to it.
60  ProgramStateRef nextState = state->BindExpr(S, LCtx, hasElementsV);
61 
62  if (auto MV = elementV.getAs<loc::MemRegionVal>())
63  if (const auto *R = dyn_cast<TypedValueRegion>(MV->getRegion())) {
64  // FIXME: The proper thing to do is to really iterate over the
65  // container. We will do this with dispatch logic to the store.
66  // For now, just 'conjure' up a symbolic value.
67  QualType T = R->getValueType();
68  assert(Loc::isLocType(T));
69 
70  SVal V;
71  if (hasElements) {
72  SymbolRef Sym = SymMgr.conjureSymbol(elem, LCtx, T,
73  currBldrCtx->blockCount());
74  V = svalBuilder.makeLoc(Sym);
75  } else {
76  V = svalBuilder.makeIntVal(0, T);
77  }
78 
79  nextState = nextState->bindLoc(elementV, V, LCtx);
80  }
81 
82  Bldr.generateNode(S, Pred, nextState);
83  }
84 }
85 
87  ExplodedNode *Pred,
88  ExplodedNodeSet &Dst) {
89 
90  // ObjCForCollectionStmts are processed in two places. This method
91  // handles the case where an ObjCForCollectionStmt* occurs as one of the
92  // statements within a basic block. This transfer function does two things:
93  //
94  // (1) binds the next container value to 'element'. This creates a new
95  // node in the ExplodedGraph.
96  //
97  // (2) binds the value 0/1 to the ObjCForCollectionStmt* itself, indicating
98  // whether or not the container has any more elements. This value
99  // will be tested in ProcessBranch. We need to explicitly bind
100  // this value because a container can contain nil elements.
101  //
102  // FIXME: Eventually this logic should actually do dispatches to
103  // 'countByEnumeratingWithState:objects:count:' (NSFastEnumeration).
104  // This will require simulating a temporary NSFastEnumerationState, either
105  // through an SVal or through the use of MemRegions. This value can
106  // be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop
107  // terminates we reclaim the temporary (it goes out of scope) and we
108  // we can test if the SVal is 0 or if the MemRegion is null (depending
109  // on what approach we take).
110  //
111  // For now: simulate (1) by assigning either a symbol or nil if the
112  // container is empty. Thus this transfer function will by default
113  // result in state splitting.
114 
115  const Stmt *elem = S->getElement();
116  const Stmt *collection = S->getCollection();
117  ProgramStateRef state = Pred->getState();
118  SVal collectionV = state->getSVal(collection, Pred->getLocationContext());
119 
120  SVal elementV;
121  if (const auto *DS = dyn_cast<DeclStmt>(elem)) {
122  const VarDecl *elemD = cast<VarDecl>(DS->getSingleDecl());
123  assert(elemD->getInit() == nullptr);
124  elementV = state->getLValue(elemD, Pred->getLocationContext());
125  } else {
126  elementV = state->getSVal(elem, Pred->getLocationContext());
127  }
128 
129  bool isContainerNull = state->isNull(collectionV).isConstrainedTrue();
130 
131  ExplodedNodeSet dstLocation;
132  evalLocation(dstLocation, S, elem, Pred, state, elementV, nullptr, false);
133 
134  ExplodedNodeSet Tmp;
135  StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
136 
137  if (!isContainerNull)
138  populateObjCForDestinationSet(dstLocation, svalBuilder, S, elem, elementV,
139  SymMgr, currBldrCtx, Bldr,
140  /*hasElements=*/true);
141 
142  populateObjCForDestinationSet(dstLocation, svalBuilder, S, elem, elementV,
143  SymMgr, currBldrCtx, Bldr,
144  /*hasElements=*/false);
145 
146  // Finally, run any custom checkers.
147  // FIXME: Eventually all pre- and post-checks should live in VisitStmt.
148  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
149 }
150 
152  ExplodedNode *Pred,
153  ExplodedNodeSet &Dst) {
156  CEMgr.getObjCMethodCall(ME, Pred->getState(), Pred->getLocationContext());
157 
158  // There are three cases for the receiver:
159  // (1) it is definitely nil,
160  // (2) it is definitely non-nil, and
161  // (3) we don't know.
162  //
163  // If the receiver is definitely nil, we skip the pre/post callbacks and
164  // instead call the ObjCMessageNil callbacks and return.
165  //
166  // If the receiver is definitely non-nil, we call the pre- callbacks,
167  // evaluate the call, and call the post- callbacks.
168  //
169  // If we don't know, we drop the potential nil flow and instead
170  // continue from the assumed non-nil state as in (2). This approach
171  // intentionally drops coverage in order to prevent false alarms
172  // in the following scenario:
173  //
174  // id result = [o someMethod]
175  // if (result) {
176  // if (!o) {
177  // // <-- This program point should be unreachable because if o is nil
178  // // it must the case that result is nil as well.
179  // }
180  // }
181  //
182  // We could avoid dropping coverage by performing an explicit case split
183  // on each method call -- but this would get very expensive. An alternative
184  // would be to introduce lazy constraints.
185  // FIXME: This ignores many potential bugs (<rdar://problem/11733396>).
186  // Revisit once we have lazier constraints.
187  if (Msg->isInstanceMessage()) {
188  SVal recVal = Msg->getReceiverSVal();
189  if (!recVal.isUndef()) {
190  // Bifurcate the state into nil and non-nil ones.
191  DefinedOrUnknownSVal receiverVal =
192  recVal.castAs<DefinedOrUnknownSVal>();
193  ProgramStateRef State = Pred->getState();
194 
195  ProgramStateRef notNilState, nilState;
196  std::tie(notNilState, nilState) = State->assume(receiverVal);
197 
198  // Receiver is definitely nil, so run ObjCMessageNil callbacks and return.
199  if (nilState && !notNilState) {
200  ExplodedNodeSet dstNil;
201  StmtNodeBuilder Bldr(Pred, dstNil, *currBldrCtx);
202  bool HasTag = Pred->getLocation().getTag();
203  Pred = Bldr.generateNode(ME, Pred, nilState, nullptr,
205  assert((Pred || HasTag) && "Should have cached out already!");
206  (void)HasTag;
207  if (!Pred)
208  return;
209 
210  ExplodedNodeSet dstPostCheckers;
211  getCheckerManager().runCheckersForObjCMessageNil(dstPostCheckers, Pred,
212  *Msg, *this);
213  for (auto I : dstPostCheckers)
214  finishArgumentConstruction(Dst, I, *Msg);
215  return;
216  }
217 
218  ExplodedNodeSet dstNonNil;
219  StmtNodeBuilder Bldr(Pred, dstNonNil, *currBldrCtx);
220  // Generate a transition to the non-nil state, dropping any potential
221  // nil flow.
222  if (notNilState != State) {
223  bool HasTag = Pred->getLocation().getTag();
224  Pred = Bldr.generateNode(ME, Pred, notNilState);
225  assert((Pred || HasTag) && "Should have cached out already!");
226  (void)HasTag;
227  if (!Pred)
228  return;
229  }
230  }
231  }
232 
233  // Handle the previsits checks.
234  ExplodedNodeSet dstPrevisit;
236  *Msg, *this);
237  ExplodedNodeSet dstGenericPrevisit;
238  getCheckerManager().runCheckersForPreCall(dstGenericPrevisit, dstPrevisit,
239  *Msg, *this);
240 
241  // Proceed with evaluate the message expression.
242  ExplodedNodeSet dstEval;
243  StmtNodeBuilder Bldr(dstGenericPrevisit, dstEval, *currBldrCtx);
244 
245  for (ExplodedNodeSet::iterator DI = dstGenericPrevisit.begin(),
246  DE = dstGenericPrevisit.end(); DI != DE; ++DI) {
247  ExplodedNode *Pred = *DI;
248  ProgramStateRef State = Pred->getState();
249  CallEventRef<ObjCMethodCall> UpdatedMsg = Msg.cloneWithState(State);
250 
251  if (UpdatedMsg->isInstanceMessage()) {
252  SVal recVal = UpdatedMsg->getReceiverSVal();
253  if (!recVal.isUndef()) {
254  if (ObjCNoRet.isImplicitNoReturn(ME)) {
255  // If we raise an exception, for now treat it as a sink.
256  // Eventually we will want to handle exceptions properly.
257  Bldr.generateSink(ME, Pred, State);
258  continue;
259  }
260  }
261  } else {
262  // Check for special class methods that are known to not return
263  // and that we should treat as a sink.
264  if (ObjCNoRet.isImplicitNoReturn(ME)) {
265  // If we raise an exception, for now treat it as a sink.
266  // Eventually we will want to handle exceptions properly.
267  Bldr.generateSink(ME, Pred, Pred->getState());
268  continue;
269  }
270  }
271 
272  defaultEvalCall(Bldr, Pred, *UpdatedMsg);
273  }
274 
275  // If there were constructors called for object-type arguments, clean them up.
276  ExplodedNodeSet dstArgCleanup;
277  for (auto I : dstEval)
278  finishArgumentConstruction(dstArgCleanup, I, *Msg);
279 
280  ExplodedNodeSet dstPostvisit;
281  getCheckerManager().runCheckersForPostCall(dstPostvisit, dstArgCleanup,
282  *Msg, *this);
283 
284  // Finally, perform the post-condition check of the ObjCMessageExpr and store
285  // the created nodes in 'Dst'.
287  *Msg, *this);
288 }
A (possibly-)qualified type.
Definition: Type.h:642
const SymExpr * SymbolRef
Stmt - This represents one statement.
Definition: Stmt.h:66
This builder class is useful for generating nodes that resulted from visiting a statement.
Definition: CoreEngine.h:370
Manages the lifetime of CallEvent objects.
Definition: CallEvent.h:1083
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const ProgramStateRef & getState() const
Represents a variable declaration or definition.
Definition: Decl.h:812
Defines the Objective-C statement AST node classes.
void runCheckersForObjCMessageNil(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const ObjCMethodCall &msg, ExprEngine &Eng)
Run checkers for visiting an obj-c message to nil.
LineState State
static void populateObjCForDestinationSet(ExplodedNodeSet &dstLocation, SValBuilder &svalBuilder, const ObjCForCollectionStmt *S, const Stmt *elem, SVal elementV, SymbolManager &SymMgr, const NodeBuilderContext *currBldrCtx, StmtNodeBuilder &Bldr, bool hasElements)
Generate a node in Bldr for an iteration statement using ObjC for-loop iterator.
void runCheckersForPostObjCMessage(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const ObjCMethodCall &msg, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting obj-c messages.
i32 captured_struct **param SharedsTy A type which contains references the shared variables *param Shareds Context with the list of shared variables from the p *TaskFunction *param Data Additional data for task generation like final * state
static bool isLocType(QualType T)
Definition: SVals.h:327
ExplodedNode * generateSink(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition: CoreEngine.h:409
void runCheckersForPreCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng)
Run checkers for pre-visiting obj-c messages.
const LocationContext * getLocationContext() const
void runCheckersForPostCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting obj-c messages.
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:543
CheckerManager & getCheckerManager() const
Definition: ExprEngine.h:183
void runCheckersForPostStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting Stmts.
void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for computing the lvalue of an Objective-C ivar.
void runCheckersForPreObjCMessage(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const ObjCMethodCall &msg, ExprEngine &Eng)
Run checkers for pre-visiting obj-c messages.
Represents Objective-C&#39;s @synchronized statement.
Definition: StmtObjC.h:262
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:904
CallEventRef< ObjCMethodCall > getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State, const LocationContext *LCtx)
Definition: CallEvent.h:1145
CallEventManager & getCallEventManager()
Definition: ProgramState.h:571
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
SVal - This represents a symbolic expression, which can be either an L-value or an R-value...
Definition: SVals.h:76
void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitObjCForCollectionStmt - Transfer function logic for ObjCForCollectionStmt.
void runCheckersForPreStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng)
Run checkers for pre-visiting Stmts.
Dataflow Directional Tag Classes.
const Expr * getInit() const
Definition: Decl.h:1217
const ProgramPointTag * getTag() const
Definition: ProgramPoint.h:179
ProgramStateManager & getStateManager() override
Definition: ExprEngine.h:365
void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred, const CallEvent &Call, const EvalCallOptions &CallOpts={})
Default implementation of call evaluation.
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:104
bool isImplicitNoReturn(const ObjCMessageExpr *ME)
Return true if the given message expression is known to never return.
Represents Objective-C&#39;s collection statement.
Definition: StmtObjC.h:24
void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for ObjCAtSynchronizedStmts.
void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
const Expr * getBase() const
Definition: ExprObjC.h:547
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:513
ExplodedNode * generateNode(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition: CoreEngine.h:399
bool isUndef() const
Definition: SVals.h:141
CallEventRef< T > cloneWithState(ProgramStateRef State) const
Definition: CallEvent.h:126