HTMLDiagnostics.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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(NULL); }
  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<!-- FILENAME " << llvm::sys::path::filename(Entry->getName()) << " -->\n";
  170. os << "\n<!-- FUNCTIONNAME " << declName << " -->\n";
  171. os << "\n<!-- BUGLINE "
  172. << path.back()->getLocation().asLocation().getExpansionLineNumber()
  173. << " -->\n";
  174. os << "\n<!-- BUGCOLUMN "
  175. << path.back()->getLocation().asLocation().getExpansionColumnNumber()
  176. << " -->\n";
  177. os << "\n<!-- BUGPATHLENGTH " << path.size() << " -->\n";
  178. // Mark the end of the tags.
  179. os << "\n<!-- BUGMETAEND -->\n";
  180. // Insert the text.
  181. R.InsertTextBefore(SMgr.getLocForStartOfFile(FID), os.str());
  182. }
  183. // Add CSS, header, and footer.
  184. html::AddHeaderFooterInternalBuiltinCSS(R, FID, Entry->getName());
  185. // Get the rewrite buffer.
  186. const RewriteBuffer *Buf = R.getRewriteBufferFor(FID);
  187. if (!Buf) {
  188. llvm::errs() << "warning: no diagnostics generated for main file.\n";
  189. return;
  190. }
  191. // Create a path for the target HTML file.
  192. int FD;
  193. SmallString<128> Model, ResultPath;
  194. llvm::sys::path::append(Model, Directory, "report-%%%%%%.html");
  195. if (llvm::error_code EC =
  196. llvm::sys::fs::createUniqueFile(Model.str(), FD, ResultPath)) {
  197. llvm::errs() << "warning: could not create file in '" << Directory
  198. << "': " << EC.message() << '\n';
  199. return;
  200. }
  201. llvm::raw_fd_ostream os(FD, true);
  202. if (filesMade)
  203. filesMade->addDiagnostic(D, getName(),
  204. llvm::sys::path::filename(ResultPath));
  205. // Emit the HTML to disk.
  206. for (RewriteBuffer::iterator I = Buf->begin(), E = Buf->end(); I!=E; ++I)
  207. os << *I;
  208. }
  209. void HTMLDiagnostics::HandlePiece(Rewriter& R, FileID BugFileID,
  210. const PathDiagnosticPiece& P,
  211. unsigned num, unsigned max) {
  212. // For now, just draw a box above the line in question, and emit the
  213. // warning.
  214. FullSourceLoc Pos = P.getLocation().asLocation();
  215. if (!Pos.isValid())
  216. return;
  217. SourceManager &SM = R.getSourceMgr();
  218. assert(&Pos.getManager() == &SM && "SourceManagers are different!");
  219. std::pair<FileID, unsigned> LPosInfo = SM.getDecomposedExpansionLoc(Pos);
  220. if (LPosInfo.first != BugFileID)
  221. return;
  222. const llvm::MemoryBuffer *Buf = SM.getBuffer(LPosInfo.first);
  223. const char* FileStart = Buf->getBufferStart();
  224. // Compute the column number. Rewind from the current position to the start
  225. // of the line.
  226. unsigned ColNo = SM.getColumnNumber(LPosInfo.first, LPosInfo.second);
  227. const char *TokInstantiationPtr =Pos.getExpansionLoc().getCharacterData();
  228. const char *LineStart = TokInstantiationPtr-ColNo;
  229. // Compute LineEnd.
  230. const char *LineEnd = TokInstantiationPtr;
  231. const char* FileEnd = Buf->getBufferEnd();
  232. while (*LineEnd != '\n' && LineEnd != FileEnd)
  233. ++LineEnd;
  234. // Compute the margin offset by counting tabs and non-tabs.
  235. unsigned PosNo = 0;
  236. for (const char* c = LineStart; c != TokInstantiationPtr; ++c)
  237. PosNo += *c == '\t' ? 8 : 1;
  238. // Create the html for the message.
  239. const char *Kind = 0;
  240. switch (P.getKind()) {
  241. case PathDiagnosticPiece::Call:
  242. llvm_unreachable("Calls should already be handled");
  243. case PathDiagnosticPiece::Event: Kind = "Event"; break;
  244. case PathDiagnosticPiece::ControlFlow: Kind = "Control"; break;
  245. // Setting Kind to "Control" is intentional.
  246. case PathDiagnosticPiece::Macro: Kind = "Control"; break;
  247. }
  248. std::string sbuf;
  249. llvm::raw_string_ostream os(sbuf);
  250. os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\"";
  251. if (num == max)
  252. os << "EndPath";
  253. else
  254. os << "Path" << num;
  255. os << "\" class=\"msg";
  256. if (Kind)
  257. os << " msg" << Kind;
  258. os << "\" style=\"margin-left:" << PosNo << "ex";
  259. // Output a maximum size.
  260. if (!isa<PathDiagnosticMacroPiece>(P)) {
  261. // Get the string and determining its maximum substring.
  262. const std::string& Msg = P.getString();
  263. unsigned max_token = 0;
  264. unsigned cnt = 0;
  265. unsigned len = Msg.size();
  266. for (std::string::const_iterator I=Msg.begin(), E=Msg.end(); I!=E; ++I)
  267. switch (*I) {
  268. default:
  269. ++cnt;
  270. continue;
  271. case ' ':
  272. case '\t':
  273. case '\n':
  274. if (cnt > max_token) max_token = cnt;
  275. cnt = 0;
  276. }
  277. if (cnt > max_token)
  278. max_token = cnt;
  279. // Determine the approximate size of the message bubble in em.
  280. unsigned em;
  281. const unsigned max_line = 120;
  282. if (max_token >= max_line)
  283. em = max_token / 2;
  284. else {
  285. unsigned characters = max_line;
  286. unsigned lines = len / max_line;
  287. if (lines > 0) {
  288. for (; characters > max_token; --characters)
  289. if (len / characters > lines) {
  290. ++characters;
  291. break;
  292. }
  293. }
  294. em = characters / 2;
  295. }
  296. if (em < max_line/2)
  297. os << "; max-width:" << em << "em";
  298. }
  299. else
  300. os << "; max-width:100em";
  301. os << "\">";
  302. if (max > 1) {
  303. os << "<table class=\"msgT\"><tr><td valign=\"top\">";
  304. os << "<div class=\"PathIndex";
  305. if (Kind) os << " PathIndex" << Kind;
  306. os << "\">" << num << "</div>";
  307. if (num > 1) {
  308. os << "</td><td><div class=\"PathNav\"><a href=\"#Path"
  309. << (num - 1)
  310. << "\" title=\"Previous event ("
  311. << (num - 1)
  312. << ")\">&#x2190;</a></div></td>";
  313. }
  314. os << "</td><td>";
  315. }
  316. if (const PathDiagnosticMacroPiece *MP =
  317. dyn_cast<PathDiagnosticMacroPiece>(&P)) {
  318. os << "Within the expansion of the macro '";
  319. // Get the name of the macro by relexing it.
  320. {
  321. FullSourceLoc L = MP->getLocation().asLocation().getExpansionLoc();
  322. assert(L.isFileID());
  323. StringRef BufferInfo = L.getBufferData();
  324. std::pair<FileID, unsigned> LocInfo = L.getDecomposedLoc();
  325. const char* MacroName = LocInfo.second + BufferInfo.data();
  326. Lexer rawLexer(SM.getLocForStartOfFile(LocInfo.first), PP.getLangOpts(),
  327. BufferInfo.begin(), MacroName, BufferInfo.end());
  328. Token TheTok;
  329. rawLexer.LexFromRawLexer(TheTok);
  330. for (unsigned i = 0, n = TheTok.getLength(); i < n; ++i)
  331. os << MacroName[i];
  332. }
  333. os << "':\n";
  334. if (max > 1) {
  335. os << "</td>";
  336. if (num < max) {
  337. os << "<td><div class=\"PathNav\"><a href=\"#";
  338. if (num == max - 1)
  339. os << "EndPath";
  340. else
  341. os << "Path" << (num + 1);
  342. os << "\" title=\"Next event ("
  343. << (num + 1)
  344. << ")\">&#x2192;</a></div></td>";
  345. }
  346. os << "</tr></table>";
  347. }
  348. // Within a macro piece. Write out each event.
  349. ProcessMacroPiece(os, *MP, 0);
  350. }
  351. else {
  352. os << html::EscapeText(P.getString());
  353. if (max > 1) {
  354. os << "</td>";
  355. if (num < max) {
  356. os << "<td><div class=\"PathNav\"><a href=\"#";
  357. if (num == max - 1)
  358. os << "EndPath";
  359. else
  360. os << "Path" << (num + 1);
  361. os << "\" title=\"Next event ("
  362. << (num + 1)
  363. << ")\">&#x2192;</a></div></td>";
  364. }
  365. os << "</tr></table>";
  366. }
  367. }
  368. os << "</div></td></tr>";
  369. // Insert the new html.
  370. unsigned DisplayPos = LineEnd - FileStart;
  371. SourceLocation Loc =
  372. SM.getLocForStartOfFile(LPosInfo.first).getLocWithOffset(DisplayPos);
  373. R.InsertTextBefore(Loc, os.str());
  374. // Now highlight the ranges.
  375. ArrayRef<SourceRange> Ranges = P.getRanges();
  376. for (ArrayRef<SourceRange>::iterator I = Ranges.begin(),
  377. E = Ranges.end(); I != E; ++I) {
  378. HighlightRange(R, LPosInfo.first, *I);
  379. }
  380. }
  381. static void EmitAlphaCounter(raw_ostream &os, unsigned n) {
  382. unsigned x = n % ('z' - 'a');
  383. n /= 'z' - 'a';
  384. if (n > 0)
  385. EmitAlphaCounter(os, n);
  386. os << char('a' + x);
  387. }
  388. unsigned HTMLDiagnostics::ProcessMacroPiece(raw_ostream &os,
  389. const PathDiagnosticMacroPiece& P,
  390. unsigned num) {
  391. for (PathPieces::const_iterator I = P.subPieces.begin(), E=P.subPieces.end();
  392. I!=E; ++I) {
  393. if (const PathDiagnosticMacroPiece *MP =
  394. dyn_cast<PathDiagnosticMacroPiece>(*I)) {
  395. num = ProcessMacroPiece(os, *MP, num);
  396. continue;
  397. }
  398. if (PathDiagnosticEventPiece *EP = dyn_cast<PathDiagnosticEventPiece>(*I)) {
  399. os << "<div class=\"msg msgEvent\" style=\"width:94%; "
  400. "margin-left:5px\">"
  401. "<table class=\"msgT\"><tr>"
  402. "<td valign=\"top\"><div class=\"PathIndex PathIndexEvent\">";
  403. EmitAlphaCounter(os, num++);
  404. os << "</div></td><td valign=\"top\">"
  405. << html::EscapeText(EP->getString())
  406. << "</td></tr></table></div>\n";
  407. }
  408. }
  409. return num;
  410. }
  411. void HTMLDiagnostics::HighlightRange(Rewriter& R, FileID BugFileID,
  412. SourceRange Range,
  413. const char *HighlightStart,
  414. const char *HighlightEnd) {
  415. SourceManager &SM = R.getSourceMgr();
  416. const LangOptions &LangOpts = R.getLangOpts();
  417. SourceLocation InstantiationStart = SM.getExpansionLoc(Range.getBegin());
  418. unsigned StartLineNo = SM.getExpansionLineNumber(InstantiationStart);
  419. SourceLocation InstantiationEnd = SM.getExpansionLoc(Range.getEnd());
  420. unsigned EndLineNo = SM.getExpansionLineNumber(InstantiationEnd);
  421. if (EndLineNo < StartLineNo)
  422. return;
  423. if (SM.getFileID(InstantiationStart) != BugFileID ||
  424. SM.getFileID(InstantiationEnd) != BugFileID)
  425. return;
  426. // Compute the column number of the end.
  427. unsigned EndColNo = SM.getExpansionColumnNumber(InstantiationEnd);
  428. unsigned OldEndColNo = EndColNo;
  429. if (EndColNo) {
  430. // Add in the length of the token, so that we cover multi-char tokens.
  431. EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM, LangOpts)-1;
  432. }
  433. // Highlight the range. Make the span tag the outermost tag for the
  434. // selected range.
  435. SourceLocation E =
  436. InstantiationEnd.getLocWithOffset(EndColNo - OldEndColNo);
  437. html::HighlightRange(R, InstantiationStart, E, HighlightStart, HighlightEnd);
  438. }