| 1 | //===- ExprEngineCXX.cpp - ExprEngine support for 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 the C++ expression evaluation engine. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #include "clang/AST/ASTContext.h" |
| 14 | #include "clang/AST/AttrIterator.h" |
| 15 | #include "clang/AST/DeclCXX.h" |
| 16 | #include "clang/AST/ParentMap.h" |
| 17 | #include "clang/AST/StmtCXX.h" |
| 18 | #include "clang/Analysis/ConstructionContext.h" |
| 19 | #include "clang/Basic/PrettyStackTrace.h" |
| 20 | #include "clang/StaticAnalyzer/Core/CheckerManager.h" |
| 21 | #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" |
| 22 | #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" |
| 23 | #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" |
| 24 | #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" |
| 25 | #include "llvm/ADT/STLExtras.h" |
| 26 | #include "llvm/ADT/Sequence.h" |
| 27 | #include "llvm/Support/Casting.h" |
| 28 | #include <optional> |
| 29 | |
| 30 | using namespace clang; |
| 31 | using namespace ento; |
| 32 | |
| 33 | void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, |
| 34 | ExplodedNode *Pred, |
| 35 | ExplodedNodeSet &Dst) { |
| 36 | const Expr *tempExpr = ME->getSubExpr()->IgnoreParens(); |
| 37 | ProgramStateRef state = Pred->getState(); |
| 38 | const StackFrame *SF = Pred->getStackFrame(); |
| 39 | |
| 40 | state = createTemporaryRegionIfNeeded(State: state, SF, InitWithAdjustments: tempExpr, Result: ME); |
| 41 | Dst.insert(N: Engine.makePostStmtNode(S: ME, State: state, Pred)); |
| 42 | } |
| 43 | |
| 44 | void ExprEngine::performTrivialCopy(ExplodedNodeSet &Dst, ExplodedNode *Pred, |
| 45 | const CallEvent &Call) { |
| 46 | SVal ThisVal; |
| 47 | bool AlwaysReturnsLValue; |
| 48 | [[maybe_unused]] const CXXRecordDecl *ThisRD = nullptr; |
| 49 | if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(Val: &Call)) { |
| 50 | assert(Ctor->getDecl()->isTrivial()); |
| 51 | assert(Ctor->getDecl()->isCopyOrMoveConstructor()); |
| 52 | ThisVal = Ctor->getCXXThisVal(); |
| 53 | ThisRD = Ctor->getDecl()->getParent(); |
| 54 | AlwaysReturnsLValue = false; |
| 55 | } else { |
| 56 | assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial()); |
| 57 | assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() == |
| 58 | OO_Equal); |
| 59 | ThisVal = cast<CXXInstanceCall>(Val: Call).getCXXThisVal(); |
| 60 | ThisRD = cast<CXXMethodDecl>(Val: Call.getDecl())->getParent(); |
| 61 | AlwaysReturnsLValue = true; |
| 62 | } |
| 63 | |
| 64 | const StackFrame *SF = Pred->getStackFrame(); |
| 65 | const Expr *CallExpr = Call.getOriginExpr(); |
| 66 | |
| 67 | ExplodedNodeSet DstEval; |
| 68 | |
| 69 | assert(ThisRD); |
| 70 | |
| 71 | if (!ThisRD->isEmpty()) { |
| 72 | SVal V = Call.getArgSVal(Index: 0); |
| 73 | const Expr *VExpr = Call.getArgExpr(Index: 0); |
| 74 | |
| 75 | // If the value being copied is not unknown, load from its location to get |
| 76 | // an aggregate rvalue. |
| 77 | if (std::optional<Loc> L = V.getAs<Loc>()) |
| 78 | V = Pred->getState()->getSVal(LV: *L); |
| 79 | else |
| 80 | assert(V.isUnknownOrUndef()); |
| 81 | |
| 82 | ExplodedNodeSet Tmp; |
| 83 | evalLocation(Dst&: Tmp, NodeEx: CallExpr, BoundEx: VExpr, Pred, St: Pred->getState(), location: V, |
| 84 | /*isLoad=*/true); |
| 85 | for (ExplodedNode *N : Tmp) |
| 86 | evalBind(Dst&: DstEval, StoreE: CallExpr, Pred: N, location: ThisVal, Val: V, AtDeclInit: !AlwaysReturnsLValue); |
| 87 | } else { |
| 88 | // We can't copy empty classes because of empty base class optimization. |
| 89 | // In that case, copying the empty base class subobject would overwrite the |
| 90 | // object that it overlaps with - so let's not do that. |
| 91 | // See issue-157467.cpp for an example. |
| 92 | DstEval.insert(N: Pred); |
| 93 | } |
| 94 | |
| 95 | for (ExplodedNode *N : DstEval) { |
| 96 | ProgramStateRef State = N->getState(); |
| 97 | if (AlwaysReturnsLValue) |
| 98 | State = State->BindExpr(E: CallExpr, SF, V: ThisVal); |
| 99 | else |
| 100 | State = bindReturnValue(Call, SF, State); |
| 101 | Dst.insert(N: Engine.makePostStmtNode(S: CallExpr, State, Pred: N)); |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | SVal ExprEngine::makeElementRegion(ProgramStateRef State, SVal LValue, |
| 106 | QualType &Ty, bool &IsArray, unsigned Idx) { |
| 107 | SValBuilder &SVB = State->getStateManager().getSValBuilder(); |
| 108 | ASTContext &Ctx = SVB.getContext(); |
| 109 | |
| 110 | if (const ArrayType *AT = Ctx.getAsArrayType(T: Ty)) { |
| 111 | while (AT) { |
| 112 | Ty = AT->getElementType(); |
| 113 | AT = dyn_cast<ArrayType>(Val: AT->getElementType()); |
| 114 | } |
| 115 | LValue = State->getLValue(ElementType: Ty, Idx: SVB.makeArrayIndex(idx: Idx), Base: LValue); |
| 116 | IsArray = true; |
| 117 | } |
| 118 | |
| 119 | return LValue; |
| 120 | } |
| 121 | |
| 122 | // In case when the prvalue is returned from the function (kind is one of |
| 123 | // SimpleReturnedValueKind, CXX17ElidedCopyReturnedValueKind), then |
| 124 | // it's materialization happens in context of the caller. |
| 125 | SVal ExprEngine::computeObjectUnderConstruction( |
| 126 | const Expr *E, ProgramStateRef State, unsigned NumVisitedCaller, |
| 127 | const StackFrame *SF, const ConstructionContext *CC, |
| 128 | EvalCallOptions &CallOpts, unsigned Idx) { |
| 129 | |
| 130 | SValBuilder &SVB = getSValBuilder(); |
| 131 | MemRegionManager &MRMgr = SVB.getRegionManager(); |
| 132 | ASTContext &ACtx = SVB.getContext(); |
| 133 | |
| 134 | // Compute the target region by exploring the construction context. |
| 135 | if (CC) { |
| 136 | switch (CC->getKind()) { |
| 137 | case ConstructionContext::CXX17ElidedCopyVariableKind: |
| 138 | case ConstructionContext::SimpleVariableKind: { |
| 139 | const auto *DSCC = cast<VariableConstructionContext>(Val: CC); |
| 140 | const auto *DS = DSCC->getDeclStmt(); |
| 141 | const auto *Var = cast<VarDecl>(Val: DS->getSingleDecl()); |
| 142 | QualType Ty = Var->getType(); |
| 143 | return makeElementRegion(State, LValue: State->getLValue(VD: Var, SF), Ty, |
| 144 | IsArray&: CallOpts.IsArrayCtorOrDtor, Idx); |
| 145 | } |
| 146 | case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: |
| 147 | case ConstructionContext::SimpleConstructorInitializerKind: { |
| 148 | const auto *ICC = cast<ConstructorInitializerConstructionContext>(Val: CC); |
| 149 | const auto *Init = ICC->getCXXCtorInitializer(); |
| 150 | const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(Val: SF->getDecl()); |
| 151 | Loc ThisPtr = SVB.getCXXThis(D: CurCtor, SF); |
| 152 | SVal ThisVal = State->getSVal(LV: ThisPtr); |
| 153 | if (Init->isBaseInitializer()) { |
| 154 | const auto *ThisReg = cast<SubRegion>(Val: ThisVal.getAsRegion()); |
| 155 | const CXXRecordDecl *BaseClass = |
| 156 | Init->getBaseClass()->getAsCXXRecordDecl(); |
| 157 | const auto *BaseReg = |
| 158 | MRMgr.getCXXBaseObjectRegion(BaseClass, Super: ThisReg, |
| 159 | IsVirtual: Init->isBaseVirtual()); |
| 160 | return SVB.makeLoc(region: BaseReg); |
| 161 | } |
| 162 | if (Init->isDelegatingInitializer()) |
| 163 | return ThisVal; |
| 164 | |
| 165 | const ValueDecl *Field; |
| 166 | SVal FieldVal; |
| 167 | if (Init->isIndirectMemberInitializer()) { |
| 168 | Field = Init->getIndirectMember(); |
| 169 | FieldVal = State->getLValue(decl: Init->getIndirectMember(), Base: ThisVal); |
| 170 | } else { |
| 171 | Field = Init->getMember(); |
| 172 | FieldVal = State->getLValue(decl: Init->getMember(), Base: ThisVal); |
| 173 | } |
| 174 | |
| 175 | QualType Ty = Field->getType(); |
| 176 | return makeElementRegion(State, LValue: FieldVal, Ty, IsArray&: CallOpts.IsArrayCtorOrDtor, |
| 177 | Idx); |
| 178 | } |
| 179 | case ConstructionContext::NewAllocatedObjectKind: { |
| 180 | if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) { |
| 181 | const auto *NECC = cast<NewAllocatedObjectConstructionContext>(Val: CC); |
| 182 | const auto *NE = NECC->getCXXNewExpr(); |
| 183 | SVal V = *getObjectUnderConstruction(State, Item: NE, SF); |
| 184 | if (const SubRegion *MR = |
| 185 | dyn_cast_or_null<SubRegion>(Val: V.getAsRegion())) { |
| 186 | if (NE->isArray()) { |
| 187 | CallOpts.IsArrayCtorOrDtor = true; |
| 188 | |
| 189 | auto Ty = NE->getType()->getPointeeType(); |
| 190 | while (const auto *AT = getContext().getAsArrayType(T: Ty)) |
| 191 | Ty = AT->getElementType(); |
| 192 | |
| 193 | auto R = MRMgr.getElementRegion(elementType: Ty, Idx: svalBuilder.makeArrayIndex(idx: Idx), |
| 194 | superRegion: MR, Ctx: SVB.getContext()); |
| 195 | |
| 196 | return loc::MemRegionVal(R); |
| 197 | } |
| 198 | return V; |
| 199 | } |
| 200 | // TODO: Detect when the allocator returns a null pointer. |
| 201 | // Constructor shall not be called in this case. |
| 202 | } |
| 203 | break; |
| 204 | } |
| 205 | case ConstructionContext::SimpleReturnedValueKind: |
| 206 | case ConstructionContext::CXX17ElidedCopyReturnedValueKind: { |
| 207 | // The temporary is to be managed by the parent stack frame. |
| 208 | // So build it in the parent stack frame if we're not in the |
| 209 | // top frame of the analysis. |
| 210 | if (const StackFrame *CallerSF = SF->getParent()) { |
| 211 | auto RTC = (*SF->getCallSiteBlock())[SF->getIndex()] |
| 212 | .getAs<CFGCXXRecordTypedCall>(); |
| 213 | if (!RTC) { |
| 214 | // We were unable to find the correct construction context for the |
| 215 | // call in the parent stack frame. This is equivalent to not being |
| 216 | // able to find construction context at all. |
| 217 | break; |
| 218 | } |
| 219 | |
| 220 | unsigned NVCaller = getNumVisited(SF: CallerSF, Block: SF->getCallSiteBlock()); |
| 221 | return computeObjectUnderConstruction( |
| 222 | E: SF->getCallSite(), State, NumVisitedCaller: NVCaller, SF: CallerSF, |
| 223 | CC: RTC->getConstructionContext(), CallOpts); |
| 224 | } else { |
| 225 | // We are on the top frame of the analysis. We do not know where is the |
| 226 | // object returned to. Conjure a symbolic region for the return value. |
| 227 | // TODO: We probably need a new MemRegion kind to represent the storage |
| 228 | // of that SymbolicRegion, so that we could produce a fancy symbol |
| 229 | // instead of an anonymous conjured symbol. |
| 230 | // TODO: Do we need to track the region to avoid having it dead |
| 231 | // too early? It does die too early, at least in C++17, but because |
| 232 | // putting anything into a SymbolicRegion causes an immediate escape, |
| 233 | // it doesn't cause any leak false positives. |
| 234 | const auto *RCC = cast<ReturnedValueConstructionContext>(Val: CC); |
| 235 | // Make sure that this doesn't coincide with any other symbol |
| 236 | // conjured for the returned expression. |
| 237 | static const int TopLevelSymRegionTag = 0; |
| 238 | const Expr *RetE = RCC->getReturnStmt()->getRetValue(); |
| 239 | assert(RetE && "Void returns should not have a construction context" ); |
| 240 | QualType ReturnTy = RetE->getType(); |
| 241 | QualType RegionTy = ACtx.getPointerType(T: ReturnTy); |
| 242 | return SVB.conjureSymbolVal(symbolTag: &TopLevelSymRegionTag, elem: getCFGElementRef(), |
| 243 | SF, type: RegionTy, count: getNumVisitedCurrent()); |
| 244 | } |
| 245 | llvm_unreachable("Unhandled return value construction context!" ); |
| 246 | } |
| 247 | case ConstructionContext::ElidedTemporaryObjectKind: { |
| 248 | assert(AMgr.getAnalyzerOptions().ShouldElideConstructors); |
| 249 | const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(Val: CC); |
| 250 | |
| 251 | // Support pre-C++17 copy elision. We'll have the elidable copy |
| 252 | // constructor in the AST and in the CFG, but we'll skip it |
| 253 | // and construct directly into the final object. This call |
| 254 | // also sets the CallOpts flags for us. |
| 255 | // If the elided copy/move constructor is not supported, there's still |
| 256 | // benefit in trying to model the non-elided constructor. |
| 257 | // Stash the call options before trying to elide, as they'll get |
| 258 | // overwritten. |
| 259 | EvalCallOptions PreElideCallOpts = CallOpts; |
| 260 | |
| 261 | SVal V = computeObjectUnderConstruction( |
| 262 | E: TCC->getConstructorAfterElision(), State, NumVisitedCaller, SF, |
| 263 | CC: TCC->getConstructionContextAfterElision(), CallOpts); |
| 264 | |
| 265 | // FIXME: This definition of "copy elision has not failed" is unreliable. |
| 266 | // It doesn't indicate that the constructor will actually be inlined |
| 267 | // later; this is still up to evalCall() to decide. |
| 268 | if (!CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) |
| 269 | return V; |
| 270 | |
| 271 | // Copy elision failed. Revert the changes and proceed as if we have |
| 272 | // a simple temporary. |
| 273 | CallOpts = PreElideCallOpts; |
| 274 | CallOpts.IsElidableCtorThatHasNotBeenElided = true; |
| 275 | [[fallthrough]]; |
| 276 | } |
| 277 | case ConstructionContext::SimpleTemporaryObjectKind: { |
| 278 | const auto *TCC = cast<TemporaryObjectConstructionContext>(Val: CC); |
| 279 | const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr(); |
| 280 | |
| 281 | CallOpts.IsTemporaryCtorOrDtor = true; |
| 282 | if (MTE) { |
| 283 | if (const ValueDecl *VD = MTE->getExtendingDecl()) { |
| 284 | StorageDuration SD = MTE->getStorageDuration(); |
| 285 | assert(SD != SD_FullExpression); |
| 286 | if (!VD->getType()->isReferenceType()) { |
| 287 | // We're lifetime-extended by a surrounding aggregate. |
| 288 | // Automatic destructors aren't quite working in this case |
| 289 | // on the CFG side. We should warn the caller about that. |
| 290 | // FIXME: Is there a better way to retrieve this information from |
| 291 | // the MaterializeTemporaryExpr? |
| 292 | CallOpts.IsTemporaryLifetimeExtendedViaAggregate = true; |
| 293 | } |
| 294 | |
| 295 | if (SD == SD_Static || SD == SD_Thread) |
| 296 | return loc::MemRegionVal( |
| 297 | MRMgr.getCXXStaticLifetimeExtendedObjectRegion(Ex: E, VD)); |
| 298 | |
| 299 | return loc::MemRegionVal( |
| 300 | MRMgr.getCXXLifetimeExtendedObjectRegion(Ex: E, VD, SF)); |
| 301 | } |
| 302 | assert(MTE->getStorageDuration() == SD_FullExpression); |
| 303 | } |
| 304 | |
| 305 | return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(Ex: E, SF)); |
| 306 | } |
| 307 | case ConstructionContext::LambdaCaptureKind: { |
| 308 | CallOpts.IsTemporaryCtorOrDtor = true; |
| 309 | |
| 310 | const auto *LCC = cast<LambdaCaptureConstructionContext>(Val: CC); |
| 311 | |
| 312 | SVal Base = loc::MemRegionVal( |
| 313 | MRMgr.getCXXTempObjectRegion(Ex: LCC->getInitializer(), SF)); |
| 314 | |
| 315 | const auto *CE = dyn_cast_or_null<CXXConstructExpr>(Val: E); |
| 316 | if (getIndexOfElementToConstruct(State, E: CE, SF)) { |
| 317 | CallOpts.IsArrayCtorOrDtor = true; |
| 318 | Base = State->getLValue(ElementType: E->getType(), Idx: svalBuilder.makeArrayIndex(idx: Idx), |
| 319 | Base); |
| 320 | } |
| 321 | |
| 322 | return Base; |
| 323 | } |
| 324 | case ConstructionContext::ArgumentKind: { |
| 325 | // Arguments are technically temporaries. |
| 326 | CallOpts.IsTemporaryCtorOrDtor = true; |
| 327 | |
| 328 | const auto *ACC = cast<ArgumentConstructionContext>(Val: CC); |
| 329 | const Expr *E = ACC->getCallLikeExpr(); |
| 330 | unsigned Idx = ACC->getIndex(); |
| 331 | |
| 332 | CallEventManager &CEMgr = getStateManager().getCallEventManager(); |
| 333 | auto getArgLoc = [&](CallEventRef<> Caller) -> std::optional<SVal> { |
| 334 | const StackFrame *FutureSF = |
| 335 | Caller->getCalleeStackFrame(BlockCount: NumVisitedCaller); |
| 336 | // Return early if we are unable to reliably foresee |
| 337 | // the future stack frame. |
| 338 | if (!FutureSF) |
| 339 | return std::nullopt; |
| 340 | |
| 341 | // This should be equivalent to Caller->getDecl() for now, but |
| 342 | // FutureSF->getDecl() is likely to support better stuff (like |
| 343 | // virtual functions) earlier. |
| 344 | const Decl *CalleeD = FutureSF->getDecl(); |
| 345 | |
| 346 | // FIXME: Support for variadic arguments is not implemented here yet. |
| 347 | if (CallEvent::isVariadic(D: CalleeD)) |
| 348 | return std::nullopt; |
| 349 | |
| 350 | // Operator arguments do not correspond to operator parameters |
| 351 | // because this-argument is implemented as a normal argument in |
| 352 | // operator call expressions but not in operator declarations. |
| 353 | const TypedValueRegion *TVR = Caller->getParameterLocation( |
| 354 | Index: *Caller->getAdjustedParameterIndex(ASTArgumentIndex: Idx), BlockCount: NumVisitedCaller); |
| 355 | if (!TVR) |
| 356 | return std::nullopt; |
| 357 | |
| 358 | return loc::MemRegionVal(TVR); |
| 359 | }; |
| 360 | |
| 361 | if (const auto *CE = dyn_cast<CallExpr>(Val: E)) { |
| 362 | CallEventRef<> Caller = |
| 363 | CEMgr.getSimpleCall(E: CE, State, SF, ElemRef: getCFGElementRef()); |
| 364 | if (std::optional<SVal> V = getArgLoc(Caller)) |
| 365 | return *V; |
| 366 | else |
| 367 | break; |
| 368 | } else if (const auto *CCE = dyn_cast<CXXConstructExpr>(Val: E)) { |
| 369 | // Don't bother figuring out the target region for the future |
| 370 | // constructor because we won't need it. |
| 371 | CallEventRef<> Caller = CEMgr.getCXXConstructorCall( |
| 372 | E: CCE, /*Target=*/nullptr, State, SF, ElemRef: getCFGElementRef()); |
| 373 | if (std::optional<SVal> V = getArgLoc(Caller)) |
| 374 | return *V; |
| 375 | else |
| 376 | break; |
| 377 | } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(Val: E)) { |
| 378 | CallEventRef<> Caller = |
| 379 | CEMgr.getObjCMethodCall(E: ME, State, SF, ElemRef: getCFGElementRef()); |
| 380 | if (std::optional<SVal> V = getArgLoc(Caller)) |
| 381 | return *V; |
| 382 | else |
| 383 | break; |
| 384 | } |
| 385 | } |
| 386 | } // switch (CC->getKind()) |
| 387 | } |
| 388 | |
| 389 | // If we couldn't find an existing region to construct into, assume we're |
| 390 | // constructing a temporary. Notify the caller of our failure. |
| 391 | CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; |
| 392 | return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(Ex: E, SF)); |
| 393 | } |
| 394 | |
| 395 | ProgramStateRef ExprEngine::updateObjectsUnderConstruction( |
| 396 | SVal V, const Expr *E, ProgramStateRef State, const StackFrame *SF, |
| 397 | const ConstructionContext *CC, const EvalCallOptions &CallOpts) { |
| 398 | if (CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) { |
| 399 | // Sounds like we failed to find the target region and therefore |
| 400 | // copy elision failed. There's nothing we can do about it here. |
| 401 | return State; |
| 402 | } |
| 403 | |
| 404 | // See if we're constructing an existing region by looking at the |
| 405 | // current construction context. |
| 406 | assert(CC && "Computed target region without construction context?" ); |
| 407 | switch (CC->getKind()) { |
| 408 | case ConstructionContext::CXX17ElidedCopyVariableKind: |
| 409 | case ConstructionContext::SimpleVariableKind: { |
| 410 | const auto *DSCC = cast<VariableConstructionContext>(Val: CC); |
| 411 | return addObjectUnderConstruction(State, Item: DSCC->getDeclStmt(), SF, V); |
| 412 | } |
| 413 | case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: |
| 414 | case ConstructionContext::SimpleConstructorInitializerKind: { |
| 415 | const auto *ICC = cast<ConstructorInitializerConstructionContext>(Val: CC); |
| 416 | const auto *Init = ICC->getCXXCtorInitializer(); |
| 417 | // Base and delegating initializers handled above |
| 418 | assert(Init->isAnyMemberInitializer() && |
| 419 | "Base and delegating initializers should have been handled by" |
| 420 | "computeObjectUnderConstruction()" ); |
| 421 | return addObjectUnderConstruction(State, Item: Init, SF, V); |
| 422 | } |
| 423 | case ConstructionContext::NewAllocatedObjectKind: { |
| 424 | return State; |
| 425 | } |
| 426 | case ConstructionContext::SimpleReturnedValueKind: |
| 427 | case ConstructionContext::CXX17ElidedCopyReturnedValueKind: { |
| 428 | const StackFrame *CallerSF = SF->getParent(); |
| 429 | if (!CallerSF) { |
| 430 | // No extra work is necessary in top frame. |
| 431 | return State; |
| 432 | } |
| 433 | |
| 434 | auto RTC = (*SF->getCallSiteBlock())[SF->getIndex()] |
| 435 | .getAs<CFGCXXRecordTypedCall>(); |
| 436 | assert(RTC && "Could not have had a target region without it" ); |
| 437 | |
| 438 | return updateObjectsUnderConstruction( |
| 439 | V, E: SF->getCallSite(), State, SF: CallerSF, CC: RTC->getConstructionContext(), |
| 440 | CallOpts); |
| 441 | } |
| 442 | case ConstructionContext::ElidedTemporaryObjectKind: { |
| 443 | assert(AMgr.getAnalyzerOptions().ShouldElideConstructors); |
| 444 | if (!CallOpts.IsElidableCtorThatHasNotBeenElided) { |
| 445 | const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(Val: CC); |
| 446 | State = updateObjectsUnderConstruction( |
| 447 | V, E: TCC->getConstructorAfterElision(), State, SF, |
| 448 | CC: TCC->getConstructionContextAfterElision(), CallOpts); |
| 449 | |
| 450 | // Remember that we've elided the constructor. |
| 451 | State = addObjectUnderConstruction( |
| 452 | State, Item: TCC->getConstructorAfterElision(), SF, V); |
| 453 | |
| 454 | // Remember that we've elided the destructor. |
| 455 | if (const auto *BTE = TCC->getCXXBindTemporaryExpr()) |
| 456 | State = elideDestructor(State, BTE, SF); |
| 457 | |
| 458 | // Instead of materialization, shamelessly return |
| 459 | // the final object destination. |
| 460 | if (const auto *MTE = TCC->getMaterializedTemporaryExpr()) |
| 461 | State = addObjectUnderConstruction(State, Item: MTE, SF, V); |
| 462 | |
| 463 | return State; |
| 464 | } |
| 465 | // If we decided not to elide the constructor, proceed as if |
| 466 | // it's a simple temporary. |
| 467 | [[fallthrough]]; |
| 468 | } |
| 469 | case ConstructionContext::SimpleTemporaryObjectKind: { |
| 470 | const auto *TCC = cast<TemporaryObjectConstructionContext>(Val: CC); |
| 471 | if (const auto *BTE = TCC->getCXXBindTemporaryExpr()) |
| 472 | State = addObjectUnderConstruction(State, Item: BTE, SF, V); |
| 473 | |
| 474 | if (const auto *MTE = TCC->getMaterializedTemporaryExpr()) |
| 475 | State = addObjectUnderConstruction(State, Item: MTE, SF, V); |
| 476 | |
| 477 | return State; |
| 478 | } |
| 479 | case ConstructionContext::LambdaCaptureKind: { |
| 480 | const auto *LCC = cast<LambdaCaptureConstructionContext>(Val: CC); |
| 481 | |
| 482 | // If we capture and array, we want to store the super region, not a |
| 483 | // sub-region. |
| 484 | if (const auto *EL = dyn_cast_or_null<ElementRegion>(Val: V.getAsRegion())) |
| 485 | V = loc::MemRegionVal(EL->getSuperRegion()); |
| 486 | |
| 487 | return addObjectUnderConstruction( |
| 488 | State, Item: {LCC->getLambdaExpr(), LCC->getIndex()}, SF, V); |
| 489 | } |
| 490 | case ConstructionContext::ArgumentKind: { |
| 491 | const auto *ACC = cast<ArgumentConstructionContext>(Val: CC); |
| 492 | if (const auto *BTE = ACC->getCXXBindTemporaryExpr()) |
| 493 | State = addObjectUnderConstruction(State, Item: BTE, SF, V); |
| 494 | |
| 495 | return addObjectUnderConstruction( |
| 496 | State, Item: {ACC->getCallLikeExpr(), ACC->getIndex()}, SF, V); |
| 497 | } |
| 498 | } |
| 499 | llvm_unreachable("Unhandled construction context!" ); |
| 500 | } |
| 501 | |
| 502 | static ProgramStateRef |
| 503 | bindRequiredArrayElementToEnvironment(ProgramStateRef State, |
| 504 | const ArrayInitLoopExpr *AILE, |
| 505 | const StackFrame *SF, NonLoc Idx) { |
| 506 | SValBuilder &SVB = State->getStateManager().getSValBuilder(); |
| 507 | MemRegionManager &MRMgr = SVB.getRegionManager(); |
| 508 | ASTContext &Ctx = SVB.getContext(); |
| 509 | |
| 510 | // HACK: There is no way we can put the index of the array element into the |
| 511 | // CFG unless we unroll the loop, so we manually select and bind the required |
| 512 | // parameter to the environment. |
| 513 | const Expr *SourceArray = AILE->getCommonExpr()->getSourceExpr(); |
| 514 | const auto *Ctor = |
| 515 | cast<CXXConstructExpr>(Val: extractElementInitializerFromNestedAILE(AILE)); |
| 516 | |
| 517 | const auto *SourceArrayRegion = |
| 518 | cast<SubRegion>(Val: State->getSVal(E: SourceArray, SF).getAsRegion()); |
| 519 | const ElementRegion *ElementRegion = |
| 520 | MRMgr.getElementRegion(elementType: Ctor->getType(), Idx, superRegion: SourceArrayRegion, Ctx); |
| 521 | |
| 522 | return State->BindExpr(E: Ctor->getArg(Arg: 0), SF, V: loc::MemRegionVal(ElementRegion)); |
| 523 | } |
| 524 | |
| 525 | void ExprEngine::handleConstructor(const Expr *E, ExplodedNode *Pred, |
| 526 | ExplodedNodeSet &Dst) { |
| 527 | const auto *CE = dyn_cast<CXXConstructExpr>(Val: E); |
| 528 | const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(Val: E); |
| 529 | assert(CE || CIE); |
| 530 | |
| 531 | const StackFrame *SF = Pred->getStackFrame(); |
| 532 | ProgramStateRef State = Pred->getState(); |
| 533 | |
| 534 | SVal Target = UnknownVal(); |
| 535 | |
| 536 | if (CE) { |
| 537 | if (std::optional<SVal> ElidedTarget = |
| 538 | getObjectUnderConstruction(State, Item: CE, SF)) { |
| 539 | // We've previously modeled an elidable constructor by pretending that |
| 540 | // it in fact constructs into the correct target. This constructor can |
| 541 | // therefore be skipped. |
| 542 | Target = *ElidedTarget; |
| 543 | State = finishObjectConstruction(State, Item: CE, SF); |
| 544 | if (auto L = Target.getAs<Loc>()) |
| 545 | State = State->BindExpr(E: CE, SF, V: State->getSVal(LV: *L, T: CE->getType())); |
| 546 | Dst.insert(N: Engine.makePostStmtNode(S: CE, State, Pred)); |
| 547 | return; |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | EvalCallOptions CallOpts; |
| 552 | auto C = getCurrentCFGElement().getAs<CFGConstructor>(); |
| 553 | assert(C || getCurrentCFGElement().getAs<CFGStmt>()); |
| 554 | const ConstructionContext *CC = C ? C->getConstructionContext() : nullptr; |
| 555 | |
| 556 | const CXXConstructionKind CK = |
| 557 | CE ? CE->getConstructionKind() : CIE->getConstructionKind(); |
| 558 | switch (CK) { |
| 559 | case CXXConstructionKind::Complete: { |
| 560 | // Inherited constructors are always base class constructors. |
| 561 | assert(CE && !CIE && "A complete constructor is inherited?!" ); |
| 562 | |
| 563 | // If the ctor is part of an ArrayInitLoopExpr, we want to handle it |
| 564 | // differently. |
| 565 | auto *AILE = CC ? CC->getArrayInitLoop() : nullptr; |
| 566 | |
| 567 | unsigned Idx = 0; |
| 568 | if (CE->getType()->isArrayType() || AILE) { |
| 569 | |
| 570 | auto isZeroSizeArray = [&] { |
| 571 | uint64_t Size = 1; |
| 572 | |
| 573 | if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: CE->getType())) |
| 574 | Size = getContext().getConstantArrayElementCount(CA: CAT); |
| 575 | else if (AILE) |
| 576 | Size = getContext().getArrayInitLoopExprElementCount(AILE); |
| 577 | |
| 578 | return Size == 0; |
| 579 | }; |
| 580 | |
| 581 | // No element construction will happen in a 0 size array. |
| 582 | if (isZeroSizeArray()) { |
| 583 | static SimpleProgramPointTag T{"ExprEngine" , |
| 584 | "Skipping 0 size array construction" }; |
| 585 | PostStmt Loc(CE, Pred->getStackFrame(), &T); |
| 586 | Dst.insert(N: Engine.makeNode(Loc, State, Pred)); |
| 587 | return; |
| 588 | } |
| 589 | |
| 590 | Idx = getIndexOfElementToConstruct(State, E: CE, SF).value_or(u: 0u); |
| 591 | State = setIndexOfElementToConstruct(State, E: CE, SF, Idx: Idx + 1); |
| 592 | } |
| 593 | |
| 594 | if (AILE) { |
| 595 | // Only set this once even though we loop through it multiple times. |
| 596 | if (!getPendingInitLoop(State, E: CE, SF)) |
| 597 | State = setPendingInitLoop( |
| 598 | State, E: CE, SF, Idx: getContext().getArrayInitLoopExprElementCount(AILE)); |
| 599 | |
| 600 | State = bindRequiredArrayElementToEnvironment( |
| 601 | State, AILE, SF, Idx: svalBuilder.makeArrayIndex(idx: Idx)); |
| 602 | } |
| 603 | |
| 604 | // The target region is found from construction context. |
| 605 | std::tie(args&: State, args&: Target) = |
| 606 | handleConstructionContext(E: CE, State, SF, CC, CallOpts, Idx); |
| 607 | break; |
| 608 | } |
| 609 | case CXXConstructionKind::VirtualBase: { |
| 610 | // Make sure we are not calling virtual base class initializers twice. |
| 611 | // Only the most-derived object should initialize virtual base classes. |
| 612 | const auto *OuterCtor = |
| 613 | dyn_cast_or_null<CXXConstructExpr>(Val: SF->getCallSite()); |
| 614 | assert( |
| 615 | (!OuterCtor || |
| 616 | OuterCtor->getConstructionKind() == CXXConstructionKind::Complete || |
| 617 | OuterCtor->getConstructionKind() == CXXConstructionKind::Delegating) && |
| 618 | ("This virtual base should have already been initialized by " |
| 619 | "the most derived class!" )); |
| 620 | (void)OuterCtor; |
| 621 | [[fallthrough]]; |
| 622 | } |
| 623 | case CXXConstructionKind::NonVirtualBase: |
| 624 | // In C++17, classes with non-virtual bases may be aggregates, so they would |
| 625 | // be initialized as aggregates without a constructor call, so we may have |
| 626 | // a base class constructed directly into an initializer list without |
| 627 | // having the derived-class constructor call on the previous stack frame. |
| 628 | // Initializer lists may be nested into more initializer lists that |
| 629 | // correspond to surrounding aggregate initializations. |
| 630 | // FIXME: For now this code essentially bails out. We need to find the |
| 631 | // correct target region and set it. |
| 632 | // FIXME: Instead of relying on the ParentMap, we should have the |
| 633 | // trigger-statement (InitListExpr or CXXParenListInitExpr in this case) |
| 634 | // passed down from CFG or otherwise always available during construction. |
| 635 | if (isa_and_nonnull<InitListExpr, CXXParenListInitExpr>( |
| 636 | Val: SF->getParentMap().getParent(S: E))) { |
| 637 | MemRegionManager &MRMgr = getSValBuilder().getRegionManager(); |
| 638 | Target = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(Ex: E, SF)); |
| 639 | CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; |
| 640 | break; |
| 641 | } |
| 642 | [[fallthrough]]; |
| 643 | case CXXConstructionKind::Delegating: { |
| 644 | const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(Val: SF->getDecl()); |
| 645 | Loc ThisPtr = getSValBuilder().getCXXThis(D: CurCtor, SF); |
| 646 | SVal ThisVal = State->getSVal(LV: ThisPtr); |
| 647 | |
| 648 | if (CK == CXXConstructionKind::Delegating) { |
| 649 | Target = ThisVal; |
| 650 | } else { |
| 651 | // Cast to the base type. |
| 652 | bool IsVirtual = (CK == CXXConstructionKind::VirtualBase); |
| 653 | SVal BaseVal = |
| 654 | getStoreManager().evalDerivedToBase(Derived: ThisVal, DerivedPtrType: E->getType(), IsVirtual); |
| 655 | Target = BaseVal; |
| 656 | } |
| 657 | break; |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | if (State != Pred->getState()) { |
| 662 | static SimpleProgramPointTag T("ExprEngine" , |
| 663 | "Prepare for object construction" ); |
| 664 | Pred = Engine.makeNode(Loc: PreStmt(E, SF, &T), State, Pred); |
| 665 | if (!Pred) |
| 666 | return; |
| 667 | } |
| 668 | |
| 669 | const MemRegion *TargetRegion = Target.getAsRegion(); |
| 670 | CallEventManager &CEMgr = getStateManager().getCallEventManager(); |
| 671 | CallEventRef<> Call = |
| 672 | CIE ? (CallEventRef<>)CEMgr.getCXXInheritedConstructorCall( |
| 673 | E: CIE, Target: TargetRegion, State, SF, ElemRef: getCFGElementRef()) |
| 674 | : (CallEventRef<>)CEMgr.getCXXConstructorCall(E: CE, Target: TargetRegion, State, |
| 675 | SF, ElemRef: getCFGElementRef()); |
| 676 | |
| 677 | ExplodedNodeSet DstPreVisit; |
| 678 | getCheckerManager().runCheckersForPreStmt(Dst&: DstPreVisit, Src: Pred, S: E, Eng&: *this); |
| 679 | |
| 680 | ExplodedNodeSet PreInitialized; |
| 681 | if (CE) { |
| 682 | // FIXME: Is it possible and/or useful to do this before PreStmt? |
| 683 | for (ExplodedNode *N : DstPreVisit) { |
| 684 | ProgramStateRef State = N->getState(); |
| 685 | if (CE->requiresZeroInitialization()) { |
| 686 | // FIXME: Once we properly handle constructors in new-expressions, we'll |
| 687 | // need to invalidate the region before setting a default value, to make |
| 688 | // sure there aren't any lingering bindings around. This probably needs |
| 689 | // to happen regardless of whether or not the object is zero-initialized |
| 690 | // to handle random fields of a placement-initialized object picking up |
| 691 | // old bindings. We might only want to do it when we need to, though. |
| 692 | // FIXME: This isn't actually correct for arrays -- we need to zero- |
| 693 | // initialize the entire array, not just the first element -- but our |
| 694 | // handling of arrays everywhere else is weak as well, so this shouldn't |
| 695 | // actually make things worse. Placement new makes this tricky as well, |
| 696 | // since it's then possible to be initializing one part of a multi- |
| 697 | // dimensional array. |
| 698 | const CXXRecordDecl *TargetHeldRecord = |
| 699 | dyn_cast_or_null<CXXRecordDecl>(Val: CE->getType()->getAsRecordDecl()); |
| 700 | |
| 701 | if (!TargetHeldRecord || !TargetHeldRecord->isEmpty()) |
| 702 | State = State->bindDefaultZero(loc: Target, SF); |
| 703 | } |
| 704 | |
| 705 | PreStmt P(CE, N->getStackFrame(), /*tag=*/nullptr); |
| 706 | PreInitialized.insert(N: Engine.makeNode(Loc: P, State, Pred: N)); |
| 707 | } |
| 708 | } else { |
| 709 | PreInitialized = DstPreVisit; |
| 710 | } |
| 711 | |
| 712 | ExplodedNodeSet DstPreCall; |
| 713 | getCheckerManager().runCheckersForPreCall(Dst&: DstPreCall, Src: PreInitialized, |
| 714 | Call: *Call, Eng&: *this); |
| 715 | |
| 716 | ExplodedNodeSet DstEvaluated; |
| 717 | |
| 718 | if (CE && CE->getConstructor()->isTrivial() && |
| 719 | CE->getConstructor()->isCopyOrMoveConstructor() && |
| 720 | !CallOpts.IsArrayCtorOrDtor) { |
| 721 | // FIXME: Handle other kinds of trivial constructors as well. |
| 722 | for (ExplodedNode *N : DstPreCall) |
| 723 | performTrivialCopy(Dst&: DstEvaluated, Pred: N, Call: *Call); |
| 724 | |
| 725 | } else { |
| 726 | for (ExplodedNode *N : DstPreCall) |
| 727 | getCheckerManager().runCheckersForEvalCall(Dst&: DstEvaluated, Src: N, CE: *Call, Eng&: *this, |
| 728 | CallOpts); |
| 729 | } |
| 730 | |
| 731 | // If the CFG was constructed without elements for temporary destructors |
| 732 | // and the just-called constructor created a temporary object then |
| 733 | // stop exploration if the temporary object has a noreturn constructor. |
| 734 | // This can lose coverage because the destructor, if it were present |
| 735 | // in the CFG, would be called at the end of the full expression or |
| 736 | // later (for life-time extended temporaries) -- but avoids infeasible |
| 737 | // paths when no-return temporary destructors are used for assertions. |
| 738 | ExplodedNodeSet DstEvaluatedPostProcessed; |
| 739 | const AnalysisDeclContext *ADC = SF->getAnalysisDeclContext(); |
| 740 | if (!ADC->getCFGBuildOptions().AddTemporaryDtors) { |
| 741 | if (llvm::isa_and_nonnull<CXXTempObjectRegion, |
| 742 | CXXLifetimeExtendedObjectRegion>(Val: TargetRegion) && |
| 743 | cast<CXXConstructorDecl>(Val: Call->getDecl()) |
| 744 | ->getParent() |
| 745 | ->isAnyDestructorNoReturn()) { |
| 746 | |
| 747 | // If we've inlined the constructor, then DstEvaluated would be empty. |
| 748 | // In this case we still want a sink, which could be implemented |
| 749 | // in processCallExit. But we don't have that implemented at the moment, |
| 750 | // so if you hit this assertion, see if you can avoid inlining |
| 751 | // the respective constructor when analyzer-config cfg-temporary-dtors |
| 752 | // is set to false. |
| 753 | // Otherwise there's nothing wrong with inlining such constructor. |
| 754 | assert(!DstEvaluated.empty() && |
| 755 | "We should not have inlined this constructor!" ); |
| 756 | |
| 757 | for (ExplodedNode *N : DstEvaluated) { |
| 758 | Engine.makePostStmtNode(S: E, State: N->getState(), Pred: N, /*MarkAsSink=*/true); |
| 759 | } |
| 760 | |
| 761 | // There is no need to run the PostCall and PostStmt checker |
| 762 | // callbacks because we just generated sinks on all nodes in th |
| 763 | // frontier. |
| 764 | return; |
| 765 | } |
| 766 | } |
| 767 | |
| 768 | DstEvaluatedPostProcessed.insert(S: DstEvaluated); |
| 769 | ExplodedNodeSet DstPostArgumentCleanup; |
| 770 | for (ExplodedNode *I : DstEvaluatedPostProcessed) |
| 771 | finishArgumentConstruction(Dst&: DstPostArgumentCleanup, Pred: I, Call: *Call); |
| 772 | |
| 773 | // If there were other constructors called for object-type arguments |
| 774 | // of this constructor, clean them up. |
| 775 | ExplodedNodeSet DstPostCall; |
| 776 | getCheckerManager().runCheckersForPostCall(Dst&: DstPostCall, |
| 777 | Src: DstPostArgumentCleanup, |
| 778 | Call: *Call, Eng&: *this); |
| 779 | getCheckerManager().runCheckersForPostStmt(Dst, Src: DstPostCall, S: E, Eng&: *this); |
| 780 | } |
| 781 | |
| 782 | void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE, |
| 783 | ExplodedNode *Pred, |
| 784 | ExplodedNodeSet &Dst) { |
| 785 | handleConstructor(E: CE, Pred, Dst); |
| 786 | } |
| 787 | |
| 788 | void ExprEngine::VisitCXXInheritedCtorInitExpr( |
| 789 | const CXXInheritedCtorInitExpr *CE, ExplodedNode *Pred, |
| 790 | ExplodedNodeSet &Dst) { |
| 791 | handleConstructor(E: CE, Pred, Dst); |
| 792 | } |
| 793 | |
| 794 | void ExprEngine::VisitCXXDestructor(QualType ObjectType, |
| 795 | const MemRegion *Dest, |
| 796 | const Stmt *S, |
| 797 | bool IsBaseDtor, |
| 798 | ExplodedNode *Pred, |
| 799 | ExplodedNodeSet &Dst, |
| 800 | EvalCallOptions &CallOpts) { |
| 801 | assert(S && "A destructor without a trigger!" ); |
| 802 | const StackFrame *SF = Pred->getStackFrame(); |
| 803 | ProgramStateRef State = Pred->getState(); |
| 804 | |
| 805 | const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl(); |
| 806 | assert(RecordDecl && "Only CXXRecordDecls should have destructors" ); |
| 807 | const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor(); |
| 808 | // FIXME: There should always be a Decl, otherwise the destructor call |
| 809 | // shouldn't have been added to the CFG in the first place. |
| 810 | if (!DtorDecl) { |
| 811 | // Skip the invalid destructor. We cannot simply return because |
| 812 | // it would interrupt the analysis instead. |
| 813 | static SimpleProgramPointTag T("ExprEngine" , "SkipInvalidDestructor" ); |
| 814 | // FIXME: PostImplicitCall with a null decl may crash elsewhere anyway. |
| 815 | PostImplicitCall PP(/*Decl=*/nullptr, S->getEndLoc(), SF, |
| 816 | getCFGElementRef(), &T); |
| 817 | Dst.insert(N: Engine.makeNode(Loc: PP, State: Pred->getState(), Pred)); |
| 818 | return; |
| 819 | } |
| 820 | |
| 821 | if (!Dest) { |
| 822 | // We're trying to destroy something that is not a region. This may happen |
| 823 | // for a variety of reasons (unknown target region, concrete integer instead |
| 824 | // of target region, etc.). The current code makes an attempt to recover. |
| 825 | // FIXME: We probably don't really need to recover when we're dealing |
| 826 | // with concrete integers specifically. |
| 827 | CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; |
| 828 | if (const Expr *E = dyn_cast_or_null<Expr>(Val: S)) { |
| 829 | Dest = MRMgr.getCXXTempObjectRegion(Ex: E, SF: Pred->getStackFrame()); |
| 830 | } else { |
| 831 | static SimpleProgramPointTag T("ExprEngine" , "SkipInvalidDestructor" ); |
| 832 | Engine.makeNode(Loc: Pred->getLocation().withTag(tag: &T), State: Pred->getState(), Pred, |
| 833 | /*MarkAsSink=*/true); |
| 834 | return; |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | CallEventManager &CEMgr = getStateManager().getCallEventManager(); |
| 839 | CallEventRef<CXXDestructorCall> Call = CEMgr.getCXXDestructorCall( |
| 840 | DD: DtorDecl, Trigger: S, Target: Dest, IsBase: IsBaseDtor, State, SF, ElemRef: getCFGElementRef()); |
| 841 | |
| 842 | PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), |
| 843 | Call->getSourceRange().getBegin(), |
| 844 | "Error evaluating destructor" ); |
| 845 | |
| 846 | ExplodedNodeSet DstPreCall; |
| 847 | getCheckerManager().runCheckersForPreCall(Dst&: DstPreCall, Src: Pred, |
| 848 | Call: *Call, Eng&: *this); |
| 849 | |
| 850 | ExplodedNodeSet DstInvalidated; |
| 851 | for (ExplodedNode *N : DstPreCall) |
| 852 | defaultEvalCall(Dst&: DstInvalidated, Pred: N, Call: *Call, CallOpts); |
| 853 | |
| 854 | getCheckerManager().runCheckersForPostCall(Dst, Src: DstInvalidated, |
| 855 | Call: *Call, Eng&: *this); |
| 856 | } |
| 857 | |
| 858 | void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, |
| 859 | ExplodedNode *Pred, |
| 860 | ExplodedNodeSet &Dst) { |
| 861 | ProgramStateRef State = Pred->getState(); |
| 862 | const StackFrame *SF = Pred->getStackFrame(); |
| 863 | PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), |
| 864 | CNE->getBeginLoc(), |
| 865 | "Error evaluating New Allocator Call" ); |
| 866 | CallEventManager &CEMgr = getStateManager().getCallEventManager(); |
| 867 | CallEventRef<CXXAllocatorCall> Call = |
| 868 | CEMgr.getCXXAllocatorCall(E: CNE, State, SF, ElemRef: getCFGElementRef()); |
| 869 | |
| 870 | ExplodedNodeSet DstPreCall; |
| 871 | getCheckerManager().runCheckersForPreCall(Dst&: DstPreCall, Src: Pred, |
| 872 | Call: *Call, Eng&: *this); |
| 873 | |
| 874 | ExplodedNodeSet DstPostCall; |
| 875 | for (ExplodedNode *I : DstPreCall) { |
| 876 | // Operator new calls (CXXNewExpr) are intentionally not eval-called, |
| 877 | // because it does not make sense to eval-call user-provided functions. |
| 878 | // 1) If the new operator can be inlined, then don't prevent it from |
| 879 | // inlining by having an eval-call of that operator. |
| 880 | // 2) If it can't be inlined, then the default conservative modeling |
| 881 | // is what we want anyway. |
| 882 | // So the best is to not allow eval-calling CXXNewExprs from checkers. |
| 883 | // Checkers can provide their pre/post-call callbacks if needed. |
| 884 | defaultEvalCall(Dst&: DstPostCall, Pred: I, Call: *Call); |
| 885 | } |
| 886 | // If the call is inlined, DstPostCall will be empty and we bail out now. |
| 887 | |
| 888 | // Store return value of operator new() for future use, until the actual |
| 889 | // CXXNewExpr gets processed. |
| 890 | ExplodedNodeSet DstPostValue; |
| 891 | for (ExplodedNode *I : DstPostCall) { |
| 892 | // FIXME: Because CNE serves as the "call site" for the allocator (due to |
| 893 | // lack of a better expression in the AST), the conjured return value symbol |
| 894 | // is going to be of the same type (C++ object pointer type). Technically |
| 895 | // this is not correct because the operator new's prototype always says that |
| 896 | // it returns a 'void *'. So we should change the type of the symbol, |
| 897 | // and then evaluate the cast over the symbolic pointer from 'void *' to |
| 898 | // the object pointer type. But without changing the symbol's type it |
| 899 | // is breaking too much to evaluate the no-op symbolic cast over it, so we |
| 900 | // skip it for now. |
| 901 | ProgramStateRef State = I->getState(); |
| 902 | SVal RetVal = State->getSVal(E: CNE, SF); |
| 903 | // [basic.stc.dynamic.allocation] (on the return value of an allocation |
| 904 | // function): |
| 905 | // "The order, contiguity, and initial value of storage allocated by |
| 906 | // successive calls to an allocation function are unspecified." |
| 907 | State = State->bindDefaultInitial(loc: RetVal, V: UndefinedVal{}, SF); |
| 908 | |
| 909 | // If this allocation function is not declared as non-throwing, failures |
| 910 | // /must/ be signalled by exceptions, and thus the return value will never |
| 911 | // be NULL. -fno-exceptions does not influence this semantics. |
| 912 | // FIXME: GCC has a -fcheck-new option, which forces it to consider the case |
| 913 | // where new can return NULL. If we end up supporting that option, we can |
| 914 | // consider adding a check for it here. |
| 915 | // C++11 [basic.stc.dynamic.allocation]p3. |
| 916 | if (const FunctionDecl *FD = CNE->getOperatorNew()) { |
| 917 | QualType Ty = FD->getType(); |
| 918 | if (const auto *ProtoType = Ty->getAs<FunctionProtoType>()) |
| 919 | if (!ProtoType->isNothrow()) |
| 920 | State = State->assume(Cond: RetVal.castAs<DefinedOrUnknownSVal>(), Assumption: true); |
| 921 | } |
| 922 | |
| 923 | DstPostValue.insert(N: Engine.makePostStmtNode( |
| 924 | S: CNE, State: addObjectUnderConstruction(State, Item: CNE, SF, V: RetVal), Pred: I)); |
| 925 | } |
| 926 | |
| 927 | ExplodedNodeSet DstPostPostCallCallback; |
| 928 | getCheckerManager().runCheckersForPostCall(Dst&: DstPostPostCallCallback, |
| 929 | Src: DstPostValue, Call: *Call, Eng&: *this); |
| 930 | for (ExplodedNode *I : DstPostPostCallCallback) { |
| 931 | getCheckerManager().runCheckersForNewAllocator(Call: *Call, Dst, Pred: I, Eng&: *this); |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, |
| 936 | ExplodedNodeSet &Dst) { |
| 937 | // FIXME: Much of this should eventually migrate to CXXAllocatorCall. |
| 938 | // Also, we need to decide how allocators actually work -- they're not |
| 939 | // really part of the CXXNewExpr because they happen BEFORE the |
| 940 | // CXXConstructExpr subexpression. See PR12014 for some discussion. |
| 941 | |
| 942 | unsigned blockCount = getNumVisitedCurrent(); |
| 943 | const StackFrame *SF = Pred->getStackFrame(); |
| 944 | SVal symVal = UnknownVal(); |
| 945 | FunctionDecl *FD = CNE->getOperatorNew(); |
| 946 | |
| 947 | bool IsStandardGlobalOpNewFunction = |
| 948 | FD->isReplaceableGlobalAllocationFunction(); |
| 949 | |
| 950 | ProgramStateRef State = Pred->getState(); |
| 951 | |
| 952 | // Retrieve the stored operator new() return value. |
| 953 | if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) { |
| 954 | symVal = *getObjectUnderConstruction(State, Item: CNE, SF); |
| 955 | State = finishObjectConstruction(State, Item: CNE, SF); |
| 956 | } |
| 957 | |
| 958 | // We assume all standard global 'operator new' functions allocate memory in |
| 959 | // heap. We realize this is an approximation that might not correctly model |
| 960 | // a custom global allocator. |
| 961 | if (symVal.isUnknown()) { |
| 962 | if (IsStandardGlobalOpNewFunction) |
| 963 | symVal = svalBuilder.getConjuredHeapSymbolVal(elem: getCFGElementRef(), SF, |
| 964 | type: CNE->getType(), Count: blockCount); |
| 965 | else |
| 966 | symVal = svalBuilder.conjureSymbolVal( |
| 967 | /*symbolTag=*/nullptr, elem: getCFGElementRef(), SF, count: blockCount); |
| 968 | } |
| 969 | |
| 970 | CallEventManager &CEMgr = getStateManager().getCallEventManager(); |
| 971 | CallEventRef<CXXAllocatorCall> Call = |
| 972 | CEMgr.getCXXAllocatorCall(E: CNE, State, SF, ElemRef: getCFGElementRef()); |
| 973 | |
| 974 | if (!AMgr.getAnalyzerOptions().MayInlineCXXAllocator) { |
| 975 | // Invalidate placement args. |
| 976 | // FIXME: Once we figure out how we want allocators to work, |
| 977 | // we should be using the usual pre-/(default-)eval-/post-call checkers |
| 978 | // here. |
| 979 | State = Call->invalidateRegions(BlockCount: blockCount, State); |
| 980 | if (!State) |
| 981 | return; |
| 982 | |
| 983 | // If this allocation function is not declared as non-throwing, failures |
| 984 | // /must/ be signalled by exceptions, and thus the return value will never |
| 985 | // be NULL. -fno-exceptions does not influence this semantics. |
| 986 | // FIXME: GCC has a -fcheck-new option, which forces it to consider the case |
| 987 | // where new can return NULL. If we end up supporting that option, we can |
| 988 | // consider adding a check for it here. |
| 989 | // C++11 [basic.stc.dynamic.allocation]p3. |
| 990 | if (const auto *ProtoType = FD->getType()->getAs<FunctionProtoType>()) |
| 991 | if (!ProtoType->isNothrow()) |
| 992 | if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>()) |
| 993 | State = State->assume(Cond: *dSymVal, Assumption: true); |
| 994 | } |
| 995 | |
| 996 | SVal Result = symVal; |
| 997 | |
| 998 | if (CNE->isArray()) { |
| 999 | |
| 1000 | if (const auto *NewReg = cast_or_null<SubRegion>(Val: symVal.getAsRegion())) { |
| 1001 | // If each element is initialized by their default constructor, the field |
| 1002 | // values are properly placed inside the required region, however if an |
| 1003 | // initializer list is used, this doesn't happen automatically. |
| 1004 | auto *Init = CNE->getInitializer(); |
| 1005 | bool isInitList = |
| 1006 | isa_and_nonnull<InitListExpr, CXXParenListInitExpr>(Val: Init); |
| 1007 | |
| 1008 | QualType ObjTy = |
| 1009 | isInitList ? Init->getType() : CNE->getType()->getPointeeType(); |
| 1010 | const ElementRegion *EleReg = |
| 1011 | MRMgr.getElementRegion(elementType: ObjTy, Idx: svalBuilder.makeArrayIndex(idx: 0), superRegion: NewReg, |
| 1012 | Ctx: svalBuilder.getContext()); |
| 1013 | Result = loc::MemRegionVal(EleReg); |
| 1014 | |
| 1015 | // If the array is list initialized, we bind the initializer list to the |
| 1016 | // memory region here, otherwise we would lose it. |
| 1017 | if (isInitList) { |
| 1018 | Pred = Engine.makePostStmtNode(S: CNE, State, Pred); |
| 1019 | |
| 1020 | SVal V = State->getSVal(E: Init, SF); |
| 1021 | ExplodedNodeSet Evaluated; |
| 1022 | evalBind(Dst&: Evaluated, StoreE: CNE, Pred, location: Result, Val: V, AtDeclInit: true); |
| 1023 | |
| 1024 | for (ExplodedNode *N : Evaluated) |
| 1025 | Dst.insert(N: Engine.makeNodeWithBinding(Pred: N, E: CNE, V: Result)); |
| 1026 | return; |
| 1027 | } |
| 1028 | } |
| 1029 | |
| 1030 | Dst.insert(N: Engine.makeNodeWithBinding(Pred, E: CNE, V: Result, State)); |
| 1031 | return; |
| 1032 | } |
| 1033 | |
| 1034 | // FIXME: Once we have proper support for CXXConstructExprs inside |
| 1035 | // CXXNewExpr, we need to make sure that the constructed object is not |
| 1036 | // immediately invalidated here. (The placement call should happen before |
| 1037 | // the constructor call anyway.) |
| 1038 | if (FD->isReservedGlobalPlacementOperator()) { |
| 1039 | // Non-array placement new should always return the placement location. |
| 1040 | SVal PlacementLoc = State->getSVal(E: CNE->getPlacementArg(I: 0), SF); |
| 1041 | Result = svalBuilder.evalCast(V: PlacementLoc, CastTy: CNE->getType(), |
| 1042 | OriginalTy: CNE->getPlacementArg(I: 0)->getType()); |
| 1043 | } |
| 1044 | |
| 1045 | // Bind the address of the object, then check to see if we cached out. |
| 1046 | ExplodedNode *NewN = Engine.makeNodeWithBinding(Pred, E: CNE, V: Result, State); |
| 1047 | Dst.insert(N: NewN); |
| 1048 | if (!NewN) |
| 1049 | return; |
| 1050 | |
| 1051 | // If the type is not a record, we won't have a CXXConstructExpr as an |
| 1052 | // initializer. Copy the value over. |
| 1053 | if (const Expr *Init = CNE->getInitializer()) { |
| 1054 | if (!isa<CXXConstructExpr>(Val: Init)) { |
| 1055 | assert(Dst.size() == 1); |
| 1056 | Dst.erase(N: NewN); |
| 1057 | evalBind(Dst, StoreE: CNE, Pred: NewN, location: Result, Val: State->getSVal(E: Init, SF), |
| 1058 | /*FirstInit=*/AtDeclInit: IsStandardGlobalOpNewFunction); |
| 1059 | } |
| 1060 | } |
| 1061 | } |
| 1062 | |
| 1063 | void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, |
| 1064 | ExplodedNode *Pred, ExplodedNodeSet &Dst) { |
| 1065 | |
| 1066 | CallEventManager &CEMgr = getStateManager().getCallEventManager(); |
| 1067 | CallEventRef<CXXDeallocatorCall> Call = CEMgr.getCXXDeallocatorCall( |
| 1068 | E: CDE, State: Pred->getState(), SF: Pred->getStackFrame(), ElemRef: getCFGElementRef()); |
| 1069 | |
| 1070 | ExplodedNodeSet DstPreCall; |
| 1071 | getCheckerManager().runCheckersForPreCall(Dst&: DstPreCall, Src: Pred, Call: *Call, Eng&: *this); |
| 1072 | ExplodedNodeSet DstPostCall; |
| 1073 | |
| 1074 | if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) { |
| 1075 | for (ExplodedNode *I : DstPreCall) { |
| 1076 | // Intentionally either inline or conservative eval-call the operator |
| 1077 | // delete, but avoid triggering an eval-call event for checkers. |
| 1078 | // As detailed at handling CXXNewExprs, in short, because it does not |
| 1079 | // really make sense to eval-call user-provided functions. |
| 1080 | defaultEvalCall(Dst&: DstPostCall, Pred: I, Call: *Call); |
| 1081 | } |
| 1082 | } else { |
| 1083 | DstPostCall = std::move(DstPreCall); |
| 1084 | } |
| 1085 | getCheckerManager().runCheckersForPostCall(Dst, Src: DstPostCall, Call: *Call, Eng&: *this); |
| 1086 | } |
| 1087 | |
| 1088 | void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, |
| 1089 | ExplodedNodeSet &Dst) { |
| 1090 | const VarDecl *VD = CS->getExceptionDecl(); |
| 1091 | if (!VD) { |
| 1092 | Dst.insert(N: Pred); |
| 1093 | return; |
| 1094 | } |
| 1095 | |
| 1096 | const StackFrame *SF = Pred->getStackFrame(); |
| 1097 | SVal V = svalBuilder.conjureSymbolVal(elem: getCFGElementRef(), SF, type: VD->getType(), |
| 1098 | visitCount: getNumVisitedCurrent()); |
| 1099 | ProgramStateRef state = Pred->getState(); |
| 1100 | state = state->bindLoc(location: state->getLValue(VD, SF), V, SF); |
| 1101 | |
| 1102 | Dst.insert(N: Engine.makePostStmtNode(S: CS, State: state, Pred)); |
| 1103 | } |
| 1104 | |
| 1105 | void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, |
| 1106 | ExplodedNodeSet &Dst) { |
| 1107 | // Get the this object region from StoreManager. |
| 1108 | const StackFrame *SF = Pred->getStackFrame(); |
| 1109 | const MemRegion *R = svalBuilder.getRegionManager().getCXXThisRegion( |
| 1110 | thisPointerTy: getContext().getCanonicalType(T: TE->getType()), SF); |
| 1111 | |
| 1112 | ProgramStateRef state = Pred->getState(); |
| 1113 | SVal V = state->getSVal(LV: loc::MemRegionVal(R)); |
| 1114 | Dst.insert(N: Engine.makeNodeWithBinding(Pred, E: TE, V)); |
| 1115 | } |
| 1116 | |
| 1117 | void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, |
| 1118 | ExplodedNodeSet &Dst) { |
| 1119 | const StackFrame *SF = Pred->getStackFrame(); |
| 1120 | |
| 1121 | // Get the region of the lambda itself. |
| 1122 | const MemRegion *R = |
| 1123 | svalBuilder.getRegionManager().getCXXTempObjectRegion(Ex: LE, SF); |
| 1124 | SVal V = loc::MemRegionVal(R); |
| 1125 | |
| 1126 | ProgramStateRef State = Pred->getState(); |
| 1127 | |
| 1128 | // If we created a new MemRegion for the lambda, we should explicitly bind |
| 1129 | // the captures. |
| 1130 | for (auto const [Idx, FieldForCapture, InitExpr] : |
| 1131 | llvm::zip(t: llvm::seq<unsigned>(Begin: 0, End: -1), u: LE->getLambdaClass()->fields(), |
| 1132 | args: LE->capture_inits())) { |
| 1133 | SVal FieldLoc = State->getLValue(decl: FieldForCapture, Base: V); |
| 1134 | |
| 1135 | SVal InitVal; |
| 1136 | if (!FieldForCapture->hasCapturedVLAType()) { |
| 1137 | assert(InitExpr && "Capture missing initialization expression" ); |
| 1138 | |
| 1139 | // Capturing a 0 length array is a no-op, so we ignore it to get a more |
| 1140 | // accurate analysis. If it's not ignored, it would set the default |
| 1141 | // binding of the lambda to 'Unknown', which can lead to falsely detecting |
| 1142 | // 'Uninitialized' values as 'Unknown' and not reporting a warning. |
| 1143 | const auto FTy = FieldForCapture->getType(); |
| 1144 | if (FTy->isConstantArrayType() && |
| 1145 | getContext().getConstantArrayElementCount( |
| 1146 | CA: getContext().getAsConstantArrayType(T: FTy)) == 0) |
| 1147 | continue; |
| 1148 | |
| 1149 | // With C++17 copy elision the InitExpr can be anything, so instead of |
| 1150 | // pattern matching all cases, we simple check if the current field is |
| 1151 | // under construction or not, regardless what it's InitExpr is. |
| 1152 | if (const auto OUC = getObjectUnderConstruction(State, Item: {LE, Idx}, SF)) { |
| 1153 | InitVal = State->getSVal(R: OUC->getAsRegion()); |
| 1154 | |
| 1155 | State = finishObjectConstruction(State, Item: {LE, Idx}, SF); |
| 1156 | } else |
| 1157 | InitVal = State->getSVal(E: InitExpr, SF); |
| 1158 | |
| 1159 | } else { |
| 1160 | |
| 1161 | assert(!getObjectUnderConstruction(State, {LE, Idx}, SF) && |
| 1162 | "VLA capture by value is a compile time error!" ); |
| 1163 | |
| 1164 | // The field stores the length of a captured variable-length array. |
| 1165 | // These captures don't have initialization expressions; instead we |
| 1166 | // get the length from the VLAType size expression. |
| 1167 | Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr(); |
| 1168 | InitVal = State->getSVal(E: SizeExpr, SF); |
| 1169 | } |
| 1170 | |
| 1171 | State = State->bindLoc(LV: FieldLoc, V: InitVal, SF); |
| 1172 | } |
| 1173 | |
| 1174 | // Decay the Loc into an RValue, because there might be a |
| 1175 | // MaterializeTemporaryExpr node above this one which expects the bound value |
| 1176 | // to be an RValue. |
| 1177 | SVal LambdaRVal = State->getSVal(R); |
| 1178 | |
| 1179 | // FIXME: is this the right program point kind? |
| 1180 | ExplodedNode *N = Engine.makeNodeWithBinding(Pred, E: LE, V: LambdaRVal, State, |
| 1181 | K: ProgramPoint::PostLValueKind); |
| 1182 | |
| 1183 | // FIXME: Move all post/pre visits to ::Visit(). |
| 1184 | getCheckerManager().runCheckersForPostStmt(Dst, Src: N, S: LE, Eng&: *this); |
| 1185 | } |
| 1186 | |
| 1187 | void ExprEngine::VisitAttributedStmt(const AttributedStmt *A, |
| 1188 | ExplodedNode *Pred, ExplodedNodeSet &Dst) { |
| 1189 | const StackFrame *SF = Pred->getStackFrame(); |
| 1190 | ExplodedNodeSet CheckerPreStmt; |
| 1191 | getCheckerManager().runCheckersForPreStmt(Dst&: CheckerPreStmt, Src: Pred, S: A, Eng&: *this); |
| 1192 | |
| 1193 | ExplodedNodeSet EvalSet; |
| 1194 | |
| 1195 | for (ExplodedNode *N : CheckerPreStmt) { |
| 1196 | ProgramStateRef State = N->getState(); |
| 1197 | for (const auto *Attr : getSpecificAttrs<CXXAssumeAttr>(container: A->getAttrs())) { |
| 1198 | SVal AssumedVal = State->getSVal(E: Attr->getAssumption(), SF); |
| 1199 | // This code ignores assumptions that evaluate to UndefinedVal. |
| 1200 | // Perhaps there should be a checker that reports this situation. |
| 1201 | if (auto ValidAssumedVal = AssumedVal.getAs<DefinedOrUnknownSVal>()) { |
| 1202 | State = State->assume(Cond: *ValidAssumedVal, Assumption: true); |
| 1203 | } |
| 1204 | |
| 1205 | if (!State) |
| 1206 | break; |
| 1207 | } |
| 1208 | |
| 1209 | if (State) |
| 1210 | EvalSet.insert(N: Engine.makePostStmtNode(S: A, State, Pred: N)); |
| 1211 | } |
| 1212 | |
| 1213 | getCheckerManager().runCheckersForPostStmt(Dst, Src: EvalSet, S: A, Eng&: *this); |
| 1214 | } |
| 1215 | |