ExprInspectionChecker.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. //==- ExprInspectionChecker.cpp - Used for regression tests ------*- C++ -*-==//
  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. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  9. #include "clang/StaticAnalyzer/Checkers/SValExplainer.h"
  10. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  11. #include "clang/StaticAnalyzer/Core/Checker.h"
  12. #include "clang/StaticAnalyzer/Core/IssueHash.h"
  13. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  14. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  15. #include "llvm/ADT/StringSwitch.h"
  16. #include "llvm/Support/ScopedPrinter.h"
  17. using namespace clang;
  18. using namespace ento;
  19. namespace {
  20. class ExprInspectionChecker : public Checker<eval::Call, check::DeadSymbols,
  21. check::EndAnalysis> {
  22. mutable std::unique_ptr<BugType> BT;
  23. // These stats are per-analysis, not per-branch, hence they shouldn't
  24. // stay inside the program state.
  25. struct ReachedStat {
  26. ExplodedNode *ExampleNode;
  27. unsigned NumTimesReached;
  28. };
  29. mutable llvm::DenseMap<const CallExpr *, ReachedStat> ReachedStats;
  30. void analyzerEval(const CallExpr *CE, CheckerContext &C) const;
  31. void analyzerCheckInlined(const CallExpr *CE, CheckerContext &C) const;
  32. void analyzerWarnIfReached(const CallExpr *CE, CheckerContext &C) const;
  33. void analyzerNumTimesReached(const CallExpr *CE, CheckerContext &C) const;
  34. void analyzerCrash(const CallExpr *CE, CheckerContext &C) const;
  35. void analyzerWarnOnDeadSymbol(const CallExpr *CE, CheckerContext &C) const;
  36. void analyzerDump(const CallExpr *CE, CheckerContext &C) const;
  37. void analyzerExplain(const CallExpr *CE, CheckerContext &C) const;
  38. void analyzerPrintState(const CallExpr *CE, CheckerContext &C) const;
  39. void analyzerGetExtent(const CallExpr *CE, CheckerContext &C) const;
  40. void analyzerHashDump(const CallExpr *CE, CheckerContext &C) const;
  41. void analyzerDenote(const CallExpr *CE, CheckerContext &C) const;
  42. void analyzerExpress(const CallExpr *CE, CheckerContext &C) const;
  43. typedef void (ExprInspectionChecker::*FnCheck)(const CallExpr *,
  44. CheckerContext &C) const;
  45. ExplodedNode *reportBug(llvm::StringRef Msg, CheckerContext &C) const;
  46. ExplodedNode *reportBug(llvm::StringRef Msg, BugReporter &BR,
  47. ExplodedNode *N) const;
  48. public:
  49. bool evalCall(const CallEvent &Call, CheckerContext &C) const;
  50. void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
  51. void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
  52. ExprEngine &Eng) const;
  53. };
  54. }
  55. REGISTER_SET_WITH_PROGRAMSTATE(MarkedSymbols, SymbolRef)
  56. REGISTER_MAP_WITH_PROGRAMSTATE(DenotedSymbols, SymbolRef, const StringLiteral *)
  57. bool ExprInspectionChecker::evalCall(const CallEvent &Call,
  58. CheckerContext &C) const {
  59. const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
  60. if (!CE)
  61. return false;
  62. // These checks should have no effect on the surrounding environment
  63. // (globals should not be invalidated, etc), hence the use of evalCall.
  64. FnCheck Handler = llvm::StringSwitch<FnCheck>(C.getCalleeName(CE))
  65. .Case("clang_analyzer_eval", &ExprInspectionChecker::analyzerEval)
  66. .Case("clang_analyzer_checkInlined",
  67. &ExprInspectionChecker::analyzerCheckInlined)
  68. .Case("clang_analyzer_crash", &ExprInspectionChecker::analyzerCrash)
  69. .Case("clang_analyzer_warnIfReached",
  70. &ExprInspectionChecker::analyzerWarnIfReached)
  71. .Case("clang_analyzer_warnOnDeadSymbol",
  72. &ExprInspectionChecker::analyzerWarnOnDeadSymbol)
  73. .StartsWith("clang_analyzer_explain", &ExprInspectionChecker::analyzerExplain)
  74. .StartsWith("clang_analyzer_dump", &ExprInspectionChecker::analyzerDump)
  75. .Case("clang_analyzer_getExtent", &ExprInspectionChecker::analyzerGetExtent)
  76. .Case("clang_analyzer_printState",
  77. &ExprInspectionChecker::analyzerPrintState)
  78. .Case("clang_analyzer_numTimesReached",
  79. &ExprInspectionChecker::analyzerNumTimesReached)
  80. .Case("clang_analyzer_hashDump", &ExprInspectionChecker::analyzerHashDump)
  81. .Case("clang_analyzer_denote", &ExprInspectionChecker::analyzerDenote)
  82. .Case("clang_analyzer_express", &ExprInspectionChecker::analyzerExpress)
  83. .Default(nullptr);
  84. if (!Handler)
  85. return false;
  86. (this->*Handler)(CE, C);
  87. return true;
  88. }
  89. static const char *getArgumentValueString(const CallExpr *CE,
  90. CheckerContext &C) {
  91. if (CE->getNumArgs() == 0)
  92. return "Missing assertion argument";
  93. ExplodedNode *N = C.getPredecessor();
  94. const LocationContext *LC = N->getLocationContext();
  95. ProgramStateRef State = N->getState();
  96. const Expr *Assertion = CE->getArg(0);
  97. SVal AssertionVal = State->getSVal(Assertion, LC);
  98. if (AssertionVal.isUndef())
  99. return "UNDEFINED";
  100. ProgramStateRef StTrue, StFalse;
  101. std::tie(StTrue, StFalse) =
  102. State->assume(AssertionVal.castAs<DefinedOrUnknownSVal>());
  103. if (StTrue) {
  104. if (StFalse)
  105. return "UNKNOWN";
  106. else
  107. return "TRUE";
  108. } else {
  109. if (StFalse)
  110. return "FALSE";
  111. else
  112. llvm_unreachable("Invalid constraint; neither true or false.");
  113. }
  114. }
  115. ExplodedNode *ExprInspectionChecker::reportBug(llvm::StringRef Msg,
  116. CheckerContext &C) const {
  117. ExplodedNode *N = C.generateNonFatalErrorNode();
  118. reportBug(Msg, C.getBugReporter(), N);
  119. return N;
  120. }
  121. ExplodedNode *ExprInspectionChecker::reportBug(llvm::StringRef Msg,
  122. BugReporter &BR,
  123. ExplodedNode *N) const {
  124. if (!N)
  125. return nullptr;
  126. if (!BT)
  127. BT.reset(new BugType(this, "Checking analyzer assumptions", "debug"));
  128. BR.emitReport(std::make_unique<PathSensitiveBugReport>(*BT, Msg, N));
  129. return N;
  130. }
  131. void ExprInspectionChecker::analyzerEval(const CallExpr *CE,
  132. CheckerContext &C) const {
  133. const LocationContext *LC = C.getPredecessor()->getLocationContext();
  134. // A specific instantiation of an inlined function may have more constrained
  135. // values than can generally be assumed. Skip the check.
  136. if (LC->getStackFrame()->getParent() != nullptr)
  137. return;
  138. reportBug(getArgumentValueString(CE, C), C);
  139. }
  140. void ExprInspectionChecker::analyzerWarnIfReached(const CallExpr *CE,
  141. CheckerContext &C) const {
  142. reportBug("REACHABLE", C);
  143. }
  144. void ExprInspectionChecker::analyzerNumTimesReached(const CallExpr *CE,
  145. CheckerContext &C) const {
  146. ++ReachedStats[CE].NumTimesReached;
  147. if (!ReachedStats[CE].ExampleNode) {
  148. // Later, in checkEndAnalysis, we'd throw a report against it.
  149. ReachedStats[CE].ExampleNode = C.generateNonFatalErrorNode();
  150. }
  151. }
  152. void ExprInspectionChecker::analyzerCheckInlined(const CallExpr *CE,
  153. CheckerContext &C) const {
  154. const LocationContext *LC = C.getPredecessor()->getLocationContext();
  155. // An inlined function could conceivably also be analyzed as a top-level
  156. // function. We ignore this case and only emit a message (TRUE or FALSE)
  157. // when we are analyzing it as an inlined function. This means that
  158. // clang_analyzer_checkInlined(true) should always print TRUE, but
  159. // clang_analyzer_checkInlined(false) should never actually print anything.
  160. if (LC->getStackFrame()->getParent() == nullptr)
  161. return;
  162. reportBug(getArgumentValueString(CE, C), C);
  163. }
  164. void ExprInspectionChecker::analyzerExplain(const CallExpr *CE,
  165. CheckerContext &C) const {
  166. if (CE->getNumArgs() == 0) {
  167. reportBug("Missing argument for explaining", C);
  168. return;
  169. }
  170. SVal V = C.getSVal(CE->getArg(0));
  171. SValExplainer Ex(C.getASTContext());
  172. reportBug(Ex.Visit(V), C);
  173. }
  174. void ExprInspectionChecker::analyzerDump(const CallExpr *CE,
  175. CheckerContext &C) const {
  176. if (CE->getNumArgs() == 0) {
  177. reportBug("Missing argument for dumping", C);
  178. return;
  179. }
  180. SVal V = C.getSVal(CE->getArg(0));
  181. llvm::SmallString<32> Str;
  182. llvm::raw_svector_ostream OS(Str);
  183. V.dumpToStream(OS);
  184. reportBug(OS.str(), C);
  185. }
  186. void ExprInspectionChecker::analyzerGetExtent(const CallExpr *CE,
  187. CheckerContext &C) const {
  188. if (CE->getNumArgs() == 0) {
  189. reportBug("Missing region for obtaining extent", C);
  190. return;
  191. }
  192. auto MR = dyn_cast_or_null<SubRegion>(C.getSVal(CE->getArg(0)).getAsRegion());
  193. if (!MR) {
  194. reportBug("Obtaining extent of a non-region", C);
  195. return;
  196. }
  197. ProgramStateRef State = C.getState();
  198. State = State->BindExpr(CE, C.getLocationContext(),
  199. MR->getExtent(C.getSValBuilder()));
  200. C.addTransition(State);
  201. }
  202. void ExprInspectionChecker::analyzerPrintState(const CallExpr *CE,
  203. CheckerContext &C) const {
  204. C.getState()->dump();
  205. }
  206. void ExprInspectionChecker::analyzerWarnOnDeadSymbol(const CallExpr *CE,
  207. CheckerContext &C) const {
  208. if (CE->getNumArgs() == 0)
  209. return;
  210. SVal Val = C.getSVal(CE->getArg(0));
  211. SymbolRef Sym = Val.getAsSymbol();
  212. if (!Sym)
  213. return;
  214. ProgramStateRef State = C.getState();
  215. State = State->add<MarkedSymbols>(Sym);
  216. C.addTransition(State);
  217. }
  218. void ExprInspectionChecker::checkDeadSymbols(SymbolReaper &SymReaper,
  219. CheckerContext &C) const {
  220. ProgramStateRef State = C.getState();
  221. const MarkedSymbolsTy &Syms = State->get<MarkedSymbols>();
  222. ExplodedNode *N = C.getPredecessor();
  223. for (auto I = Syms.begin(), E = Syms.end(); I != E; ++I) {
  224. SymbolRef Sym = *I;
  225. if (!SymReaper.isDead(Sym))
  226. continue;
  227. // The non-fatal error node should be the same for all reports.
  228. if (ExplodedNode *BugNode = reportBug("SYMBOL DEAD", C))
  229. N = BugNode;
  230. State = State->remove<MarkedSymbols>(Sym);
  231. }
  232. for (auto I : State->get<DenotedSymbols>()) {
  233. SymbolRef Sym = I.first;
  234. if (!SymReaper.isLive(Sym))
  235. State = State->remove<DenotedSymbols>(Sym);
  236. }
  237. C.addTransition(State, N);
  238. }
  239. void ExprInspectionChecker::checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
  240. ExprEngine &Eng) const {
  241. for (auto Item: ReachedStats) {
  242. unsigned NumTimesReached = Item.second.NumTimesReached;
  243. ExplodedNode *N = Item.second.ExampleNode;
  244. reportBug(llvm::to_string(NumTimesReached), BR, N);
  245. }
  246. ReachedStats.clear();
  247. }
  248. void ExprInspectionChecker::analyzerCrash(const CallExpr *CE,
  249. CheckerContext &C) const {
  250. LLVM_BUILTIN_TRAP;
  251. }
  252. void ExprInspectionChecker::analyzerHashDump(const CallExpr *CE,
  253. CheckerContext &C) const {
  254. const LangOptions &Opts = C.getLangOpts();
  255. const SourceManager &SM = C.getSourceManager();
  256. FullSourceLoc FL(CE->getArg(0)->getBeginLoc(), SM);
  257. std::string HashContent =
  258. GetIssueString(SM, FL, getCheckerName().getName(), "Category",
  259. C.getLocationContext()->getDecl(), Opts);
  260. reportBug(HashContent, C);
  261. }
  262. void ExprInspectionChecker::analyzerDenote(const CallExpr *CE,
  263. CheckerContext &C) const {
  264. if (CE->getNumArgs() < 2) {
  265. reportBug("clang_analyzer_denote() requires a symbol and a string literal",
  266. C);
  267. return;
  268. }
  269. SymbolRef Sym = C.getSVal(CE->getArg(0)).getAsSymbol();
  270. if (!Sym) {
  271. reportBug("Not a symbol", C);
  272. return;
  273. }
  274. const auto *E = dyn_cast<StringLiteral>(CE->getArg(1)->IgnoreParenCasts());
  275. if (!E) {
  276. reportBug("Not a string literal", C);
  277. return;
  278. }
  279. ProgramStateRef State = C.getState();
  280. C.addTransition(C.getState()->set<DenotedSymbols>(Sym, E));
  281. }
  282. namespace {
  283. class SymbolExpressor
  284. : public SymExprVisitor<SymbolExpressor, Optional<std::string>> {
  285. ProgramStateRef State;
  286. public:
  287. SymbolExpressor(ProgramStateRef State) : State(State) {}
  288. Optional<std::string> lookup(const SymExpr *S) {
  289. if (const StringLiteral *const *SLPtr = State->get<DenotedSymbols>(S)) {
  290. const StringLiteral *SL = *SLPtr;
  291. return std::string(SL->getBytes());
  292. }
  293. return None;
  294. }
  295. Optional<std::string> VisitSymExpr(const SymExpr *S) {
  296. return lookup(S);
  297. }
  298. Optional<std::string> VisitSymIntExpr(const SymIntExpr *S) {
  299. if (Optional<std::string> Str = lookup(S))
  300. return Str;
  301. if (Optional<std::string> Str = Visit(S->getLHS()))
  302. return (*Str + " " + BinaryOperator::getOpcodeStr(S->getOpcode()) + " " +
  303. std::to_string(S->getRHS().getLimitedValue()) +
  304. (S->getRHS().isUnsigned() ? "U" : ""))
  305. .str();
  306. return None;
  307. }
  308. Optional<std::string> VisitSymSymExpr(const SymSymExpr *S) {
  309. if (Optional<std::string> Str = lookup(S))
  310. return Str;
  311. if (Optional<std::string> Str1 = Visit(S->getLHS()))
  312. if (Optional<std::string> Str2 = Visit(S->getRHS()))
  313. return (*Str1 + " " + BinaryOperator::getOpcodeStr(S->getOpcode()) +
  314. " " + *Str2).str();
  315. return None;
  316. }
  317. Optional<std::string> VisitSymbolCast(const SymbolCast *S) {
  318. if (Optional<std::string> Str = lookup(S))
  319. return Str;
  320. if (Optional<std::string> Str = Visit(S->getOperand()))
  321. return (Twine("(") + S->getType().getAsString() + ")" + *Str).str();
  322. return None;
  323. }
  324. };
  325. } // namespace
  326. void ExprInspectionChecker::analyzerExpress(const CallExpr *CE,
  327. CheckerContext &C) const {
  328. if (CE->getNumArgs() == 0) {
  329. reportBug("clang_analyzer_express() requires a symbol", C);
  330. return;
  331. }
  332. SymbolRef Sym = C.getSVal(CE->getArg(0)).getAsSymbol();
  333. if (!Sym) {
  334. reportBug("Not a symbol", C);
  335. return;
  336. }
  337. SymbolExpressor V(C.getState());
  338. auto Str = V.Visit(Sym);
  339. if (!Str) {
  340. reportBug("Unable to express", C);
  341. return;
  342. }
  343. reportBug(*Str, C);
  344. }
  345. void ento::registerExprInspectionChecker(CheckerManager &Mgr) {
  346. Mgr.registerChecker<ExprInspectionChecker>();
  347. }
  348. bool ento::shouldRegisterExprInspectionChecker(const LangOptions &LO) {
  349. return true;
  350. }