1 //===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the C++ expression evaluation engine.
12 //===----------------------------------------------------------------------===//
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"
24 using namespace clang;
27 void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
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();
35 state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME);
36 Bldr.generateNode(ME, Pred, state);
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) {
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;
53 assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial());
54 assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() ==
56 ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal();
57 ThisRD = cast<CXXMethodDecl>(Call.getDecl())->getParent();
58 AlwaysReturnsLValue = true;
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.
69 const LocationContext *LCtx = Pred->getLocationContext();
74 SVal V = Call.getArgSVal(0);
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);
81 assert(V.isUnknownOrUndef());
83 const Expr *CallExpr = Call.getOriginExpr();
84 evalBind(Dst, CallExpr, Pred, ThisVal, V, true);
86 PostStmt PS(CallExpr, LCtx);
87 for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end();
89 ProgramStateRef State = (*I)->getState();
90 if (AlwaysReturnsLValue)
91 State = State->BindExpr(CallExpr, LCtx, ThisVal);
93 State = bindReturnValue(Call, LCtx, State);
94 Bldr.generateNode(PS, State, *I);
99 SVal ExprEngine::makeZeroElementRegion(ProgramStateRef State, SVal LValue,
100 QualType &Ty, bool &IsArray) {
101 SValBuilder &SVB = State->getStateManager().getSValBuilder();
102 ASTContext &Ctx = SVB.getContext();
104 while (const ArrayType *AT = Ctx.getAsArrayType(Ty)) {
105 Ty = AT->getElementType();
106 LValue = State->getLValue(Ty, SVB.makeZeroArrayIndex(), LValue);
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();
118 // See if we're constructing an existing region by looking at the
119 // current construction context.
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();
130 makeZeroElementRegion(State, LValue, Ty, CallOpts.IsArrayCtorOrDtor);
132 addObjectUnderConstruction(State, DSCC->getDeclStmt(), LCtx, LValue);
133 return std::make_pair(State, LValue);
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());
142 getSValBuilder().getCXXThis(CurCtor, LCtx->getStackFrame());
143 SVal ThisVal = State->getSVal(ThisPtr);
145 const ValueDecl *Field;
147 if (Init->isIndirectMemberInitializer()) {
148 Field = Init->getIndirectMember();
149 FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal);
151 Field = Init->getMember();
152 FieldVal = State->getLValue(Init->getMember(), ThisVal);
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);
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())) {
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())));
176 return std::make_pair(State, V);
178 // TODO: Detect when the allocator returns a null pointer.
179 // Constructor shall not be called in this case.
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>();
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.
198 return prepareForObjectConstruction(
199 cast<Expr>(SFC->getCallSite()), State, CallerLCtx,
200 RTC->getConstructionContext(), CallOpts);
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);
210 llvm_unreachable("Unhandled return value construction context!");
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();
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.
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;
230 std::tie(State, V) = prepareForObjectConstruction(
231 CE, State, LCtx, TCC->getConstructionContextAfterElision(), CallOpts);
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);
240 // Remember that we've elided the destructor.
242 State = elideDestructor(State, BTE, LCtx);
244 // Instead of materialization, shamelessly return
245 // the final object destination.
247 State = addObjectUnderConstruction(State, MTE, LCtx, V);
249 return std::make_pair(State, V);
251 // Copy elision failed. Revert the changes and proceed as if we have
252 // a simple temporary.
253 State = PreElideState;
254 CallOpts = PreElideCallOpts;
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();
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;
277 if (MTE->getStorageDuration() == SD_Static ||
278 MTE->getStorageDuration() == SD_Thread)
279 V = loc::MemRegionVal(MRMgr.getCXXStaticTempObjectRegion(E));
283 V = loc::MemRegionVal(MRMgr.getCXXTempObjectRegion(E, LCtx));
286 State = addObjectUnderConstruction(State, BTE, LCtx, V);
289 State = addObjectUnderConstruction(State, MTE, LCtx, V);
291 CallOpts.IsTemporaryCtorOrDtor = true;
292 return std::make_pair(State, V);
294 case ConstructionContext::ArgumentKind: {
295 // Function argument constructors. Not implemented yet.
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)));
307 void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
309 ExplodedNodeSet &destNodes) {
310 const LocationContext *LCtx = Pred->getLocationContext();
311 ProgramStateRef State = Pred->getState();
313 SVal Target = UnknownVal();
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
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);
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).
333 EvalCallOptions CallOpts;
334 auto C = getCurrentCFGElement().getAs<CFGConstructor>();
335 assert(C || getCurrentCFGElement().getAs<CFGStmt>());
336 const ConstructionContext *CC = C ? C->getConstructionContext() : nullptr;
338 switch (CE->getConstructionKind()) {
339 case CXXConstructExpr::CK_Complete: {
340 std::tie(State, Target) =
341 prepareForObjectConstruction(CE, State, LCtx, CC, CallOpts);
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);
350 switch (OuterCtor->getConstructionKind()) {
351 case CXXConstructExpr::CK_NonVirtualBase:
352 case CXXConstructExpr::CK_VirtualBase:
356 case CXXConstructExpr::CK_Complete:
357 case CXXConstructExpr::CK_Delegating:
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;
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);
388 if (CE->getConstructionKind() == CXXConstructExpr::CK_Delegating) {
391 // Cast to the base type.
393 (CE->getConstructionKind() == CXXConstructExpr::CK_VirtualBase);
394 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, CE->getType(),
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)
411 Pred = *BldrPrepare.begin();
414 CallEventManager &CEMgr = getStateManager().getCallEventManager();
415 CallEventRef<CXXConstructorCall> Call =
416 CEMgr.getCXXConstructorCall(CE, Target.getAsRegion(), State, LCtx);
418 ExplodedNodeSet DstPreVisit;
419 getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this);
421 // FIXME: Is it possible and/or useful to do this before PreStmt?
422 ExplodedNodeSet PreInitialized;
424 StmtNodeBuilder Bldr(DstPreVisit, PreInitialized, *currBldrCtx);
425 for (ExplodedNodeSet::iterator I = DstPreVisit.begin(),
426 E = DstPreVisit.end();
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);
445 Bldr.generateNode(CE, *I, State, /*tag=*/nullptr,
446 ProgramPoint::PreStmtKind);
450 ExplodedNodeSet DstPreCall;
451 getCheckerManager().runCheckersForPreCall(DstPreCall, PreInitialized,
454 ExplodedNodeSet DstEvaluated;
455 StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
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();
463 performTrivialCopy(Bldr, *I, *Call);
466 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
468 defaultEvalCall(Bldr, *I, *Call, CallOpts);
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()) {
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
490 // Otherwise there's nothing wrong with inlining such constructor.
491 assert(!DstEvaluated.empty() &&
492 "We should not have inlined this constructor!");
494 for (ExplodedNode *N : DstEvaluated) {
495 Bldr.generateSink(CE, N, N->getState());
498 // There is no need to run the PostCall and PostStmt checker
499 // callbacks because we just generated sinks on all nodes in th
505 ExplodedNodeSet DstPostCall;
506 getCheckerManager().runCheckersForPostCall(DstPostCall, DstEvaluated,
508 getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this);
511 void ExprEngine::VisitCXXDestructor(QualType ObjectType,
512 const MemRegion *Dest,
516 ExplodedNodeSet &Dst,
517 const EvalCallOptions &CallOpts) {
518 const LocationContext *LCtx = Pred->getLocationContext();
519 ProgramStateRef State = Pred->getState();
521 const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
522 assert(RecordDecl && "Only CXXRecordDecls should have destructors");
523 const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
525 CallEventManager &CEMgr = getStateManager().getCallEventManager();
526 CallEventRef<CXXDestructorCall> Call =
527 CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
529 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
530 Call->getSourceRange().getBegin(),
531 "Error evaluating destructor");
533 ExplodedNodeSet DstPreCall;
534 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
537 ExplodedNodeSet DstInvalidated;
538 StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
539 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
541 defaultEvalCall(Bldr, *I, *Call, CallOpts);
543 ExplodedNodeSet DstPostCall;
544 getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
548 void ExprEngine::VisitCXXNewAllocatorCall(const CXXNewExpr *CNE,
550 ExplodedNodeSet &Dst) {
551 ProgramStateRef State = Pred->getState();
552 const LocationContext *LCtx = Pred->getLocationContext();
553 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
555 "Error evaluating New Allocator Call");
556 CallEventManager &CEMgr = getStateManager().getCallEventManager();
557 CallEventRef<CXXAllocatorCall> Call =
558 CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
560 ExplodedNodeSet DstPreCall;
561 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
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);
570 // If the call is inlined, DstPostCall will be empty and we bail out now.
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
586 ProgramStateRef State = I->getState();
587 SVal RetVal = State->getSVal(CNE, LCtx);
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);
603 ValueBldr.generateNode(
604 CNE, I, addObjectUnderConstruction(State, CNE, LCtx, RetVal));
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,
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.
624 unsigned blockCount = currBldrCtx->blockCount();
625 const LocationContext *LCtx = Pred->getLocationContext();
626 SVal symVal = UnknownVal();
627 FunctionDecl *FD = CNE->getOperatorNew();
629 bool IsStandardGlobalOpNewFunction =
630 FD->isReplaceableGlobalAllocationFunction();
632 ProgramStateRef State = Pred->getState();
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);
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);
647 symVal = svalBuilder.conjureSymbolVal(nullptr, CNE, LCtx, CNE->getType(),
651 CallEventManager &CEMgr = getStateManager().getCallEventManager();
652 CallEventRef<CXXAllocatorCall> Call =
653 CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
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);
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.
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);
679 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
681 SVal Result = symVal;
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);
693 State = State->BindExpr(CNE, Pred->getLocationContext(), Result);
694 Bldr.generateNode(CNE, Pred, State);
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());
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);
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);
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);
734 void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS,
736 ExplodedNodeSet &Dst) {
737 const VarDecl *VD = CS->getExceptionDecl();
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);
749 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
750 Bldr.generateNode(CS, Pred, state);
753 void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
754 ExplodedNodeSet &Dst) {
755 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
757 // Get the this object region from StoreManager.
758 const LocationContext *LCtx = Pred->getLocationContext();
760 svalBuilder.getRegionManager().getCXXThisRegion(
761 getContext().getCanonicalType(TE->getType()),
764 ProgramStateRef state = Pred->getState();
765 SVal V = state->getSVal(loc::MemRegionVal(R));
766 Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
769 void ExprEngine::VisitLambdaExpr(const LambdaExpr *LE, ExplodedNode *Pred,
770 ExplodedNodeSet &Dst) {
771 const LocationContext *LocCtxt = Pred->getLocationContext();
773 // Get the region of the lambda itself.
774 const MemRegion *R = svalBuilder.getRegionManager().getCXXTempObjectRegion(
776 SVal V = loc::MemRegionVal(R);
778 ProgramStateRef State = Pred->getState();
780 // If we created a new MemRegion for the lambda, we should explicitly bind
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);
790 if (!FieldForCapture->hasCapturedVLAType()) {
792 assert(InitExpr && "Capture missing initialization expression");
793 InitVal = State->getSVal(InitExpr, LocCtxt);
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);
802 State = State->bindLoc(FieldLoc, InitVal, LocCtxt);
805 // Decay the Loc into an RValue, because there might be a
806 // MaterializeTemporaryExpr node above this one which expects the bound value
808 SVal LambdaRVal = State->getSVal(R);
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);
817 // FIXME: Move all post/pre visits to ::Visit().
818 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, LE, *this);