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