ExprEngineCXX.cpp 33 KB

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