1 //===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines the C++ expression evaluation engine. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 15 #include "clang/Analysis/ConstructionContext.h" 16 #include "clang/AST/DeclCXX.h" 17 #include "clang/AST/StmtCXX.h" 18 #include "clang/AST/ParentMap.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 24 using namespace clang; 25 using namespace ento; 26 27 void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, 28 ExplodedNode *Pred, 29 ExplodedNodeSet &Dst) { 30 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 31 const Expr *tempExpr = ME->GetTemporaryExpr()->IgnoreParens(); 32 ProgramStateRef state = Pred->getState(); 33 const LocationContext *LCtx = Pred->getLocationContext(); 34 35 state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME); 36 Bldr.generateNode(ME, Pred, state); 37 } 38 39 // FIXME: This is the sort of code that should eventually live in a Core 40 // checker rather than as a special case in ExprEngine. 41 void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred, 42 const CallEvent &Call) { 43 SVal ThisVal; 44 bool AlwaysReturnsLValue; 45 const CXXRecordDecl *ThisRD = nullptr; 46 if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) { 47 assert(Ctor->getDecl()->isTrivial()); 48 assert(Ctor->getDecl()->isCopyOrMoveConstructor()); 49 ThisVal = Ctor->getCXXThisVal(); 50 ThisRD = Ctor->getDecl()->getParent(); 51 AlwaysReturnsLValue = false; 52 } else { 53 assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial()); 54 assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() == 55 OO_Equal); 56 ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal(); 57 ThisRD = cast<CXXMethodDecl>(Call.getDecl())->getParent(); 58 AlwaysReturnsLValue = true; 59 } 60 61 assert(ThisRD); 62 if (ThisRD->isEmpty()) { 63 // Do nothing for empty classes. Otherwise it'd retrieve an UnknownVal 64 // and bind it and RegionStore would think that the actual value 65 // in this region at this offset is unknown. 66 return; 67 } 68 69 const LocationContext *LCtx = Pred->getLocationContext(); 70 71 ExplodedNodeSet Dst; 72 Bldr.takeNodes(Pred); 73 74 SVal V = Call.getArgSVal(0); 75 76 // If the value being copied is not unknown, load from its location to get 77 // an aggregate rvalue. 78 if (Optional<Loc> L = V.getAs<Loc>()) 79 V = Pred->getState()->getSVal(*L); 80 else 81 assert(V.isUnknownOrUndef()); 82 83 const Expr *CallExpr = Call.getOriginExpr(); 84 evalBind(Dst, CallExpr, Pred, ThisVal, V, true); 85 86 PostStmt PS(CallExpr, LCtx); 87 for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end(); 88 I != E; ++I) { 89 ProgramStateRef State = (*I)->getState(); 90 if (AlwaysReturnsLValue) 91 State = State->BindExpr(CallExpr, LCtx, ThisVal); 92 else 93 State = bindReturnValue(Call, LCtx, State); 94 Bldr.generateNode(PS, State, *I); 95 } 96 } 97 98 99 SVal ExprEngine::makeZeroElementRegion(ProgramStateRef State, SVal LValue, 100 QualType &Ty, bool &IsArray) { 101 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 102 ASTContext &Ctx = SVB.getContext(); 103 104 while (const ArrayType *AT = Ctx.getAsArrayType(Ty)) { 105 Ty = AT->getElementType(); 106 LValue = State->getLValue(Ty, SVB.makeZeroArrayIndex(), LValue); 107 IsArray = true; 108 } 109 110 return LValue; 111 } 112 113 std::pair<ProgramStateRef, SVal> ExprEngine::prepareForObjectConstruction( 114 const Expr *E, ProgramStateRef State, const LocationContext *LCtx, 115 const ConstructionContext *CC, EvalCallOptions &CallOpts) { 116 MemRegionManager &MRMgr = getSValBuilder().getRegionManager(); 117 118 // See if we're constructing an existing region by looking at the 119 // current 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 SVal LValue = State->getLValue(Var, LCtx); 128 QualType Ty = Var->getType(); 129 LValue = 130 makeZeroElementRegion(State, LValue, Ty, CallOpts.IsArrayCtorOrDtor); 131 State = 132 addObjectUnderConstruction(State, DSCC->getDeclStmt(), LCtx, LValue); 133 return std::make_pair(State, LValue); 134 } 135 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: 136 case ConstructionContext::SimpleConstructorInitializerKind: { 137 const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC); 138 const auto *Init = ICC->getCXXCtorInitializer(); 139 assert(Init->isAnyMemberInitializer()); 140 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl()); 141 Loc ThisPtr = 142 getSValBuilder().getCXXThis(CurCtor, LCtx->getStackFrame()); 143 SVal ThisVal = State->getSVal(ThisPtr); 144 145 const ValueDecl *Field; 146 SVal FieldVal; 147 if (Init->isIndirectMemberInitializer()) { 148 Field = Init->getIndirectMember(); 149 FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal); 150 } else { 151 Field = Init->getMember(); 152 FieldVal = State->getLValue(Init->getMember(), ThisVal); 153 } 154 155 QualType Ty = Field->getType(); 156 FieldVal = makeZeroElementRegion(State, FieldVal, Ty, 157 CallOpts.IsArrayCtorOrDtor); 158 State = addObjectUnderConstruction(State, Init, LCtx, FieldVal); 159 return std::make_pair(State, FieldVal); 160 } 161 case ConstructionContext::NewAllocatedObjectKind: { 162 if (AMgr.getAnalyzerOptions().mayInlineCXXAllocator()) { 163 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC); 164 const auto *NE = NECC->getCXXNewExpr(); 165 SVal V = *getObjectUnderConstruction(State, NE, LCtx); 166 if (const SubRegion *MR = 167 dyn_cast_or_null<SubRegion>(V.getAsRegion())) { 168 if (NE->isArray()) { 169 // TODO: In fact, we need to call the constructor for every 170 // allocated element, not just the first one! 171 CallOpts.IsArrayCtorOrDtor = true; 172 return std::make_pair( 173 State, loc::MemRegionVal(getStoreManager().GetElementZeroRegion( 174 MR, NE->getType()->getPointeeType()))); 175 } 176 return std::make_pair(State, V); 177 } 178 // TODO: Detect when the allocator returns a null pointer. 179 // Constructor shall not be called in this case. 180 } 181 break; 182 } 183 case ConstructionContext::SimpleReturnedValueKind: 184 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: { 185 // The temporary is to be managed by the parent stack frame. 186 // So build it in the parent stack frame if we're not in the 187 // top frame of the analysis. 188 const StackFrameContext *SFC = LCtx->getStackFrame(); 189 if (const LocationContext *CallerLCtx = SFC->getParent()) { 190 auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()] 191 .getAs<CFGCXXRecordTypedCall>(); 192 if (!RTC) { 193 // We were unable to find the correct construction context for the 194 // call in the parent stack frame. This is equivalent to not being 195 // able to find construction context at all. 196 break; 197 } 198 return prepareForObjectConstruction( 199 cast<Expr>(SFC->getCallSite()), State, CallerLCtx, 200 RTC->getConstructionContext(), CallOpts); 201 } else { 202 // We are on the top frame of the analysis. 203 // TODO: What exactly happens when we are? Does the temporary object 204 // live long enough in the region store in this case? Would checkers 205 // think that this object immediately goes out of scope? 206 CallOpts.IsTemporaryCtorOrDtor = true; 207 SVal V = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx)); 208 return std::make_pair(State, V); 209 } 210 llvm_unreachable("Unhandled return value construction context!"); 211 } 212 case ConstructionContext::ElidedTemporaryObjectKind: { 213 assert(AMgr.getAnalyzerOptions().shouldElideConstructors()); 214 const auto *TCC = cast<ElidedTemporaryObjectConstructionContext>(CC); 215 const CXXBindTemporaryExpr *BTE = TCC->getCXXBindTemporaryExpr(); 216 const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr(); 217 const CXXConstructExpr *CE = TCC->getConstructorAfterElision(); 218 219 // Support pre-C++17 copy elision. We'll have the elidable copy 220 // constructor in the AST and in the CFG, but we'll skip it 221 // and construct directly into the final object. This call 222 // also sets the CallOpts flags for us. 223 SVal V; 224 // If the elided copy/move constructor is not supported, there's still 225 // benefit in trying to model the non-elided constructor. 226 // Stash our state before trying to elide, as it'll get overwritten. 227 ProgramStateRef PreElideState = State; 228 EvalCallOptions PreElideCallOpts = CallOpts; 229 230 std::tie(State, V) = prepareForObjectConstruction( 231 CE, State, LCtx, TCC->getConstructionContextAfterElision(), CallOpts); 232 233 // FIXME: This definition of "copy elision has not failed" is unreliable. 234 // It doesn't indicate that the constructor will actually be inlined 235 // later; it is still up to evalCall() to decide. 236 if (!CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion) { 237 // Remember that we've elided the constructor. 238 State = addObjectUnderConstruction(State, CE, LCtx, V); 239 240 // Remember that we've elided the destructor. 241 if (BTE) 242 State = elideDestructor(State, BTE, LCtx); 243 244 // Instead of materialization, shamelessly return 245 // the final object destination. 246 if (MTE) 247 State = addObjectUnderConstruction(State, MTE, LCtx, V); 248 249 return std::make_pair(State, V); 250 } else { 251 // Copy elision failed. Revert the changes and proceed as if we have 252 // a simple temporary. 253 State = PreElideState; 254 CallOpts = PreElideCallOpts; 255 } 256 LLVM_FALLTHROUGH; 257 } 258 case ConstructionContext::SimpleTemporaryObjectKind: { 259 const auto *TCC = cast<TemporaryObjectConstructionContext>(CC); 260 const CXXBindTemporaryExpr *BTE = TCC->getCXXBindTemporaryExpr(); 261 const MaterializeTemporaryExpr *MTE = TCC->getMaterializedTemporaryExpr(); 262 SVal V = UnknownVal(); 263 264 if (MTE) { 265 if (const ValueDecl *VD = MTE->getExtendingDecl()) { 266 assert(MTE->getStorageDuration() != SD_FullExpression); 267 if (!VD->getType()->isReferenceType()) { 268 // We're lifetime-extended by a surrounding aggregate. 269 // Automatic destructors aren't quite working in this case 270 // on the CFG side. We should warn the caller about that. 271 // FIXME: Is there a better way to retrieve this information from 272 // the MaterializeTemporaryExpr? 273 CallOpts.IsTemporaryLifetimeExtendedViaAggregate = true; 274 } 275 } 276 277 if (MTE->getStorageDuration() == SD_Static || 278 MTE->getStorageDuration() == SD_Thread) 279 V = loc::MemRegionVal(MRMgr.getCXXStaticTempObjectRegion(E)); 280 } 281 282 if (V.isUnknown()) 283 V = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx)); 284 285 if (BTE) 286 State = addObjectUnderConstruction(State, BTE, LCtx, V); 287 288 if (MTE) 289 State = addObjectUnderConstruction(State, MTE, LCtx, V); 290 291 CallOpts.IsTemporaryCtorOrDtor = true; 292 return std::make_pair(State, V); 293 } 294 case ConstructionContext::ArgumentKind: { 295 // Function argument constructors. Not implemented yet. 296 break; 297 } 298 } 299 } 300 // If we couldn't find an existing region to construct into, assume we're 301 // constructing a temporary. Notify the caller of our failure. 302 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 303 return std::make_pair( 304 State, loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx))); 305 } 306 307 void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE, 308 ExplodedNode *Pred, 309 ExplodedNodeSet &destNodes) { 310 const LocationContext *LCtx = Pred->getLocationContext(); 311 ProgramStateRef State = Pred->getState(); 312 313 SVal Target = UnknownVal(); 314 315 if (Optional<SVal> ElidedTarget = 316 getObjectUnderConstruction(State, CE, LCtx)) { 317 // We've previously modeled an elidable constructor by pretending that it in 318 // fact constructs into the correct target. This constructor can therefore 319 // be skipped. 320 Target = *ElidedTarget; 321 StmtNodeBuilder Bldr(Pred, destNodes, *currBldrCtx); 322 State = finishObjectConstruction(State, CE, LCtx); 323 if (auto L = Target.getAs<Loc>()) 324 State = State->BindExpr(CE, LCtx, State->getSVal(*L, CE->getType())); 325 Bldr.generateNode(CE, Pred, State); 326 return; 327 } 328 329 // FIXME: Handle arrays, which run the same constructor for every element. 330 // For now, we just run the first constructor (which should still invalidate 331 // the entire array). 332 333 EvalCallOptions CallOpts; 334 auto C = getCurrentCFGElement().getAs<CFGConstructor>(); 335 assert(C || getCurrentCFGElement().getAs<CFGStmt>()); 336 const ConstructionContext *CC = C ? C->getConstructionContext() : nullptr; 337 338 switch (CE->getConstructionKind()) { 339 case CXXConstructExpr::CK_Complete: { 340 std::tie(State, Target) = 341 prepareForObjectConstruction(CE, State, LCtx, CC, CallOpts); 342 break; 343 } 344 case CXXConstructExpr::CK_VirtualBase: 345 // Make sure we are not calling virtual base class initializers twice. 346 // Only the most-derived object should initialize virtual base classes. 347 if (const Stmt *Outer = LCtx->getStackFrame()->getCallSite()) { 348 const CXXConstructExpr *OuterCtor = dyn_cast<CXXConstructExpr>(Outer); 349 if (OuterCtor) { 350 switch (OuterCtor->getConstructionKind()) { 351 case CXXConstructExpr::CK_NonVirtualBase: 352 case CXXConstructExpr::CK_VirtualBase: 353 // Bail out! 354 destNodes.Add(Pred); 355 return; 356 case CXXConstructExpr::CK_Complete: 357 case CXXConstructExpr::CK_Delegating: 358 break; 359 } 360 } 361 } 362 // FALLTHROUGH 363 case CXXConstructExpr::CK_NonVirtualBase: 364 // In C++17, classes with non-virtual bases may be aggregates, so they would 365 // be initialized as aggregates without a constructor call, so we may have 366 // a base class constructed directly into an initializer list without 367 // having the derived-class constructor call on the previous stack frame. 368 // Initializer lists may be nested into more initializer lists that 369 // correspond to surrounding aggregate initializations. 370 // FIXME: For now this code essentially bails out. We need to find the 371 // correct target region and set it. 372 // FIXME: Instead of relying on the ParentMap, we should have the 373 // trigger-statement (InitListExpr in this case) passed down from CFG or 374 // otherwise always available during construction. 375 if (dyn_cast_or_null<InitListExpr>(LCtx->getParentMap().getParent(CE))) { 376 MemRegionManager &MRMgr = getSValBuilder().getRegionManager(); 377 Target = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(CE, LCtx)); 378 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 379 break; 380 } 381 // FALLTHROUGH 382 case CXXConstructExpr::CK_Delegating: { 383 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl()); 384 Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor, 385 LCtx->getStackFrame()); 386 SVal ThisVal = State->getSVal(ThisPtr); 387 388 if (CE->getConstructionKind() == CXXConstructExpr::CK_Delegating) { 389 Target = ThisVal; 390 } else { 391 // Cast to the base type. 392 bool IsVirtual = 393 (CE->getConstructionKind() == CXXConstructExpr::CK_VirtualBase); 394 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, CE->getType(), 395 IsVirtual); 396 Target = BaseVal; 397 } 398 break; 399 } 400 } 401 402 if (State != Pred->getState()) { 403 static SimpleProgramPointTag T("ExprEngine", 404 "Prepare for object construction"); 405 ExplodedNodeSet DstPrepare; 406 StmtNodeBuilder BldrPrepare(Pred, DstPrepare, *currBldrCtx); 407 BldrPrepare.generateNode(CE, Pred, State, &T, ProgramPoint::PreStmtKind); 408 assert(DstPrepare.size() <= 1); 409 if (DstPrepare.size() == 0) 410 return; 411 Pred = *BldrPrepare.begin(); 412 } 413 414 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 415 CallEventRef<CXXConstructorCall> Call = 416 CEMgr.getCXXConstructorCall(CE, Target.getAsRegion(), State, LCtx); 417 418 ExplodedNodeSet DstPreVisit; 419 getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this); 420 421 // FIXME: Is it possible and/or useful to do this before PreStmt? 422 ExplodedNodeSet PreInitialized; 423 { 424 StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx); 425 for (ExplodedNodeSet::iterator I = DstPreVisit.begin(), 426 E = DstPreVisit.end(); 427 I != E; ++I) { 428 ProgramStateRef State = (*I)->getState(); 429 if (CE->requiresZeroInitialization()) { 430 // FIXME: Once we properly handle constructors in new-expressions, we'll 431 // need to invalidate the region before setting a default value, to make 432 // sure there aren't any lingering bindings around. This probably needs 433 // to happen regardless of whether or not the object is zero-initialized 434 // to handle random fields of a placement-initialized object picking up 435 // old bindings. We might only want to do it when we need to, though. 436 // FIXME: This isn't actually correct for arrays -- we need to zero- 437 // initialize the entire array, not just the first element -- but our 438 // handling of arrays everywhere else is weak as well, so this shouldn't 439 // actually make things worse. Placement new makes this tricky as well, 440 // since it's then possible to be initializing one part of a multi- 441 // dimensional array. 442 State = State->bindDefaultZero(Target, LCtx); 443 } 444 445 Bldr.generateNode(CE, *I, State, /*tag=*/nullptr, 446 ProgramPoint::PreStmtKind); 447 } 448 } 449 450 ExplodedNodeSet DstPreCall; 451 getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized, 452 *Call, *this); 453 454 ExplodedNodeSet DstEvaluated; 455 StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx); 456 457 if (CE->getConstructor()->isTrivial() && 458 CE->getConstructor()->isCopyOrMoveConstructor() && 459 !CallOpts.IsArrayCtorOrDtor) { 460 // FIXME: Handle other kinds of trivial constructors as well. 461 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 462 I != E; ++I) 463 performTrivialCopy(Bldr, *I, *Call); 464 465 } else { 466 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 467 I != E; ++I) 468 defaultEvalCall(Bldr, *I, *Call, CallOpts); 469 } 470 471 // If the CFG was constructed without elements for temporary destructors 472 // and the just-called constructor created a temporary object then 473 // stop exploration if the temporary object has a noreturn constructor. 474 // This can lose coverage because the destructor, if it were present 475 // in the CFG, would be called at the end of the full expression or 476 // later (for life-time extended temporaries) -- but avoids infeasible 477 // paths when no-return temporary destructors are used for assertions. 478 const AnalysisDeclContext *ADC = LCtx->getAnalysisDeclContext(); 479 if (!ADC->getCFGBuildOptions().AddTemporaryDtors) { 480 const MemRegion *Target = Call->getCXXThisVal().getAsRegion(); 481 if (Target && isa<CXXTempObjectRegion>(Target) && 482 Call->getDecl()->getParent()->isAnyDestructorNoReturn()) { 483 484 // If we've inlined the constructor, then DstEvaluated would be empty. 485 // In this case we still want a sink, which could be implemented 486 // in processCallExit. But we don't have that implemented at the moment, 487 // so if you hit this assertion, see if you can avoid inlining 488 // the respective constructor when analyzer-config cfg-temporary-dtors 489 // is set to false. 490 // Otherwise there's nothing wrong with inlining such constructor. 491 assert(!DstEvaluated.empty() && 492 "We should not have inlined this constructor!"); 493 494 for (ExplodedNode *N : DstEvaluated) { 495 Bldr.generateSink(CE, N, N->getState()); 496 } 497 498 // There is no need to run the PostCall and PostStmt checker 499 // callbacks because we just generated sinks on all nodes in th 500 // frontier. 501 return; 502 } 503 } 504 505 ExplodedNodeSet DstPostCall; 506 getCheckerManager().runCheckersForPostCall(DstPostCall, DstEvaluated, 507 *Call, *this); 508 getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this); 509 } 510 511 void ExprEngine::VisitCXXDestructor(QualType ObjectType, 512 const MemRegion *Dest, 513 const Stmt *S, 514 bool IsBaseDtor, 515 ExplodedNode *Pred, 516 ExplodedNodeSet &Dst, 517 const EvalCallOptions &CallOpts) { 518 const LocationContext *LCtx = Pred->getLocationContext(); 519 ProgramStateRef State = Pred->getState(); 520 521 const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl(); 522 assert(RecordDecl && "Only CXXRecordDecls should have destructors"); 523 const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor(); 524 525 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 526 CallEventRef<CXXDestructorCall> Call = 527 CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx); 528 529 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 530 Call->getSourceRange().getBegin(), 531 "Error evaluating destructor"); 532 533 ExplodedNodeSet DstPreCall; 534 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, 535 *Call, *this); 536 537 ExplodedNodeSet DstInvalidated; 538 StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx); 539 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 540 I != E; ++I) 541 defaultEvalCall(Bldr, *I, *Call, CallOpts); 542 543 ExplodedNodeSet DstPostCall; 544 getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated, 545 *Call, *this); 546 } 547 548 void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, 549 ExplodedNode *Pred, 550 ExplodedNodeSet &Dst) { 551 ProgramStateRef State = Pred->getState(); 552 const LocationContext *LCtx = Pred->getLocationContext(); 553 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 554 CNE->getStartLoc(), 555 "Error evaluating New Allocator Call"); 556 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 557 CallEventRef<CXXAllocatorCall> Call = 558 CEMgr.getCXXAllocatorCall(CNE, State, LCtx); 559 560 ExplodedNodeSet DstPreCall; 561 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, 562 *Call, *this); 563 564 ExplodedNodeSet DstPostCall; 565 StmtNodeBuilder CallBldr(DstPreCall, DstPostCall, *currBldrCtx); 566 for (auto I : DstPreCall) { 567 // FIXME: Provide evalCall for checkers? 568 defaultEvalCall(CallBldr, I, *Call); 569 } 570 // If the call is inlined, DstPostCall will be empty and we bail out now. 571 572 // Store return value of operator new() for future use, until the actual 573 // CXXNewExpr gets processed. 574 ExplodedNodeSet DstPostValue; 575 StmtNodeBuilder ValueBldr(DstPostCall, DstPostValue, *currBldrCtx); 576 for (auto I : DstPostCall) { 577 // FIXME: Because CNE serves as the "call site" for the allocator (due to 578 // lack of a better expression in the AST), the conjured return value symbol 579 // is going to be of the same type (C++ object pointer type). Technically 580 // this is not correct because the operator new's prototype always says that 581 // it returns a 'void *'. So we should change the type of the symbol, 582 // and then evaluate the cast over the symbolic pointer from 'void *' to 583 // the object pointer type. But without changing the symbol's type it 584 // is breaking too much to evaluate the no-op symbolic cast over it, so we 585 // skip it for now. 586 ProgramStateRef State = I->getState(); 587 SVal RetVal = State->getSVal(CNE, LCtx); 588 589 // If this allocation function is not declared as non-throwing, failures 590 // /must/ be signalled by exceptions, and thus the return value will never 591 // be NULL. -fno-exceptions does not influence this semantics. 592 // FIXME: GCC has a -fcheck-new option, which forces it to consider the case 593 // where new can return NULL. If we end up supporting that option, we can 594 // consider adding a check for it here. 595 // C++11 [basic.stc.dynamic.allocation]p3. 596 if (const FunctionDecl *FD = CNE->getOperatorNew()) { 597 QualType Ty = FD->getType(); 598 if (const auto *ProtoType = Ty->getAs<FunctionProtoType>()) 599 if (!ProtoType->isNothrow()) 600 State = State->assume(RetVal.castAs<DefinedOrUnknownSVal>(), true); 601 } 602 603 ValueBldr.generateNode( 604 CNE, I, addObjectUnderConstruction(State, CNE, LCtx, RetVal)); 605 } 606 607 ExplodedNodeSet DstPostPostCallCallback; 608 getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback, 609 DstPostValue, *Call, *this); 610 for (auto I : DstPostPostCallCallback) { 611 getCheckerManager().runCheckersForNewAllocator( 612 CNE, *getObjectUnderConstruction(I->getState(), CNE, LCtx), Dst, I, 613 *this); 614 } 615 } 616 617 void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, 618 ExplodedNodeSet &Dst) { 619 // FIXME: Much of this should eventually migrate to CXXAllocatorCall. 620 // Also, we need to decide how allocators actually work -- they're not 621 // really part of the CXXNewExpr because they happen BEFORE the 622 // CXXConstructExpr subexpression. See PR12014 for some discussion. 623 624 unsigned blockCount = currBldrCtx->blockCount(); 625 const LocationContext *LCtx = Pred->getLocationContext(); 626 SVal symVal = UnknownVal(); 627 FunctionDecl *FD = CNE->getOperatorNew(); 628 629 bool IsStandardGlobalOpNewFunction = 630 FD->isReplaceableGlobalAllocationFunction(); 631 632 ProgramStateRef State = Pred->getState(); 633 634 // Retrieve the stored operator new() return value. 635 if (AMgr.getAnalyzerOptions().mayInlineCXXAllocator()) { 636 symVal = *getObjectUnderConstruction(State, CNE, LCtx); 637 State = finishObjectConstruction(State, CNE, LCtx); 638 } 639 640 // We assume all standard global 'operator new' functions allocate memory in 641 // heap. We realize this is an approximation that might not correctly model 642 // a custom global allocator. 643 if (symVal.isUnknown()) { 644 if (IsStandardGlobalOpNewFunction) 645 symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount); 646 else 647 symVal = svalBuilder.conjureSymbolVal(nullptr, CNE, LCtx, CNE->getType(), 648 blockCount); 649 } 650 651 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 652 CallEventRef<CXXAllocatorCall> Call = 653 CEMgr.getCXXAllocatorCall(CNE, State, LCtx); 654 655 if (!AMgr.getAnalyzerOptions().mayInlineCXXAllocator()) { 656 // Invalidate placement args. 657 // FIXME: Once we figure out how we want allocators to work, 658 // we should be using the usual pre-/(default-)eval-/post-call checks here. 659 State = Call->invalidateRegions(blockCount); 660 if (!State) 661 return; 662 663 // If this allocation function is not declared as non-throwing, failures 664 // /must/ be signalled by exceptions, and thus the return value will never 665 // be NULL. -fno-exceptions does not influence this semantics. 666 // FIXME: GCC has a -fcheck-new option, which forces it to consider the case 667 // where new can return NULL. If we end up supporting that option, we can 668 // consider adding a check for it here. 669 // C++11 [basic.stc.dynamic.allocation]p3. 670 if (FD) { 671 QualType Ty = FD->getType(); 672 if (const auto *ProtoType = Ty->getAs<FunctionProtoType>()) 673 if (!ProtoType->isNothrow()) 674 if (auto dSymVal = symVal.getAs<DefinedOrUnknownSVal>()) 675 State = State->assume(*dSymVal, true); 676 } 677 } 678 679 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 680 681 SVal Result = symVal; 682 683 if (CNE->isArray()) { 684 // FIXME: allocating an array requires simulating the constructors. 685 // For now, just return a symbolicated region. 686 if (const SubRegion *NewReg = 687 dyn_cast_or_null<SubRegion>(symVal.getAsRegion())) { 688 QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType(); 689 const ElementRegion *EleReg = 690 getStoreManager().GetElementZeroRegion(NewReg, ObjTy); 691 Result = loc::MemRegionVal(EleReg); 692 } 693 State = State->BindExpr(CNE, Pred->getLocationContext(), Result); 694 Bldr.generateNode(CNE, Pred, State); 695 return; 696 } 697 698 // FIXME: Once we have proper support for CXXConstructExprs inside 699 // CXXNewExpr, we need to make sure that the constructed object is not 700 // immediately invalidated here. (The placement call should happen before 701 // the constructor call anyway.) 702 if (FD && FD->isReservedGlobalPlacementOperator()) { 703 // Non-array placement new should always return the placement location. 704 SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx); 705 Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(), 706 CNE->getPlacementArg(0)->getType()); 707 } 708 709 // Bind the address of the object, then check to see if we cached out. 710 State = State->BindExpr(CNE, LCtx, Result); 711 ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State); 712 if (!NewN) 713 return; 714 715 // If the type is not a record, we won't have a CXXConstructExpr as an 716 // initializer. Copy the value over. 717 if (const Expr *Init = CNE->getInitializer()) { 718 if (!isa<CXXConstructExpr>(Init)) { 719 assert(Bldr.getResults().size() == 1); 720 Bldr.takeNodes(NewN); 721 evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx), 722 /*FirstInit=*/IsStandardGlobalOpNewFunction); 723 } 724 } 725 } 726 727 void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, 728 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 729 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 730 ProgramStateRef state = Pred->getState(); 731 Bldr.generateNode(CDE, Pred, state); 732 } 733 734 void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS, 735 ExplodedNode *Pred, 736 ExplodedNodeSet &Dst) { 737 const VarDecl *VD = CS->getExceptionDecl(); 738 if (!VD) { 739 Dst.Add(Pred); 740 return; 741 } 742 743 const LocationContext *LCtx = Pred->getLocationContext(); 744 SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(), 745 currBldrCtx->blockCount()); 746 ProgramStateRef state = Pred->getState(); 747 state = state->bindLoc(state->getLValue(VD, LCtx), V, LCtx); 748 749 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 750 Bldr.generateNode(CS, Pred, state); 751 } 752 753 void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, 754 ExplodedNodeSet &Dst) { 755 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 756 757 // Get the this object region from StoreManager. 758 const LocationContext *LCtx = Pred->getLocationContext(); 759 const MemRegion *R = 760 svalBuilder.getRegionManager().getCXXThisRegion( 761 getContext().getCanonicalType(TE->getType()), 762 LCtx); 763 764 ProgramStateRef state = Pred->getState(); 765 SVal V = state->getSVal(loc::MemRegionVal(R)); 766 Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V)); 767 } 768 769 void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred, 770 ExplodedNodeSet &Dst) { 771 const LocationContext *LocCtxt = Pred->getLocationContext(); 772 773 // Get the region of the lambda itself. 774 const MemRegion *R = svalBuilder.getRegionManager().getCXXTempObjectRegion( 775 LE, LocCtxt); 776 SVal V = loc::MemRegionVal(R); 777 778 ProgramStateRef State = Pred->getState(); 779 780 // If we created a new MemRegion for the lambda, we should explicitly bind 781 // the captures. 782 CXXRecordDecl::field_iterator CurField = LE->getLambdaClass()->field_begin(); 783 for (LambdaExpr::const_capture_init_iterator i = LE->capture_init_begin(), 784 e = LE->capture_init_end(); 785 i != e; ++i, ++CurField) { 786 FieldDecl *FieldForCapture = *CurField; 787 SVal FieldLoc = State->getLValue(FieldForCapture, V); 788 789 SVal InitVal; 790 if (!FieldForCapture->hasCapturedVLAType()) { 791 Expr *InitExpr = *i; 792 assert(InitExpr && "Capture missing initialization expression"); 793 InitVal = State->getSVal(InitExpr, LocCtxt); 794 } else { 795 // The field stores the length of a captured variable-length array. 796 // These captures don't have initialization expressions; instead we 797 // get the length from the VLAType size expression. 798 Expr *SizeExpr = FieldForCapture->getCapturedVLAType()->getSizeExpr(); 799 InitVal = State->getSVal(SizeExpr, LocCtxt); 800 } 801 802 State = State->bindLoc(FieldLoc, InitVal, LocCtxt); 803 } 804 805 // Decay the Loc into an RValue, because there might be a 806 // MaterializeTemporaryExpr node above this one which expects the bound value 807 // to be an RValue. 808 SVal LambdaRVal = State->getSVal(R); 809 810 ExplodedNodeSet Tmp; 811 StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx); 812 // FIXME: is this the right program point kind? 813 Bldr.generateNode(LE, Pred, 814 State->BindExpr(LE, LocCtxt, LambdaRVal), 815 nullptr, ProgramPoint::PostLValueKind); 816 817 // FIXME: Move all post/pre visits to ::Visit(). 818 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this); 819 } 820