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