ExprEngineCXX.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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/Basic/PrettyStackTrace.h"
  17. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  20. using namespace clang;
  21. using namespace ento;
  22. void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME,
  23. ExplodedNode *Pred,
  24. ExplodedNodeSet &Dst) {
  25. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  26. const Expr *tempExpr = ME->GetTemporaryExpr()->IgnoreParens();
  27. ProgramStateRef state = Pred->getState();
  28. const LocationContext *LCtx = Pred->getLocationContext();
  29. // Bind the temporary object to the value of the expression. Then bind
  30. // the expression to the location of the object.
  31. SVal V = state->getSVal(tempExpr, LCtx);
  32. // If the value is already a CXXTempObjectRegion, it is fine as it is.
  33. // Otherwise, create a new CXXTempObjectRegion, and copy the value into it.
  34. const MemRegion *MR = V.getAsRegion();
  35. if (!MR || !isa<CXXTempObjectRegion>(MR)) {
  36. const MemRegion *R =
  37. svalBuilder.getRegionManager().getCXXTempObjectRegion(ME, LCtx);
  38. SVal L = loc::MemRegionVal(R);
  39. state = state->bindLoc(L, V);
  40. V = L;
  41. }
  42. Bldr.generateNode(ME, Pred, state->BindExpr(ME, LCtx, V));
  43. }
  44. void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred,
  45. const CXXConstructorCall &Call) {
  46. const CXXConstructExpr *CtorExpr = Call.getOriginExpr();
  47. assert(CtorExpr->getConstructor()->isCopyOrMoveConstructor());
  48. assert(CtorExpr->getConstructor()->isTrivial());
  49. SVal ThisVal = Call.getCXXThisVal();
  50. const LocationContext *LCtx = Pred->getLocationContext();
  51. ExplodedNodeSet Dst;
  52. Bldr.takeNodes(Pred);
  53. SVal V = Call.getArgSVal(0);
  54. // Make sure the value being copied is not unknown.
  55. if (Optional<Loc> L = V.getAs<Loc>())
  56. V = Pred->getState()->getSVal(*L);
  57. evalBind(Dst, CtorExpr, Pred, ThisVal, V, true);
  58. PostStmt PS(CtorExpr, LCtx);
  59. for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end();
  60. I != E; ++I) {
  61. ProgramStateRef State = (*I)->getState();
  62. State = bindReturnValue(Call, LCtx, State);
  63. Bldr.generateNode(PS, State, *I);
  64. }
  65. }
  66. void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
  67. ExplodedNode *Pred,
  68. ExplodedNodeSet &destNodes) {
  69. const LocationContext *LCtx = Pred->getLocationContext();
  70. ProgramStateRef State = Pred->getState();
  71. const MemRegion *Target = 0;
  72. bool IsArray = false;
  73. switch (CE->getConstructionKind()) {
  74. case CXXConstructExpr::CK_Complete: {
  75. // See if we're constructing an existing region by looking at the next
  76. // element in the CFG.
  77. const CFGBlock *B = currBldrCtx->getBlock();
  78. if (currStmtIdx + 1 < B->size()) {
  79. CFGElement Next = (*B)[currStmtIdx+1];
  80. // Is this a constructor for a local variable?
  81. if (const CFGStmt *StmtElem = dyn_cast<CFGStmt>(&Next)) {
  82. if (const DeclStmt *DS = dyn_cast<DeclStmt>(StmtElem->getStmt())) {
  83. if (const VarDecl *Var = dyn_cast<VarDecl>(DS->getSingleDecl())) {
  84. if (Var->getInit()->IgnoreImplicit() == CE) {
  85. QualType Ty = Var->getType();
  86. if (const ArrayType *AT = getContext().getAsArrayType(Ty)) {
  87. // FIXME: Handle arrays, which run the same constructor for
  88. // every element. This workaround will just run the first
  89. // constructor (which should still invalidate the entire array).
  90. SVal Base = State->getLValue(Var, LCtx);
  91. Target = State->getLValue(AT->getElementType(),
  92. getSValBuilder().makeZeroArrayIndex(),
  93. Base).getAsRegion();
  94. IsArray = true;
  95. } else {
  96. Target = State->getLValue(Var, LCtx).getAsRegion();
  97. }
  98. }
  99. }
  100. }
  101. }
  102. // Is this a constructor for a member?
  103. if (const CFGInitializer *InitElem = dyn_cast<CFGInitializer>(&Next)) {
  104. const CXXCtorInitializer *Init = InitElem->getInitializer();
  105. assert(Init->isAnyMemberInitializer());
  106. const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
  107. Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
  108. LCtx->getCurrentStackFrame());
  109. SVal ThisVal = State->getSVal(ThisPtr);
  110. if (Init->isIndirectMemberInitializer()) {
  111. SVal Field = State->getLValue(Init->getIndirectMember(), ThisVal);
  112. Target = Field.getAsRegion();
  113. } else {
  114. SVal Field = State->getLValue(Init->getMember(), ThisVal);
  115. Target = Field.getAsRegion();
  116. }
  117. }
  118. // FIXME: This will eventually need to handle new-expressions as well.
  119. }
  120. // If we couldn't find an existing region to construct into, assume we're
  121. // constructing a temporary.
  122. if (!Target) {
  123. MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
  124. Target = MRMgr.getCXXTempObjectRegion(CE, LCtx);
  125. }
  126. break;
  127. }
  128. case CXXConstructExpr::CK_NonVirtualBase:
  129. case CXXConstructExpr::CK_VirtualBase:
  130. case CXXConstructExpr::CK_Delegating: {
  131. const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
  132. Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
  133. LCtx->getCurrentStackFrame());
  134. SVal ThisVal = State->getSVal(ThisPtr);
  135. if (CE->getConstructionKind() == CXXConstructExpr::CK_Delegating) {
  136. Target = ThisVal.getAsRegion();
  137. } else {
  138. // Cast to the base type.
  139. QualType BaseTy = CE->getType();
  140. SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy);
  141. Target = BaseVal.getAsRegion();
  142. }
  143. break;
  144. }
  145. }
  146. CallEventManager &CEMgr = getStateManager().getCallEventManager();
  147. CallEventRef<CXXConstructorCall> Call =
  148. CEMgr.getCXXConstructorCall(CE, Target, State, LCtx);
  149. ExplodedNodeSet DstPreVisit;
  150. getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this);
  151. ExplodedNodeSet DstPreCall;
  152. getCheckerManager().runCheckersForPreCall(DstPreCall, DstPreVisit,
  153. *Call, *this);
  154. ExplodedNodeSet DstEvaluated;
  155. StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx);
  156. if (CE->getConstructor()->isTrivial() &&
  157. CE->getConstructor()->isCopyOrMoveConstructor() &&
  158. !IsArray) {
  159. // FIXME: Handle other kinds of trivial constructors as well.
  160. for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
  161. I != E; ++I)
  162. performTrivialCopy(Bldr, *I, *Call);
  163. } else {
  164. for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
  165. I != E; ++I)
  166. defaultEvalCall(Bldr, *I, *Call);
  167. }
  168. ExplodedNodeSet DstPostCall;
  169. getCheckerManager().runCheckersForPostCall(DstPostCall, DstEvaluated,
  170. *Call, *this);
  171. getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this);
  172. }
  173. void ExprEngine::VisitCXXDestructor(QualType ObjectType,
  174. const MemRegion *Dest,
  175. const Stmt *S,
  176. bool IsBaseDtor,
  177. ExplodedNode *Pred,
  178. ExplodedNodeSet &Dst) {
  179. const LocationContext *LCtx = Pred->getLocationContext();
  180. ProgramStateRef State = Pred->getState();
  181. // FIXME: We need to run the same destructor on every element of the array.
  182. // This workaround will just run the first destructor (which will still
  183. // invalidate the entire array).
  184. // This is a loop because of multidimensional arrays.
  185. while (const ArrayType *AT = getContext().getAsArrayType(ObjectType)) {
  186. ObjectType = AT->getElementType();
  187. Dest = State->getLValue(ObjectType, getSValBuilder().makeZeroArrayIndex(),
  188. loc::MemRegionVal(Dest)).getAsRegion();
  189. }
  190. const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
  191. assert(RecordDecl && "Only CXXRecordDecls should have destructors");
  192. const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
  193. CallEventManager &CEMgr = getStateManager().getCallEventManager();
  194. CallEventRef<CXXDestructorCall> Call =
  195. CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
  196. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  197. Call->getSourceRange().getBegin(),
  198. "Error evaluating destructor");
  199. ExplodedNodeSet DstPreCall;
  200. getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
  201. *Call, *this);
  202. ExplodedNodeSet DstInvalidated;
  203. StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
  204. for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
  205. I != E; ++I)
  206. defaultEvalCall(Bldr, *I, *Call);
  207. ExplodedNodeSet DstPostCall;
  208. getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
  209. *Call, *this);
  210. }
  211. void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
  212. ExplodedNodeSet &Dst) {
  213. // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
  214. // Also, we need to decide how allocators actually work -- they're not
  215. // really part of the CXXNewExpr because they happen BEFORE the
  216. // CXXConstructExpr subexpression. See PR12014 for some discussion.
  217. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  218. unsigned blockCount = currBldrCtx->blockCount();
  219. const LocationContext *LCtx = Pred->getLocationContext();
  220. DefinedOrUnknownSVal symVal = svalBuilder.conjureSymbolVal(0, CNE, LCtx,
  221. CNE->getType(),
  222. blockCount);
  223. ProgramStateRef State = Pred->getState();
  224. CallEventManager &CEMgr = getStateManager().getCallEventManager();
  225. CallEventRef<CXXAllocatorCall> Call =
  226. CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
  227. // Invalidate placement args.
  228. // FIXME: Once we figure out how we want allocators to work,
  229. // we should be using the usual pre-/(default-)eval-/post-call checks here.
  230. State = Call->invalidateRegions(blockCount);
  231. // If we're compiling with exceptions enabled, and this allocation function
  232. // is not declared as non-throwing, failures /must/ be signalled by
  233. // exceptions, and thus the return value will never be NULL.
  234. // C++11 [basic.stc.dynamic.allocation]p3.
  235. FunctionDecl *FD = CNE->getOperatorNew();
  236. if (FD && getContext().getLangOpts().CXXExceptions) {
  237. QualType Ty = FD->getType();
  238. if (const FunctionProtoType *ProtoType = Ty->getAs<FunctionProtoType>())
  239. if (!ProtoType->isNothrow(getContext()))
  240. State = State->assume(symVal, true);
  241. }
  242. if (CNE->isArray()) {
  243. // FIXME: allocating an array requires simulating the constructors.
  244. // For now, just return a symbolicated region.
  245. const MemRegion *NewReg = symVal.castAs<loc::MemRegionVal>().getRegion();
  246. QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
  247. const ElementRegion *EleReg =
  248. getStoreManager().GetElementZeroRegion(NewReg, ObjTy);
  249. State = State->BindExpr(CNE, Pred->getLocationContext(),
  250. loc::MemRegionVal(EleReg));
  251. Bldr.generateNode(CNE, Pred, State);
  252. return;
  253. }
  254. // FIXME: Once we have proper support for CXXConstructExprs inside
  255. // CXXNewExpr, we need to make sure that the constructed object is not
  256. // immediately invalidated here. (The placement call should happen before
  257. // the constructor call anyway.)
  258. if (FD && FD->isReservedGlobalPlacementOperator()) {
  259. // Non-array placement new should always return the placement location.
  260. SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
  261. SVal Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
  262. CNE->getPlacementArg(0)->getType());
  263. State = State->BindExpr(CNE, LCtx, Result);
  264. } else {
  265. State = State->BindExpr(CNE, LCtx, symVal);
  266. }
  267. // If the type is not a record, we won't have a CXXConstructExpr as an
  268. // initializer. Copy the value over.
  269. if (const Expr *Init = CNE->getInitializer()) {
  270. if (!isa<CXXConstructExpr>(Init)) {
  271. QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
  272. (void)ObjTy;
  273. assert(!ObjTy->isRecordType());
  274. SVal Location = State->getSVal(CNE, LCtx);
  275. if (Optional<Loc> LV = Location.getAs<Loc>())
  276. State = State->bindLoc(*LV, State->getSVal(Init, LCtx));
  277. }
  278. }
  279. Bldr.generateNode(CNE, Pred, State);
  280. }
  281. void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE,
  282. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  283. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  284. ProgramStateRef state = Pred->getState();
  285. Bldr.generateNode(CDE, Pred, state);
  286. }
  287. void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS,
  288. ExplodedNode *Pred,
  289. ExplodedNodeSet &Dst) {
  290. const VarDecl *VD = CS->getExceptionDecl();
  291. if (!VD) {
  292. Dst.Add(Pred);
  293. return;
  294. }
  295. const LocationContext *LCtx = Pred->getLocationContext();
  296. SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(),
  297. currBldrCtx->blockCount());
  298. ProgramStateRef state = Pred->getState();
  299. state = state->bindLoc(state->getLValue(VD, LCtx), V);
  300. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  301. Bldr.generateNode(CS, Pred, state);
  302. }
  303. void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
  304. ExplodedNodeSet &Dst) {
  305. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  306. // Get the this object region from StoreManager.
  307. const LocationContext *LCtx = Pred->getLocationContext();
  308. const MemRegion *R =
  309. svalBuilder.getRegionManager().getCXXThisRegion(
  310. getContext().getCanonicalType(TE->getType()),
  311. LCtx);
  312. ProgramStateRef state = Pred->getState();
  313. SVal V = state->getSVal(loc::MemRegionVal(R));
  314. Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
  315. }