clang  6.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 
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() == nullptr);
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, nullptr, false);
89 
90  ExplodedNodeSet Tmp;
91  StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
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 
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  SymbolRef Sym = SymMgr.conjureSymbol(elem, LCtx, T,
116  currBldrCtx->blockCount());
117  SVal V = svalBuilder.makeLoc(Sym);
118  hasElems = hasElems->bindLoc(elementV, V, LCtx);
119 
120  // Bind the location to 'nil' on the false branch.
121  SVal nilV = svalBuilder.makeIntVal(0, T);
122  noElems = noElems->bindLoc(elementV, nilV, LCtx);
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 
136  ExplodedNode *Pred,
137  ExplodedNodeSet &Dst) {
140  CEMgr.getObjCMethodCall(ME, Pred->getState(), Pred->getLocationContext());
141 
142  // There are three cases for the receiver:
143  // (1) it is definitely nil,
144  // (2) it is definitely non-nil, and
145  // (3) we don't know.
146  //
147  // If the receiver is definitely nil, we skip the pre/post callbacks and
148  // instead call the ObjCMessageNil callbacks and return.
149  //
150  // If the receiver is definitely non-nil, we call the pre- callbacks,
151  // evaluate the call, and call the post- callbacks.
152  //
153  // If we don't know, we drop the potential nil flow and instead
154  // continue from the assumed non-nil state as in (2). This approach
155  // intentionally drops coverage in order to prevent false alarms
156  // in the following scenario:
157  //
158  // id result = [o someMethod]
159  // if (result) {
160  // if (!o) {
161  // // <-- This program point should be unreachable because if o is nil
162  // // it must the case that result is nil as well.
163  // }
164  // }
165  //
166  // We could avoid dropping coverage by performing an explicit case split
167  // on each method call -- but this would get very expensive. An alternative
168  // would be to introduce lazy constraints.
169  // FIXME: This ignores many potential bugs (<rdar://problem/11733396>).
170  // Revisit once we have lazier constraints.
171  if (Msg->isInstanceMessage()) {
172  SVal recVal = Msg->getReceiverSVal();
173  if (!recVal.isUndef()) {
174  // Bifurcate the state into nil and non-nil ones.
175  DefinedOrUnknownSVal receiverVal =
176  recVal.castAs<DefinedOrUnknownSVal>();
177  ProgramStateRef State = Pred->getState();
178 
179  ProgramStateRef notNilState, nilState;
180  std::tie(notNilState, nilState) = State->assume(receiverVal);
181 
182  // Receiver is definitely nil, so run ObjCMessageNil callbacks and return.
183  if (nilState && !notNilState) {
184  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
185  bool HasTag = Pred->getLocation().getTag();
186  Pred = Bldr.generateNode(ME, Pred, nilState, nullptr,
188  assert((Pred || HasTag) && "Should have cached out already!");
189  (void)HasTag;
190  if (!Pred)
191  return;
193  *Msg, *this);
194  return;
195  }
196 
197  ExplodedNodeSet dstNonNil;
198  StmtNodeBuilder Bldr(Pred, dstNonNil, *currBldrCtx);
199  // Generate a transition to the non-nil state, dropping any potential
200  // nil flow.
201  if (notNilState != State) {
202  bool HasTag = Pred->getLocation().getTag();
203  Pred = Bldr.generateNode(ME, Pred, notNilState);
204  assert((Pred || HasTag) && "Should have cached out already!");
205  (void)HasTag;
206  if (!Pred)
207  return;
208  }
209  }
210  }
211 
212  // Handle the previsits checks.
213  ExplodedNodeSet dstPrevisit;
215  *Msg, *this);
216  ExplodedNodeSet dstGenericPrevisit;
217  getCheckerManager().runCheckersForPreCall(dstGenericPrevisit, dstPrevisit,
218  *Msg, *this);
219 
220  // Proceed with evaluate the message expression.
221  ExplodedNodeSet dstEval;
222  StmtNodeBuilder Bldr(dstGenericPrevisit, dstEval, *currBldrCtx);
223 
224  for (ExplodedNodeSet::iterator DI = dstGenericPrevisit.begin(),
225  DE = dstGenericPrevisit.end(); DI != DE; ++DI) {
226  ExplodedNode *Pred = *DI;
227  ProgramStateRef State = Pred->getState();
228  CallEventRef<ObjCMethodCall> UpdatedMsg = Msg.cloneWithState(State);
229 
230  if (UpdatedMsg->isInstanceMessage()) {
231  SVal recVal = UpdatedMsg->getReceiverSVal();
232  if (!recVal.isUndef()) {
233  if (ObjCNoRet.isImplicitNoReturn(ME)) {
234  // If we raise an exception, for now treat it as a sink.
235  // Eventually we will want to handle exceptions properly.
236  Bldr.generateSink(ME, Pred, State);
237  continue;
238  }
239  }
240  } else {
241  // Check for special class methods that are known to not return
242  // and that we should treat as a sink.
243  if (ObjCNoRet.isImplicitNoReturn(ME)) {
244  // If we raise an exception, for now treat it as a sink.
245  // Eventually we will want to handle exceptions properly.
246  Bldr.generateSink(ME, Pred, Pred->getState());
247  continue;
248  }
249  }
250 
251  defaultEvalCall(Bldr, Pred, *UpdatedMsg);
252  }
253 
254  ExplodedNodeSet dstPostvisit;
255  getCheckerManager().runCheckersForPostCall(dstPostvisit, dstEval,
256  *Msg, *this);
257 
258  // Finally, perform the post-condition check of the ObjCMessageExpr and store
259  // the created nodes in 'Dst'.
261  *Msg, *this);
262 }
TypedValueRegion - An abstract class representing regions having a typed value.
Definition: MemRegion.h:511
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
Definition: SValBuilder.h:254
A (possibly-)qualified type.
Definition: Type.h:614
unsigned blockCount() const
Returns the number of times the current basic block has been visited on the exploded graph path...
Definition: CoreEngine.h:195
Stmt - This represents one statement.
Definition: Stmt.h:60
This builder class is useful for generating nodes that resulted from visiting a statement.
Definition: CoreEngine.h:349
Manages the lifetime of CallEvent objects.
Definition: CallEvent.h:982
const ProgramStateRef & getState() const
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:771
Defines the Objective-C statement AST node classes.
Symbolic value.
Definition: SymExpr.h:29
void runCheckersForObjCMessageNil(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const ObjCMethodCall &msg, ExprEngine &Eng)
Run checkers for visiting an obj-c message to nil.
LineState State
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:307
ExplodedNode * generateSink(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition: CoreEngine.h:389
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:505
CheckerManager & getCheckerManager() const
Definition: ExprEngine.h:127
Loc makeLoc(SymbolRef sym)
Definition: SValBuilder.h:329
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.
const FunctionProtoType * T
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:860
CallEventRef< ObjCMethodCall > getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State, const LocationContext *LCtx)
Definition: CallEvent.h:1045
Optional< T > getAs() const
Convert to the specified SVal type, returning None if this SVal is not of the desired type...
Definition: SVals.h:100
CallEventManager & getCallEventManager()
Definition: ProgramState.h:527
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:467
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:63
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:1159
const ProgramPointTag * getTag() const
Definition: ProgramPoint.h:177
const SymbolConjured * conjureSymbol(const Stmt *E, const LocationContext *LCtx, QualType T, unsigned VisitCount, const void *SymbolTag=nullptr)
ProgramStateManager & getStateManager() override
Definition: ExprEngine.h:305
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:92
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:509
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:479
void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred, const CallEvent &Call)
Default implementation of call evaluation.
ExplodedNode * generateNode(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition: CoreEngine.h:379
bool isUndef() const
Definition: SVals.h:132
nonloc::ConcreteInt makeTruthVal(bool b, QualType type)
Definition: SValBuilder.h:310
CallEventRef< T > cloneWithState(ProgramStateRef State) const
Definition: CallEvent.h:85