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