ExprEngineCXX.cpp 32 KB

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