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 const NodeBuilderContext *currBldrCtx,
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, currBldrCtx->blockCount());
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, currBldrCtx,
140 Bldr,
141 /*hasElements=*/true);
142
143 populateObjCForDestinationSet(DstLocationSingleton, svalBuilder, S, elemRef,
144 elementV, SymMgr, currBldrCtx, Bldr,
145 /*hasElements=*/false);
146
147 // Finally, run any custom checkers.
148 // FIXME: Eventually all pre- and post-checks should live in VisitStmt.
149 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
150 }
151}
152
154 ExplodedNode *Pred,
155 ExplodedNodeSet &Dst) {
158 ME, Pred->getState(), Pred->getLocationContext(), getCFGElementRef());
159
160 // There are three cases for the receiver:
161 // (1) it is definitely nil,
162 // (2) it is definitely non-nil, and
163 // (3) we don't know.
164 //
165 // If the receiver is definitely nil, we skip the pre/post callbacks and
166 // instead call the ObjCMessageNil callbacks and return.
167 //
168 // If the receiver is definitely non-nil, we call the pre- callbacks,
169 // evaluate the call, and call the post- callbacks.
170 //
171 // If we don't know, we drop the potential nil flow and instead
172 // continue from the assumed non-nil state as in (2). This approach
173 // intentionally drops coverage in order to prevent false alarms
174 // in the following scenario:
175 //
176 // id result = [o someMethod]
177 // if (result) {
178 // if (!o) {
179 // // <-- This program point should be unreachable because if o is nil
180 // // it must the case that result is nil as well.
181 // }
182 // }
183 //
184 // However, it also loses coverage of the nil path prematurely,
185 // leading to missed reports.
186 //
187 // It's possible to handle this by performing a state split on every call:
188 // explore the state where the receiver is non-nil, and independently
189 // explore the state where it's nil. But this is not only slow, but
190 // completely unwarranted. The mere presence of the message syntax in the code
191 // isn't sufficient evidence that nil is a realistic possibility.
192 //
193 // An ideal solution would be to add the following constraint that captures
194 // both possibilities without splitting the state:
195 //
196 // ($x == 0) => ($y == 0) (1)
197 //
198 // where in our case '$x' is the receiver symbol, '$y' is the returned symbol,
199 // and '=>' is logical implication. But RangeConstraintManager can't handle
200 // such constraints yet, so for now we go with a simpler, more restrictive
201 // constraint: $x != 0, from which (1) follows as a vacuous truth.
202 if (Msg->isInstanceMessage()) {
203 SVal recVal = Msg->getReceiverSVal();
204 if (!recVal.isUndef()) {
205 // Bifurcate the state into nil and non-nil ones.
206 DefinedOrUnknownSVal receiverVal =
208 ProgramStateRef State = Pred->getState();
209
210 ProgramStateRef notNilState, nilState;
211 std::tie(notNilState, nilState) = State->assume(receiverVal);
212
213 // Receiver is definitely nil, so run ObjCMessageNil callbacks and return.
214 if (nilState && !notNilState) {
215 ExplodedNodeSet dstNil;
216 NodeBuilder Bldr(Pred, dstNil, *currBldrCtx);
217 bool HasTag = Pred->getLocation().getTag();
218 Pred = Bldr.generateNode(ME, Pred, nilState, nullptr,
220 assert((Pred || HasTag) && "Should have cached out already!");
221 (void)HasTag;
222 if (!Pred)
223 return;
224
225 ExplodedNodeSet dstPostCheckers;
226 getCheckerManager().runCheckersForObjCMessageNil(dstPostCheckers, Pred,
227 *Msg, *this);
228 for (auto *I : dstPostCheckers)
229 finishArgumentConstruction(Dst, I, *Msg);
230 return;
231 }
232
233 ExplodedNodeSet dstNonNil;
234 NodeBuilder Bldr(Pred, dstNonNil, *currBldrCtx);
235 // Generate a transition to the non-nil state, dropping any potential
236 // nil flow.
237 if (notNilState != State) {
238 bool HasTag = Pred->getLocation().getTag();
239 Pred = Bldr.generateNode(ME, Pred, notNilState);
240 assert((Pred || HasTag) && "Should have cached out already!");
241 (void)HasTag;
242 if (!Pred)
243 return;
244 }
245 }
246 }
247
248 // Handle the previsits checks.
249 ExplodedNodeSet dstPrevisit;
251 *Msg, *this);
252 ExplodedNodeSet dstGenericPrevisit;
253 getCheckerManager().runCheckersForPreCall(dstGenericPrevisit, dstPrevisit,
254 *Msg, *this);
255
256 // Proceed with evaluate the message expression.
257 ExplodedNodeSet dstEval;
258 NodeBuilder Bldr(dstGenericPrevisit, dstEval, *currBldrCtx);
259
260 for (ExplodedNodeSet::iterator DI = dstGenericPrevisit.begin(),
261 DE = dstGenericPrevisit.end(); DI != DE; ++DI) {
262 ExplodedNode *Pred = *DI;
263 ProgramStateRef State = Pred->getState();
264 CallEventRef<ObjCMethodCall> UpdatedMsg = Msg.cloneWithState(State);
265
266 if (UpdatedMsg->isInstanceMessage()) {
267 SVal recVal = UpdatedMsg->getReceiverSVal();
268 if (!recVal.isUndef()) {
269 if (ObjCNoRet.isImplicitNoReturn(ME)) {
270 // If we raise an exception, for now treat it as a sink.
271 // Eventually we will want to handle exceptions properly.
272 Bldr.generateSink(ME, Pred, State);
273 continue;
274 }
275 }
276 } else {
277 // Check for special class methods that are known to not return
278 // and that we should treat as a sink.
279 if (ObjCNoRet.isImplicitNoReturn(ME)) {
280 // If we raise an exception, for now treat it as a sink.
281 // Eventually we will want to handle exceptions properly.
282 Bldr.generateSink(ME, Pred, Pred->getState());
283 continue;
284 }
285 }
286
287 defaultEvalCall(Bldr, Pred, *UpdatedMsg);
288 }
289
290 // If there were constructors called for object-type arguments, clean them up.
291 ExplodedNodeSet dstArgCleanup;
292 for (auto *I : dstEval)
293 finishArgumentConstruction(dstArgCleanup, I, *Msg);
294
295 ExplodedNodeSet dstPostvisit;
296 getCheckerManager().runCheckersForPostCall(dstPostvisit, dstArgCleanup,
297 *Msg, *this);
298
299 // Finally, perform the post-condition check of the ObjCMessageExpr and store
300 // the created nodes in 'Dst'.
302 *Msg, *this);
303}
#define V(N, I)
static void populateObjCForDestinationSet(ExplodedNodeSet &dstLocation, SValBuilder &svalBuilder, const ObjCForCollectionStmt *S, ConstCFGElementRef elem, SVal elementV, SymbolManager &SymMgr, const NodeBuilderContext *currBldrCtx, 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:421
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:231
CheckerManager & getCheckerManager() const
Definition ExprEngine.h:204
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
unsigned blockCount() const
Returns the number of times the current basic block has been visited on the exploded graph path.
Definition CoreEngine.h:222
This is the simplest builder which generates nodes in the ExplodedGraph.
Definition CoreEngine.h:238
ExplodedNode * generateNode(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred)
Generates a node in the ExplodedGraph.
Definition CoreEngine.h:270
ExplodedNode * generateSink(const ProgramPoint &PP, ProgramStateRef State, ExplodedNode *Pred)
Generates a sink in the ExplodedGraph.
Definition CoreEngine.h:283
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