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"
14#include "clang/StaticAnalyzer/Core/CheckerManager.h"
15#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
16#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17
18using namespace clang;
19using namespace ento;
20
21void ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *Ex,
22 ExplodedNode *Pred,
23 ExplodedNodeSet &Dst) {
24 ProgramStateRef state = Pred->getState();
25 const LocationContext *LCtx = Pred->getLocationContext();
26 SVal baseVal = state->getSVal(Ex: Ex->getBase(), LCtx);
27 SVal location = state->getLValue(D: Ex->getDecl(), Base: baseVal);
28
29 ExplodedNodeSet dstIvar;
30 NodeBuilder Bldr(Pred, dstIvar, *currBldrCtx);
31 Bldr.generateNode(S: Ex, Pred, St: state->BindExpr(S: Ex, LCtx, V: location));
32
33 // Perform the post-condition check of the ObjCIvarRefExpr and store
34 // the created nodes in 'Dst'.
35 getCheckerManager().runCheckersForPostStmt(Dst, Src: dstIvar, S: Ex, Eng&: *this);
36}
37
38void ExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
39 ExplodedNode *Pred,
40 ExplodedNodeSet &Dst) {
41 getCheckerManager().runCheckersForPreStmt(Dst, Src: Pred, S, Eng&: *this);
42}
43
44/// Generate a node in \p Bldr for an iteration statement using ObjC
45/// for-loop iterator.
46static void populateObjCForDestinationSet(ExplodedNodeSet &dstLocation,
47 SValBuilder &svalBuilder,
48 const ObjCForCollectionStmt *S,
49 ConstCFGElementRef elem,
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: state, O: S, LC: LCtx, HasMoreIteraton: hasElements);
60
61 if (auto MV = elementV.getAs<loc::MemRegionVal>())
62 if (const auto *R = dyn_cast<TypedValueRegion>(Val: 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: elem, LCtx, T, VisitCount: NumVisitedCurrent);
73 V = svalBuilder.makeLoc(sym: Sym);
74 } else {
75 V = svalBuilder.makeIntVal(integer: 0, type: T);
76 }
77
78 nextState = nextState->bindLoc(LV: elementV, V, LCtx);
79 }
80
81 Bldr.generateNode(S, Pred, St: nextState);
82 }
83}
84
85void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
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(Ex: collection, LCtx: Pred->getLocationContext());
118
119 SVal elementV;
120 if (const auto *DS = dyn_cast<DeclStmt>(Val: elem)) {
121 const VarDecl *elemD = cast<VarDecl>(Val: DS->getSingleDecl());
122 assert(elemD->getInit() == nullptr);
123 elementV = state->getLValue(VD: elemD, LC: Pred->getLocationContext());
124 } else {
125 elementV = state->getSVal(Ex: elem, LCtx: Pred->getLocationContext());
126 }
127
128 bool isContainerNull = state->isNull(V: collectionV).isConstrainedTrue();
129
130 ExplodedNodeSet DstLocation; // states in `DstLocation` may differ from `Pred`
131 evalLocation(Dst&: DstLocation, NodeEx: S, BoundEx: elem, Pred, St: state, location: elementV, isLoad: false);
132
133 for (ExplodedNode *dstLocation : DstLocation) {
134 ExplodedNodeSet DstLocationSingleton{dstLocation}, Tmp;
135 NodeBuilder Bldr(dstLocation, Tmp, *currBldrCtx);
136
137 if (!isContainerNull)
138 populateObjCForDestinationSet(dstLocation&: DstLocationSingleton, svalBuilder, S,
139 elem: elemRef, elementV, SymMgr,
140 NumVisitedCurrent: getNumVisitedCurrent(), Bldr,
141 /*hasElements=*/true);
142
143 populateObjCForDestinationSet(dstLocation&: DstLocationSingleton, svalBuilder, S, elem: elemRef,
144 elementV, SymMgr, NumVisitedCurrent: getNumVisitedCurrent(),
145 Bldr,
146 /*hasElements=*/false);
147
148 // Finally, run any custom checkers.
149 // FIXME: Eventually all pre- and post-checks should live in VisitStmt.
150 getCheckerManager().runCheckersForPostStmt(Dst, Src: Tmp, S, Eng&: *this);
151 }
152}
153
154void ExprEngine::VisitObjCMessage(const ObjCMessageExpr *ME,
155 ExplodedNode *Pred,
156 ExplodedNodeSet &Dst) {
157 CallEventManager &CEMgr = getStateManager().getCallEventManager();
158 CallEventRef<ObjCMethodCall> Msg = CEMgr.getObjCMethodCall(
159 E: ME, State: Pred->getState(), LCtx: Pred->getLocationContext(), ElemRef: getCFGElementRef());
160
161 // There are three cases for the receiver:
162 // (1) it is definitely nil,
163 // (2) it is definitely non-nil, and
164 // (3) we don't know.
165 //
166 // If the receiver is definitely nil, we skip the pre/post callbacks and
167 // instead call the ObjCMessageNil callbacks and return.
168 //
169 // If the receiver is definitely non-nil, we call the pre- callbacks,
170 // evaluate the call, and call the post- callbacks.
171 //
172 // If we don't know, we drop the potential nil flow and instead
173 // continue from the assumed non-nil state as in (2). This approach
174 // intentionally drops coverage in order to prevent false alarms
175 // in the following scenario:
176 //
177 // id result = [o someMethod]
178 // if (result) {
179 // if (!o) {
180 // // <-- This program point should be unreachable because if o is nil
181 // // it must the case that result is nil as well.
182 // }
183 // }
184 //
185 // However, it also loses coverage of the nil path prematurely,
186 // leading to missed reports.
187 //
188 // It's possible to handle this by performing a state split on every call:
189 // explore the state where the receiver is non-nil, and independently
190 // explore the state where it's nil. But this is not only slow, but
191 // completely unwarranted. The mere presence of the message syntax in the code
192 // isn't sufficient evidence that nil is a realistic possibility.
193 //
194 // An ideal solution would be to add the following constraint that captures
195 // both possibilities without splitting the state:
196 //
197 // ($x == 0) => ($y == 0) (1)
198 //
199 // where in our case '$x' is the receiver symbol, '$y' is the returned symbol,
200 // and '=>' is logical implication. But RangeConstraintManager can't handle
201 // such constraints yet, so for now we go with a simpler, more restrictive
202 // constraint: $x != 0, from which (1) follows as a vacuous truth.
203 if (Msg->isInstanceMessage()) {
204 SVal recVal = Msg->getReceiverSVal();
205 if (!recVal.isUndef()) {
206 // Bifurcate the state into nil and non-nil ones.
207 DefinedOrUnknownSVal receiverVal =
208 recVal.castAs<DefinedOrUnknownSVal>();
209 ProgramStateRef State = Pred->getState();
210
211 ProgramStateRef notNilState, nilState;
212 std::tie(args&: notNilState, args&: nilState) = State->assume(Cond: receiverVal);
213
214 // Receiver is definitely nil, so run ObjCMessageNil callbacks and return.
215 if (nilState && !notNilState) {
216 ExplodedNodeSet dstNil;
217 NodeBuilder Bldr(Pred, dstNil, *currBldrCtx);
218 bool HasTag = Pred->getLocation().getTag();
219 Pred = Bldr.generateNode(S: ME, Pred, St: nilState, tag: nullptr,
220 K: ProgramPoint::PreStmtKind);
221 assert((Pred || HasTag) && "Should have cached out already!");
222 (void)HasTag;
223 if (!Pred)
224 return;
225
226 ExplodedNodeSet dstPostCheckers;
227 getCheckerManager().runCheckersForObjCMessageNil(Dst&: dstPostCheckers, Src: Pred,
228 msg: *Msg, Eng&: *this);
229 for (auto *I : dstPostCheckers)
230 finishArgumentConstruction(Dst, Pred: I, Call: *Msg);
231 return;
232 }
233
234 ExplodedNodeSet dstNonNil;
235 NodeBuilder Bldr(Pred, dstNonNil, *currBldrCtx);
236 // Generate a transition to the non-nil state, dropping any potential
237 // nil flow.
238 if (notNilState != State) {
239 bool HasTag = Pred->getLocation().getTag();
240 Pred = Bldr.generateNode(S: ME, Pred, St: notNilState);
241 assert((Pred || HasTag) && "Should have cached out already!");
242 (void)HasTag;
243 if (!Pred)
244 return;
245 }
246 }
247 }
248
249 // Handle the previsits checks.
250 ExplodedNodeSet dstPrevisit;
251 getCheckerManager().runCheckersForPreObjCMessage(Dst&: dstPrevisit, Src: Pred,
252 msg: *Msg, Eng&: *this);
253 ExplodedNodeSet dstGenericPrevisit;
254 getCheckerManager().runCheckersForPreCall(Dst&: dstGenericPrevisit, Src: dstPrevisit,
255 Call: *Msg, Eng&: *this);
256
257 // Proceed with evaluate the message expression.
258 ExplodedNodeSet dstEval;
259 NodeBuilder Bldr(dstGenericPrevisit, dstEval, *currBldrCtx);
260
261 for (ExplodedNodeSet::iterator DI = dstGenericPrevisit.begin(),
262 DE = dstGenericPrevisit.end(); DI != DE; ++DI) {
263 ExplodedNode *Pred = *DI;
264 ProgramStateRef State = Pred->getState();
265 CallEventRef<ObjCMethodCall> UpdatedMsg = Msg.cloneWithState(State);
266
267 if (UpdatedMsg->isInstanceMessage()) {
268 SVal recVal = UpdatedMsg->getReceiverSVal();
269 if (!recVal.isUndef()) {
270 if (ObjCNoRet.isImplicitNoReturn(ME)) {
271 // If we raise an exception, for now treat it as a sink.
272 // Eventually we will want to handle exceptions properly.
273 Bldr.generateSink(S: ME, Pred, St: State);
274 continue;
275 }
276 }
277 } else {
278 // Check for special class methods that are known to not return
279 // and that we should treat as a sink.
280 if (ObjCNoRet.isImplicitNoReturn(ME)) {
281 // If we raise an exception, for now treat it as a sink.
282 // Eventually we will want to handle exceptions properly.
283 Bldr.generateSink(S: ME, Pred, St: Pred->getState());
284 continue;
285 }
286 }
287
288 defaultEvalCall(B&: Bldr, Pred, Call: *UpdatedMsg);
289 }
290
291 // If there were constructors called for object-type arguments, clean them up.
292 ExplodedNodeSet dstArgCleanup;
293 for (auto *I : dstEval)
294 finishArgumentConstruction(Dst&: dstArgCleanup, Pred: I, Call: *Msg);
295
296 ExplodedNodeSet dstPostvisit;
297 getCheckerManager().runCheckersForPostCall(Dst&: dstPostvisit, Src: dstArgCleanup,
298 Call: *Msg, Eng&: *this);
299
300 // Finally, perform the post-condition check of the ObjCMessageExpr and store
301 // the created nodes in 'Dst'.
302 getCheckerManager().runCheckersForPostObjCMessage(Dst, Src: dstPostvisit,
303 msg: *Msg, Eng&: *this);
304}
305