Environment.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. //===- Environment.cpp - Map from Stmt* to Locations/Values ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defined the Environment and EnvironmentManager classes.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/StaticAnalyzer/Core/PathSensitive/Environment.h"
  13. #include "clang/AST/Expr.h"
  14. #include "clang/AST/ExprCXX.h"
  15. #include "clang/AST/PrettyPrinter.h"
  16. #include "clang/AST/Stmt.h"
  17. #include "clang/AST/StmtObjC.h"
  18. #include "clang/Analysis/AnalysisDeclContext.h"
  19. #include "clang/Basic/LLVM.h"
  20. #include "clang/Basic/LangOptions.h"
  21. #include "clang/Basic/JsonSupport.h"
  22. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  23. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  24. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  25. #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
  26. #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
  27. #include "llvm/ADT/ImmutableMap.h"
  28. #include "llvm/ADT/SmallPtrSet.h"
  29. #include "llvm/Support/Casting.h"
  30. #include "llvm/Support/ErrorHandling.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include <cassert>
  33. using namespace clang;
  34. using namespace ento;
  35. static const Expr *ignoreTransparentExprs(const Expr *E) {
  36. E = E->IgnoreParens();
  37. switch (E->getStmtClass()) {
  38. case Stmt::OpaqueValueExprClass:
  39. E = cast<OpaqueValueExpr>(E)->getSourceExpr();
  40. break;
  41. case Stmt::ExprWithCleanupsClass:
  42. E = cast<ExprWithCleanups>(E)->getSubExpr();
  43. break;
  44. case Stmt::ConstantExprClass:
  45. E = cast<ConstantExpr>(E)->getSubExpr();
  46. break;
  47. case Stmt::CXXBindTemporaryExprClass:
  48. E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
  49. break;
  50. case Stmt::SubstNonTypeTemplateParmExprClass:
  51. E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
  52. break;
  53. default:
  54. // This is the base case: we can't look through more than we already have.
  55. return E;
  56. }
  57. return ignoreTransparentExprs(E);
  58. }
  59. static const Stmt *ignoreTransparentExprs(const Stmt *S) {
  60. if (const auto *E = dyn_cast<Expr>(S))
  61. return ignoreTransparentExprs(E);
  62. return S;
  63. }
  64. EnvironmentEntry::EnvironmentEntry(const Stmt *S, const LocationContext *L)
  65. : std::pair<const Stmt *,
  66. const StackFrameContext *>(ignoreTransparentExprs(S),
  67. L ? L->getStackFrame()
  68. : nullptr) {}
  69. SVal Environment::lookupExpr(const EnvironmentEntry &E) const {
  70. const SVal* X = ExprBindings.lookup(E);
  71. if (X) {
  72. SVal V = *X;
  73. return V;
  74. }
  75. return UnknownVal();
  76. }
  77. SVal Environment::getSVal(const EnvironmentEntry &Entry,
  78. SValBuilder& svalBuilder) const {
  79. const Stmt *S = Entry.getStmt();
  80. assert(!isa<ObjCForCollectionStmt>(S) &&
  81. "Use ExprEngine::hasMoreIteration()!");
  82. assert((isa<Expr, ReturnStmt>(S)) &&
  83. "Environment can only argue about Exprs, since only they express "
  84. "a value! Any non-expression statement stored in Environment is a "
  85. "result of a hack!");
  86. const LocationContext *LCtx = Entry.getLocationContext();
  87. switch (S->getStmtClass()) {
  88. case Stmt::CXXBindTemporaryExprClass:
  89. case Stmt::ExprWithCleanupsClass:
  90. case Stmt::GenericSelectionExprClass:
  91. case Stmt::OpaqueValueExprClass:
  92. case Stmt::ConstantExprClass:
  93. case Stmt::ParenExprClass:
  94. case Stmt::SubstNonTypeTemplateParmExprClass:
  95. llvm_unreachable("Should have been handled by ignoreTransparentExprs");
  96. case Stmt::AddrLabelExprClass:
  97. case Stmt::CharacterLiteralClass:
  98. case Stmt::CXXBoolLiteralExprClass:
  99. case Stmt::CXXScalarValueInitExprClass:
  100. case Stmt::ImplicitValueInitExprClass:
  101. case Stmt::IntegerLiteralClass:
  102. case Stmt::ObjCBoolLiteralExprClass:
  103. case Stmt::CXXNullPtrLiteralExprClass:
  104. case Stmt::ObjCStringLiteralClass:
  105. case Stmt::StringLiteralClass:
  106. case Stmt::TypeTraitExprClass:
  107. case Stmt::SizeOfPackExprClass:
  108. case Stmt::PredefinedExprClass:
  109. // Known constants; defer to SValBuilder.
  110. return *svalBuilder.getConstantVal(cast<Expr>(S));
  111. case Stmt::ReturnStmtClass: {
  112. const auto *RS = cast<ReturnStmt>(S);
  113. if (const Expr *RE = RS->getRetValue())
  114. return getSVal(EnvironmentEntry(RE, LCtx), svalBuilder);
  115. return UndefinedVal();
  116. }
  117. // Handle all other Stmt* using a lookup.
  118. default:
  119. return lookupExpr(EnvironmentEntry(S, LCtx));
  120. }
  121. }
  122. Environment EnvironmentManager::bindExpr(Environment Env,
  123. const EnvironmentEntry &E,
  124. SVal V,
  125. bool Invalidate) {
  126. if (V.isUnknown()) {
  127. if (Invalidate)
  128. return Environment(F.remove(Env.ExprBindings, E));
  129. else
  130. return Env;
  131. }
  132. return Environment(F.add(Env.ExprBindings, E, V));
  133. }
  134. namespace {
  135. class MarkLiveCallback final : public SymbolVisitor {
  136. SymbolReaper &SymReaper;
  137. public:
  138. MarkLiveCallback(SymbolReaper &symreaper) : SymReaper(symreaper) {}
  139. bool VisitSymbol(SymbolRef sym) override {
  140. SymReaper.markLive(sym);
  141. return true;
  142. }
  143. bool VisitMemRegion(const MemRegion *R) override {
  144. SymReaper.markLive(R);
  145. return true;
  146. }
  147. };
  148. } // namespace
  149. // removeDeadBindings:
  150. // - Remove subexpression bindings.
  151. // - Remove dead block expression bindings.
  152. // - Keep live block expression bindings:
  153. // - Mark their reachable symbols live in SymbolReaper,
  154. // see ScanReachableSymbols.
  155. // - Mark the region in DRoots if the binding is a loc::MemRegionVal.
  156. Environment
  157. EnvironmentManager::removeDeadBindings(Environment Env,
  158. SymbolReaper &SymReaper,
  159. ProgramStateRef ST) {
  160. // We construct a new Environment object entirely, as this is cheaper than
  161. // individually removing all the subexpression bindings (which will greatly
  162. // outnumber block-level expression bindings).
  163. Environment NewEnv = getInitialEnvironment();
  164. MarkLiveCallback CB(SymReaper);
  165. ScanReachableSymbols RSScaner(ST, CB);
  166. llvm::ImmutableMapRef<EnvironmentEntry, SVal>
  167. EBMapRef(NewEnv.ExprBindings.getRootWithoutRetain(),
  168. F.getTreeFactory());
  169. // Iterate over the block-expr bindings.
  170. for (Environment::iterator I = Env.begin(), End = Env.end(); I != End; ++I) {
  171. const EnvironmentEntry &BlkExpr = I.getKey();
  172. const SVal &X = I.getData();
  173. const Expr *E = dyn_cast<Expr>(BlkExpr.getStmt());
  174. if (!E)
  175. continue;
  176. if (SymReaper.isLive(E, BlkExpr.getLocationContext())) {
  177. // Copy the binding to the new map.
  178. EBMapRef = EBMapRef.add(BlkExpr, X);
  179. // Mark all symbols in the block expr's value live.
  180. RSScaner.scan(X);
  181. }
  182. }
  183. NewEnv.ExprBindings = EBMapRef.asImmutableMap();
  184. return NewEnv;
  185. }
  186. void Environment::printJson(raw_ostream &Out, const ASTContext &Ctx,
  187. const LocationContext *LCtx, const char *NL,
  188. unsigned int Space, bool IsDot) const {
  189. Indent(Out, Space, IsDot) << "\"environment\": ";
  190. if (ExprBindings.isEmpty()) {
  191. Out << "null," << NL;
  192. return;
  193. }
  194. ++Space;
  195. if (!LCtx) {
  196. // Find the freshest location context.
  197. llvm::SmallPtrSet<const LocationContext *, 16> FoundContexts;
  198. for (const auto &I : *this) {
  199. const LocationContext *LC = I.first.getLocationContext();
  200. if (FoundContexts.count(LC) == 0) {
  201. // This context is fresher than all other contexts so far.
  202. LCtx = LC;
  203. for (const LocationContext *LCI = LC; LCI; LCI = LCI->getParent())
  204. FoundContexts.insert(LCI);
  205. }
  206. }
  207. }
  208. assert(LCtx);
  209. Out << "{ \"pointer\": \"" << (const void *)LCtx->getStackFrame()
  210. << "\", \"items\": [" << NL;
  211. PrintingPolicy PP = Ctx.getPrintingPolicy();
  212. LCtx->printJson(Out, NL, Space, IsDot, [&](const LocationContext *LC) {
  213. // LCtx items begin
  214. bool HasItem = false;
  215. unsigned int InnerSpace = Space + 1;
  216. // Store the last ExprBinding which we will print.
  217. BindingsTy::iterator LastI = ExprBindings.end();
  218. for (BindingsTy::iterator I = ExprBindings.begin(); I != ExprBindings.end();
  219. ++I) {
  220. if (I->first.getLocationContext() != LC)
  221. continue;
  222. if (!HasItem) {
  223. HasItem = true;
  224. Out << '[' << NL;
  225. }
  226. const Stmt *S = I->first.getStmt();
  227. (void)S;
  228. assert(S != nullptr && "Expected non-null Stmt");
  229. LastI = I;
  230. }
  231. for (BindingsTy::iterator I = ExprBindings.begin(); I != ExprBindings.end();
  232. ++I) {
  233. if (I->first.getLocationContext() != LC)
  234. continue;
  235. const Stmt *S = I->first.getStmt();
  236. Indent(Out, InnerSpace, IsDot)
  237. << "{ \"stmt_id\": " << S->getID(Ctx) << ", \"kind\": \""
  238. << S->getStmtClassName() << "\", \"pretty\": ";
  239. S->printJson(Out, nullptr, PP, /*AddQuotes=*/true);
  240. Out << ", \"value\": ";
  241. I->second.printJson(Out, /*AddQuotes=*/true);
  242. Out << " }";
  243. if (I != LastI)
  244. Out << ',';
  245. Out << NL;
  246. }
  247. if (HasItem)
  248. Indent(Out, --InnerSpace, IsDot) << ']';
  249. else
  250. Out << "null ";
  251. });
  252. Indent(Out, --Space, IsDot) << "]}," << NL;
  253. }