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 StackFrame *SF = Pred->getStackFrame();
26 SVal baseVal = state->getSVal(E: Ex->getBase(), SF);
27 SVal location = state->getLValue(D: Ex->getDecl(), Base: baseVal);
28 Dst.insert(N: Engine.makeNodeWithBinding(Pred, E: Ex, V: location));
29}
30
31void ExprEngine::populateObjCForDestinationSet(const ObjCForCollectionStmt *S,
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, O: S, SF, HasMoreIteraton: HasElements);
40
41 if (auto MV = ElementV.getAs<loc::MemRegionVal>())
42 if (const auto *R = dyn_cast<TypedValueRegion>(Val: 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(Elem: getCFGElementRef(), SF, T,
52 VisitCount: getNumVisitedCurrent());
53 V = svalBuilder.makeLoc(sym: Sym);
54 } else {
55 V = svalBuilder.makeIntVal(integer: 0, type: T);
56 }
57
58 State = State->bindLoc(LV: ElementV, V, SF);
59 }
60
61 Dst.insert(N: Engine.makePostStmtNode(S, State, Pred));
62}
63
64void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
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(E: collection, SF: Pred->getStackFrame());
97
98 SVal elementV = UnknownVal();
99 if (const auto *DS = dyn_cast<DeclStmt>(Val: elem)) {
100 const VarDecl *elemD = cast<VarDecl>(Val: DS->getSingleDecl());
101 assert(elemD->getInit() == nullptr);
102 elementV = state->getLValue(VD: elemD, SF: Pred->getStackFrame());
103 } else if (const auto *Ex = dyn_cast<Expr>(Val: elem)) {
104 elementV = state->getSVal(E: Ex, SF: Pred->getStackFrame());
105 }
106
107 bool isContainerNull = state->isNull(V: collectionV).isConstrainedTrue();
108
109 ExplodedNodeSet DstLocation; // states in `DstLocation` may differ from `Pred`
110 evalLocation(Dst&: DstLocation, NodeEx: S, BoundEx: elem, Pred, St: state, location: elementV, isLoad: false);
111
112 for (ExplodedNode *N : DstLocation) {
113 ExplodedNodeSet Tmp;
114
115 if (!isContainerNull)
116 populateObjCForDestinationSet(S, Pred: N, Dst&: Tmp, ElementV: elementV, /*hasElements=*/HasElements: true);
117
118 populateObjCForDestinationSet(S, Pred: N, Dst&: Tmp, ElementV: elementV, /*hasElements=*/HasElements: false);
119
120 Dst.insert(S: Tmp);
121 }
122}
123
124void ExprEngine::VisitObjCMessage(const ObjCMessageExpr *ME,
125 ExplodedNode *Pred,
126 ExplodedNodeSet &Dst) {
127 CallEventManager &CEMgr = getStateManager().getCallEventManager();
128 CallEventRef<ObjCMethodCall> Msg = CEMgr.getObjCMethodCall(
129 E: ME, State: Pred->getState(), SF: Pred->getStackFrame(), ElemRef: 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 =
178 recVal.castAs<DefinedOrUnknownSVal>();
179 ProgramStateRef State = Pred->getState();
180
181 ProgramStateRef notNilState, nilState;
182 std::tie(args&: notNilState, args&: nilState) = State->assume(Cond: 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(Loc: PS, State: nilState, Pred);
188 if (!Pred)
189 return;
190
191 ExplodedNodeSet dstPostCheckers;
192 getCheckerManager().runCheckersForObjCMessageNil(Dst&: dstPostCheckers, Src: Pred,
193 msg: *Msg, Eng&: *this);
194 for (auto *I : dstPostCheckers)
195 finishArgumentConstruction(Dst, Pred: I, Call: *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(S: ME, State: notNilState, Pred);
203 if (!Pred)
204 return;
205 }
206 }
207 }
208
209 // Handle the previsits checks.
210 ExplodedNodeSet dstPrevisit;
211 getCheckerManager().runCheckersForPreObjCMessage(Dst&: dstPrevisit, Src: Pred,
212 msg: *Msg, Eng&: *this);
213 ExplodedNodeSet dstGenericPrevisit;
214 getCheckerManager().runCheckersForPreCall(Dst&: dstGenericPrevisit, Src: dstPrevisit,
215 Call: *Msg, Eng&: *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(S: ME, State, Pred, /*MarkAsSink=*/true);
230 continue;
231 }
232
233 defaultEvalCall(Dst&: dstEval, Pred, Call: *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(Dst&: dstArgCleanup, Pred: I, Call: *Msg);
240
241 ExplodedNodeSet dstPostvisit;
242 getCheckerManager().runCheckersForPostCall(Dst&: dstPostvisit, Src: dstArgCleanup,
243 Call: *Msg, Eng&: *this);
244
245 // Finally, perform the post-condition check of the ObjCMessageExpr and store
246 // the created nodes in 'Dst'.
247 getCheckerManager().runCheckersForPostObjCMessage(Dst, Src: dstPostvisit,
248 msg: *Msg, Eng&: *this);
249}
250