clang 21.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 StmtNodeBuilder 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
39 ExplodedNode *Pred,
40 ExplodedNodeSet &Dst) {
41 getCheckerManager().runCheckersForPreStmt(Dst, Pred, S, *this);
42}
43
44/// Generate a node in \p Bldr for an iteration statement using ObjC
45/// for-loop iterator.
47 ExplodedNodeSet &dstLocation, SValBuilder &svalBuilder,
48 const ObjCForCollectionStmt *S, const Stmt *elem, SVal elementV,
49 SymbolManager &SymMgr, const NodeBuilderContext *currBldrCtx,
50 StmtNodeBuilder &Bldr, bool hasElements) {
51
52 for (ExplodedNode *Pred : dstLocation) {
53 ProgramStateRef state = Pred->getState();
54 const LocationContext *LCtx = Pred->getLocationContext();
55
56 ProgramStateRef nextState =
57 ExprEngine::setWhetherHasMoreIteration(state, S, LCtx, hasElements);
58
59 if (auto MV = elementV.getAs<loc::MemRegionVal>())
60 if (const auto *R = dyn_cast<TypedValueRegion>(MV->getRegion())) {
61 // FIXME: The proper thing to do is to really iterate over the
62 // container. We will do this with dispatch logic to the store.
63 // For now, just 'conjure' up a symbolic value.
64 QualType T = R->getValueType();
65 assert(Loc::isLocType(T));
66
67 SVal V;
68 if (hasElements) {
69 SymbolRef Sym = SymMgr.conjureSymbol(elem, LCtx, T,
70 currBldrCtx->blockCount());
71 V = svalBuilder.makeLoc(Sym);
72 } else {
73 V = svalBuilder.makeIntVal(0, T);
74 }
75
76 nextState = nextState->bindLoc(elementV, V, LCtx);
77 }
78
79 Bldr.generateNode(S, Pred, nextState);
80 }
81}
82
84 ExplodedNode *Pred,
85 ExplodedNodeSet &Dst) {
86
87 // ObjCForCollectionStmts are processed in two places. This method
88 // handles the case where an ObjCForCollectionStmt* occurs as one of the
89 // statements within a basic block. This transfer function does two things:
90 //
91 // (1) binds the next container value to 'element'. This creates a new
92 // node in the ExplodedGraph.
93 //
94 // (2) note whether the collection has any more elements (or in other words,
95 // whether the loop has more iterations). This will be tested in
96 // processBranch.
97 //
98 // FIXME: Eventually this logic should actually do dispatches to
99 // 'countByEnumeratingWithState:objects:count:' (NSFastEnumeration).
100 // This will require simulating a temporary NSFastEnumerationState, either
101 // through an SVal or through the use of MemRegions. This value can
102 // be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop
103 // terminates we reclaim the temporary (it goes out of scope) and we
104 // we can test if the SVal is 0 or if the MemRegion is null (depending
105 // on what approach we take).
106 //
107 // For now: simulate (1) by assigning either a symbol or nil if the
108 // container is empty. Thus this transfer function will by default
109 // result in state splitting.
110
111 const Stmt *elem = S->getElement();
112 const Stmt *collection = S->getCollection();
113 ProgramStateRef state = Pred->getState();
114 SVal collectionV = state->getSVal(collection, Pred->getLocationContext());
115
116 SVal elementV;
117 if (const auto *DS = dyn_cast<DeclStmt>(elem)) {
118 const VarDecl *elemD = cast<VarDecl>(DS->getSingleDecl());
119 assert(elemD->getInit() == nullptr);
120 elementV = state->getLValue(elemD, Pred->getLocationContext());
121 } else {
122 elementV = state->getSVal(elem, Pred->getLocationContext());
123 }
124
125 bool isContainerNull = state->isNull(collectionV).isConstrainedTrue();
126
127 ExplodedNodeSet DstLocation; // states in `DstLocation` may differ from `Pred`
128 evalLocation(DstLocation, S, elem, Pred, state, elementV, false);
129
130 for (ExplodedNode *dstLocation : DstLocation) {
131 ExplodedNodeSet DstLocationSingleton{dstLocation}, Tmp;
132 StmtNodeBuilder Bldr(dstLocation, Tmp, *currBldrCtx);
133
134 if (!isContainerNull)
135 populateObjCForDestinationSet(DstLocationSingleton, svalBuilder, S, elem,
136 elementV, SymMgr, currBldrCtx, Bldr,
137 /*hasElements=*/true);
138
139 populateObjCForDestinationSet(DstLocationSingleton, svalBuilder, S, elem,
140 elementV, SymMgr, currBldrCtx, Bldr,
141 /*hasElements=*/false);
142
143 // Finally, run any custom checkers.
144 // FIXME: Eventually all pre- and post-checks should live in VisitStmt.
145 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
146 }
147}
148
150 ExplodedNode *Pred,
151 ExplodedNodeSet &Dst) {
154 ME, Pred->getState(), Pred->getLocationContext(), getCFGElementRef());
155
156 // There are three cases for the receiver:
157 // (1) it is definitely nil,
158 // (2) it is definitely non-nil, and
159 // (3) we don't know.
160 //
161 // If the receiver is definitely nil, we skip the pre/post callbacks and
162 // instead call the ObjCMessageNil callbacks and return.
163 //
164 // If the receiver is definitely non-nil, we call the pre- callbacks,
165 // evaluate the call, and call the post- callbacks.
166 //
167 // If we don't know, we drop the potential nil flow and instead
168 // continue from the assumed non-nil state as in (2). This approach
169 // intentionally drops coverage in order to prevent false alarms
170 // in the following scenario:
171 //
172 // id result = [o someMethod]
173 // if (result) {
174 // if (!o) {
175 // // <-- This program point should be unreachable because if o is nil
176 // // it must the case that result is nil as well.
177 // }
178 // }
179 //
180 // However, it also loses coverage of the nil path prematurely,
181 // leading to missed reports.
182 //
183 // It's possible to handle this by performing a state split on every call:
184 // explore the state where the receiver is non-nil, and independently
185 // explore the state where it's nil. But this is not only slow, but
186 // completely unwarranted. The mere presence of the message syntax in the code
187 // isn't sufficient evidence that nil is a realistic possibility.
188 //
189 // An ideal solution would be to add the following constraint that captures
190 // both possibilities without splitting the state:
191 //
192 // ($x == 0) => ($y == 0) (1)
193 //
194 // where in our case '$x' is the receiver symbol, '$y' is the returned symbol,
195 // and '=>' is logical implication. But RangeConstraintManager can't handle
196 // such constraints yet, so for now we go with a simpler, more restrictive
197 // constraint: $x != 0, from which (1) follows as a vacuous truth.
198 if (Msg->isInstanceMessage()) {
199 SVal recVal = Msg->getReceiverSVal();
200 if (!recVal.isUndef()) {
201 // Bifurcate the state into nil and non-nil ones.
202 DefinedOrUnknownSVal receiverVal =
204 ProgramStateRef State = Pred->getState();
205
206 ProgramStateRef notNilState, nilState;
207 std::tie(notNilState, nilState) = State->assume(receiverVal);
208
209 // Receiver is definitely nil, so run ObjCMessageNil callbacks and return.
210 if (nilState && !notNilState) {
211 ExplodedNodeSet dstNil;
212 StmtNodeBuilder Bldr(Pred, dstNil, *currBldrCtx);
213 bool HasTag = Pred->getLocation().getTag();
214 Pred = Bldr.generateNode(ME, Pred, nilState, nullptr,
216 assert((Pred || HasTag) && "Should have cached out already!");
217 (void)HasTag;
218 if (!Pred)
219 return;
220
221 ExplodedNodeSet dstPostCheckers;
222 getCheckerManager().runCheckersForObjCMessageNil(dstPostCheckers, Pred,
223 *Msg, *this);
224 for (auto *I : dstPostCheckers)
225 finishArgumentConstruction(Dst, I, *Msg);
226 return;
227 }
228
229 ExplodedNodeSet dstNonNil;
230 StmtNodeBuilder Bldr(Pred, dstNonNil, *currBldrCtx);
231 // Generate a transition to the non-nil state, dropping any potential
232 // nil flow.
233 if (notNilState != State) {
234 bool HasTag = Pred->getLocation().getTag();
235 Pred = Bldr.generateNode(ME, Pred, notNilState);
236 assert((Pred || HasTag) && "Should have cached out already!");
237 (void)HasTag;
238 if (!Pred)
239 return;
240 }
241 }
242 }
243
244 // Handle the previsits checks.
245 ExplodedNodeSet dstPrevisit;
247 *Msg, *this);
248 ExplodedNodeSet dstGenericPrevisit;
249 getCheckerManager().runCheckersForPreCall(dstGenericPrevisit, dstPrevisit,
250 *Msg, *this);
251
252 // Proceed with evaluate the message expression.
253 ExplodedNodeSet dstEval;
254 StmtNodeBuilder Bldr(dstGenericPrevisit, dstEval, *currBldrCtx);
255
256 for (ExplodedNodeSet::iterator DI = dstGenericPrevisit.begin(),
257 DE = dstGenericPrevisit.end(); DI != DE; ++DI) {
258 ExplodedNode *Pred = *DI;
259 ProgramStateRef State = Pred->getState();
260 CallEventRef<ObjCMethodCall> UpdatedMsg = Msg.cloneWithState(State);
261
262 if (UpdatedMsg->isInstanceMessage()) {
263 SVal recVal = UpdatedMsg->getReceiverSVal();
264 if (!recVal.isUndef()) {
265 if (ObjCNoRet.isImplicitNoReturn(ME)) {
266 // If we raise an exception, for now treat it as a sink.
267 // Eventually we will want to handle exceptions properly.
268 Bldr.generateSink(ME, Pred, State);
269 continue;
270 }
271 }
272 } else {
273 // Check for special class methods that are known to not return
274 // and that we should treat as a sink.
275 if (ObjCNoRet.isImplicitNoReturn(ME)) {
276 // If we raise an exception, for now treat it as a sink.
277 // Eventually we will want to handle exceptions properly.
278 Bldr.generateSink(ME, Pred, Pred->getState());
279 continue;
280 }
281 }
282
283 defaultEvalCall(Bldr, Pred, *UpdatedMsg);
284 }
285
286 // If there were constructors called for object-type arguments, clean them up.
287 ExplodedNodeSet dstArgCleanup;
288 for (auto *I : dstEval)
289 finishArgumentConstruction(dstArgCleanup, I, *Msg);
290
291 ExplodedNodeSet dstPostvisit;
292 getCheckerManager().runCheckersForPostCall(dstPostvisit, dstArgCleanup,
293 *Msg, *this);
294
295 // Finally, perform the post-condition check of the ObjCMessageExpr and store
296 // the created nodes in 'Dst'.
298 *Msg, *this);
299}
#define V(N, I)
Definition: ASTContext.h:3460
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.
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:549
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:579
const Expr * getBase() const
Definition: ExprObjC.h:583
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:941
bool isImplicitNoReturn(const ObjCMessageExpr *ME)
Return true if the given message expression is known to never return.
const ProgramPointTag * getTag() const
Definition: ProgramPoint.h:173
A (possibly-)qualified type.
Definition: Type.h:929
Stmt - This represents one statement.
Definition: Stmt.h:84
Represents a variable declaration or definition.
Definition: Decl.h:886
const Expr * getInit() const
Definition: Decl.h:1323
Manages the lifetime of CallEvent objects.
Definition: CallEvent.h:1361
CallEventRef< ObjCMethodCall > getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State, const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef)
Definition: CallEvent.h:1432
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:414
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.
CFGBlock::ConstCFGElementRef getCFGElementRef() const
Definition: ExprEngine.h:229
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 iteratios to model.
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:224
CallEventManager & getCallEventManager()
Definition: ProgramState.h:571
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
Definition: SValBuilder.h:288
loc::MemRegionVal makeLoc(SymbolRef sym)
Definition: SValBuilder.h:374
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
This builder class is useful for generating nodes that resulted from visiting a statement.
Definition: CoreEngine.h:384
ExplodedNode * generateNode(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition: CoreEngine.h:413
ExplodedNode * generateSink(const Stmt *S, ExplodedNode *Pred, ProgramStateRef St, const ProgramPointTag *tag=nullptr, ProgramPoint::Kind K=ProgramPoint::PostStmtKind)
Definition: CoreEngine.h:423
Symbolic value.
Definition: SymExpr.h:32
const SymbolConjured * conjureSymbol(const Stmt *E, const LocationContext *LCtx, QualType T, unsigned VisitCount, const void *SymbolTag=nullptr)
The JSON file list parser is used to communicate input to InstallAPI.
const FunctionProtoType * T