ExprEngineCXX.cpp 29 KB

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