PageRenderTime 35ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/clang/lib/StaticAnalyzer/Core/SarifDiagnostics.cpp

https://gitlab.com/williamwp/riscv-rv32x-llvm
C++ | 349 lines | 313 code | 12 blank | 24 comment | 11 complexity | 883b966a0c331f8b15809b94ab1be190 MD5 | raw file
  1. //===--- SarifDiagnostics.cpp - Sarif Diagnostics for Paths -----*- 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. //
  9. // This file defines the SarifDiagnostics object.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Basic/Version.h"
  13. #include "clang/Lex/Preprocessor.h"
  14. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  15. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  16. #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/StringMap.h"
  19. #include "llvm/Support/JSON.h"
  20. #include "llvm/Support/Path.h"
  21. using namespace llvm;
  22. using namespace clang;
  23. using namespace ento;
  24. namespace {
  25. class SarifDiagnostics : public PathDiagnosticConsumer {
  26. std::string OutputFile;
  27. public:
  28. SarifDiagnostics(AnalyzerOptions &, const std::string &Output)
  29. : OutputFile(Output) {}
  30. ~SarifDiagnostics() override = default;
  31. void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
  32. FilesMade *FM) override;
  33. StringRef getName() const override { return "SarifDiagnostics"; }
  34. PathGenerationScheme getGenerationScheme() const override { return Minimal; }
  35. bool supportsLogicalOpControlFlow() const override { return true; }
  36. bool supportsCrossFileDiagnostics() const override { return true; }
  37. };
  38. } // end anonymous namespace
  39. void ento::createSarifDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
  40. PathDiagnosticConsumers &C,
  41. const std::string &Output,
  42. const Preprocessor &) {
  43. C.push_back(new SarifDiagnostics(AnalyzerOpts, Output));
  44. }
  45. static StringRef getFileName(const FileEntry &FE) {
  46. StringRef Filename = FE.tryGetRealPathName();
  47. if (Filename.empty())
  48. Filename = FE.getName();
  49. return Filename;
  50. }
  51. static std::string percentEncodeURICharacter(char C) {
  52. // RFC 3986 claims alpha, numeric, and this handful of
  53. // characters are not reserved for the path component and
  54. // should be written out directly. Otherwise, percent
  55. // encode the character and write that out instead of the
  56. // reserved character.
  57. if (llvm::isAlnum(C) ||
  58. StringRef::npos != StringRef("-._~:@!$&'()*+,;=").find(C))
  59. return std::string(&C, 1);
  60. return "%" + llvm::toHex(StringRef(&C, 1));
  61. }
  62. static std::string fileNameToURI(StringRef Filename) {
  63. llvm::SmallString<32> Ret = StringRef("file://");
  64. // Get the root name to see if it has a URI authority.
  65. StringRef Root = sys::path::root_name(Filename);
  66. if (Root.startswith("//")) {
  67. // There is an authority, so add it to the URI.
  68. Ret += Root.drop_front(2).str();
  69. } else if (!Root.empty()) {
  70. // There is no authority, so end the component and add the root to the URI.
  71. Ret += Twine("/" + Root).str();
  72. }
  73. auto Iter = sys::path::begin(Filename), End = sys::path::end(Filename);
  74. assert(Iter != End && "Expected there to be a non-root path component.");
  75. // Add the rest of the path components, encoding any reserved characters;
  76. // we skip past the first path component, as it was handled it above.
  77. std::for_each(++Iter, End, [&Ret](StringRef Component) {
  78. // For reasons unknown to me, we may get a backslash with Windows native
  79. // paths for the initial backslash following the drive component, which
  80. // we need to ignore as a URI path part.
  81. if (Component == "\\")
  82. return;
  83. // Add the separator between the previous path part and the one being
  84. // currently processed.
  85. Ret += "/";
  86. // URI encode the part.
  87. for (char C : Component) {
  88. Ret += percentEncodeURICharacter(C);
  89. }
  90. });
  91. return Ret.str().str();
  92. }
  93. static json::Object createFileLocation(const FileEntry &FE) {
  94. return json::Object{{"uri", fileNameToURI(getFileName(FE))}};
  95. }
  96. static json::Object createFile(const FileEntry &FE) {
  97. return json::Object{{"fileLocation", createFileLocation(FE)},
  98. {"roles", json::Array{"resultFile"}},
  99. {"length", FE.getSize()},
  100. {"mimeType", "text/plain"}};
  101. }
  102. static json::Object createFileLocation(const FileEntry &FE,
  103. json::Array &Files) {
  104. std::string FileURI = fileNameToURI(getFileName(FE));
  105. // See if the Files array contains this URI already. If it does not, create
  106. // a new file object to add to the array.
  107. auto I = llvm::find_if(Files, [&](const json::Value &File) {
  108. if (const json::Object *Obj = File.getAsObject()) {
  109. if (const json::Object *FileLoc = Obj->getObject("fileLocation")) {
  110. Optional<StringRef> URI = FileLoc->getString("uri");
  111. return URI && URI->equals(FileURI);
  112. }
  113. }
  114. return false;
  115. });
  116. // Calculate the index within the file location array so it can be stored in
  117. // the JSON object.
  118. auto Index = static_cast<unsigned>(std::distance(Files.begin(), I));
  119. if (I == Files.end())
  120. Files.push_back(createFile(FE));
  121. return json::Object{{"uri", FileURI}, {"fileIndex", Index}};
  122. }
  123. static json::Object createTextRegion(SourceRange R, const SourceManager &SM) {
  124. return json::Object{
  125. {"startLine", SM.getExpansionLineNumber(R.getBegin())},
  126. {"endLine", SM.getExpansionLineNumber(R.getEnd())},
  127. {"startColumn", SM.getExpansionColumnNumber(R.getBegin())},
  128. {"endColumn", SM.getExpansionColumnNumber(R.getEnd())}};
  129. }
  130. static json::Object createPhysicalLocation(SourceRange R, const FileEntry &FE,
  131. const SourceManager &SMgr,
  132. json::Array &Files) {
  133. return json::Object{{{"fileLocation", createFileLocation(FE, Files)},
  134. {"region", createTextRegion(R, SMgr)}}};
  135. }
  136. enum class Importance { Important, Essential, Unimportant };
  137. static StringRef importanceToStr(Importance I) {
  138. switch (I) {
  139. case Importance::Important:
  140. return "important";
  141. case Importance::Essential:
  142. return "essential";
  143. case Importance::Unimportant:
  144. return "unimportant";
  145. }
  146. llvm_unreachable("Fully covered switch is not so fully covered");
  147. }
  148. static json::Object createThreadFlowLocation(json::Object &&Location,
  149. Importance I) {
  150. return json::Object{{"location", std::move(Location)},
  151. {"importance", importanceToStr(I)}};
  152. }
  153. static json::Object createMessage(StringRef Text) {
  154. return json::Object{{"text", Text.str()}};
  155. }
  156. static json::Object createLocation(json::Object &&PhysicalLocation,
  157. StringRef Message = "") {
  158. json::Object Ret{{"physicalLocation", std::move(PhysicalLocation)}};
  159. if (!Message.empty())
  160. Ret.insert({"message", createMessage(Message)});
  161. return Ret;
  162. }
  163. static Importance calculateImportance(const PathDiagnosticPiece &Piece) {
  164. switch (Piece.getKind()) {
  165. case PathDiagnosticPiece::Call:
  166. case PathDiagnosticPiece::Macro:
  167. case PathDiagnosticPiece::Note:
  168. case PathDiagnosticPiece::PopUp:
  169. // FIXME: What should be reported here?
  170. break;
  171. case PathDiagnosticPiece::Event:
  172. return Piece.getTagStr() == "ConditionBRVisitor" ? Importance::Important
  173. : Importance::Essential;
  174. case PathDiagnosticPiece::ControlFlow:
  175. return Importance::Unimportant;
  176. }
  177. return Importance::Unimportant;
  178. }
  179. static json::Object createThreadFlow(const PathPieces &Pieces,
  180. json::Array &Files) {
  181. const SourceManager &SMgr = Pieces.front()->getLocation().getManager();
  182. json::Array Locations;
  183. for (const auto &Piece : Pieces) {
  184. const PathDiagnosticLocation &P = Piece->getLocation();
  185. Locations.push_back(createThreadFlowLocation(
  186. createLocation(createPhysicalLocation(P.asRange(),
  187. *P.asLocation().getFileEntry(),
  188. SMgr, Files),
  189. Piece->getString()),
  190. calculateImportance(*Piece)));
  191. }
  192. return json::Object{{"locations", std::move(Locations)}};
  193. }
  194. static json::Object createCodeFlow(const PathPieces &Pieces,
  195. json::Array &Files) {
  196. return json::Object{
  197. {"threadFlows", json::Array{createThreadFlow(Pieces, Files)}}};
  198. }
  199. static json::Object createTool() {
  200. return json::Object{{"name", "clang"},
  201. {"fullName", "clang static analyzer"},
  202. {"language", "en-US"},
  203. {"version", getClangFullVersion()}};
  204. }
  205. static json::Object createResult(const PathDiagnostic &Diag, json::Array &Files,
  206. const StringMap<unsigned> &RuleMapping) {
  207. const PathPieces &Path = Diag.path.flatten(false);
  208. const SourceManager &SMgr = Path.front()->getLocation().getManager();
  209. auto Iter = RuleMapping.find(Diag.getCheckName());
  210. assert(Iter != RuleMapping.end() && "Rule ID is not in the array index map?");
  211. return json::Object{
  212. {"message", createMessage(Diag.getVerboseDescription())},
  213. {"codeFlows", json::Array{createCodeFlow(Path, Files)}},
  214. {"locations",
  215. json::Array{createLocation(createPhysicalLocation(
  216. Diag.getLocation().asRange(),
  217. *Diag.getLocation().asLocation().getFileEntry(), SMgr, Files))}},
  218. {"ruleIndex", Iter->getValue()},
  219. {"ruleId", Diag.getCheckName()}};
  220. }
  221. static StringRef getRuleDescription(StringRef CheckName) {
  222. return llvm::StringSwitch<StringRef>(CheckName)
  223. #define GET_CHECKERS
  224. #define CHECKER(FULLNAME, CLASS, HELPTEXT, DOC_URI, IS_HIDDEN) \
  225. .Case(FULLNAME, HELPTEXT)
  226. #include "clang/StaticAnalyzer/Checkers/Checkers.inc"
  227. #undef CHECKER
  228. #undef GET_CHECKERS
  229. ;
  230. }
  231. static StringRef getRuleHelpURIStr(StringRef CheckName) {
  232. return llvm::StringSwitch<StringRef>(CheckName)
  233. #define GET_CHECKERS
  234. #define CHECKER(FULLNAME, CLASS, HELPTEXT, DOC_URI, IS_HIDDEN) \
  235. .Case(FULLNAME, DOC_URI)
  236. #include "clang/StaticAnalyzer/Checkers/Checkers.inc"
  237. #undef CHECKER
  238. #undef GET_CHECKERS
  239. ;
  240. }
  241. static json::Object createRule(const PathDiagnostic &Diag) {
  242. StringRef CheckName = Diag.getCheckName();
  243. json::Object Ret{
  244. {"fullDescription", createMessage(getRuleDescription(CheckName))},
  245. {"name", createMessage(CheckName)},
  246. {"id", CheckName}};
  247. std::string RuleURI = getRuleHelpURIStr(CheckName);
  248. if (!RuleURI.empty())
  249. Ret["helpUri"] = RuleURI;
  250. return Ret;
  251. }
  252. static json::Array createRules(std::vector<const PathDiagnostic *> &Diags,
  253. StringMap<unsigned> &RuleMapping) {
  254. json::Array Rules;
  255. llvm::StringSet<> Seen;
  256. llvm::for_each(Diags, [&](const PathDiagnostic *D) {
  257. StringRef RuleID = D->getCheckName();
  258. std::pair<llvm::StringSet<>::iterator, bool> P = Seen.insert(RuleID);
  259. if (P.second) {
  260. RuleMapping[RuleID] = Rules.size(); // Maps RuleID to an Array Index.
  261. Rules.push_back(createRule(*D));
  262. }
  263. });
  264. return Rules;
  265. }
  266. static json::Object createResources(std::vector<const PathDiagnostic *> &Diags,
  267. StringMap<unsigned> &RuleMapping) {
  268. return json::Object{{"rules", createRules(Diags, RuleMapping)}};
  269. }
  270. static json::Object createRun(std::vector<const PathDiagnostic *> &Diags) {
  271. json::Array Results, Files;
  272. StringMap<unsigned> RuleMapping;
  273. json::Object Resources = createResources(Diags, RuleMapping);
  274. llvm::for_each(Diags, [&](const PathDiagnostic *D) {
  275. Results.push_back(createResult(*D, Files, RuleMapping));
  276. });
  277. return json::Object{{"tool", createTool()},
  278. {"resources", std::move(Resources)},
  279. {"results", std::move(Results)},
  280. {"files", std::move(Files)}};
  281. }
  282. void SarifDiagnostics::FlushDiagnosticsImpl(
  283. std::vector<const PathDiagnostic *> &Diags, FilesMade *) {
  284. // We currently overwrite the file if it already exists. However, it may be
  285. // useful to add a feature someday that allows the user to append a run to an
  286. // existing SARIF file. One danger from that approach is that the size of the
  287. // file can become large very quickly, so decoding into JSON to append a run
  288. // may be an expensive operation.
  289. std::error_code EC;
  290. llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_Text);
  291. if (EC) {
  292. llvm::errs() << "warning: could not create file: " << EC.message() << '\n';
  293. return;
  294. }
  295. json::Object Sarif{
  296. {"$schema",
  297. "http://json.schemastore.org/sarif-2.0.0-csd.2.beta.2018-11-28"},
  298. {"version", "2.0.0-csd.2.beta.2018-11-28"},
  299. {"runs", json::Array{createRun(Diags)}}};
  300. OS << llvm::formatv("{0:2}\n", json::Value(std::move(Sarif)));
  301. }