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 const MemRegion * 115 ExprEngine::getRegionForConstructedObject(const CXXConstructExpr *CE, 116 ExplodedNode *Pred, 117 const ConstructionContext *CC, 118 EvalCallOptions &CallOpts) { 119 const LocationContext *LCtx = Pred->getLocationContext(); 120 ProgramStateRef State = Pred->getState(); 121 MemRegionManager &MRMgr = getSValBuilder().getRegionManager(); 122 123 // See if we're constructing an existing region by looking at the 124 // current construction context. 125 if (CC) { 126 switch (CC->getKind()) { 127 case ConstructionContext::SimpleVariableKind: { 128 const auto *DSCC = cast<SimpleVariableConstructionContext>(CC); 129 const auto *DS = DSCC->getDeclStmt(); 130 const auto *Var = cast<VarDecl>(DS->getSingleDecl()); 131 SVal LValue = State->getLValue(Var, LCtx); 132 QualType Ty = Var->getType(); 133 LValue = 134 makeZeroElementRegion(State, LValue, Ty, CallOpts.IsArrayCtorOrDtor); 135 return LValue.getAsRegion(); 136 } 137 case ConstructionContext::SimpleConstructorInitializerKind: { 138 const auto *ICC = cast<ConstructorInitializerConstructionContext>(CC); 139 const auto *Init = ICC->getCXXCtorInitializer(); 140 assert(Init->isAnyMemberInitializer()); 141 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl()); 142 Loc ThisPtr = 143 getSValBuilder().getCXXThis(CurCtor, LCtx->getCurrentStackFrame()); 144 SVal ThisVal = State->getSVal(ThisPtr); 145 146 const ValueDecl *Field; 147 SVal FieldVal; 148 if (Init->isIndirectMemberInitializer()) { 149 Field = Init->getIndirectMember(); 150 FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal); 151 } else { 152 Field = Init->getMember(); 153 FieldVal = State->getLValue(Init->getMember(), ThisVal); 154 } 155 156 QualType Ty = Field->getType(); 157 FieldVal = makeZeroElementRegion(State, FieldVal, Ty, 158 CallOpts.IsArrayCtorOrDtor); 159 return FieldVal.getAsRegion(); 160 } 161 case ConstructionContext::NewAllocatedObjectKind: { 162 if (AMgr.getAnalyzerOptions().mayInlineCXXAllocator()) { 163 const auto *NECC = cast<NewAllocatedObjectConstructionContext>(CC); 164 const auto *NE = NECC->getCXXNewExpr(); 165 // TODO: Detect when the allocator returns a null pointer. 166 // Constructor shall not be called in this case. 167 if (const SubRegion *MR = dyn_cast_or_null<SubRegion>( 168 getCXXNewAllocatorValue(State, NE, LCtx).getAsRegion())) { 169 if (NE->isArray()) { 170 // TODO: In fact, we need to call the constructor for every 171 // allocated element, not just the first one! 172 CallOpts.IsArrayCtorOrDtor = true; 173 return getStoreManager().GetElementZeroRegion( 174 MR, NE->getType()->getPointeeType()); 175 } 176 return MR; 177 } 178 } 179 break; 180 } 181 case ConstructionContext::TemporaryObjectKind: { 182 const auto *TOCC = cast<TemporaryObjectConstructionContext>(CC); 183 // See if we're lifetime-extended via our field. If so, take a note. 184 // Because automatic destructors aren't quite working in this case. 185 if (const auto *MTE = TOCC->getMaterializedTemporaryExpr()) { 186 if (const ValueDecl *VD = MTE->getExtendingDecl()) { 187 assert(VD->getType()->isReferenceType()); 188 if (VD->getType()->getPointeeType().getCanonicalType() != 189 MTE->GetTemporaryExpr()->getType().getCanonicalType()) { 190 CallOpts.IsTemporaryLifetimeExtendedViaSubobject = true; 191 } 192 } 193 } 194 // TODO: Support temporaries lifetime-extended via static references. 195 // They'd need a getCXXStaticTempObjectRegion(). 196 CallOpts.IsTemporaryCtorOrDtor = true; 197 return MRMgr.getCXXTempObjectRegion(CE, LCtx); 198 } 199 case ConstructionContext::SimpleReturnedValueKind: { 200 // The temporary is to be managed by the parent stack frame. 201 // So build it in the parent stack frame if we're not in the 202 // top frame of the analysis. 203 // TODO: What exactly happens when we are? Does the temporary object live 204 // long enough in the region store in this case? Would checkers think 205 // that this object immediately goes out of scope? 206 const LocationContext *TempLCtx = LCtx; 207 const StackFrameContext *SFC = LCtx->getCurrentStackFrame(); 208 if (const LocationContext *CallerLCtx = SFC->getParent()) { 209 auto RTC = (*SFC->getCallSiteBlock())[SFC->getIndex()] 210 .getAs<CFGCXXRecordTypedCall>(); 211 if (!RTC) { 212 // We were unable to find the correct construction context for the 213 // call in the parent stack frame. This is equivalent to not being 214 // able to find construction context at all. 215 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 216 } else if (!isa<TemporaryObjectConstructionContext>( 217 RTC->getConstructionContext())) { 218 // FXIME: The return value is constructed directly into a 219 // non-temporary due to C++17 mandatory copy elision. This is not 220 // implemented yet. 221 assert(getContext().getLangOpts().CPlusPlus17); 222 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 223 } 224 TempLCtx = CallerLCtx; 225 } 226 CallOpts.IsTemporaryCtorOrDtor = true; 227 return MRMgr.getCXXTempObjectRegion(CE, TempLCtx); 228 } 229 case ConstructionContext::CXX17ElidedCopyVariableKind: 230 case ConstructionContext::CXX17ElidedCopyReturnedValueKind: 231 case ConstructionContext::CXX17ElidedCopyConstructorInitializerKind: 232 // Not implemented yet. 233 break; 234 } 235 } 236 // If we couldn't find an existing region to construct into, assume we're 237 // constructing a temporary. Notify the caller of our failure. 238 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 239 return MRMgr.getCXXTempObjectRegion(CE, LCtx); 240 } 241 242 const CXXConstructExpr * 243 ExprEngine::findDirectConstructorForCurrentCFGElement() { 244 // Go backward in the CFG to see if the previous element (ignoring 245 // destructors) was a CXXConstructExpr. If so, that constructor 246 // was constructed directly into an existing region. 247 // This process is essentially the inverse of that performed in 248 // findElementDirectlyInitializedByCurrentConstructor(). 249 if (currStmtIdx == 0) 250 return nullptr; 251 252 const CFGBlock *B = getBuilderContext().getBlock(); 253 254 unsigned int PreviousStmtIdx = currStmtIdx - 1; 255 CFGElement Previous = (*B)[PreviousStmtIdx]; 256 257 while (Previous.getAs<CFGImplicitDtor>() && PreviousStmtIdx > 0) { 258 --PreviousStmtIdx; 259 Previous = (*B)[PreviousStmtIdx]; 260 } 261 262 if (Optional<CFGStmt> PrevStmtElem = Previous.getAs<CFGStmt>()) { 263 if (auto *CtorExpr = dyn_cast<CXXConstructExpr>(PrevStmtElem->getStmt())) { 264 return CtorExpr; 265 } 266 } 267 268 return nullptr; 269 } 270 271 void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE, 272 ExplodedNode *Pred, 273 ExplodedNodeSet &destNodes) { 274 const LocationContext *LCtx = Pred->getLocationContext(); 275 ProgramStateRef State = Pred->getState(); 276 277 const MemRegion *Target = nullptr; 278 279 // FIXME: Handle arrays, which run the same constructor for every element. 280 // For now, we just run the first constructor (which should still invalidate 281 // the entire array). 282 283 EvalCallOptions CallOpts; 284 auto C = getCurrentCFGElement().getAs<CFGConstructor>(); 285 assert(C || getCurrentCFGElement().getAs<CFGStmt>()); 286 const ConstructionContext *CC = C ? C->getConstructionContext() : nullptr; 287 288 switch (CE->getConstructionKind()) { 289 case CXXConstructExpr::CK_Complete: { 290 Target = getRegionForConstructedObject(CE, Pred, CC, CallOpts); 291 break; 292 } 293 case CXXConstructExpr::CK_VirtualBase: 294 // Make sure we are not calling virtual base class initializers twice. 295 // Only the most-derived object should initialize virtual base classes. 296 if (const Stmt *Outer = LCtx->getCurrentStackFrame()->getCallSite()) { 297 const CXXConstructExpr *OuterCtor = dyn_cast<CXXConstructExpr>(Outer); 298 if (OuterCtor) { 299 switch (OuterCtor->getConstructionKind()) { 300 case CXXConstructExpr::CK_NonVirtualBase: 301 case CXXConstructExpr::CK_VirtualBase: 302 // Bail out! 303 destNodes.Add(Pred); 304 return; 305 case CXXConstructExpr::CK_Complete: 306 case CXXConstructExpr::CK_Delegating: 307 break; 308 } 309 } 310 } 311 // FALLTHROUGH 312 case CXXConstructExpr::CK_NonVirtualBase: 313 // In C++17, classes with non-virtual bases may be aggregates, so they would 314 // be initialized as aggregates without a constructor call, so we may have 315 // a base class constructed directly into an initializer list without 316 // having the derived-class constructor call on the previous stack frame. 317 // Initializer lists may be nested into more initializer lists that 318 // correspond to surrounding aggregate initializations. 319 // FIXME: For now this code essentially bails out. We need to find the 320 // correct target region and set it. 321 // FIXME: Instead of relying on the ParentMap, we should have the 322 // trigger-statement (InitListExpr in this case) passed down from CFG or 323 // otherwise always available during construction. 324 if (dyn_cast_or_null<InitListExpr>(LCtx->getParentMap().getParent(CE))) { 325 MemRegionManager &MRMgr = getSValBuilder().getRegionManager(); 326 Target = MRMgr.getCXXTempObjectRegion(CE, LCtx); 327 CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true; 328 break; 329 } 330 // FALLTHROUGH 331 case CXXConstructExpr::CK_Delegating: { 332 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl()); 333 Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor, 334 LCtx->getCurrentStackFrame()); 335 SVal ThisVal = State->getSVal(ThisPtr); 336 337 if (CE->getConstructionKind() == CXXConstructExpr::CK_Delegating) { 338 Target = ThisVal.getAsRegion(); 339 } else { 340 // Cast to the base type. 341 bool IsVirtual = 342 (CE->getConstructionKind() == CXXConstructExpr::CK_VirtualBase); 343 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, CE->getType(), 344 IsVirtual); 345 Target = BaseVal.getAsRegion(); 346 } 347 break; 348 } 349 } 350 351 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 352 CallEventRef<CXXConstructorCall> Call = 353 CEMgr.getCXXConstructorCall(CE, Target, State, LCtx); 354 355 ExplodedNodeSet DstPreVisit; 356 getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this); 357 358 // FIXME: Is it possible and/or useful to do this before PreStmt? 359 ExplodedNodeSet PreInitialized; 360 { 361 StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx); 362 for (ExplodedNodeSet::iterator I = DstPreVisit.begin(), 363 E = DstPreVisit.end(); 364 I != E; ++I) { 365 ProgramStateRef State = (*I)->getState(); 366 if (CE->requiresZeroInitialization()) { 367 // Type of the zero doesn't matter. 368 SVal ZeroVal = svalBuilder.makeZeroVal(getContext().CharTy); 369 370 // FIXME: Once we properly handle constructors in new-expressions, we'll 371 // need to invalidate the region before setting a default value, to make 372 // sure there aren't any lingering bindings around. This probably needs 373 // to happen regardless of whether or not the object is zero-initialized 374 // to handle random fields of a placement-initialized object picking up 375 // old bindings. We might only want to do it when we need to, though. 376 // FIXME: This isn't actually correct for arrays -- we need to zero- 377 // initialize the entire array, not just the first element -- but our 378 // handling of arrays everywhere else is weak as well, so this shouldn't 379 // actually make things worse. Placement new makes this tricky as well, 380 // since it's then possible to be initializing one part of a multi- 381 // dimensional array. 382 State = State->bindDefault(loc::MemRegionVal(Target), ZeroVal, LCtx); 383 } 384 385 State = addAllNecessaryTemporaryInfo(State, CC, LCtx, Target); 386 387 Bldr.generateNode(CE, *I, State, /*tag=*/nullptr, 388 ProgramPoint::PreStmtKind); 389 } 390 } 391 392 ExplodedNodeSet DstPreCall; 393 getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized, 394 *Call, *this); 395 396 ExplodedNodeSet DstEvaluated; 397 StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx); 398 399 if (CE->getConstructor()->isTrivial() && 400 CE->getConstructor()->isCopyOrMoveConstructor() && 401 !CallOpts.IsArrayCtorOrDtor) { 402 // FIXME: Handle other kinds of trivial constructors as well. 403 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 404 I != E; ++I) 405 performTrivialCopy(Bldr, *I, *Call); 406 407 } else { 408 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 409 I != E; ++I) 410 defaultEvalCall(Bldr, *I, *Call, CallOpts); 411 } 412 413 // If the CFG was constructed without elements for temporary destructors 414 // and the just-called constructor created a temporary object then 415 // stop exploration if the temporary object has a noreturn constructor. 416 // This can lose coverage because the destructor, if it were present 417 // in the CFG, would be called at the end of the full expression or 418 // later (for life-time extended temporaries) -- but avoids infeasible 419 // paths when no-return temporary destructors are used for assertions. 420 const AnalysisDeclContext *ADC = LCtx->getAnalysisDeclContext(); 421 if (!ADC->getCFGBuildOptions().AddTemporaryDtors) { 422 const MemRegion *Target = Call->getCXXThisVal().getAsRegion(); 423 if (Target && isa<CXXTempObjectRegion>(Target) && 424 Call->getDecl()->getParent()->isAnyDestructorNoReturn()) { 425 426 // If we've inlined the constructor, then DstEvaluated would be empty. 427 // In this case we still want a sink, which could be implemented 428 // in processCallExit. But we don't have that implemented at the moment, 429 // so if you hit this assertion, see if you can avoid inlining 430 // the respective constructor when analyzer-config cfg-temporary-dtors 431 // is set to false. 432 // Otherwise there's nothing wrong with inlining such constructor. 433 assert(!DstEvaluated.empty() && 434 "We should not have inlined this constructor!"); 435 436 for (ExplodedNode *N : DstEvaluated) { 437 Bldr.generateSink(CE, N, N->getState()); 438 } 439 440 // There is no need to run the PostCall and PostStmt checker 441 // callbacks because we just generated sinks on all nodes in th 442 // frontier. 443 return; 444 } 445 } 446 447 ExplodedNodeSet DstPostCall; 448 getCheckerManager().runCheckersForPostCall(DstPostCall, DstEvaluated, 449 *Call, *this); 450 getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this); 451 } 452 453 void ExprEngine::VisitCXXDestructor(QualType ObjectType, 454 const MemRegion *Dest, 455 const Stmt *S, 456 bool IsBaseDtor, 457 ExplodedNode *Pred, 458 ExplodedNodeSet &Dst, 459 const EvalCallOptions &CallOpts) { 460 const LocationContext *LCtx = Pred->getLocationContext(); 461 ProgramStateRef State = Pred->getState(); 462 463 const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl(); 464 assert(RecordDecl && "Only CXXRecordDecls should have destructors"); 465 const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor(); 466 467 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 468 CallEventRef<CXXDestructorCall> Call = 469 CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx); 470 471 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 472 Call->getSourceRange().getBegin(), 473 "Error evaluating destructor"); 474 475 ExplodedNodeSet DstPreCall; 476 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, 477 *Call, *this); 478 479 ExplodedNodeSet DstInvalidated; 480 StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx); 481 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 482 I != E; ++I) 483 defaultEvalCall(Bldr, *I, *Call, CallOpts); 484 485 ExplodedNodeSet DstPostCall; 486 getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated, 487 *Call, *this); 488 } 489 490 void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE, 491 ExplodedNode *Pred, 492 ExplodedNodeSet &Dst) { 493 ProgramStateRef State = Pred->getState(); 494 const LocationContext *LCtx = Pred->getLocationContext(); 495 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 496 CNE->getStartLoc(), 497 "Error evaluating New Allocator Call"); 498 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 499 CallEventRef<CXXAllocatorCall> Call = 500 CEMgr.getCXXAllocatorCall(CNE, State, LCtx); 501 502 ExplodedNodeSet DstPreCall; 503 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, 504 *Call, *this); 505 506 ExplodedNodeSet DstPostCall; 507 StmtNodeBuilder CallBldr(DstPreCall, DstPostCall, *currBldrCtx); 508 for (auto I : DstPreCall) { 509 // FIXME: Provide evalCall for checkers? 510 defaultEvalCall(CallBldr, I, *Call); 511 } 512 // If the call is inlined, DstPostCall will be empty and we bail out now. 513 514 // Store return value of operator new() for future use, until the actual 515 // CXXNewExpr gets processed. 516 ExplodedNodeSet DstPostValue; 517 StmtNodeBuilder ValueBldr(DstPostCall, DstPostValue, *currBldrCtx); 518 for (auto I : DstPostCall) { 519 // FIXME: Because CNE serves as the "call site" for the allocator (due to 520 // lack of a better expression in the AST), the conjured return value symbol 521 // is going to be of the same type (C++ object pointer type). Technically 522 // this is not correct because the operator new's prototype always says that 523 // it returns a 'void *'. So we should change the type of the symbol, 524 // and then evaluate the cast over the symbolic pointer from 'void *' to 525 // the object pointer type. But without changing the symbol's type it 526 // is breaking too much to evaluate the no-op symbolic cast over it, so we 527 // skip it for now. 528 ProgramStateRef State = I->getState(); 529 SVal RetVal = State->getSVal(CNE, LCtx); 530 531 // If this allocation function is not declared as non-throwing, failures 532 // /must/ be signalled by exceptions, and thus the return value will never 533 // be NULL. -fno-exceptions does not influence this semantics. 534 // FIXME: GCC has a -fcheck-new option, which forces it to consider the case 535 // where new can return NULL. If we end up supporting that option, we can 536 // consider adding a check for it here. 537 // C++11 [basic.stc.dynamic.allocation]p3. 538 if (const FunctionDecl *FD = CNE->getOperatorNew()) { 539 QualType Ty = FD->getType(); 540 if (const auto *ProtoType = Ty->getAs<FunctionProtoType>()) 541 if (!ProtoType->isNothrow(getContext())) 542 State = State->assume(RetVal.castAs<DefinedOrUnknownSVal>(), true); 543 } 544 545 ValueBldr.generateNode(CNE, I, 546 setCXXNewAllocatorValue(State, CNE, LCtx, RetVal)); 547 } 548 549 ExplodedNodeSet DstPostPostCallCallback; 550 getCheckerManager().runCheckersForPostCall(DstPostPostCallCallback, 551 DstPostValue, *Call, *this); 552 for (auto I : DstPostPostCallCallback) { 553 getCheckerManager().runCheckersForNewAllocator( 554 CNE, getCXXNewAllocatorValue(I->getState(), CNE, LCtx), Dst, I, *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 = getCXXNewAllocatorValue(State, CNE, LCtx); 578 State = clearCXXNewAllocatorValue(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(getContext())) 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