xref: /openbsd-src/gnu/llvm/clang/lib/StaticAnalyzer/Core/ExprEngineObjC.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //=-- ExprEngineObjC.cpp - ExprEngine support for Objective-C ---*- C++ -*-===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick //  This file defines ExprEngine's support for Objective-C expressions.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick 
13e5dd7070Spatrick #include "clang/AST/StmtObjC.h"
14e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/CheckerManager.h"
15e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
16e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17e5dd7070Spatrick 
18e5dd7070Spatrick using namespace clang;
19e5dd7070Spatrick using namespace ento;
20e5dd7070Spatrick 
VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr * Ex,ExplodedNode * Pred,ExplodedNodeSet & Dst)21e5dd7070Spatrick void ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *Ex,
22e5dd7070Spatrick                                           ExplodedNode *Pred,
23e5dd7070Spatrick                                           ExplodedNodeSet &Dst) {
24e5dd7070Spatrick   ProgramStateRef state = Pred->getState();
25e5dd7070Spatrick   const LocationContext *LCtx = Pred->getLocationContext();
26e5dd7070Spatrick   SVal baseVal = state->getSVal(Ex->getBase(), LCtx);
27e5dd7070Spatrick   SVal location = state->getLValue(Ex->getDecl(), baseVal);
28e5dd7070Spatrick 
29e5dd7070Spatrick   ExplodedNodeSet dstIvar;
30e5dd7070Spatrick   StmtNodeBuilder Bldr(Pred, dstIvar, *currBldrCtx);
31e5dd7070Spatrick   Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, location));
32e5dd7070Spatrick 
33e5dd7070Spatrick   // Perform the post-condition check of the ObjCIvarRefExpr and store
34e5dd7070Spatrick   // the created nodes in 'Dst'.
35e5dd7070Spatrick   getCheckerManager().runCheckersForPostStmt(Dst, dstIvar, Ex, *this);
36e5dd7070Spatrick }
37e5dd7070Spatrick 
VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt * S,ExplodedNode * Pred,ExplodedNodeSet & Dst)38e5dd7070Spatrick void ExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
39e5dd7070Spatrick                                              ExplodedNode *Pred,
40e5dd7070Spatrick                                              ExplodedNodeSet &Dst) {
41e5dd7070Spatrick   getCheckerManager().runCheckersForPreStmt(Dst, Pred, S, *this);
42e5dd7070Spatrick }
43e5dd7070Spatrick 
44e5dd7070Spatrick /// Generate a node in \p Bldr for an iteration statement using ObjC
45e5dd7070Spatrick /// for-loop iterator.
populateObjCForDestinationSet(ExplodedNodeSet & dstLocation,SValBuilder & svalBuilder,const ObjCForCollectionStmt * S,const Stmt * elem,SVal elementV,SymbolManager & SymMgr,const NodeBuilderContext * currBldrCtx,StmtNodeBuilder & Bldr,bool hasElements)46e5dd7070Spatrick static void populateObjCForDestinationSet(
47e5dd7070Spatrick     ExplodedNodeSet &dstLocation, SValBuilder &svalBuilder,
48e5dd7070Spatrick     const ObjCForCollectionStmt *S, const Stmt *elem, SVal elementV,
49e5dd7070Spatrick     SymbolManager &SymMgr, const NodeBuilderContext *currBldrCtx,
50e5dd7070Spatrick     StmtNodeBuilder &Bldr, bool hasElements) {
51e5dd7070Spatrick 
52e5dd7070Spatrick   for (ExplodedNode *Pred : dstLocation) {
53e5dd7070Spatrick     ProgramStateRef state = Pred->getState();
54e5dd7070Spatrick     const LocationContext *LCtx = Pred->getLocationContext();
55e5dd7070Spatrick 
56a9ac8606Spatrick     ProgramStateRef nextState =
57a9ac8606Spatrick         ExprEngine::setWhetherHasMoreIteration(state, S, LCtx, hasElements);
58e5dd7070Spatrick 
59e5dd7070Spatrick     if (auto MV = elementV.getAs<loc::MemRegionVal>())
60e5dd7070Spatrick       if (const auto *R = dyn_cast<TypedValueRegion>(MV->getRegion())) {
61e5dd7070Spatrick         // FIXME: The proper thing to do is to really iterate over the
62e5dd7070Spatrick         //  container.  We will do this with dispatch logic to the store.
63e5dd7070Spatrick         //  For now, just 'conjure' up a symbolic value.
64e5dd7070Spatrick         QualType T = R->getValueType();
65e5dd7070Spatrick         assert(Loc::isLocType(T));
66e5dd7070Spatrick 
67e5dd7070Spatrick         SVal V;
68e5dd7070Spatrick         if (hasElements) {
69e5dd7070Spatrick           SymbolRef Sym = SymMgr.conjureSymbol(elem, LCtx, T,
70e5dd7070Spatrick                                                currBldrCtx->blockCount());
71e5dd7070Spatrick           V = svalBuilder.makeLoc(Sym);
72e5dd7070Spatrick         } else {
73e5dd7070Spatrick           V = svalBuilder.makeIntVal(0, T);
74e5dd7070Spatrick         }
75e5dd7070Spatrick 
76e5dd7070Spatrick         nextState = nextState->bindLoc(elementV, V, LCtx);
77e5dd7070Spatrick       }
78e5dd7070Spatrick 
79e5dd7070Spatrick     Bldr.generateNode(S, Pred, nextState);
80e5dd7070Spatrick   }
81e5dd7070Spatrick }
82e5dd7070Spatrick 
VisitObjCForCollectionStmt(const ObjCForCollectionStmt * S,ExplodedNode * Pred,ExplodedNodeSet & Dst)83e5dd7070Spatrick void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
84e5dd7070Spatrick                                             ExplodedNode *Pred,
85e5dd7070Spatrick                                             ExplodedNodeSet &Dst) {
86e5dd7070Spatrick 
87e5dd7070Spatrick   // ObjCForCollectionStmts are processed in two places.  This method
88e5dd7070Spatrick   // handles the case where an ObjCForCollectionStmt* occurs as one of the
89e5dd7070Spatrick   // statements within a basic block.  This transfer function does two things:
90e5dd7070Spatrick   //
91e5dd7070Spatrick   //  (1) binds the next container value to 'element'.  This creates a new
92e5dd7070Spatrick   //      node in the ExplodedGraph.
93e5dd7070Spatrick   //
94a9ac8606Spatrick   //  (2) note whether the collection has any more elements (or in other words,
95a9ac8606Spatrick   //      whether the loop has more iterations). This will be tested in
96a9ac8606Spatrick   //      processBranch.
97e5dd7070Spatrick   //
98e5dd7070Spatrick   // FIXME: Eventually this logic should actually do dispatches to
99e5dd7070Spatrick   //   'countByEnumeratingWithState:objects:count:' (NSFastEnumeration).
100e5dd7070Spatrick   //   This will require simulating a temporary NSFastEnumerationState, either
101e5dd7070Spatrick   //   through an SVal or through the use of MemRegions.  This value can
102e5dd7070Spatrick   //   be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop
103e5dd7070Spatrick   //   terminates we reclaim the temporary (it goes out of scope) and we
104e5dd7070Spatrick   //   we can test if the SVal is 0 or if the MemRegion is null (depending
105e5dd7070Spatrick   //   on what approach we take).
106e5dd7070Spatrick   //
107e5dd7070Spatrick   //  For now: simulate (1) by assigning either a symbol or nil if the
108e5dd7070Spatrick   //    container is empty.  Thus this transfer function will by default
109e5dd7070Spatrick   //    result in state splitting.
110e5dd7070Spatrick 
111e5dd7070Spatrick   const Stmt *elem = S->getElement();
112e5dd7070Spatrick   const Stmt *collection = S->getCollection();
113e5dd7070Spatrick   ProgramStateRef state = Pred->getState();
114e5dd7070Spatrick   SVal collectionV = state->getSVal(collection, Pred->getLocationContext());
115e5dd7070Spatrick 
116e5dd7070Spatrick   SVal elementV;
117e5dd7070Spatrick   if (const auto *DS = dyn_cast<DeclStmt>(elem)) {
118e5dd7070Spatrick     const VarDecl *elemD = cast<VarDecl>(DS->getSingleDecl());
119e5dd7070Spatrick     assert(elemD->getInit() == nullptr);
120e5dd7070Spatrick     elementV = state->getLValue(elemD, Pred->getLocationContext());
121e5dd7070Spatrick   } else {
122e5dd7070Spatrick     elementV = state->getSVal(elem, Pred->getLocationContext());
123e5dd7070Spatrick   }
124e5dd7070Spatrick 
125e5dd7070Spatrick   bool isContainerNull = state->isNull(collectionV).isConstrainedTrue();
126e5dd7070Spatrick 
127e5dd7070Spatrick   ExplodedNodeSet dstLocation;
128e5dd7070Spatrick   evalLocation(dstLocation, S, elem, Pred, state, elementV, false);
129e5dd7070Spatrick 
130e5dd7070Spatrick   ExplodedNodeSet Tmp;
131e5dd7070Spatrick   StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
132e5dd7070Spatrick 
133e5dd7070Spatrick   if (!isContainerNull)
134e5dd7070Spatrick     populateObjCForDestinationSet(dstLocation, svalBuilder, S, elem, elementV,
135e5dd7070Spatrick                                   SymMgr, currBldrCtx, Bldr,
136e5dd7070Spatrick                                   /*hasElements=*/true);
137e5dd7070Spatrick 
138e5dd7070Spatrick   populateObjCForDestinationSet(dstLocation, svalBuilder, S, elem, elementV,
139e5dd7070Spatrick                                 SymMgr, currBldrCtx, Bldr,
140e5dd7070Spatrick                                 /*hasElements=*/false);
141e5dd7070Spatrick 
142e5dd7070Spatrick   // Finally, run any custom checkers.
143e5dd7070Spatrick   // FIXME: Eventually all pre- and post-checks should live in VisitStmt.
144e5dd7070Spatrick   getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
145e5dd7070Spatrick }
146e5dd7070Spatrick 
VisitObjCMessage(const ObjCMessageExpr * ME,ExplodedNode * Pred,ExplodedNodeSet & Dst)147e5dd7070Spatrick void ExprEngine::VisitObjCMessage(const ObjCMessageExpr *ME,
148e5dd7070Spatrick                                   ExplodedNode *Pred,
149e5dd7070Spatrick                                   ExplodedNodeSet &Dst) {
150e5dd7070Spatrick   CallEventManager &CEMgr = getStateManager().getCallEventManager();
151e5dd7070Spatrick   CallEventRef<ObjCMethodCall> Msg =
152e5dd7070Spatrick     CEMgr.getObjCMethodCall(ME, Pred->getState(), Pred->getLocationContext());
153e5dd7070Spatrick 
154e5dd7070Spatrick   // There are three cases for the receiver:
155e5dd7070Spatrick   //   (1) it is definitely nil,
156e5dd7070Spatrick   //   (2) it is definitely non-nil, and
157e5dd7070Spatrick   //   (3) we don't know.
158e5dd7070Spatrick   //
159e5dd7070Spatrick   // If the receiver is definitely nil, we skip the pre/post callbacks and
160e5dd7070Spatrick   // instead call the ObjCMessageNil callbacks and return.
161e5dd7070Spatrick   //
162e5dd7070Spatrick   // If the receiver is definitely non-nil, we call the pre- callbacks,
163e5dd7070Spatrick   // evaluate the call, and call the post- callbacks.
164e5dd7070Spatrick   //
165e5dd7070Spatrick   // If we don't know, we drop the potential nil flow and instead
166e5dd7070Spatrick   // continue from the assumed non-nil state as in (2). This approach
167e5dd7070Spatrick   // intentionally drops coverage in order to prevent false alarms
168e5dd7070Spatrick   // in the following scenario:
169e5dd7070Spatrick   //
170e5dd7070Spatrick   // id result = [o someMethod]
171e5dd7070Spatrick   // if (result) {
172e5dd7070Spatrick   //   if (!o) {
173e5dd7070Spatrick   //     // <-- This program point should be unreachable because if o is nil
174e5dd7070Spatrick   //     // it must the case that result is nil as well.
175e5dd7070Spatrick   //   }
176e5dd7070Spatrick   // }
177e5dd7070Spatrick   //
178e5dd7070Spatrick   // We could avoid dropping coverage by performing an explicit case split
179e5dd7070Spatrick   // on each method call -- but this would get very expensive. An alternative
180e5dd7070Spatrick   // would be to introduce lazy constraints.
181e5dd7070Spatrick   // FIXME: This ignores many potential bugs (<rdar://problem/11733396>).
182e5dd7070Spatrick   // Revisit once we have lazier constraints.
183e5dd7070Spatrick   if (Msg->isInstanceMessage()) {
184e5dd7070Spatrick     SVal recVal = Msg->getReceiverSVal();
185e5dd7070Spatrick     if (!recVal.isUndef()) {
186e5dd7070Spatrick       // Bifurcate the state into nil and non-nil ones.
187e5dd7070Spatrick       DefinedOrUnknownSVal receiverVal =
188e5dd7070Spatrick           recVal.castAs<DefinedOrUnknownSVal>();
189e5dd7070Spatrick       ProgramStateRef State = Pred->getState();
190e5dd7070Spatrick 
191e5dd7070Spatrick       ProgramStateRef notNilState, nilState;
192e5dd7070Spatrick       std::tie(notNilState, nilState) = State->assume(receiverVal);
193e5dd7070Spatrick 
194e5dd7070Spatrick       // Receiver is definitely nil, so run ObjCMessageNil callbacks and return.
195e5dd7070Spatrick       if (nilState && !notNilState) {
196e5dd7070Spatrick         ExplodedNodeSet dstNil;
197e5dd7070Spatrick         StmtNodeBuilder Bldr(Pred, dstNil, *currBldrCtx);
198e5dd7070Spatrick         bool HasTag = Pred->getLocation().getTag();
199e5dd7070Spatrick         Pred = Bldr.generateNode(ME, Pred, nilState, nullptr,
200e5dd7070Spatrick                                  ProgramPoint::PreStmtKind);
201e5dd7070Spatrick         assert((Pred || HasTag) && "Should have cached out already!");
202e5dd7070Spatrick         (void)HasTag;
203e5dd7070Spatrick         if (!Pred)
204e5dd7070Spatrick           return;
205e5dd7070Spatrick 
206e5dd7070Spatrick         ExplodedNodeSet dstPostCheckers;
207e5dd7070Spatrick         getCheckerManager().runCheckersForObjCMessageNil(dstPostCheckers, Pred,
208e5dd7070Spatrick                                                          *Msg, *this);
209*12c85518Srobert         for (auto *I : dstPostCheckers)
210e5dd7070Spatrick           finishArgumentConstruction(Dst, I, *Msg);
211e5dd7070Spatrick         return;
212e5dd7070Spatrick       }
213e5dd7070Spatrick 
214e5dd7070Spatrick       ExplodedNodeSet dstNonNil;
215e5dd7070Spatrick       StmtNodeBuilder Bldr(Pred, dstNonNil, *currBldrCtx);
216e5dd7070Spatrick       // Generate a transition to the non-nil state, dropping any potential
217e5dd7070Spatrick       // nil flow.
218e5dd7070Spatrick       if (notNilState != State) {
219e5dd7070Spatrick         bool HasTag = Pred->getLocation().getTag();
220e5dd7070Spatrick         Pred = Bldr.generateNode(ME, Pred, notNilState);
221e5dd7070Spatrick         assert((Pred || HasTag) && "Should have cached out already!");
222e5dd7070Spatrick         (void)HasTag;
223e5dd7070Spatrick         if (!Pred)
224e5dd7070Spatrick           return;
225e5dd7070Spatrick       }
226e5dd7070Spatrick     }
227e5dd7070Spatrick   }
228e5dd7070Spatrick 
229e5dd7070Spatrick   // Handle the previsits checks.
230e5dd7070Spatrick   ExplodedNodeSet dstPrevisit;
231e5dd7070Spatrick   getCheckerManager().runCheckersForPreObjCMessage(dstPrevisit, Pred,
232e5dd7070Spatrick                                                    *Msg, *this);
233e5dd7070Spatrick   ExplodedNodeSet dstGenericPrevisit;
234e5dd7070Spatrick   getCheckerManager().runCheckersForPreCall(dstGenericPrevisit, dstPrevisit,
235e5dd7070Spatrick                                             *Msg, *this);
236e5dd7070Spatrick 
237e5dd7070Spatrick   // Proceed with evaluate the message expression.
238e5dd7070Spatrick   ExplodedNodeSet dstEval;
239e5dd7070Spatrick   StmtNodeBuilder Bldr(dstGenericPrevisit, dstEval, *currBldrCtx);
240e5dd7070Spatrick 
241e5dd7070Spatrick   for (ExplodedNodeSet::iterator DI = dstGenericPrevisit.begin(),
242e5dd7070Spatrick        DE = dstGenericPrevisit.end(); DI != DE; ++DI) {
243e5dd7070Spatrick     ExplodedNode *Pred = *DI;
244e5dd7070Spatrick     ProgramStateRef State = Pred->getState();
245e5dd7070Spatrick     CallEventRef<ObjCMethodCall> UpdatedMsg = Msg.cloneWithState(State);
246e5dd7070Spatrick 
247e5dd7070Spatrick     if (UpdatedMsg->isInstanceMessage()) {
248e5dd7070Spatrick       SVal recVal = UpdatedMsg->getReceiverSVal();
249e5dd7070Spatrick       if (!recVal.isUndef()) {
250e5dd7070Spatrick         if (ObjCNoRet.isImplicitNoReturn(ME)) {
251e5dd7070Spatrick           // If we raise an exception, for now treat it as a sink.
252e5dd7070Spatrick           // Eventually we will want to handle exceptions properly.
253e5dd7070Spatrick           Bldr.generateSink(ME, Pred, State);
254e5dd7070Spatrick           continue;
255e5dd7070Spatrick         }
256e5dd7070Spatrick       }
257e5dd7070Spatrick     } else {
258e5dd7070Spatrick       // Check for special class methods that are known to not return
259e5dd7070Spatrick       // and that we should treat as a sink.
260e5dd7070Spatrick       if (ObjCNoRet.isImplicitNoReturn(ME)) {
261e5dd7070Spatrick         // If we raise an exception, for now treat it as a sink.
262e5dd7070Spatrick         // Eventually we will want to handle exceptions properly.
263e5dd7070Spatrick         Bldr.generateSink(ME, Pred, Pred->getState());
264e5dd7070Spatrick         continue;
265e5dd7070Spatrick       }
266e5dd7070Spatrick     }
267e5dd7070Spatrick 
268e5dd7070Spatrick     defaultEvalCall(Bldr, Pred, *UpdatedMsg);
269e5dd7070Spatrick   }
270e5dd7070Spatrick 
271e5dd7070Spatrick   // If there were constructors called for object-type arguments, clean them up.
272e5dd7070Spatrick   ExplodedNodeSet dstArgCleanup;
273*12c85518Srobert   for (auto *I : dstEval)
274e5dd7070Spatrick     finishArgumentConstruction(dstArgCleanup, I, *Msg);
275e5dd7070Spatrick 
276e5dd7070Spatrick   ExplodedNodeSet dstPostvisit;
277e5dd7070Spatrick   getCheckerManager().runCheckersForPostCall(dstPostvisit, dstArgCleanup,
278e5dd7070Spatrick                                              *Msg, *this);
279e5dd7070Spatrick 
280e5dd7070Spatrick   // Finally, perform the post-condition check of the ObjCMessageExpr and store
281e5dd7070Spatrick   // the created nodes in 'Dst'.
282e5dd7070Spatrick   getCheckerManager().runCheckersForPostObjCMessage(Dst, dstPostvisit,
283e5dd7070Spatrick                                                     *Msg, *this);
284e5dd7070Spatrick }
285