ExprEngineCXX.cpp 32 KB

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