HTMLDiagnostics.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. //===--- HTMLDiagnostics.cpp - HTML Diagnostics for Paths ----*- 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 HTMLDiagnostics object.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Decl.h"
  16. #include "clang/Basic/FileManager.h"
  17. #include "clang/Basic/SourceManager.h"
  18. #include "clang/Lex/Lexer.h"
  19. #include "clang/Lex/Preprocessor.h"
  20. #include "clang/Rewrite/Core/HTMLRewrite.h"
  21. #include "clang/Rewrite/Core/Rewriter.h"
  22. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include "llvm/Support/MemoryBuffer.h"
  25. #include "llvm/Support/Path.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. using namespace clang;
  28. using namespace ento;
  29. //===----------------------------------------------------------------------===//
  30. // Boilerplate.
  31. //===----------------------------------------------------------------------===//
  32. namespace {
  33. class HTMLDiagnostics : public PathDiagnosticConsumer {
  34. std::string Directory;
  35. bool createdDir, noDir;
  36. const Preprocessor &PP;
  37. public:
  38. HTMLDiagnostics(const std::string& prefix, const Preprocessor &pp);
  39. virtual ~HTMLDiagnostics() { FlushDiagnostics(nullptr); }
  40. void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
  41. FilesMade *filesMade) override;
  42. StringRef getName() const override {
  43. return "HTMLDiagnostics";
  44. }
  45. unsigned ProcessMacroPiece(raw_ostream &os,
  46. const PathDiagnosticMacroPiece& P,
  47. unsigned num);
  48. void HandlePiece(Rewriter& R, FileID BugFileID,
  49. const PathDiagnosticPiece& P, unsigned num, unsigned max);
  50. void HighlightRange(Rewriter& R, FileID BugFileID, SourceRange Range,
  51. const char *HighlightStart = "<span class=\"mrange\">",
  52. const char *HighlightEnd = "</span>");
  53. void ReportDiag(const PathDiagnostic& D,
  54. FilesMade *filesMade);
  55. };
  56. } // end anonymous namespace
  57. HTMLDiagnostics::HTMLDiagnostics(const std::string& prefix,
  58. const Preprocessor &pp)
  59. : Directory(prefix), createdDir(false), noDir(false), PP(pp) {
  60. }
  61. void ento::createHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
  62. PathDiagnosticConsumers &C,
  63. const std::string& prefix,
  64. const Preprocessor &PP) {
  65. C.push_back(new HTMLDiagnostics(prefix, PP));
  66. }
  67. //===----------------------------------------------------------------------===//
  68. // Report processing.
  69. //===----------------------------------------------------------------------===//
  70. void HTMLDiagnostics::FlushDiagnosticsImpl(
  71. std::vector<const PathDiagnostic *> &Diags,
  72. FilesMade *filesMade) {
  73. for (std::vector<const PathDiagnostic *>::iterator it = Diags.begin(),
  74. et = Diags.end(); it != et; ++it) {
  75. ReportDiag(**it, filesMade);
  76. }
  77. }
  78. void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D,
  79. FilesMade *filesMade) {
  80. // Create the HTML directory if it is missing.
  81. if (!createdDir) {
  82. createdDir = true;
  83. if (llvm::error_code ec = llvm::sys::fs::create_directories(Directory)) {
  84. llvm::errs() << "warning: could not create directory '"
  85. << Directory << "': " << ec.message() << '\n';
  86. noDir = true;
  87. return;
  88. }
  89. }
  90. if (noDir)
  91. return;
  92. // First flatten out the entire path to make it easier to use.
  93. PathPieces path = D.path.flatten(/*ShouldFlattenMacros=*/false);
  94. // The path as already been prechecked that all parts of the path are
  95. // from the same file and that it is non-empty.
  96. const SourceManager &SMgr = (*path.begin())->getLocation().getManager();
  97. assert(!path.empty());
  98. FileID FID =
  99. (*path.begin())->getLocation().asLocation().getExpansionLoc().getFileID();
  100. assert(!FID.isInvalid());
  101. // Create a new rewriter to generate HTML.
  102. Rewriter R(const_cast<SourceManager&>(SMgr), PP.getLangOpts());
  103. // Process the path.
  104. unsigned n = path.size();
  105. unsigned max = n;
  106. for (PathPieces::const_reverse_iterator I = path.rbegin(),
  107. E = path.rend();
  108. I != E; ++I, --n)
  109. HandlePiece(R, FID, **I, n, max);
  110. // Add line numbers, header, footer, etc.
  111. // unsigned FID = R.getSourceMgr().getMainFileID();
  112. html::EscapeText(R, FID);
  113. html::AddLineNumbers(R, FID);
  114. // If we have a preprocessor, relex the file and syntax highlight.
  115. // We might not have a preprocessor if we come from a deserialized AST file,
  116. // for example.
  117. html::SyntaxHighlight(R, FID, PP);
  118. html::HighlightMacros(R, FID, PP);
  119. // Get the full directory name of the analyzed file.
  120. const FileEntry* Entry = SMgr.getFileEntryForID(FID);
  121. // This is a cludge; basically we want to append either the full
  122. // working directory if we have no directory information. This is
  123. // a work in progress.
  124. llvm::SmallString<0> DirName;
  125. if (llvm::sys::path::is_relative(Entry->getName())) {
  126. llvm::sys::fs::current_path(DirName);
  127. DirName += '/';
  128. }
  129. // Add the name of the file as an <h1> tag.
  130. {
  131. std::string s;
  132. llvm::raw_string_ostream os(s);
  133. os << "<!-- REPORTHEADER -->\n"
  134. << "<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n"
  135. "<tr><td class=\"rowname\">File:</td><td>"
  136. << html::EscapeText(DirName)
  137. << html::EscapeText(Entry->getName())
  138. << "</td></tr>\n<tr><td class=\"rowname\">Location:</td><td>"
  139. "<a href=\"#EndPath\">line "
  140. << (*path.rbegin())->getLocation().asLocation().getExpansionLineNumber()
  141. << ", column "
  142. << (*path.rbegin())->getLocation().asLocation().getExpansionColumnNumber()
  143. << "</a></td></tr>\n"
  144. "<tr><td class=\"rowname\">Description:</td><td>"
  145. << D.getVerboseDescription() << "</td></tr>\n";
  146. // Output any other meta data.
  147. for (PathDiagnostic::meta_iterator I=D.meta_begin(), E=D.meta_end();
  148. I!=E; ++I) {
  149. os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n";
  150. }
  151. os << "</table>\n<!-- REPORTSUMMARYEXTRA -->\n"
  152. "<h3>Annotated Source Code</h3>\n";
  153. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
  154. }
  155. // Embed meta-data tags.
  156. {
  157. std::string s;
  158. llvm::raw_string_ostream os(s);
  159. StringRef BugDesc = D.getVerboseDescription();
  160. if (!BugDesc.empty())
  161. os << "\n<!-- BUGDESC " << BugDesc << " -->\n";
  162. StringRef BugType = D.getBugType();
  163. if (!BugType.empty())
  164. os << "\n<!-- BUGTYPE " << BugType << " -->\n";
  165. StringRef BugCategory = D.getCategory();
  166. if (!BugCategory.empty())
  167. os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n";
  168. os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n";
  169. os << "\n<!-- BUGLINE "
  170. << path.back()->getLocation().asLocation().getExpansionLineNumber()
  171. << " -->\n";
  172. os << "\n<!-- BUGCOLUMN "
  173. << path.back()->getLocation().asLocation().getExpansionColumnNumber()
  174. << " -->\n";
  175. os << "\n<!-- BUGPATHLENGTH " << path.size() << " -->\n";
  176. // Mark the end of the tags.
  177. os << "\n<!-- BUGMETAEND -->\n";
  178. // Insert the text.
  179. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
  180. }
  181. // Add CSS, header, and footer.
  182. html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
  183. // Get the rewrite buffer.
  184. const RewriteBuffer *Buf = R.getRewriteBufferFor(FID);
  185. if (!Buf) {
  186. llvm::errs() << "warning: no diagnostics generated for main file.\n";
  187. return;
  188. }
  189. // Create a path for the target HTML file.
  190. int FD;
  191. SmallString<128> Model, ResultPath;
  192. llvm::sys::path::append(Model, Directory, "report-%%%%%%.html");
  193. if (llvm::error_code EC =
  194. llvm::sys::fs::createUniqueFile(Model.str(), FD, ResultPath)) {
  195. llvm::errs() << "warning: could not create file in '" << Directory
  196. << "': " << EC.message() << '\n';
  197. return;
  198. }
  199. llvm::raw_fd_ostream os(FD, true);
  200. if (filesMade)
  201. filesMade->addDiagnostic(D, getName(),
  202. llvm::sys::path::filename(ResultPath));
  203. // Emit the HTML to disk.
  204. for (RewriteBuffer::iterator I = Buf->begin(), E = Buf->end(); I!=E; ++I)
  205. os << *I;
  206. }
  207. void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID,
  208. const PathDiagnosticPiece& P,
  209. unsigned num, unsigned max) {
  210. // For now, just draw a box above the line in question, and emit the
  211. // warning.
  212. FullSourceLoc Pos = P.getLocation().asLocation();
  213. if (!Pos.isValid())
  214. return;
  215. SourceManager &SM = R.getSourceMgr();
  216. assert(&Pos.getManager() == &SM && "SourceManagers are different!");
  217. std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
  218. if (LPosInfo.first != BugFileID)
  219. return;
  220. const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
  221. const char* FileStart = Buf->getBufferStart();
  222. // Compute the column number. Rewind from the current position to the start
  223. // of the line.
  224. unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
  225. const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
  226. const char *LineStart = TokInstantiationPtr-ColNo;
  227. // Compute LineEnd.
  228. const char *LineEnd = TokInstantiationPtr;
  229. const char* FileEnd = Buf->getBufferEnd();
  230. while (*LineEnd != '\n' && LineEnd != FileEnd)
  231. ++LineEnd;
  232. // Compute the margin offset by counting tabs and non-tabs.
  233. unsigned PosNo = 0;
  234. for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
  235. PosNo += *c == '\t' ? 8 : 1;
  236. // Create the html for the message.
  237. const char *Kind = nullptr;
  238. switch (P.getKind()) {
  239. case PathDiagnosticPiece::Call:
  240. llvm_unreachable("Calls should already be handled");
  241. case PathDiagnosticPiece::Event: Kind = "Event"; break;
  242. case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
  243. // Setting Kind to "Control" is intentional.
  244. case PathDiagnosticPiece::Macro: Kind = "Control"; break;
  245. }
  246. std::string sbuf;
  247. llvm::raw_string_ostream os(sbuf);
  248. os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
  249. if (num == max)
  250. os << "EndPath";
  251. else
  252. os << "Path" << num;
  253. os << "\" class=\"msg";
  254. if (Kind)
  255. os << " msg" << Kind;
  256. os << "\" style=\"margin-left:" << PosNo << "ex";
  257. // Output a maximum size.
  258. if (!isa<PathDiagnosticMacroPiece>(P)) {
  259. // Get the string and determining its maximum substring.
  260. const std::string& Msg = P.getString();
  261. unsigned max_token = 0;
  262. unsigned cnt = 0;
  263. unsigned len = Msg.size();
  264. for (std::string::const_iterator I=Msg.begin(), E=Msg.end(); I!=E; ++I)
  265. switch (*I) {
  266. default:
  267. ++cnt;
  268. continue;
  269. case ' ':
  270. case '\t':
  271. case '\n':
  272. if (cnt > max_token) max_token = cnt;
  273. cnt = 0;
  274. }
  275. if (cnt > max_token)
  276. max_token = cnt;
  277. // Determine the approximate size of the message bubble in em.
  278. unsigned em;
  279. const unsigned max_line = 120;
  280. if (max_token >= max_line)
  281. em = max_token / 2;
  282. else {
  283. unsigned characters = max_line;
  284. unsigned lines = len / max_line;
  285. if (lines > 0) {
  286. for (; characters > max_token; --characters)
  287. if (len / characters > lines) {
  288. ++characters;
  289. break;
  290. }
  291. }
  292. em = characters / 2;
  293. }
  294. if (em < max_line/2)
  295. os << "; max-width:" << em << "em";
  296. }
  297. else
  298. os << "; max-width:100em";
  299. os << "\">";
  300. if (max > 1) {
  301. os << "<table class=\"msgT\"><tr><td valign=\"top\">";
  302. os << "<div class=\"PathIndex";
  303. if (Kind) os << " PathIndex" << Kind;
  304. os << "\">" << num << "</div>";
  305. if (num > 1) {
  306. os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
  307. << (num - 1)
  308. << "\" title=\"Previous event ("
  309. << (num - 1)
  310. << ")\">&#x2190;</a></div></td>";
  311. }
  312. os << "</td><td>";
  313. }
  314. if (const PathDiagnosticMacroPiece *MP =
  315. dyn_cast<PathDiagnosticMacroPiece>(&P)) {
  316. os << "Within the expansion of the macro '";
  317. // Get the name of the macro by relexing it.
  318. {
  319. FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
  320. assert(L.isFileID());
  321. StringRef BufferInfo = L.getBufferData();
  322. std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
  323. const char* MacroName = LocInfo.second + BufferInfo.data();
  324. Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
  325. BufferInfo.begin(), MacroName, BufferInfo.end());
  326. Token TheTok;
  327. rawLexer.LexFromRawLexer(TheTok);
  328. for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
  329. os << MacroName[i];
  330. }
  331. os << "':\n";
  332. if (max > 1) {
  333. os << "</td>";
  334. if (num < max) {
  335. os << "<td><div class=\"PathNav\"><a href=\"#";
  336. if (num == max - 1)
  337. os << "EndPath";
  338. else
  339. os << "Path" << (num + 1);
  340. os << "\" title=\"Next event ("
  341. << (num + 1)
  342. << ")\">&#x2192;</a></div></td>";
  343. }
  344. os << "</tr></table>";
  345. }
  346. // Within a macro piece. Write out each event.
  347. ProcessMacroPiece(os, *MP, 0);
  348. }
  349. else {
  350. os << html::EscapeText(P.getString());
  351. if (max > 1) {
  352. os << "</td>";
  353. if (num < max) {
  354. os << "<td><div class=\"PathNav\"><a href=\"#";
  355. if (num == max - 1)
  356. os << "EndPath";
  357. else
  358. os << "Path" << (num + 1);
  359. os << "\" title=\"Next event ("
  360. << (num + 1)
  361. << ")\">&#x2192;</a></div></td>";
  362. }
  363. os << "</tr></table>";
  364. }
  365. }
  366. os << "</div></td></tr>";
  367. // Insert the new html.
  368. unsigned DisplayPos = LineEnd - FileStart;
  369. SourceLocation Loc =
  370. SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
  371. R.InsertTextBefore(Loc, os.str());
  372. // Now highlight the ranges.
  373. ArrayRef<SourceRange> Ranges = P.getRanges();
  374. for (ArrayRef<SourceRange>::iterator I = Ranges.begin(),
  375. E = Ranges.end(); I != E; ++I) {
  376. HighlightRange(R, LPosInfo.first, *I);
  377. }
  378. }
  379. static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
  380. unsigned x = n % ('z' - 'a');
  381. n /= 'z' - 'a';
  382. if (n > 0)
  383. EmitAlphaCounter(os, n);
  384. os << char('a' + x);
  385. }
  386. unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
  387. const PathDiagnosticMacroPiece& P,
  388. unsigned num) {
  389. for (PathPieces::const_iterator I = P.subPieces.begin(), E=P.subPieces.end();
  390. I!=E; ++I) {
  391. if (const PathDiagnosticMacroPiece *MP =
  392. dyn_cast<PathDiagnosticMacroPiece>(*I)) {
  393. num = ProcessMacroPiece(os, *MP, num);
  394. continue;
  395. }
  396. if (PathDiagnosticEventPiece *EP = dyn_cast<PathDiagnosticEventPiece>(*I)) {
  397. os << "<div class=\"msg msgEvent\" style=\"width:94%; "
  398. "margin-left:5px\">"
  399. "<table class=\"msgT\"><tr>"
  400. "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
  401. EmitAlphaCounter(os, num++);
  402. os << "</div></td><td valign=\"top\">"
  403. << html::EscapeText(EP->getString())
  404. << "</td></tr></table></div>\n";
  405. }
  406. }
  407. return num;
  408. }
  409. void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
  410. SourceRange Range,
  411. const char *HighlightStart,
  412. const char *HighlightEnd) {
  413. SourceManager &SM = R.getSourceMgr();
  414. const LangOptions &LangOpts = R.getLangOpts();
  415. SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
  416. unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
  417. SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
  418. unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
  419. if (EndLineNo < StartLineNo)
  420. return;
  421. if (SM.getFileID(InstantiationStart) != BugFileID ||
  422. SM.getFileID(InstantiationEnd) != BugFileID)
  423. return;
  424. // Compute the column number of the end.
  425. unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
  426. unsigned OldEndColNo = EndColNo;
  427. if (EndColNo) {
  428. // Add in the length of the token, so that we cover multi-char tokens.
  429. EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
  430. }
  431. // Highlight the range. Make the span tag the outermost tag for the
  432. // selected range.
  433. SourceLocation E =
  434. InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
  435. html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);
  436. }