clang 23.0.0git
ExprEngineObjC.cpp
Go to the documentation of this file.
1//=-- ExprEngineObjC.cpp - ExprEngine support for Objective-C ---*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines ExprEngine's support for Objective-C expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/StmtObjC.h"
17
18using namespace clang;
19using namespace ento;
20
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 NodeBuilder Bldr(Pred, dstIvar, *currBldrCtx);
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
43
44/// Generate a node in \p Bldr for an iteration statement using ObjC
45/// for-loop iterator.
47 SValBuilder &svalBuilder,
48 const ObjCForCollectionStmt *S,
50 SVal elementV, SymbolManager &SymMgr,
51 unsigned NumVisitedCurrent,
52 NodeBuilder &Bldr, bool hasElements) {
53
54 for (ExplodedNode *Pred : dstLocation) {
55 ProgramStateRef state = Pred->getState();
56 const LocationContext *LCtx = Pred->getLocationContext();
57
58 ProgramStateRef nextState =
59 ExprEngine::setWhetherHasMoreIteration(state, S, LCtx, hasElements);
60
61 if (auto MV = elementV.getAs<loc::MemRegionVal>())
62 if (const auto *R = dyn_cast<TypedValueRegion>(MV->getRegion())) {
63 // FIXME: The proper thing to do is to really iterate over the
64 // container. We will do this with dispatch logic to the store.
65 // For now, just 'conjure' up a symbolic value.
66 QualType T = R->getValueType();
67 assert(Loc::isLocType(T));
68
69 SVal V;
70 if (hasElements) {
71 SymbolRef Sym =
72 SymMgr.conjureSymbol(elem, LCtx, T, NumVisitedCurrent);
73 V = svalBuilder.makeLoc(Sym);
74 } else {
75 V = svalBuilder.makeIntVal(0, T);
76 }
77
78 nextState = nextState->bindLoc(elementV, V, LCtx);
79 }
80
81 Bldr.generateNode(S, Pred, nextState);
82 }
83}
84
86 ExplodedNode *Pred,
87 ExplodedNodeSet &Dst) {
88
89 // ObjCForCollectionStmts are processed in two places. This method
90 // handles the case where an ObjCForCollectionStmt* occurs as one of the
91 // statements within a basic block. This transfer function does two things:
92 //
93 // (1) binds the next container value to 'element'. This creates a new
94 // node in the ExplodedGraph.
95 //
96 // (2) note whether the collection has any more elements (or in other words,
97 // whether the loop has more iterations). This will be tested in
98 // processBranch.
99 //
100 // FIXME: Eventually this logic should actually do dispatches to
101 // 'countByEnumeratingWithState:objects:count:' (NSFastEnumeration).
102 // This will require simulating a temporary NSFastEnumerationState, either
103 // through an SVal or through the use of MemRegions. This value can
104 // be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop
105 // terminates we reclaim the temporary (it goes out of scope) and we
106 // we can test if the SVal is 0 or if the MemRegion is null (depending
107 // on what approach we take).
108 //
109 // For now: simulate (1) by assigning either a symbol or nil if the
110 // container is empty. Thus this transfer function will by default
111 // result in state splitting.
112
113 const Stmt *elem = S->getElement();
114 const Stmt *collection = S->getCollection();
115 const ConstCFGElementRef &elemRef = getCFGElementRef();
116 ProgramStateRef state = Pred->getState();
117 SVal collectionV = state->getSVal(collection, Pred->getLocationContext());
118
119 SVal elementV;
120 if (const auto *DS = dyn_cast<DeclStmt>(elem)) {
121 const VarDecl *elemD = cast<VarDecl>(DS->getSingleDecl());
122 assert(elemD->getInit() == nullptr);
123 elementV = state->getLValue(elemD, Pred->getLocationContext());
124 } else {
125 elementV = state->getSVal(elem, Pred->getLocationContext());
126 }
127
128 bool isContainerNull = state->isNull(collectionV).isConstrainedTrue();
129
130 ExplodedNodeSet DstLocation; // states in `DstLocation` may differ from `Pred`
131 evalLocation(DstLocation, S, elem, Pred, state, elementV, false);
132
133 for (ExplodedNode *dstLocation : DstLocation) {
134 ExplodedNodeSet DstLocationSingleton{dstLocation}, Tmp;
135 NodeBuilder Bldr(dstLocation, Tmp, *currBldrCtx);
136
137 if (!isContainerNull)
138 populateObjCForDestinationSet(DstLocationSingleton, svalBuilder, S,
139 elemRef, elementV, SymMgr,
140 getNumVisitedCurrent(), Bldr,
141 /*hasElements=*/true);
142
143 populateObjCForDestinationSet(DstLocationSingleton, svalBuilder, S, elemRef,
144 elementV, SymMgr, getNumVisitedCurrent(),
145 Bldr,
146 /*hasElements=*/false);
147
148 // Finally, run any custom checkers.
149 // FIXME: Eventually all pre- and post-checks should live in VisitStmt.
150 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
151 }
152}
153
155 ExplodedNode *Pred,
156 ExplodedNodeSet &Dst) {
159 ME, Pred->getState(), Pred->getLocationContext(), getCFGElementRef());
160
161 // There are three cases for the receiver:
162 // (1) it is definitely nil,
163 // (2) it is definitely non-nil, and
164 // (3) we don't know.
165 //
166 // If the receiver is definitely nil, we skip the pre/post callbacks and
167 // instead call the ObjCMessageNil callbacks and return.
168 //
169 // If the receiver is definitely non-nil, we call the pre- callbacks,
170 // evaluate the call, and call the post- callbacks.
171 //
172 // If we don't know, we drop the potential nil flow and instead
173 // continue from the assumed non-nil state as in (2). This approach
174 // intentionally drops coverage in order to prevent false alarms
175 // in the following scenario:
176 //
177 // id result = [o someMethod]
178 // if (result) {
179 // if (!o) {
180 // // <-- This program point should be unreachable because if o is nil
181 // // it must the case that result is nil as well.
182 // }
183 // }
184 //
185 // However, it also loses coverage of the nil path prematurely,
186 // leading to missed reports.
187 //
188 // It's possible to handle this by performing a state split on every call:
189 // explore the state where the receiver is non-nil, and independently
190 // explore the state where it's nil. But this is not only slow, but
191 // completely unwarranted. The mere presence of the message syntax in the code
192 // isn't sufficient evidence that nil is a realistic possibility.
193 //
194 // An ideal solution would be to add the following constraint that captures
195 // both possibilities without splitting the state:
196 //
197 // ($x == 0) => ($y == 0) (1)
198 //
199 // where in our case '$x' is the receiver symbol, '$y' is the returned symbol,
200 // and '=>' is logical implication. But RangeConstraintManager can't handle
201 // such constraints yet, so for now we go with a simpler, more restrictive
202 // constraint: $x != 0, from which (1) follows as a vacuous truth.
203 if (Msg->isInstanceMessage()) {
204 SVal recVal = Msg->getReceiverSVal();
205 if (!recVal.isUndef()) {
206 // Bifurcate the state into nil and non-nil ones.
207 DefinedOrUnknownSVal receiverVal =
209 ProgramStateRef State = Pred->getState();
210
211 ProgramStateRef notNilState, nilState;
212 std::tie(notNilState, nilState) = State->assume(receiverVal);
213
214 // Receiver is definitely nil, so run ObjCMessageNil callbacks and return.
215 if (nilState && !notNilState) {
216 ExplodedNodeSet dstNil;
217 NodeBuilder Bldr(Pred, dstNil, *currBldrCtx);
218 bool HasTag = Pred->getLocation().getTag();
219 Pred = Bldr.generateNode(ME, Pred, nilState, nullptr,
221 assert((Pred || HasTag) && "Should have cached out already!");
222 (void)HasTag;
223 if (!Pred)
224 return;
225
226 ExplodedNodeSet dstPostCheckers;
227 getCheckerManager().runCheckersForObjCMessageNil(dstPostCheckers, Pred,
228 *Msg, *this);
229 for (auto *I : dstPostCheckers)
230 finishArgumentConstruction(Dst, I, *Msg);
231 return;
232 }
233
234 ExplodedNodeSet dstNonNil;
235 NodeBuilder Bldr(Pred, dstNonNil, *currBldrCtx);
236 // Generate a transition to the non-nil state, dropping any potential
237 // nil flow.
238 if (notNilState != State) {
239 bool HasTag = Pred->getLocation().getTag();
240 Pred = Bldr.generateNode(ME, Pred, notNilState);
241 assert((Pred || HasTag) && "Should have cached out already!");
242 (void)HasTag;
243 if (!Pred)
244 return;
245 }
246 }
247 }
248
249 // Handle the previsits checks.
250 ExplodedNodeSet dstPrevisit;
252 *Msg, *this);
253 ExplodedNodeSet dstGenericPrevisit;
254 getCheckerManager().runCheckersForPreCall(dstGenericPrevisit, dstPrevisit,
255 *Msg, *this);
256
257 // Proceed with evaluate the message expression.
258 ExplodedNodeSet dstEval;
259 NodeBuilder Bldr(dstGenericPrevisit, dstEval, *currBldrCtx);
260
261 for (ExplodedNodeSet::iterator DI = dstGenericPrevisit.begin(),
262 DE = dstGenericPrevisit.end(); DI != DE; ++DI) {
263 ExplodedNode *Pred = *DI;
264 ProgramStateRef State = Pred->getState();
265 CallEventRef<ObjCMethodCall> UpdatedMsg = Msg.cloneWithState(State);
266
267 if (UpdatedMsg->isInstanceMessage()) {
268 SVal recVal = UpdatedMsg->getReceiverSVal();
269 if (!recVal.isUndef()) {
270 if (ObjCNoRet.isImplicitNoReturn(ME)) {
271 // If we raise an exception, for now treat it as a sink.
272 // Eventually we will want to handle exceptions properly.
273 Bldr.generateSink(ME, Pred, State);
274 continue;
275 }
276 }
277 } else {
278 // Check for special class methods that are known to not return
279 // and that we should treat as a sink.
280 if (ObjCNoRet.isImplicitNoReturn(ME)) {
281 // If we raise an exception, for now treat it as a sink.
282 // Eventually we will want to handle exceptions properly.
283 Bldr.generateSink(ME, Pred, Pred->getState());
284 continue;
285 }
286 }
287
288 defaultEvalCall(Bldr, Pred, *UpdatedMsg);
289 }
290
291 // If there were constructors called for object-type arguments, clean them up.
292 ExplodedNodeSet dstArgCleanup;
293 for (auto *I : dstEval)
294 finishArgumentConstruction(dstArgCleanup, I, *Msg);
295
296 ExplodedNodeSet dstPostvisit;
297 getCheckerManager().runCheckersForPostCall(dstPostvisit, dstArgCleanup,
298 *Msg, *this);
299
300 // Finally, perform the post-condition check of the ObjCMessageExpr and store
301 // the created nodes in 'Dst'.
303 *Msg, *this);
304}
#define V(N, I)
static void populateObjCForDestinationSet(ExplodedNodeSet &dstLocation, SValBuilder &svalBuilder, const ObjCForCollectionStmt *S, ConstCFGElementRef elem, SVal elementV, SymbolManager &SymMgr, unsigned NumVisitedCurrent, NodeBuilder &Bldr, bool hasElements)
Generate a node in Bldr for an iteration statement using ObjC for-loop iterator.
Defines the Objective-C statement AST node classes.
It wraps the AnalysisDeclContext to represent both the call stack with the help of StackFrameContext ...
Represents Objective-C's @synchronized statement.
Definition StmtObjC.h:303
Represents Objective-C's collection statement.
Definition StmtObjC.h:23
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:546
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:576
const Expr * getBase() const
Definition ExprObjC.h:580
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:937
const ProgramPointTag * getTag() const
A (possibly-)qualified type.
Definition TypeBase.h:937
Stmt - This represents one statement.
Definition Stmt.h:86
Represents a variable declaration or definition.
Definition Decl.h:926
const Expr * getInit() const
Definition Decl.h:1368
Manages the lifetime of CallEvent objects.
Definition CallEvent.h:1374
CallEventRef< ObjCMethodCall > getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1445
CallEventRef< T > cloneWithState(ProgramStateRef State) const
Definition CallEvent.h:92
void runCheckersForPreObjCMessage(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const ObjCMethodCall &msg, ExprEngine &Eng)
Run checkers for pre-visiting obj-c messages.
void runCheckersForPreCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng)
Run checkers for pre-visiting obj-c messages.
void runCheckersForPostObjCMessage(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const ObjCMethodCall &msg, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting obj-c messages.
void runCheckersForPostStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting Stmts.
void runCheckersForPreStmt(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const Stmt *S, ExprEngine &Eng)
Run checkers for pre-visiting Stmts.
void runCheckersForObjCMessageNil(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const ObjCMethodCall &msg, ExprEngine &Eng)
Run checkers for visiting an obj-c message to nil.
void runCheckersForPostCall(ExplodedNodeSet &Dst, const ExplodedNodeSet &Src, const CallEvent &Call, ExprEngine &Eng, bool wasInlined=false)
Run checkers for post-visiting obj-c messages.
const ProgramStateRef & getState() const
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
const LocationContext * getLocationContext() const
ProgramStateManager & getStateManager()
Definition ExprEngine.h:477
void VisitObjCMessage(const ObjCMessageExpr *ME, ExplodedNode *Pred, ExplodedNodeSet &Dst)
void VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for ObjCAtSynchronizedStmts.
void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst)
VisitObjCForCollectionStmt - Transfer function logic for ObjCForCollectionStmt.
void VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *DR, ExplodedNode *Pred, ExplodedNodeSet &Dst)
Transfer function logic for computing the lvalue of an Objective-C ivar.
ConstCFGElementRef getCFGElementRef() const
Definition ExprEngine.h:289
CheckerManager & getCheckerManager() const
Definition ExprEngine.h:226
unsigned getNumVisitedCurrent() const
Definition ExprEngine.h:299
void defaultEvalCall(NodeBuilder &B, ExplodedNode *Pred, const CallEvent &Call, const EvalCallOptions &CallOpts={})
Default implementation of call evaluation.
static ProgramStateRef setWhetherHasMoreIteration(ProgramStateRef State, const ObjCForCollectionStmt *O, const LocationContext *LC, bool HasMoreIteraton)
Note whether this loop has any more iterations to model. These methods.
static bool isLocType(QualType T)
Definition SVals.h:262
This is the simplest builder which generates nodes in the ExplodedGraph.
Definition CoreEngine.h:246
ExplodedNode * generateNode(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred, bool MarkAsSink=false)
Generates a node in the ExplodedGraph.
ExplodedNode * generateSink(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred)
Generates a sink in the ExplodedGraph.
Definition CoreEngine.h:281
CallEventManager & getCallEventManager()
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
loc::MemRegionVal makeLoc(SymbolRef sym)
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:56
bool isUndef() const
Definition SVals.h:107
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition SVals.h:87
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition SVals.h:83
const SymbolConjured * conjureSymbol(ConstCFGElementRef Elem, const LocationContext *LCtx, QualType T, unsigned VisitCount, const void *SymbolTag=nullptr)
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:133
The JSON file list parser is used to communicate input to InstallAPI.
CFGBlock::ConstCFGElementRef ConstCFGElementRef
Definition CFG.h:1227
U cast(CodeGen::Address addr)
Definition Address.h:327