HTMLDiagnostics.cpp 19 KB

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