ExprInspectionChecker.cpp 17 KB

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