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 Expr *collection = S->getCollection();
115 const ConstCFGElementRef &elemRef = getCFGElementRef();
116 ProgramStateRef state = Pred->getState();
117
118 SVal collectionV = state->getSVal(collection, Pred->getLocationContext());
119
120 SVal elementV = UnknownVal();
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 if (const auto *Ex = dyn_cast<Expr>(elem)) {
126 elementV = state->getSVal(Ex, Pred->getLocationContext());
127 }
128
129 bool isContainerNull = state->isNull(collectionV).isConstrainedTrue();
130
131 ExplodedNodeSet DstLocation; // states in `DstLocation` may differ from `Pred`
132 evalLocation(DstLocation, S, elem, Pred, state, elementV, false);
133
134 for (ExplodedNode *dstLocation : DstLocation) {
135 ExplodedNodeSet DstLocationSingleton{dstLocation}, Tmp;
136 NodeBuilder Bldr(dstLocation, Tmp, *currBldrCtx);
137
138 if (!isContainerNull)
139 populateObjCForDestinationSet(DstLocationSingleton, svalBuilder, S,
140 elemRef, elementV, SymMgr,
141 getNumVisitedCurrent(), Bldr,
142 /*hasElements=*/true);
143
144 populateObjCForDestinationSet(DstLocationSingleton, svalBuilder, S, elemRef,
145 elementV, SymMgr, getNumVisitedCurrent(),
146 Bldr,
147 /*hasElements=*/false);
148
149 // Finally, run any custom checkers.
150 // FIXME: Eventually all pre- and post-checks should live in VisitStmt.
151 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
152 }
153}
154
156 ExplodedNode *Pred,
157 ExplodedNodeSet &Dst) {
160 ME, Pred->getState(), Pred->getLocationContext(), getCFGElementRef());
161
162 // There are three cases for the receiver:
163 // (1) it is definitely nil,
164 // (2) it is definitely non-nil, and
165 // (3) we don't know.
166 //
167 // If the receiver is definitely nil, we skip the pre/post callbacks and
168 // instead call the ObjCMessageNil callbacks and return.
169 //
170 // If the receiver is definitely non-nil, we call the pre- callbacks,
171 // evaluate the call, and call the post- callbacks.
172 //
173 // If we don't know, we drop the potential nil flow and instead
174 // continue from the assumed non-nil state as in (2). This approach
175 // intentionally drops coverage in order to prevent false alarms
176 // in the following scenario:
177 //
178 // id result = [o someMethod]
179 // if (result) {
180 // if (!o) {
181 // // <-- This program point should be unreachable because if o is nil
182 // // it must the case that result is nil as well.
183 // }
184 // }
185 //
186 // However, it also loses coverage of the nil path prematurely,
187 // leading to missed reports.
188 //
189 // It's possible to handle this by performing a state split on every call:
190 // explore the state where the receiver is non-nil, and independently
191 // explore the state where it's nil. But this is not only slow, but
192 // completely unwarranted. The mere presence of the message syntax in the code
193 // isn't sufficient evidence that nil is a realistic possibility.
194 //
195 // An ideal solution would be to add the following constraint that captures
196 // both possibilities without splitting the state:
197 //
198 // ($x == 0) => ($y == 0) (1)
199 //
200 // where in our case '$x' is the receiver symbol, '$y' is the returned symbol,
201 // and '=>' is logical implication. But RangeConstraintManager can't handle
202 // such constraints yet, so for now we go with a simpler, more restrictive
203 // constraint: $x != 0, from which (1) follows as a vacuous truth.
204 if (Msg->isInstanceMessage()) {
205 SVal recVal = Msg->getReceiverSVal();
206 if (!recVal.isUndef()) {
207 // Bifurcate the state into nil and non-nil ones.
208 DefinedOrUnknownSVal receiverVal =
210 ProgramStateRef State = Pred->getState();
211
212 ProgramStateRef notNilState, nilState;
213 std::tie(notNilState, nilState) = State->assume(receiverVal);
214
215 // Receiver is definitely nil, so run ObjCMessageNil callbacks and return.
216 if (nilState && !notNilState) {
217 ExplodedNodeSet dstNil;
218 NodeBuilder Bldr(Pred, dstNil, *currBldrCtx);
219 bool HasTag = Pred->getLocation().getTag();
220 Pred = Bldr.generateNode(ME, Pred, nilState, nullptr,
222 assert((Pred || HasTag) && "Should have cached out already!");
223 (void)HasTag;
224 if (!Pred)
225 return;
226
227 ExplodedNodeSet dstPostCheckers;
228 getCheckerManager().runCheckersForObjCMessageNil(dstPostCheckers, Pred,
229 *Msg, *this);
230 for (auto *I : dstPostCheckers)
231 finishArgumentConstruction(Dst, I, *Msg);
232 return;
233 }
234
235 ExplodedNodeSet dstNonNil;
236 NodeBuilder Bldr(Pred, dstNonNil, *currBldrCtx);
237 // Generate a transition to the non-nil state, dropping any potential
238 // nil flow.
239 if (notNilState != State) {
240 bool HasTag = Pred->getLocation().getTag();
241 Pred = Bldr.generateNode(ME, Pred, notNilState);
242 assert((Pred || HasTag) && "Should have cached out already!");
243 (void)HasTag;
244 if (!Pred)
245 return;
246 }
247 }
248 }
249
250 // Handle the previsits checks.
251 ExplodedNodeSet dstPrevisit;
253 *Msg, *this);
254 ExplodedNodeSet dstGenericPrevisit;
255 getCheckerManager().runCheckersForPreCall(dstGenericPrevisit, dstPrevisit,
256 *Msg, *this);
257
258 // Proceed with evaluate the message expression.
259 ExplodedNodeSet dstEval;
260 NodeBuilder Bldr(dstGenericPrevisit, dstEval, *currBldrCtx);
261
262 for (ExplodedNodeSet::iterator DI = dstGenericPrevisit.begin(),
263 DE = dstGenericPrevisit.end(); DI != DE; ++DI) {
264 ExplodedNode *Pred = *DI;
265 ProgramStateRef State = Pred->getState();
266 CallEventRef<ObjCMethodCall> UpdatedMsg = Msg.cloneWithState(State);
267
268 if (UpdatedMsg->isInstanceMessage()) {
269 SVal recVal = UpdatedMsg->getReceiverSVal();
270 if (!recVal.isUndef()) {
271 if (ObjCNoRet.isImplicitNoReturn(ME)) {
272 // If we raise an exception, for now treat it as a sink.
273 // Eventually we will want to handle exceptions properly.
274 Bldr.generateSink(ME, Pred, State);
275 continue;
276 }
277 }
278 } else {
279 // Check for special class methods that are known to not return
280 // and that we should treat as a sink.
281 if (ObjCNoRet.isImplicitNoReturn(ME)) {
282 // If we raise an exception, for now treat it as a sink.
283 // Eventually we will want to handle exceptions properly.
284 Bldr.generateSink(ME, Pred, Pred->getState());
285 continue;
286 }
287 }
288
289 defaultEvalCall(Bldr, Pred, *UpdatedMsg);
290 }
291
292 // If there were constructors called for object-type arguments, clean them up.
293 ExplodedNodeSet dstArgCleanup;
294 for (auto *I : dstEval)
295 finishArgumentConstruction(dstArgCleanup, I, *Msg);
296
297 ExplodedNodeSet dstPostvisit;
298 getCheckerManager().runCheckersForPostCall(dstPostvisit, dstArgCleanup,
299 *Msg, *this);
300
301 // Finally, perform the post-condition check of the ObjCMessageExpr and store
302 // the created nodes in 'Dst'.
304 *Msg, *this);
305}
#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.
This represents one expression.
Definition Expr.h:112
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:580
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:610
const Expr * getBase() const
Definition ExprObjC.h:614
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:971
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:924
const Expr * getInit() const
Definition Decl.h:1381
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 function calls (including methods, constructors, destructors etc.
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 function calls (including methods, constructors, destructors etc.
ExplodedNodeSet is a set of ExplodedNode * elements with the invariant that its elements cannot be nu...
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:480
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:292
CheckerManager & getCheckerManager() const
Definition ExprEngine.h:224
unsigned getNumVisitedCurrent() const
Definition ExprEngine.h:302
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:244
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:279
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