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