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/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 14#include "clang/Analysis/ConstructionContext.h" 15#include "clang/AST/DeclCXX.h" 16#include "clang/AST/StmtCXX.h" 17#include "clang/AST/ParentMap.h" 18#include "clang/Basic/PrettyStackTrace.h" 19#include "clang/StaticAnalyzer/Core/CheckerManager.h" 20#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 21#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 22 23using namespace clang; 24using namespace ento; 25 26void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, 27 ExplodedNode *Pred, 28 ExplodedNodeSet &Dst) { 29 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 30 const Expr *tempExpr = ME->getSubExpr()->IgnoreParens(); 31 ProgramStateRef state = Pred->getState(); 32 const LocationContext *LCtx = Pred->getLocationContext(); 33 34 state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME); 35 Bldr.generateNode(ME, Pred, state); 36} 37 38// FIXME: This is the sort of code that should eventually live in a Core 39// checker rather than as a special case in ExprEngine. 40void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred, 41 const CallEvent &Call) { 42 SVal ThisVal; 43 bool AlwaysReturnsLValue; 44 const CXXRecordDecl *ThisRD = nullptr; 45 if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) { 46 assert(Ctor->getDecl()->isTrivial()); 47 assert(Ctor->getDecl()->isCopyOrMoveConstructor()); 48 ThisVal = Ctor->getCXXThisVal(); 49 ThisRD = Ctor->getDecl()->getParent(); 50 AlwaysReturnsLValue = false; 51 } else { 52 assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial()); 53 assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() == 54 OO_Equal); 55 ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal(); 56 ThisRD = cast<CXXMethodDecl>(Call.getDecl())->getParent(); 57 AlwaysReturnsLValue = true; 58 } 59 60 assert(ThisRD); 61 if (ThisRD->isEmpty()) { 62 // Do nothing for empty classes. Otherwise it'd retrieve an UnknownVal 63 // and bind it and RegionStore would think that the actual value 64 // in this region at this offset is unknown. 65 return; 66 } 67 68 const LocationContext *LCtx = Pred->getLocationContext(); 69 70 ExplodedNodeSet Dst; 71 Bldr.takeNodes(Pred); 72 73 SVal V = Call.getArgSVal(0); 74 75 // If the value being copied is not unknown, load from its location to get 76 // an aggregate rvalue. 77 if (Optional<Loc> L = V.getAs<Loc>()) 78 V = Pred->getState()->getSVal(*L); 79 else 80 assert(V.isUnknownOrUndef()); 81 82 const Expr *CallExpr = Call.getOriginExpr(); 83 evalBind(Dst, CallExpr, Pred, ThisVal, V, true); 84 85 PostStmt PS(CallExpr, LCtx); 86 for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end(); 87 I != E; ++I) { 88 ProgramStateRef State = (*I)->getState(); 89 if (AlwaysReturnsLValue) 90 State = State->BindExpr(CallExpr, LCtx, ThisVal); 91 else 92 State = bindReturnValue(Call, LCtx, State); 93 Bldr.generateNode(PS, State, *I); 94 } 95} 96 97 98SVal ExprEngine::makeZeroElementRegion(ProgramStateRef State, SVal LValue, 99 QualType &Ty, bool &IsArray) { 100 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 101 ASTContext &Ctx = SVB.getContext(); 102 103 while (const ArrayType *AT = Ctx.getAsArrayType(Ty)) { 104 Ty = AT->getElementType(); 105 LValue = State->getLValue(Ty, SVB.makeZeroArrayIndex(), LValue); 106 IsArray = true; 107 } 108 109 return LValue; 110} 111 112SVal ExprEngine::computeObjectUnderConstruction( 113 const Expr *E, ProgramStateRef State, const LocationContext *LCtx, 114 const ConstructionContext *CC, EvalCallOptions &CallOpts) { 115 SValBuilder &SVB = getSValBuilder(); 116 MemRegionManager &MRMgr = SVB.getRegionManager(); 117 ASTContext &ACtx = SVB.getContext(); 118 119 // Compute the target region by exploring the construction context. 120 if (CC) { 121 switch (CC->getKind()) { 122 case ConstructionContext::CXX17ElidedCopyVariableKind: 123 case ConstructionContext::SimpleVariableKind: { 124 const auto *DSCC = cast<VariableConstructionContext>(CC); 125 const auto *DS = DSCC->getDeclStmt(); 126 const auto *Var = cast<VarDecl>(DS->getSingleDecl()); 127 QualType Ty = Var->getType(); 128 return makeZeroElementRegion(State, State->getLValue(Var, LCtx), Ty, 129 CallOpts.IsArrayCtorOrDtor); 130 } 131 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: 132 case ConstructionContext::SimpleConstructorInitializerKind: { 133 const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC); 134 const auto *Init = ICC->getCXXCtorInitializer(); 135 assert(Init->isAnyMemberInitializer()); 136 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl()); 137 Loc ThisPtr = SVB.getCXXThis(CurCtor, LCtx->getStackFrame()); 138 SVal ThisVal = State->getSVal(ThisPtr); 139 140 const ValueDecl *Field; 141 SVal FieldVal; 142 if (Init->isIndirectMemberInitializer()) { 143 Field = Init->getIndirectMember(); 144 FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal); 145 } else { 146 Field = Init->getMember(); 147 FieldVal = State->getLValue(Init->getMember(), ThisVal); 148 } 149 150 QualType Ty = Field->getType(); 151 return makeZeroElementRegion(State, FieldVal, Ty, 152 CallOpts.IsArrayCtorOrDtor); 153 } 154 case ConstructionContext::NewAllocatedObjectKind: { 155 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) { 156 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC); 157 const auto *NE = NECC->getCXXNewExpr(); 158 SVal V = *getObjectUnderConstruction(State, NE, LCtx); 159 if (const SubRegion *MR = 160 dyn_cast_or_null<SubRegion>(V.getAsRegion())) { 161 if (NE->isArray()) { 162 // TODO: In fact, we need to call the constructor for every 163 // allocated element, not just the first one! 164 CallOpts.IsArrayCtorOrDtor = true; 165 return loc::MemRegionVal(getStoreManager().GetElementZeroRegion( 166 MR, NE->getType()->getPointeeType())); 167 } 168 return V; 169 } 170 // TODO: Detect when the allocator returns a null pointer. 171 // Constructor shall not be called in this case. 172 } 173 break; 174 } 175 case ConstructionContext::SimpleReturnedValueKind: 176 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: { 177 // The temporary is to be managed by the parent stack frame. 178 // So build it in the parent stack frame if we're not in the 179 // top frame of the analysis. 180 const StackFrameContext *SFC = LCtx->getStackFrame(); 181 if (const LocationContext *CallerLCtx = SFC->getParent()) { 182 auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()] 183 .getAs<CFGCXXRecordTypedCall>(); 184 if (!RTC) { 185 // We were unable to find the correct construction context for the 186 // call in the parent stack frame. This is equivalent to not being 187 // able to find construction context at all. 188 break; 189 } 190 if (isa<BlockInvocationContext>(CallerLCtx)) { 191 // Unwrap block invocation contexts. They're mostly part of 192 // the current stack frame. 193 CallerLCtx = CallerLCtx->getParent(); 194 assert(!isa<BlockInvocationContext>(CallerLCtx)); 195 } 196 return computeObjectUnderConstruction( 197 cast<Expr>(SFC->getCallSite()), State, CallerLCtx, 198 RTC->getConstructionContext(), CallOpts); 199 } else { 200 // We are on the top frame of the analysis. We do not know where is the 201 // object returned to. Conjure a symbolic region for the return value. 202 // TODO: We probably need a new MemRegion kind to represent the storage 203 // of that SymbolicRegion, so that we cound produce a fancy symbol 204 // instead of an anonymous conjured symbol. 205 // TODO: Do we need to track the region to avoid having it dead 206 // too early? It does die too early, at least in C++17, but because 207 // putting anything into a SymbolicRegion causes an immediate escape, 208 // it doesn't cause any leak false positives. 209 const auto *RCC = cast<ReturnedValueConstructionContext>(CC); 210 // Make sure that this doesn't coincide with any other symbol 211 // conjured for the returned expression. 212 static const int TopLevelSymRegionTag = 0; 213 const Expr *RetE = RCC->getReturnStmt()->getRetValue(); 214 assert(RetE && "Void returns should not have a construction context"); 215 QualType ReturnTy = RetE->getType(); 216 QualType RegionTy = ACtx.getPointerType(ReturnTy); 217 return SVB.conjureSymbolVal(&TopLevelSymRegionTag, RetE, SFC, RegionTy, 218 currBldrCtx->blockCount()); 219 } 220 llvm_unreachable("Unhandled return value construction context!"); 221 } 222 case ConstructionContext::ElidedTemporaryObjectKind: { 223 assert(AMgr.getAnalyzerOptions().ShouldElideConstructors); 224 const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(CC); 225 226 // Support pre-C++17 copy elision. We'll have the elidable copy 227 // constructor in the AST and in the CFG, but we'll skip it 228 // and construct directly into the final object. This call 229 // also sets the CallOpts flags for us. 230 // If the elided copy/move constructor is not supported, there's still 231 // benefit in trying to model the non-elided constructor. 232 // Stash our state before trying to elide, as it'll get overwritten. 233 ProgramStateRef PreElideState = State; 234 EvalCallOptions PreElideCallOpts = CallOpts; 235 236 SVal V = computeObjectUnderConstruction( 237 TCC->getConstructorAfterElision(), State, LCtx, 238 TCC->getConstructionContextAfterElision(), CallOpts); 239 240 // FIXME: This definition of "copy elision has not failed" is unreliable. 241 // It doesn't indicate that the constructor will actually be inlined 242 // later; this is still up to evalCall() to decide. 243 if (!CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) 244 return V; 245 246 // Copy elision failed. Revert the changes and proceed as if we have 247 // a simple temporary. 248 CallOpts = PreElideCallOpts; 249 CallOpts.IsElidableCtorThatHasNotBeenElided = true; 250 LLVM_FALLTHROUGH; 251 } 252 case ConstructionContext::SimpleTemporaryObjectKind: { 253 const auto *TCC = cast<TemporaryObjectConstructionContext>(CC); 254 const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr(); 255 256 CallOpts.IsTemporaryCtorOrDtor = true; 257 if (MTE) { 258 if (const ValueDecl *VD = MTE->getExtendingDecl()) { 259 assert(MTE->getStorageDuration() != SD_FullExpression); 260 if (!VD->getType()->isReferenceType()) { 261 // We're lifetime-extended by a surrounding aggregate. 262 // Automatic destructors aren't quite working in this case 263 // on the CFG side. We should warn the caller about that. 264 // FIXME: Is there a better way to retrieve this information from 265 // the MaterializeTemporaryExpr? 266 CallOpts.IsTemporaryLifetimeExtendedViaAggregate = true; 267 } 268 } 269 270 if (MTE->getStorageDuration() == SD_Static || 271 MTE->getStorageDuration() == SD_Thread) 272 return loc::MemRegionVal(MRMgr.getCXXStaticTempObjectRegion(E)); 273 } 274 275 return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx)); 276 } 277 case ConstructionContext::ArgumentKind: { 278 // Arguments are technically temporaries. 279 CallOpts.IsTemporaryCtorOrDtor = true; 280 281 const auto *ACC = cast<ArgumentConstructionContext>(CC); 282 const Expr *E = ACC->getCallLikeExpr(); 283 unsigned Idx = ACC->getIndex(); 284 285 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 286 auto getArgLoc = [&](CallEventRef<> Caller) -> Optional<SVal> { 287 const LocationContext *FutureSFC = 288 Caller->getCalleeStackFrame(currBldrCtx->blockCount()); 289 // Return early if we are unable to reliably foresee 290 // the future stack frame. 291 if (!FutureSFC) 292 return None; 293 294 // This should be equivalent to Caller->getDecl() for now, but 295 // FutureSFC->getDecl() is likely to support better stuff (like 296 // virtual functions) earlier. 297 const Decl *CalleeD = FutureSFC->getDecl(); 298 299 // FIXME: Support for variadic arguments is not implemented here yet. 300 if (CallEvent::isVariadic(CalleeD)) 301 return None; 302 303 // Operator arguments do not correspond to operator parameters 304 // because this-argument is implemented as a normal argument in 305 // operator call expressions but not in operator declarations. 306 const TypedValueRegion *TVR = Caller->getParameterLocation( 307 *Caller->getAdjustedParameterIndex(Idx), currBldrCtx->blockCount()); 308 if (!TVR) 309 return None; 310 311 return loc::MemRegionVal(TVR); 312 }; 313 314 if (const auto *CE = dyn_cast<CallExpr>(E)) { 315 CallEventRef<> Caller = CEMgr.getSimpleCall(CE, State, LCtx); 316 if (Optional<SVal> V = getArgLoc(Caller)) 317 return *V; 318 else 319 break; 320 } else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) { 321 // Don't bother figuring out the target region for the future 322 // constructor because we won't need it. 323 CallEventRef<> Caller = 324 CEMgr.getCXXConstructorCall(CCE, /*Target=*/nullptr, State, LCtx); 325 if (Optional<SVal> V = getArgLoc(Caller)) 326 return *V; 327 else 328 break; 329 } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(E)) { 330 CallEventRef<> Caller = CEMgr.getObjCMethodCall(ME, State, LCtx); 331 if (Optional<SVal> V = getArgLoc(Caller)) 332 return *V; 333 else 334 break; 335 } 336 } 337 } // switch (CC->getKind()) 338 } 339 340 // If we couldn't find an existing region to construct into, assume we're 341 // constructing a temporary. Notify the caller of our failure. 342 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 343 return loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx)); 344} 345 346ProgramStateRef ExprEngine::updateObjectsUnderConstruction( 347 SVal V, const Expr *E, ProgramStateRef State, const LocationContext *LCtx, 348 const ConstructionContext *CC, const EvalCallOptions &CallOpts) { 349 if (CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) { 350 // Sounds like we failed to find the target region and therefore 351 // copy elision failed. There's nothing we can do about it here. 352 return State; 353 } 354 355 // See if we're constructing an existing region by looking at the 356 // current construction context. 357 assert(CC && "Computed target region without construction context?"); 358 switch (CC->getKind()) { 359 case ConstructionContext::CXX17ElidedCopyVariableKind: 360 case ConstructionContext::SimpleVariableKind: { 361 const auto *DSCC = cast<VariableConstructionContext>(CC); 362 return addObjectUnderConstruction(State, DSCC->getDeclStmt(), LCtx, V); 363 } 364 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: 365 case ConstructionContext::SimpleConstructorInitializerKind: { 366 const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC); 367 return addObjectUnderConstruction(State, ICC->getCXXCtorInitializer(), 368 LCtx, V); 369 } 370 case ConstructionContext::NewAllocatedObjectKind: { 371 return State; 372 } 373 case ConstructionContext::SimpleReturnedValueKind: 374 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: { 375 const StackFrameContext *SFC = LCtx->getStackFrame(); 376 const LocationContext *CallerLCtx = SFC->getParent(); 377 if (!CallerLCtx) { 378 // No extra work is necessary in top frame. 379 return State; 380 } 381 382 auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()] 383 .getAs<CFGCXXRecordTypedCall>(); 384 assert(RTC && "Could not have had a target region without it"); 385 if (isa<BlockInvocationContext>(CallerLCtx)) { 386 // Unwrap block invocation contexts. They're mostly part of 387 // the current stack frame. 388 CallerLCtx = CallerLCtx->getParent(); 389 assert(!isa<BlockInvocationContext>(CallerLCtx)); 390 } 391 392 return updateObjectsUnderConstruction(V, 393 cast<Expr>(SFC->getCallSite()), State, CallerLCtx, 394 RTC->getConstructionContext(), CallOpts); 395 } 396 case ConstructionContext::ElidedTemporaryObjectKind: { 397 assert(AMgr.getAnalyzerOptions().ShouldElideConstructors); 398 if (!CallOpts.IsElidableCtorThatHasNotBeenElided) { 399 const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(CC); 400 State = updateObjectsUnderConstruction( 401 V, TCC->getConstructorAfterElision(), State, LCtx, 402 TCC->getConstructionContextAfterElision(), CallOpts); 403 404 // Remember that we've elided the constructor. 405 State = addObjectUnderConstruction( 406 State, TCC->getConstructorAfterElision(), LCtx, V); 407 408 // Remember that we've elided the destructor. 409 if (const auto *BTE = TCC->getCXXBindTemporaryExpr()) 410 State = elideDestructor(State, BTE, LCtx); 411 412 // Instead of materialization, shamelessly return 413 // the final object destination. 414 if (const auto *MTE = TCC->getMaterializedTemporaryExpr()) 415 State = addObjectUnderConstruction(State, MTE, LCtx, V); 416 417 return State; 418 } 419 // If we decided not to elide the constructor, proceed as if 420 // it's a simple temporary. 421 LLVM_FALLTHROUGH; 422 } 423 case ConstructionContext::SimpleTemporaryObjectKind: { 424 const auto *TCC = cast<TemporaryObjectConstructionContext>(CC); 425 if (const auto *BTE = TCC->getCXXBindTemporaryExpr()) 426 State = addObjectUnderConstruction(State, BTE, LCtx, V); 427 428 if (const auto *MTE = TCC->getMaterializedTemporaryExpr()) 429 State = addObjectUnderConstruction(State, MTE, LCtx, V); 430 431 return State; 432 } 433 case ConstructionContext::ArgumentKind: { 434 const auto *ACC = cast<ArgumentConstructionContext>(CC); 435 if (const auto *BTE = ACC->getCXXBindTemporaryExpr()) 436 State = addObjectUnderConstruction(State, BTE, LCtx, V); 437 438 return addObjectUnderConstruction( 439 State, {ACC->getCallLikeExpr(), ACC->getIndex()}, LCtx, V); 440 } 441 } 442 llvm_unreachable("Unhandled construction context!"); 443} 444 445void ExprEngine::handleConstructor(const Expr *E, 446 ExplodedNode *Pred, 447 ExplodedNodeSet &destNodes) { 448 const auto *CE = dyn_cast<CXXConstructExpr>(E); 449 const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(E); 450 assert(CE || CIE); 451 452 const LocationContext *LCtx = Pred->getLocationContext(); 453 ProgramStateRef State = Pred->getState(); 454 455 SVal Target = UnknownVal(); 456 457 if (CE) { 458 if (Optional<SVal> ElidedTarget = 459 getObjectUnderConstruction(State, CE, LCtx)) { 460 // We've previously modeled an elidable constructor by pretending that it 461 // in fact constructs into the correct target. This constructor can 462 // therefore be skipped. 463 Target = *ElidedTarget; 464 StmtNodeBuilder Bldr(Pred, destNodes, *currBldrCtx); 465 State = finishObjectConstruction(State, CE, LCtx); 466 if (auto L = Target.getAs<Loc>()) 467 State = State->BindExpr(CE, LCtx, State->getSVal(*L, CE->getType())); 468 Bldr.generateNode(CE, Pred, State); 469 return; 470 } 471 } 472 473 // FIXME: Handle arrays, which run the same constructor for every element. 474 // For now, we just run the first constructor (which should still invalidate 475 // the entire array). 476 477 EvalCallOptions CallOpts; 478 auto C = getCurrentCFGElement().getAs<CFGConstructor>(); 479 assert(C || getCurrentCFGElement().getAs<CFGStmt>()); 480 const ConstructionContext *CC = C ? C->getConstructionContext() : nullptr; 481 482 const CXXConstructExpr::ConstructionKind CK = 483 CE ? CE->getConstructionKind() : CIE->getConstructionKind(); 484 switch (CK) { 485 case CXXConstructExpr::CK_Complete: { 486 // Inherited constructors are always base class constructors. 487 assert(CE && !CIE && "A complete constructor is inherited?!"); 488 489 // The target region is found from construction context. 490 std::tie(State, Target) = 491 handleConstructionContext(CE, State, LCtx, CC, CallOpts); 492 break; 493 } 494 case CXXConstructExpr::CK_VirtualBase: { 495 // Make sure we are not calling virtual base class initializers twice. 496 // Only the most-derived object should initialize virtual base classes. 497 const auto *OuterCtor = dyn_cast_or_null<CXXConstructExpr>( 498 LCtx->getStackFrame()->getCallSite()); 499 assert( 500 (!OuterCtor || 501 OuterCtor->getConstructionKind() == CXXConstructExpr::CK_Complete || 502 OuterCtor->getConstructionKind() == CXXConstructExpr::CK_Delegating) && 503 ("This virtual base should have already been initialized by " 504 "the most derived class!")); 505 (void)OuterCtor; 506 LLVM_FALLTHROUGH; 507 } 508 case CXXConstructExpr::CK_NonVirtualBase: 509 // In C++17, classes with non-virtual bases may be aggregates, so they would 510 // be initialized as aggregates without a constructor call, so we may have 511 // a base class constructed directly into an initializer list without 512 // having the derived-class constructor call on the previous stack frame. 513 // Initializer lists may be nested into more initializer lists that 514 // correspond to surrounding aggregate initializations. 515 // FIXME: For now this code essentially bails out. We need to find the 516 // correct target region and set it. 517 // FIXME: Instead of relying on the ParentMap, we should have the 518 // trigger-statement (InitListExpr in this case) passed down from CFG or 519 // otherwise always available during construction. 520 if (dyn_cast_or_null<InitListExpr>(LCtx->getParentMap().getParent(E))) { 521 MemRegionManager &MRMgr = getSValBuilder().getRegionManager(); 522 Target = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx)); 523 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 524 break; 525 } 526 LLVM_FALLTHROUGH; 527 case CXXConstructExpr::CK_Delegating: { 528 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl()); 529 Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor, 530 LCtx->getStackFrame()); 531 SVal ThisVal = State->getSVal(ThisPtr); 532 533 if (CK == CXXConstructExpr::CK_Delegating) { 534 Target = ThisVal; 535 } else { 536 // Cast to the base type. 537 bool IsVirtual = (CK == CXXConstructExpr::CK_VirtualBase); 538 SVal BaseVal = 539 getStoreManager().evalDerivedToBase(ThisVal, E->getType(), IsVirtual); 540 Target = BaseVal; 541 } 542 break; 543 } 544 } 545 546 if (State != Pred->getState()) { 547 static SimpleProgramPointTag T("ExprEngine", 548 "Prepare for object construction"); 549 ExplodedNodeSet DstPrepare; 550 StmtNodeBuilder BldrPrepare(Pred, DstPrepare, *currBldrCtx); 551 BldrPrepare.generateNode(E, Pred, State, &T, ProgramPoint::PreStmtKind); 552 assert(DstPrepare.size() <= 1); 553 if (DstPrepare.size() == 0) 554 return; 555 Pred = *BldrPrepare.begin(); 556 } 557 558 const MemRegion *TargetRegion = Target.getAsRegion(); 559 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 560 CallEventRef<> Call = 561 CIE ? (CallEventRef<>)CEMgr.getCXXInheritedConstructorCall( 562 CIE, TargetRegion, State, LCtx) 563 : (CallEventRef<>)CEMgr.getCXXConstructorCall( 564 CE, TargetRegion, State, LCtx); 565 566 ExplodedNodeSet DstPreVisit; 567 getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, E, *this); 568 569 ExplodedNodeSet PreInitialized; 570 if (CE) { 571 // FIXME: Is it possible and/or useful to do this before PreStmt? 572 StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx); 573 for (ExplodedNodeSet::iterator I = DstPreVisit.begin(), 574 E = DstPreVisit.end(); 575 I != E; ++I) { 576 ProgramStateRef State = (*I)->getState(); 577 if (CE->requiresZeroInitialization()) { 578 // FIXME: Once we properly handle constructors in new-expressions, we'll 579 // need to invalidate the region before setting a default value, to make 580 // sure there aren't any lingering bindings around. This probably needs 581 // to happen regardless of whether or not the object is zero-initialized 582 // to handle random fields of a placement-initialized object picking up 583 // old bindings. We might only want to do it when we need to, though. 584 // FIXME: This isn't actually correct for arrays -- we need to zero- 585 // initialize the entire array, not just the first element -- but our 586 // handling of arrays everywhere else is weak as well, so this shouldn't 587 // actually make things worse. Placement new makes this tricky as well, 588 // since it's then possible to be initializing one part of a multi- 589 // dimensional array. 590 State = State->bindDefaultZero(Target, LCtx); 591 } 592 593 Bldr.generateNode(CE, *I, State, /*tag=*/nullptr, 594 ProgramPoint::PreStmtKind); 595 } 596 } else { 597 PreInitialized = DstPreVisit; 598 } 599 600 ExplodedNodeSet DstPreCall; 601 getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized, 602 *Call, *this); 603 604 ExplodedNodeSet DstEvaluated; 605 StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx); 606 607 if (CE && CE->getConstructor()->isTrivial() && 608 CE->getConstructor()->isCopyOrMoveConstructor() && 609 !CallOpts.IsArrayCtorOrDtor) { 610 // FIXME: Handle other kinds of trivial constructors as well. 611 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 612 I != E; ++I) 613 performTrivialCopy(Bldr, *I, *Call); 614 615 } else { 616 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 617 I != E; ++I) 618 getCheckerManager().runCheckersForEvalCall(DstEvaluated, *I, *Call, *this, 619 CallOpts); 620 } 621 622 // If the CFG was constructed without elements for temporary destructors 623 // and the just-called constructor created a temporary object then 624 // stop exploration if the temporary object has a noreturn constructor. 625 // This can lose coverage because the destructor, if it were present 626 // in the CFG, would be called at the end of the full expression or 627 // later (for life-time extended temporaries) -- but avoids infeasible 628 // paths when no-return temporary destructors are used for assertions. 629 const AnalysisDeclContext *ADC = LCtx->getAnalysisDeclContext(); 630 if (!ADC->getCFGBuildOptions().AddTemporaryDtors) { 631 if (llvm::isa_and_nonnull<CXXTempObjectRegion>(TargetRegion) && 632 cast<CXXConstructorDecl>(Call->getDecl()) 633 ->getParent() 634 ->isAnyDestructorNoReturn()) { 635 636 // If we've inlined the constructor, then DstEvaluated would be empty. 637 // In this case we still want a sink, which could be implemented 638 // in processCallExit. But we don't have that implemented at the moment, 639 // so if you hit this assertion, see if you can avoid inlining 640 // the respective constructor when analyzer-config cfg-temporary-dtors 641 // is set to false. 642 // Otherwise there's nothing wrong with inlining such constructor. 643 assert(!DstEvaluated.empty() && 644 "We should not have inlined this constructor!"); 645 646 for (ExplodedNode *N : DstEvaluated) { 647 Bldr.generateSink(E, N, N->getState()); 648 } 649 650 // There is no need to run the PostCall and PostStmt checker 651 // callbacks because we just generated sinks on all nodes in th 652 // frontier. 653 return; 654 } 655 } 656 657 ExplodedNodeSet DstPostArgumentCleanup; 658 for (ExplodedNode *I : DstEvaluated) 659 finishArgumentConstruction(DstPostArgumentCleanup, I, *Call); 660 661 // If there were other constructors called for object-type arguments 662 // of this constructor, clean them up. 663 ExplodedNodeSet DstPostCall; 664 getCheckerManager().runCheckersForPostCall(DstPostCall, 665 DstPostArgumentCleanup, 666 *Call, *this); 667 getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, E, *this); 668} 669 670void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE, 671 ExplodedNode *Pred, 672 ExplodedNodeSet &Dst) { 673 handleConstructor(CE, Pred, Dst); 674} 675 676void ExprEngine::VisitCXXInheritedCtorInitExpr( 677 const CXXInheritedCtorInitExpr *CE, ExplodedNode *Pred, 678 ExplodedNodeSet &Dst) { 679 handleConstructor(CE, Pred, Dst); 680} 681 682void ExprEngine::VisitCXXDestructor(QualType ObjectType, 683 const MemRegion *Dest, 684 const Stmt *S, 685 bool IsBaseDtor, 686 ExplodedNode *Pred, 687 ExplodedNodeSet &Dst, 688 EvalCallOptions &CallOpts) { 689 assert(S && "A destructor without a trigger!"); 690 const LocationContext *LCtx = Pred->getLocationContext(); 691 ProgramStateRef State = Pred->getState(); 692 693 const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl(); 694 assert(RecordDecl && "Only CXXRecordDecls should have destructors"); 695 const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor(); 696 // FIXME: There should always be a Decl, otherwise the destructor call 697 // shouldn't have been added to the CFG in the first place. 698 if (!DtorDecl) { 699 // Skip the invalid destructor. We cannot simply return because 700 // it would interrupt the analysis instead. 701 static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor"); 702 // FIXME: PostImplicitCall with a null decl may crash elsewhere anyway. 703 PostImplicitCall PP(/*Decl=*/nullptr, S->getEndLoc(), LCtx, &T); 704 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 705 Bldr.generateNode(PP, Pred->getState(), Pred); 706 return; 707 } 708 709 if (!Dest) { 710 // We're trying to destroy something that is not a region. This may happen 711 // for a variety of reasons (unknown target region, concrete integer instead 712 // of target region, etc.). The current code makes an attempt to recover. 713 // FIXME: We probably don't really need to recover when we're dealing 714 // with concrete integers specifically. 715 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 716 if (const Expr *E = dyn_cast_or_null<Expr>(S)) { 717 Dest = MRMgr.getCXXTempObjectRegion(E, Pred->getLocationContext()); 718 } else { 719 static SimpleProgramPointTag T("ExprEngine", "SkipInvalidDestructor"); 720 NodeBuilder Bldr(Pred, Dst, *currBldrCtx); 721 Bldr.generateSink(Pred->getLocation().withTag(&T), 722 Pred->getState(), Pred); 723 return; 724 } 725 } 726 727 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 728 CallEventRef<CXXDestructorCall> Call = 729 CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx); 730 731 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 732 Call->getSourceRange().getBegin(), 733 "Error evaluating destructor"); 734 735 ExplodedNodeSet DstPreCall; 736 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, 737 *Call, *this); 738 739 ExplodedNodeSet DstInvalidated; 740 StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx); 741 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 742 I != E; ++I) 743 defaultEvalCall(Bldr, *I, *Call, CallOpts); 744 745 getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated, 746 *Call, *this); 747} 748 749void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, 750 ExplodedNode *Pred, 751 ExplodedNodeSet &Dst) { 752 ProgramStateRef State = Pred->getState(); 753 const LocationContext *LCtx = Pred->getLocationContext(); 754 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 755 CNE->getBeginLoc(), 756 "Error evaluating New Allocator Call"); 757 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 758 CallEventRef<CXXAllocatorCall> Call = 759 CEMgr.getCXXAllocatorCall(CNE, State, LCtx); 760 761 ExplodedNodeSet DstPreCall; 762 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, 763 *Call, *this); 764 765 ExplodedNodeSet DstPostCall; 766 StmtNodeBuilder CallBldr(DstPreCall, DstPostCall, *currBldrCtx); 767 for (ExplodedNode *I : DstPreCall) { 768 // FIXME: Provide evalCall for checkers? 769 defaultEvalCall(CallBldr, I, *Call); 770 } 771 // If the call is inlined, DstPostCall will be empty and we bail out now. 772 773 // Store return value of operator new() for future use, until the actual 774 // CXXNewExpr gets processed. 775 ExplodedNodeSet DstPostValue; 776 StmtNodeBuilder ValueBldr(DstPostCall, DstPostValue, *currBldrCtx); 777 for (ExplodedNode *I : DstPostCall) { 778 // FIXME: Because CNE serves as the "call site" for the allocator (due to 779 // lack of a better expression in the AST), the conjured return value symbol 780 // is going to be of the same type (C++ object pointer type). Technically 781 // this is not correct because the operator new's prototype always says that 782 // it returns a 'void *'. So we should change the type of the symbol, 783 // and then evaluate the cast over the symbolic pointer from 'void *' to 784 // the object pointer type. But without changing the symbol's type it 785 // is breaking too much to evaluate the no-op symbolic cast over it, so we 786 // skip it for now. 787 ProgramStateRef State = I->getState(); 788 SVal RetVal = State->getSVal(CNE, LCtx); 789 790 // If this allocation function is not declared as non-throwing, failures 791 // /must/ be signalled by exceptions, and thus the return value will never 792 // be NULL. -fno-exceptions does not influence this semantics. 793 // FIXME: GCC has a -fcheck-new option, which forces it to consider the case 794 // where new can return NULL. If we end up supporting that option, we can 795 // consider adding a check for it here. 796 // C++11 [basic.stc.dynamic.allocation]p3. 797 if (const FunctionDecl *FD = CNE->getOperatorNew()) { 798 QualType Ty = FD->getType(); 799 if (const auto *ProtoType = Ty->getAs<FunctionProtoType>()) 800 if (!ProtoType->isNothrow()) 801 State = State->assume(RetVal.castAs<DefinedOrUnknownSVal>(), true); 802 } 803 804 ValueBldr.generateNode( 805 CNE, I, addObjectUnderConstruction(State, CNE, LCtx, RetVal)); 806 } 807 808 ExplodedNodeSet DstPostPostCallCallback; 809 getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback, 810 DstPostValue, *Call, *this); 811 for (ExplodedNode *I : DstPostPostCallCallback) { 812 getCheckerManager().runCheckersForNewAllocator(*Call, Dst, I, *this); 813 } 814} 815 816void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, 817 ExplodedNodeSet &Dst) { 818 // FIXME: Much of this should eventually migrate to CXXAllocatorCall. 819 // Also, we need to decide how allocators actually work -- they're not 820 // really part of the CXXNewExpr because they happen BEFORE the 821 // CXXConstructExpr subexpression. See PR12014 for some discussion. 822 823 unsigned blockCount = currBldrCtx->blockCount(); 824 const LocationContext *LCtx = Pred->getLocationContext(); 825 SVal symVal = UnknownVal(); 826 FunctionDecl *FD = CNE->getOperatorNew(); 827 828 bool IsStandardGlobalOpNewFunction = 829 FD->isReplaceableGlobalAllocationFunction(); 830 831 ProgramStateRef State = Pred->getState(); 832 833 // Retrieve the stored operator new() return value. 834 if (AMgr.getAnalyzerOptions().MayInlineCXXAllocator) { 835 symVal = *getObjectUnderConstruction(State, CNE, LCtx); 836 State = finishObjectConstruction(State, CNE, LCtx); 837 } 838 839 // We assume all standard global 'operator new' functions allocate memory in 840 // heap. We realize this is an approximation that might not correctly model 841 // a custom global allocator. 842 if (symVal.isUnknown()) { 843 if (IsStandardGlobalOpNewFunction) 844 symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount); 845 else 846 symVal = svalBuilder.conjureSymbolVal(nullptr, CNE, LCtx, CNE->getType(), 847 blockCount); 848 } 849 850 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 851 CallEventRef<CXXAllocatorCall> Call = 852 CEMgr.getCXXAllocatorCall(CNE, State, LCtx); 853 854 if (!AMgr.getAnalyzerOptions().MayInlineCXXAllocator) { 855 // Invalidate placement args. 856 // FIXME: Once we figure out how we want allocators to work, 857 // we should be using the usual pre-/(default-)eval-/post-call checkers 858 // here. 859 State = Call->invalidateRegions(blockCount); 860 if (!State) 861 return; 862 863 // If this allocation function is not declared as non-throwing, failures 864 // /must/ be signalled by exceptions, and thus the return value will never 865 // be NULL. -fno-exceptions does not influence this semantics. 866 // FIXME: GCC has a -fcheck-new option, which forces it to consider the case 867 // where new can return NULL. If we end up supporting that option, we can 868 // consider adding a check for it here. 869 // C++11 [basic.stc.dynamic.allocation]p3. 870 if (FD) { 871 QualType Ty = FD->getType(); 872 if (const auto *ProtoType = Ty->getAs<FunctionProtoType>()) 873 if (!ProtoType->isNothrow()) 874 if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>()) 875 State = State->assume(*dSymVal, true); 876 } 877 } 878 879 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 880 881 SVal Result = symVal; 882 883 if (CNE->isArray()) { 884 // FIXME: allocating an array requires simulating the constructors. 885 // For now, just return a symbolicated region. 886 if (const auto *NewReg = cast_or_null<SubRegion>(symVal.getAsRegion())) { 887 QualType ObjTy = CNE->getType()->getPointeeType(); 888 const ElementRegion *EleReg = 889 getStoreManager().GetElementZeroRegion(NewReg, ObjTy); 890 Result = loc::MemRegionVal(EleReg); 891 } 892 State = State->BindExpr(CNE, Pred->getLocationContext(), Result); 893 Bldr.generateNode(CNE, Pred, State); 894 return; 895 } 896 897 // FIXME: Once we have proper support for CXXConstructExprs inside 898 // CXXNewExpr, we need to make sure that the constructed object is not 899 // immediately invalidated here. (The placement call should happen before 900 // the constructor call anyway.) 901 if (FD && FD->isReservedGlobalPlacementOperator()) { 902 // Non-array placement new should always return the placement location. 903 SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx); 904 Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(), 905 CNE->getPlacementArg(0)->getType()); 906 } 907 908 // Bind the address of the object, then check to see if we cached out. 909 State = State->BindExpr(CNE, LCtx, Result); 910 ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State); 911 if (!NewN) 912 return; 913 914 // If the type is not a record, we won't have a CXXConstructExpr as an 915 // initializer. Copy the value over. 916 if (const Expr *Init = CNE->getInitializer()) { 917 if (!isa<CXXConstructExpr>(Init)) { 918 assert(Bldr.getResults().size() == 1); 919 Bldr.takeNodes(NewN); 920 evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx), 921 /*FirstInit=*/IsStandardGlobalOpNewFunction); 922 } 923 } 924} 925 926void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, 927 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 928 929 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 930 CallEventRef<CXXDeallocatorCall> Call = CEMgr.getCXXDeallocatorCall( 931 CDE, Pred->getState(), Pred->getLocationContext()); 932 933 ExplodedNodeSet DstPreCall; 934 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, *Call, *this); 935 936 getCheckerManager().runCheckersForPostCall(Dst, DstPreCall, *Call, *this); 937} 938 939void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS, ExplodedNode *Pred, 940 ExplodedNodeSet &Dst) { 941 const VarDecl *VD = CS->getExceptionDecl(); 942 if (!VD) { 943 Dst.Add(Pred); 944 return; 945 } 946 947 const LocationContext *LCtx = Pred->getLocationContext(); 948 SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(), 949 currBldrCtx->blockCount()); 950 ProgramStateRef state = Pred->getState(); 951 state = state->bindLoc(state->getLValue(VD, LCtx), V, LCtx); 952 953 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 954 Bldr.generateNode(CS, Pred, state); 955} 956 957void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, 958 ExplodedNodeSet &Dst) { 959 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 960 961 // Get the this object region from StoreManager. 962 const LocationContext *LCtx = Pred->getLocationContext(); 963 const MemRegion *R = 964 svalBuilder.getRegionManager().getCXXThisRegion( 965 getContext().getCanonicalType(TE->getType()), 966 LCtx); 967 968 ProgramStateRef state = Pred->getState(); 969 SVal V = state->getSVal(loc::MemRegionVal(R)); 970 Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V)); 971} 972 973void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, 974 ExplodedNodeSet &Dst) { 975 const LocationContext *LocCtxt = Pred->getLocationContext(); 976 977 // Get the region of the lambda itself. 978 const MemRegion *R = svalBuilder.getRegionManager().getCXXTempObjectRegion( 979 LE, LocCtxt); 980 SVal V = loc::MemRegionVal(R); 981 982 ProgramStateRef State = Pred->getState(); 983 984 // If we created a new MemRegion for the lambda, we should explicitly bind 985 // the captures. 986 CXXRecordDecl::field_iterator CurField = LE->getLambdaClass()->field_begin(); 987 for (LambdaExpr::const_capture_init_iterator i = LE->capture_init_begin(), 988 e = LE->capture_init_end(); 989 i != e; ++i, ++CurField) { 990 FieldDecl *FieldForCapture = *CurField; 991 SVal FieldLoc = State->getLValue(FieldForCapture, V); 992 993 SVal InitVal; 994 if (!FieldForCapture->hasCapturedVLAType()) { 995 Expr *InitExpr = *i; 996 assert(InitExpr && "Capture missing initialization expression"); 997 InitVal = State->getSVal(InitExpr, LocCtxt); 998 } else { 999 // The field stores the length of a captured variable-length array. 1000 // These captures don't have initialization expressions; instead we 1001 // get the length from the VLAType size expression. 1002 Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr(); 1003 InitVal = State->getSVal(SizeExpr, LocCtxt); 1004 } 1005 1006 State = State->bindLoc(FieldLoc, InitVal, LocCtxt); 1007 } 1008 1009 // Decay the Loc into an RValue, because there might be a 1010 // MaterializeTemporaryExpr node above this one which expects the bound value 1011 // to be an RValue. 1012 SVal LambdaRVal = State->getSVal(R); 1013 1014 ExplodedNodeSet Tmp; 1015 StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx); 1016 // FIXME: is this the right program point kind? 1017 Bldr.generateNode(LE, Pred, 1018 State->BindExpr(LE, LocCtxt, LambdaRVal), 1019 nullptr, ProgramPoint::PostLValueKind); 1020 1021 // FIXME: Move all post/pre visits to ::Visit(). 1022 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this); 1023} 1024