ExprEngineCXX.cpp 32 KB

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