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 StackFrame *SF = Pred->getStackFrame();
26 SVal baseVal = state->getSVal(Ex->getBase(), SF);
27 SVal location = state->getLValue(Ex->getDecl(), baseVal);
28
29 ExplodedNode *N = Engine.makeNodeWithBinding(Pred, Ex, location);
30
31 // Perform the post-condition check of the ObjCIvarRefExpr and store
32 // the created nodes in 'Dst'.
33 getCheckerManager().runCheckersForPostStmt(Dst, N, Ex, *this);
34}
35
41
43 ExplodedNode *Pred,
44 ExplodedNodeSet &Dst,
45 SVal ElementV,
46 bool HasElements) {
47 ProgramStateRef State = Pred->getState();
48 const StackFrame *SF = Pred->getStackFrame();
49
50 State = ExprEngine::setWhetherHasMoreIteration(State, S, SF, HasElements);
51
52 if (auto MV = ElementV.getAs<loc::MemRegionVal>())
53 if (const auto *R = dyn_cast<TypedValueRegion>(MV->getRegion())) {
54 // FIXME: The proper thing to do is to really iterate over the
55 // container. We will do this with dispatch logic to the store.
56 // For now, just 'conjure' up a symbolic value.
57 QualType T = R->getValueType();
58 assert(Loc::isLocType(T));
59
60 SVal V;
61 if (HasElements) {
62 SymbolRef Sym = SymMgr.conjureSymbol(getCFGElementRef(), SF, T,
64 V = svalBuilder.makeLoc(Sym);
65 } else {
66 V = svalBuilder.makeIntVal(0, T);
67 }
68
69 State = State->bindLoc(ElementV, V, SF);
70 }
71
72 Dst.insert(Engine.makePostStmtNode(S, State, Pred));
73}
74
76 ExplodedNode *Pred,
77 ExplodedNodeSet &Dst) {
78
79 // ObjCForCollectionStmts are processed in two places. This method
80 // handles the case where an ObjCForCollectionStmt* occurs as one of the
81 // statements within a basic block. This transfer function does two things:
82 //
83 // (1) binds the next container value to 'element'. This creates a new
84 // node in the ExplodedGraph.
85 //
86 // (2) note whether the collection has any more elements (or in other words,
87 // whether the loop has more iterations). This will be tested in
88 // processBranch.
89 //
90 // FIXME: Eventually this logic should actually do dispatches to
91 // 'countByEnumeratingWithState:objects:count:' (NSFastEnumeration).
92 // This will require simulating a temporary NSFastEnumerationState, either
93 // through an SVal or through the use of MemRegions. This value can
94 // be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop
95 // terminates we reclaim the temporary (it goes out of scope) and we
96 // we can test if the SVal is 0 or if the MemRegion is null (depending
97 // on what approach we take).
98 //
99 // For now: simulate (1) by assigning either a symbol or nil if the
100 // container is empty. Thus this transfer function will by default
101 // result in state splitting.
102
103 const Stmt *elem = S->getElement();
104 const Expr *collection = S->getCollection();
105 ProgramStateRef state = Pred->getState();
106
107 SVal collectionV = state->getSVal(collection, Pred->getStackFrame());
108
109 SVal elementV = UnknownVal();
110 if (const auto *DS = dyn_cast<DeclStmt>(elem)) {
111 const VarDecl *elemD = cast<VarDecl>(DS->getSingleDecl());
112 assert(elemD->getInit() == nullptr);
113 elementV = state->getLValue(elemD, Pred->getStackFrame());
114 } else if (const auto *Ex = dyn_cast<Expr>(elem)) {
115 elementV = state->getSVal(Ex, Pred->getStackFrame());
116 }
117
118 bool isContainerNull = state->isNull(collectionV).isConstrainedTrue();
119
120 ExplodedNodeSet DstLocation; // states in `DstLocation` may differ from `Pred`
121 evalLocation(DstLocation, S, elem, Pred, state, elementV, false);
122
123 for (ExplodedNode *N : DstLocation) {
124 ExplodedNodeSet Tmp;
125
126 if (!isContainerNull)
127 populateObjCForDestinationSet(S, N, Tmp, elementV, /*hasElements=*/true);
128
129 populateObjCForDestinationSet(S, N, Tmp, elementV, /*hasElements=*/false);
130
131 // Finally, run any custom checkers.
132 // FIXME: Eventually all pre- and post-checks should live in VisitStmt.
133 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
134 }
135}
136
138 ExplodedNode *Pred,
139 ExplodedNodeSet &Dst) {
142 ME, Pred->getState(), Pred->getStackFrame(), getCFGElementRef());
143
144 // There are three cases for the receiver:
145 // (1) it is definitely nil,
146 // (2) it is definitely non-nil, and
147 // (3) we don't know.
148 //
149 // If the receiver is definitely nil, we skip the pre/post callbacks and
150 // instead call the ObjCMessageNil callbacks and return.
151 //
152 // If the receiver is definitely non-nil, we call the pre- callbacks,
153 // evaluate the call, and call the post- callbacks.
154 //
155 // If we don't know, we drop the potential nil flow and instead
156 // continue from the assumed non-nil state as in (2). This approach
157 // intentionally drops coverage in order to prevent false alarms
158 // in the following scenario:
159 //
160 // id result = [o someMethod]
161 // if (result) {
162 // if (!o) {
163 // // <-- This program point should be unreachable because if o is nil
164 // // it must the case that result is nil as well.
165 // }
166 // }
167 //
168 // However, it also loses coverage of the nil path prematurely,
169 // leading to missed reports.
170 //
171 // It's possible to handle this by performing a state split on every call:
172 // explore the state where the receiver is non-nil, and independently
173 // explore the state where it's nil. But this is not only slow, but
174 // completely unwarranted. The mere presence of the message syntax in the code
175 // isn't sufficient evidence that nil is a realistic possibility.
176 //
177 // An ideal solution would be to add the following constraint that captures
178 // both possibilities without splitting the state:
179 //
180 // ($x == 0) => ($y == 0) (1)
181 //
182 // where in our case '$x' is the receiver symbol, '$y' is the returned symbol,
183 // and '=>' is logical implication. But RangeConstraintManager can't handle
184 // such constraints yet, so for now we go with a simpler, more restrictive
185 // constraint: $x != 0, from which (1) follows as a vacuous truth.
186 if (Msg->isInstanceMessage()) {
187 SVal recVal = Msg->getReceiverSVal();
188 if (!recVal.isUndef()) {
189 // Bifurcate the state into nil and non-nil ones.
190 DefinedOrUnknownSVal receiverVal =
192 ProgramStateRef State = Pred->getState();
193
194 ProgramStateRef notNilState, nilState;
195 std::tie(notNilState, nilState) = State->assume(receiverVal);
196
197 // Receiver is definitely nil, so run ObjCMessageNil callbacks and return.
198 if (nilState && !notNilState) {
199 PreStmt PS(ME, Pred->getStackFrame(), nullptr);
200 Pred = Engine.makeNode(PS, nilState, Pred);
201 if (!Pred)
202 return;
203
204 ExplodedNodeSet dstPostCheckers;
205 getCheckerManager().runCheckersForObjCMessageNil(dstPostCheckers, Pred,
206 *Msg, *this);
207 for (auto *I : dstPostCheckers)
208 finishArgumentConstruction(Dst, I, *Msg);
209 return;
210 }
211
212 // Generate a transition to the non-nil state, dropping any potential
213 // nil flow.
214 if (notNilState != State) {
215 Pred = Engine.makePostStmtNode(ME, notNilState, Pred);
216 if (!Pred)
217 return;
218 }
219 }
220 }
221
222 // Handle the previsits checks.
223 ExplodedNodeSet dstPrevisit;
225 *Msg, *this);
226 ExplodedNodeSet dstGenericPrevisit;
227 getCheckerManager().runCheckersForPreCall(dstGenericPrevisit, dstPrevisit,
228 *Msg, *this);
229
230 // Proceed with evaluate the message expression.
231 ExplodedNodeSet dstEval;
232
233 for (ExplodedNode *Pred : dstGenericPrevisit) {
234 ProgramStateRef State = Pred->getState();
235 CallEventRef<ObjCMethodCall> UpdatedMsg = Msg.cloneWithState(State);
236
237 if (ObjCNoRet.isImplicitNoReturn(ME) &&
238 !(UpdatedMsg->isInstanceMessage() &&
239 UpdatedMsg->getReceiverSVal().isUndef())) {
240 // If we raise an exception, for now treat it as a sink.
241 // Eventually we will want to handle exceptions properly.
242 Engine.makePostStmtNode(ME, State, Pred, /*MarkAsSink=*/true);
243 continue;
244 }
245
246 defaultEvalCall(dstEval, Pred, *UpdatedMsg);
247 }
248
249 // If there were constructors called for object-type arguments, clean them up.
250 ExplodedNodeSet dstArgCleanup;
251 for (auto *I : dstEval)
252 finishArgumentConstruction(dstArgCleanup, I, *Msg);
253
254 ExplodedNodeSet dstPostvisit;
255 getCheckerManager().runCheckersForPostCall(dstPostvisit, dstArgCleanup,
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}
#define V(N, I)
Defines the Objective-C statement AST node classes.
This represents one expression.
Definition Expr.h:112
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
A (possibly-)qualified type.
Definition TypeBase.h:937
It represents a stack frame of the call stack.
Stmt - This represents one statement.
Definition Stmt.h:86
Represents a variable declaration or definition.
Definition Decl.h:932
const Expr * getInit() const
Definition Decl.h:1389
Manages the lifetime of CallEvent objects.
Definition CallEvent.h:1363
CallEventRef< ObjCMethodCall > getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Definition CallEvent.h:1433
CallEventRef< T > cloneWithState(ProgramStateRef State) const
Definition CallEvent.h:91
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...
void insert(ExplodedNode *N)
const ProgramStateRef & getState() const
const StackFrame * getStackFrame() const
ProgramStateManager & getStateManager()
Definition ExprEngine.h:476
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.
void defaultEvalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred, const CallEvent &Call, const EvalCallOptions &CallOpts={})
Default implementation of call evaluation.
ConstCFGElementRef getCFGElementRef() const
Definition ExprEngine.h:290
void populateObjCForDestinationSet(const ObjCForCollectionStmt *S, ExplodedNode *Pred, ExplodedNodeSet &Dst, SVal ElementV, bool HasElements)
Implementation detail of VisitObjCForCollectionStmt, which contains the logic that needs to be execut...
static ProgramStateRef setWhetherHasMoreIteration(ProgramStateRef State, const ObjCForCollectionStmt *O, const StackFrame *SF, bool HasMoreIteraton)
Note whether this loop has any more iterations to model. These methods.
CheckerManager & getCheckerManager() const
Definition ExprEngine.h:223
unsigned getNumVisitedCurrent() const
Definition ExprEngine.h:299
static bool isLocType(QualType T)
Definition SVals.h:268
CallEventManager & getCallEventManager()
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
bool isUndef() const
Definition SVals.h:113
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:88
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition SVals.h:84
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:133
The JSON file list parser is used to communicate input to InstallAPI.
U cast(CodeGen::Address addr)
Definition Address.h:327