| 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 | |
| 18 | using namespace clang; |
| 19 | using namespace ento; |
| 20 | |
| 21 | void 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 | |
| 38 | void 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. |
| 46 | static void populateObjCForDestinationSet(ExplodedNodeSet &dstLocation, |
| 47 | SValBuilder &svalBuilder, |
| 48 | const ObjCForCollectionStmt *S, |
| 49 | ConstCFGElementRef elem, |
| 50 | SVal elementV, SymbolManager &SymMgr, |
| 51 | const NodeBuilderContext *currBldrCtx, |
| 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: currBldrCtx->blockCount()); |
| 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 | |
| 85 | void 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, currBldrCtx, |
| 140 | Bldr, |
| 141 | /*hasElements=*/true); |
| 142 | |
| 143 | populateObjCForDestinationSet(dstLocation&: DstLocationSingleton, svalBuilder, S, elem: elemRef, |
| 144 | elementV, SymMgr, currBldrCtx, Bldr, |
| 145 | /*hasElements=*/false); |
| 146 | |
| 147 | // Finally, run any custom checkers. |
| 148 | // FIXME: Eventually all pre- and post-checks should live in VisitStmt. |
| 149 | getCheckerManager().runCheckersForPostStmt(Dst, Src: Tmp, S, Eng&: *this); |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | void ExprEngine::VisitObjCMessage(const ObjCMessageExpr *ME, |
| 154 | ExplodedNode *Pred, |
| 155 | ExplodedNodeSet &Dst) { |
| 156 | CallEventManager &CEMgr = getStateManager().getCallEventManager(); |
| 157 | CallEventRef<ObjCMethodCall> Msg = CEMgr.getObjCMethodCall( |
| 158 | E: ME, State: Pred->getState(), LCtx: Pred->getLocationContext(), ElemRef: getCFGElementRef()); |
| 159 | |
| 160 | // There are three cases for the receiver: |
| 161 | // (1) it is definitely nil, |
| 162 | // (2) it is definitely non-nil, and |
| 163 | // (3) we don't know. |
| 164 | // |
| 165 | // If the receiver is definitely nil, we skip the pre/post callbacks and |
| 166 | // instead call the ObjCMessageNil callbacks and return. |
| 167 | // |
| 168 | // If the receiver is definitely non-nil, we call the pre- callbacks, |
| 169 | // evaluate the call, and call the post- callbacks. |
| 170 | // |
| 171 | // If we don't know, we drop the potential nil flow and instead |
| 172 | // continue from the assumed non-nil state as in (2). This approach |
| 173 | // intentionally drops coverage in order to prevent false alarms |
| 174 | // in the following scenario: |
| 175 | // |
| 176 | // id result = [o someMethod] |
| 177 | // if (result) { |
| 178 | // if (!o) { |
| 179 | // // <-- This program point should be unreachable because if o is nil |
| 180 | // // it must the case that result is nil as well. |
| 181 | // } |
| 182 | // } |
| 183 | // |
| 184 | // However, it also loses coverage of the nil path prematurely, |
| 185 | // leading to missed reports. |
| 186 | // |
| 187 | // It's possible to handle this by performing a state split on every call: |
| 188 | // explore the state where the receiver is non-nil, and independently |
| 189 | // explore the state where it's nil. But this is not only slow, but |
| 190 | // completely unwarranted. The mere presence of the message syntax in the code |
| 191 | // isn't sufficient evidence that nil is a realistic possibility. |
| 192 | // |
| 193 | // An ideal solution would be to add the following constraint that captures |
| 194 | // both possibilities without splitting the state: |
| 195 | // |
| 196 | // ($x == 0) => ($y == 0) (1) |
| 197 | // |
| 198 | // where in our case '$x' is the receiver symbol, '$y' is the returned symbol, |
| 199 | // and '=>' is logical implication. But RangeConstraintManager can't handle |
| 200 | // such constraints yet, so for now we go with a simpler, more restrictive |
| 201 | // constraint: $x != 0, from which (1) follows as a vacuous truth. |
| 202 | if (Msg->isInstanceMessage()) { |
| 203 | SVal recVal = Msg->getReceiverSVal(); |
| 204 | if (!recVal.isUndef()) { |
| 205 | // Bifurcate the state into nil and non-nil ones. |
| 206 | DefinedOrUnknownSVal receiverVal = |
| 207 | recVal.castAs<DefinedOrUnknownSVal>(); |
| 208 | ProgramStateRef State = Pred->getState(); |
| 209 | |
| 210 | ProgramStateRef notNilState, nilState; |
| 211 | std::tie(args&: notNilState, args&: nilState) = State->assume(Cond: receiverVal); |
| 212 | |
| 213 | // Receiver is definitely nil, so run ObjCMessageNil callbacks and return. |
| 214 | if (nilState && !notNilState) { |
| 215 | ExplodedNodeSet dstNil; |
| 216 | NodeBuilder Bldr(Pred, dstNil, *currBldrCtx); |
| 217 | bool HasTag = Pred->getLocation().getTag(); |
| 218 | Pred = Bldr.generateNode(S: ME, Pred, St: nilState, tag: nullptr, |
| 219 | K: ProgramPoint::PreStmtKind); |
| 220 | assert((Pred || HasTag) && "Should have cached out already!" ); |
| 221 | (void)HasTag; |
| 222 | if (!Pred) |
| 223 | return; |
| 224 | |
| 225 | ExplodedNodeSet dstPostCheckers; |
| 226 | getCheckerManager().runCheckersForObjCMessageNil(Dst&: dstPostCheckers, Src: Pred, |
| 227 | msg: *Msg, Eng&: *this); |
| 228 | for (auto *I : dstPostCheckers) |
| 229 | finishArgumentConstruction(Dst, Pred: I, Call: *Msg); |
| 230 | return; |
| 231 | } |
| 232 | |
| 233 | ExplodedNodeSet dstNonNil; |
| 234 | NodeBuilder Bldr(Pred, dstNonNil, *currBldrCtx); |
| 235 | // Generate a transition to the non-nil state, dropping any potential |
| 236 | // nil flow. |
| 237 | if (notNilState != State) { |
| 238 | bool HasTag = Pred->getLocation().getTag(); |
| 239 | Pred = Bldr.generateNode(S: ME, Pred, St: notNilState); |
| 240 | assert((Pred || HasTag) && "Should have cached out already!" ); |
| 241 | (void)HasTag; |
| 242 | if (!Pred) |
| 243 | return; |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | // Handle the previsits checks. |
| 249 | ExplodedNodeSet dstPrevisit; |
| 250 | getCheckerManager().runCheckersForPreObjCMessage(Dst&: dstPrevisit, Src: Pred, |
| 251 | msg: *Msg, Eng&: *this); |
| 252 | ExplodedNodeSet dstGenericPrevisit; |
| 253 | getCheckerManager().runCheckersForPreCall(Dst&: dstGenericPrevisit, Src: dstPrevisit, |
| 254 | Call: *Msg, Eng&: *this); |
| 255 | |
| 256 | // Proceed with evaluate the message expression. |
| 257 | ExplodedNodeSet dstEval; |
| 258 | NodeBuilder Bldr(dstGenericPrevisit, dstEval, *currBldrCtx); |
| 259 | |
| 260 | for (ExplodedNodeSet::iterator DI = dstGenericPrevisit.begin(), |
| 261 | DE = dstGenericPrevisit.end(); DI != DE; ++DI) { |
| 262 | ExplodedNode *Pred = *DI; |
| 263 | ProgramStateRef State = Pred->getState(); |
| 264 | CallEventRef<ObjCMethodCall> UpdatedMsg = Msg.cloneWithState(State); |
| 265 | |
| 266 | if (UpdatedMsg->isInstanceMessage()) { |
| 267 | SVal recVal = UpdatedMsg->getReceiverSVal(); |
| 268 | if (!recVal.isUndef()) { |
| 269 | if (ObjCNoRet.isImplicitNoReturn(ME)) { |
| 270 | // If we raise an exception, for now treat it as a sink. |
| 271 | // Eventually we will want to handle exceptions properly. |
| 272 | Bldr.generateSink(S: ME, Pred, St: State); |
| 273 | continue; |
| 274 | } |
| 275 | } |
| 276 | } else { |
| 277 | // Check for special class methods that are known to not return |
| 278 | // and that we should treat as a sink. |
| 279 | if (ObjCNoRet.isImplicitNoReturn(ME)) { |
| 280 | // If we raise an exception, for now treat it as a sink. |
| 281 | // Eventually we will want to handle exceptions properly. |
| 282 | Bldr.generateSink(S: ME, Pred, St: Pred->getState()); |
| 283 | continue; |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | defaultEvalCall(B&: Bldr, Pred, Call: *UpdatedMsg); |
| 288 | } |
| 289 | |
| 290 | // If there were constructors called for object-type arguments, clean them up. |
| 291 | ExplodedNodeSet dstArgCleanup; |
| 292 | for (auto *I : dstEval) |
| 293 | finishArgumentConstruction(Dst&: dstArgCleanup, Pred: I, Call: *Msg); |
| 294 | |
| 295 | ExplodedNodeSet dstPostvisit; |
| 296 | getCheckerManager().runCheckersForPostCall(Dst&: dstPostvisit, Src: dstArgCleanup, |
| 297 | Call: *Msg, Eng&: *this); |
| 298 | |
| 299 | // Finally, perform the post-condition check of the ObjCMessageExpr and store |
| 300 | // the created nodes in 'Dst'. |
| 301 | getCheckerManager().runCheckersForPostObjCMessage(Dst, Src: dstPostvisit, |
| 302 | msg: *Msg, Eng&: *this); |
| 303 | } |
| 304 | |