1 //===-- HTMLLogger.cpp ----------------------------------------------------===//
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 implements the HTML logger. Given a directory dir/, we write
10 // dir/0.html for the first analysis, etc.
11 // These files contain a visualization that allows inspecting the CFG and the
12 // state of the analysis at each point.
13 // Static assets (HTMLLogger.js, HTMLLogger.css) and SVG graphs etc are embedded
14 // so each output file is self-contained.
15 //
16 // VIEWS
17 //
18 // The timeline and function view are always shown. These allow selecting basic
19 // blocks, statements within them, and processing iterations (BBs are visited
20 // multiple times when e.g. loops are involved).
21 // These are written directly into the HTML body.
22 //
23 // There are also listings of particular basic blocks, and dumps of the state
24 // at particular analysis points (i.e. BB2 iteration 3 statement 2).
25 // These are only shown when the relevant BB/analysis point is *selected*.
26 //
27 // DATA AND TEMPLATES
28 //
29 // The HTML proper is mostly static.
30 // The analysis data is in a JSON object HTMLLoggerData which is embedded as
31 // a <script> in the <head>.
32 // This gets rendered into DOM by a simple template processor which substitutes
33 // the data into <template> tags embedded in the HTML. (see inflate() in JS).
34 //
35 // SELECTION
36 //
37 // This is the only real interactive mechanism.
38 //
39 // At any given time, there are several named selections, e.g.:
40 //   bb: B2               (basic block 0 is selected)
41 //   elt: B2.4            (statement 4 is selected)
42 //   iter: B2:1           (iteration 1 of the basic block is selected)
43 //   hover: B3            (hovering over basic block 3)
44 //
45 // The selection is updated by mouse events: hover by moving the mouse and
46 // others by clicking. Elements that are click targets generally have attributes
47 // (id or data-foo) that define what they should select.
48 // See watchSelection() in JS for the exact logic.
49 //
50 // When the "bb" selection is set to "B2":
51 //   - sections <section data-selection="bb"> get shown
52 //   - templates under such sections get re-rendered
53 //   - elements with class/id "B2" get class "bb-select"
54 //
55 //===----------------------------------------------------------------------===//
56 
57 #include "clang/Analysis/FlowSensitive/ControlFlowContext.h"
58 #include "clang/Analysis/FlowSensitive/DebugSupport.h"
59 #include "clang/Analysis/FlowSensitive/Logger.h"
60 #include "clang/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.h"
61 #include "clang/Analysis/FlowSensitive/Value.h"
62 #include "clang/Basic/SourceManager.h"
63 #include "clang/Lex/Lexer.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/ScopeExit.h"
66 #include "llvm/Support/Error.h"
67 #include "llvm/Support/FormatVariadic.h"
68 #include "llvm/Support/JSON.h"
69 #include "llvm/Support/Program.h"
70 #include "llvm/Support/ScopedPrinter.h"
71 #include "llvm/Support/raw_ostream.h"
72 // Defines assets: HTMLLogger_{html_js,css}
73 #include "HTMLLogger.inc"
74 
75 namespace clang::dataflow {
76 namespace {
77 
78 // Render a graphviz graph specification to SVG using the `dot` tool.
79 llvm::Expected<std::string> renderSVG(llvm::StringRef DotGraph);
80 
81 using StreamFactory = std::function<std::unique_ptr<llvm::raw_ostream>()>;
82 
83 // Recursively dumps Values/StorageLocations as JSON
84 class ModelDumper {
85 public:
86   ModelDumper(llvm::json::OStream &JOS, const Environment &Env)
87       : JOS(JOS), Env(Env) {}
88 
89   void dump(Value &V) {
90     JOS.attribute("value_id", llvm::to_string(&V));
91     if (!Visited.insert(&V).second)
92       return;
93 
94     JOS.attribute("kind", debugString(V.getKind()));
95 
96     switch (V.getKind()) {
97     case Value::Kind::Integer:
98     case Value::Kind::TopBool:
99     case Value::Kind::AtomicBool:
100     case Value::Kind::FormulaBool:
101       break;
102     case Value::Kind::Reference:
103       JOS.attributeObject(
104           "referent", [&] { dump(cast<ReferenceValue>(V).getReferentLoc()); });
105       break;
106     case Value::Kind::Pointer:
107       JOS.attributeObject(
108           "pointee", [&] { dump(cast<PointerValue>(V).getPointeeLoc()); });
109       break;
110     case Value::Kind::Struct:
111       for (const auto &Child :
112            cast<StructValue>(V).getAggregateLoc().children())
113         JOS.attributeObject("f:" + Child.first->getNameAsString(), [&] {
114           if (Child.second)
115             if (Value *Val = Env.getValue(*Child.second))
116               dump(*Val);
117         });
118       break;
119     }
120 
121     for (const auto& Prop : V.properties())
122       JOS.attributeObject(("p:" + Prop.first()).str(),
123                           [&] { dump(*Prop.second); });
124 
125     // Running the SAT solver is expensive, but knowing which booleans are
126     // guaranteed true/false here is valuable and hard to determine by hand.
127     if (auto *B = llvm::dyn_cast<BoolValue>(&V)) {
128       JOS.attribute("formula", llvm::to_string(B->formula()));
129       JOS.attribute(
130           "truth", Env.flowConditionImplies(B->formula()) ? "true"
131                    : Env.flowConditionImplies(Env.arena().makeNot(B->formula()))
132                        ? "false"
133                        : "unknown");
134     }
135   }
136   void dump(const StorageLocation &L) {
137     JOS.attribute("location", llvm::to_string(&L));
138     if (!Visited.insert(&L).second)
139       return;
140 
141     JOS.attribute("type", L.getType().getAsString());
142     if (auto *V = Env.getValue(L))
143       dump(*V);
144   }
145 
146   llvm::DenseSet<const void*> Visited;
147   llvm::json::OStream &JOS;
148   const Environment &Env;
149 };
150 
151 class HTMLLogger : public Logger {
152   StreamFactory Streams;
153   std::unique_ptr<llvm::raw_ostream> OS;
154   std::optional<llvm::json::OStream> JOS;
155 
156   const ControlFlowContext *CFG;
157   // Timeline of iterations of CFG block visitation.
158   std::vector<std::pair<const CFGBlock *, unsigned>> Iters;
159   // Number of times each CFG block has been seen.
160   llvm::DenseMap<const CFGBlock *, unsigned> BlockIters;
161   // The messages logged in the current context but not yet written.
162   std::string ContextLogs;
163   // The number of elements we have visited within the current CFG block.
164   unsigned ElementIndex;
165 
166 public:
167   explicit HTMLLogger(StreamFactory Streams) : Streams(std::move(Streams)) {}
168   void beginAnalysis(const ControlFlowContext &CFG,
169                      TypeErasedDataflowAnalysis &A) override {
170     OS = Streams();
171     this->CFG = &CFG;
172     *OS << llvm::StringRef(HTMLLogger_html).split("<?INJECT?>").first;
173 
174     if (const auto *D = CFG.getDecl()) {
175       const auto &SM = A.getASTContext().getSourceManager();
176       *OS << "<title>";
177       if (const auto *ND = dyn_cast<NamedDecl>(D))
178         *OS << ND->getNameAsString() << " at ";
179       *OS << SM.getFilename(D->getLocation()) << ":"
180           << SM.getSpellingLineNumber(D->getLocation());
181       *OS << "</title>\n";
182     };
183 
184     *OS << "<style>" << HTMLLogger_css << "</style>\n";
185     *OS << "<script>" << HTMLLogger_js << "</script>\n";
186 
187     writeCode();
188     writeCFG();
189 
190     *OS << "<script>var HTMLLoggerData = \n";
191     JOS.emplace(*OS, /*Indent=*/2);
192     JOS->objectBegin();
193     JOS->attributeBegin("states");
194     JOS->objectBegin();
195   }
196   // Between beginAnalysis() and endAnalysis() we write all the states for
197   // particular analysis points into the `timeline` array.
198   void endAnalysis() override {
199     JOS->objectEnd();
200     JOS->attributeEnd();
201 
202     JOS->attributeArray("timeline", [&] {
203       for (const auto &E : Iters) {
204         JOS->object([&] {
205           JOS->attribute("block", blockID(E.first->getBlockID()));
206           JOS->attribute("iter", E.second);
207         });
208       }
209     });
210     JOS->attributeObject("cfg", [&] {
211       for (const auto &E : BlockIters)
212         writeBlock(*E.first, E.second);
213     });
214 
215     JOS->objectEnd();
216     JOS.reset();
217     *OS << ";\n</script>\n";
218     *OS << llvm::StringRef(HTMLLogger_html).split("<?INJECT?>").second;
219   }
220 
221   void enterBlock(const CFGBlock &B) override {
222     Iters.emplace_back(&B, ++BlockIters[&B]);
223     ElementIndex = 0;
224   }
225   void enterElement(const CFGElement &E) override {
226     ++ElementIndex;
227   }
228 
229   static std::string blockID(unsigned Block) {
230     return llvm::formatv("B{0}", Block);
231   }
232   static std::string eltID(unsigned Block, unsigned Element) {
233     return llvm::formatv("B{0}.{1}", Block, Element);
234   }
235   static std::string iterID(unsigned Block, unsigned Iter) {
236     return llvm::formatv("B{0}:{1}", Block, Iter);
237   }
238   static std::string elementIterID(unsigned Block, unsigned Iter,
239                                    unsigned Element) {
240     return llvm::formatv("B{0}:{1}_B{0}.{2}", Block, Iter, Element);
241   }
242 
243   // Write the analysis state associated with a particular analysis point.
244   // FIXME: this dump is fairly opaque. We should show:
245   //  - values associated with the current Stmt
246   //  - values associated with its children
247   //  - meaningful names for values
248   //  - which boolean values are implied true/false by the flow condition
249   void recordState(TypeErasedDataflowAnalysisState &State) override {
250     unsigned Block = Iters.back().first->getBlockID();
251     unsigned Iter = Iters.back().second;
252     JOS->attributeObject(elementIterID(Block, Iter, ElementIndex), [&] {
253       JOS->attribute("block", blockID(Block));
254       JOS->attribute("iter", Iter);
255       JOS->attribute("element", ElementIndex);
256 
257       // If this state immediately follows an Expr, show its built-in model.
258       if (ElementIndex > 0) {
259         auto S =
260             Iters.back().first->Elements[ElementIndex - 1].getAs<CFGStmt>();
261         if (const Expr *E = S ? llvm::dyn_cast<Expr>(S->getStmt()) : nullptr)
262           if (auto *Loc = State.Env.getStorageLocation(*E, SkipPast::None))
263             JOS->attributeObject(
264                 "value", [&] { ModelDumper(*JOS, State.Env).dump(*Loc); });
265       }
266       if (!ContextLogs.empty()) {
267         JOS->attribute("logs", ContextLogs);
268         ContextLogs.clear();
269       }
270       {
271         std::string BuiltinLattice;
272         llvm::raw_string_ostream BuiltinLatticeS(BuiltinLattice);
273         State.Env.dump(BuiltinLatticeS);
274         JOS->attribute("builtinLattice", BuiltinLattice);
275       }
276     });
277   }
278   void blockConverged() override { logText("Block converged"); }
279 
280   void logText(llvm::StringRef S) override {
281     ContextLogs.append(S.begin(), S.end());
282     ContextLogs.push_back('\n');
283   }
284 
285 private:
286   // Write the CFG block details.
287   // Currently this is just the list of elements in execution order.
288   // FIXME: an AST dump would be a useful view, too.
289   void writeBlock(const CFGBlock &B, unsigned Iters) {
290     JOS->attributeObject(blockID(B.getBlockID()), [&] {
291       JOS->attribute("iters", Iters);
292       JOS->attributeArray("elements", [&] {
293         for (const auto &Elt : B.Elements) {
294           std::string Dump;
295           llvm::raw_string_ostream DumpS(Dump);
296           Elt.dumpToStream(DumpS);
297           JOS->value(Dump);
298         }
299       });
300     });
301   }
302 
303   // Write the code of function being examined.
304   // We want to overlay the code with <span>s that mark which BB particular
305   // tokens are associated with, and even which BB element (so that clicking
306   // can select the right element).
307   void writeCode() {
308     if (!CFG->getDecl())
309       return;
310     const auto &AST = CFG->getDecl()->getASTContext();
311     bool Invalid = false;
312 
313     // Extract the source code from the original file.
314     // Pretty-printing from the AST would probably be nicer (no macros or
315     // indentation to worry about), but we need the boundaries of particular
316     // AST nodes and the printer doesn't provide this.
317     auto Range = clang::Lexer::makeFileCharRange(
318         CharSourceRange::getTokenRange(CFG->getDecl()->getSourceRange()),
319         AST.getSourceManager(), AST.getLangOpts());
320     if (Range.isInvalid())
321       return;
322     llvm::StringRef Code = clang::Lexer::getSourceText(
323         Range, AST.getSourceManager(), AST.getLangOpts(), &Invalid);
324     if (Invalid)
325       return;
326 
327     static constexpr unsigned Missing = -1;
328     // TokenInfo stores the BB and set of elements that a token is part of.
329     struct TokenInfo {
330       // The basic block this is part of.
331       // This is the BB of the stmt with the smallest containing range.
332       unsigned BB = Missing;
333       unsigned BBPriority = 0;
334       // The most specific stmt this is part of (smallest range).
335       unsigned Elt = Missing;
336       unsigned EltPriority = 0;
337       // All stmts this is part of.
338       SmallVector<unsigned> Elts;
339 
340       // Mark this token as being part of BB.Elt.
341       // RangeLen is the character length of the element's range, used to
342       // distinguish inner vs outer statements.
343       // For example in `a==0`, token "a" is part of the stmts "a" and "a==0".
344       // However "a" has a smaller range, so is more specific. Clicking on the
345       // token "a" should select the stmt "a".
346       void assign(unsigned BB, unsigned Elt, unsigned RangeLen) {
347         // A worse BB (larger range) => ignore.
348         if (this->BB != Missing && BB != this->BB && BBPriority <= RangeLen)
349           return;
350         if (BB != this->BB) {
351           this->BB = BB;
352           Elts.clear();
353           BBPriority = RangeLen;
354         }
355         BBPriority = std::min(BBPriority, RangeLen);
356         Elts.push_back(Elt);
357         if (this->Elt == Missing || EltPriority > RangeLen)
358           this->Elt = Elt;
359       }
360       bool operator==(const TokenInfo &Other) const {
361         return std::tie(BB, Elt, Elts) ==
362                std::tie(Other.BB, Other.Elt, Other.Elts);
363       }
364       // Write the attributes for the <span> on this token.
365       void write(llvm::raw_ostream &OS) const {
366         OS << "class='c";
367         if (BB != Missing)
368           OS << " " << blockID(BB);
369         for (unsigned Elt : Elts)
370           OS << " " << eltID(BB, Elt);
371         OS << "'";
372 
373         if (Elt != Missing)
374           OS << " data-elt='" << eltID(BB, Elt) << "'";
375         if (BB != Missing)
376           OS << " data-bb='" << blockID(BB) << "'";
377       }
378     };
379 
380     // Construct one TokenInfo per character in a flat array.
381     // This is inefficient (chars in a token all have the same info) but simple.
382     std::vector<TokenInfo> State(Code.size());
383     for (const auto *Block : CFG->getCFG()) {
384       unsigned EltIndex = 0;
385       for (const auto& Elt : *Block) {
386         ++EltIndex;
387         if (const auto S = Elt.getAs<CFGStmt>()) {
388           auto EltRange = clang::Lexer::makeFileCharRange(
389               CharSourceRange::getTokenRange(S->getStmt()->getSourceRange()),
390               AST.getSourceManager(), AST.getLangOpts());
391           if (EltRange.isInvalid())
392             continue;
393           if (EltRange.getBegin() < Range.getBegin() ||
394               EltRange.getEnd() >= Range.getEnd() ||
395               EltRange.getEnd() < Range.getBegin() ||
396               EltRange.getEnd() >= Range.getEnd())
397             continue;
398           unsigned Off = EltRange.getBegin().getRawEncoding() -
399                          Range.getBegin().getRawEncoding();
400           unsigned Len = EltRange.getEnd().getRawEncoding() -
401                          EltRange.getBegin().getRawEncoding();
402           for (unsigned I = 0; I < Len; ++I)
403             State[Off + I].assign(Block->getBlockID(), EltIndex, Len);
404         }
405       }
406     }
407 
408     // Finally, write the code with the correct <span>s.
409     unsigned Line =
410         AST.getSourceManager().getSpellingLineNumber(Range.getBegin());
411     *OS << "<template data-copy='code'>\n";
412     *OS << "<code class='filename'>";
413     llvm::printHTMLEscaped(
414         llvm::sys::path::filename(
415             AST.getSourceManager().getFilename(Range.getBegin())),
416         *OS);
417     *OS << "</code>";
418     *OS << "<code class='line' data-line='" << Line++ << "'>";
419     for (unsigned I = 0; I < Code.size(); ++I) {
420       // Don't actually write a <span> around each character, only break spans
421       // when the TokenInfo changes.
422       bool NeedOpen = I == 0 || !(State[I] == State[I-1]);
423       bool NeedClose = I + 1 == Code.size() || !(State[I] == State[I + 1]);
424       if (NeedOpen) {
425         *OS << "<span ";
426         State[I].write(*OS);
427         *OS << ">";
428       }
429       if (Code[I] == '\n')
430         *OS << "</code>\n<code class='line' data-line='" << Line++ << "'>";
431       else
432         llvm::printHTMLEscaped(Code.substr(I, 1), *OS);
433       if (NeedClose) *OS << "</span>";
434     }
435     *OS << "</code>\n";
436     *OS << "</template>";
437   }
438 
439   // Write the CFG diagram, a graph of basic blocks.
440   // Laying out graphs is hard, so we construct a graphviz description and shell
441   // out to `dot` to turn it into an SVG.
442   void writeCFG() {
443     *OS << "<template data-copy='cfg'>\n";
444     if (auto SVG = renderSVG(buildCFGDot(CFG->getCFG())))
445       *OS << *SVG;
446     else
447       *OS << "Can't draw CFG: " << toString(SVG.takeError());
448     *OS << "</template>\n";
449   }
450 
451   // Produce a graphviz description of a CFG.
452   static std::string buildCFGDot(const clang::CFG &CFG) {
453     std::string Graph;
454     llvm::raw_string_ostream GraphS(Graph);
455     // Graphviz likes to add unhelpful tooltips everywhere, " " suppresses.
456     GraphS << R"(digraph {
457       tooltip=" "
458       node[class=bb, shape=square, fontname="sans-serif", tooltip=" "]
459       edge[tooltip = " "]
460 )";
461     for (unsigned I = 0; I < CFG.getNumBlockIDs(); ++I)
462       GraphS << "  " << blockID(I) << " [id=" << blockID(I) << "]\n";
463     for (const auto *Block : CFG) {
464       for (const auto &Succ : Block->succs()) {
465         GraphS << "  " << blockID(Block->getBlockID()) << " -> "
466                << blockID(Succ.getReachableBlock()->getBlockID()) << "\n";
467       }
468     }
469     GraphS << "}\n";
470     return Graph;
471   }
472 };
473 
474 // Nothing interesting here, just subprocess/temp-file plumbing.
475 llvm::Expected<std::string> renderSVG(llvm::StringRef DotGraph) {
476   std::string DotPath;
477   if (const auto *FromEnv = ::getenv("GRAPHVIZ_DOT"))
478     DotPath = FromEnv;
479   else {
480     auto FromPath = llvm::sys::findProgramByName("dot");
481     if (!FromPath)
482       return llvm::createStringError(FromPath.getError(),
483                                      "'dot' not found on PATH");
484     DotPath = FromPath.get();
485   }
486 
487   // Create input and output files for `dot` subprocess.
488   // (We create the output file as empty, to reserve the temp filename).
489   llvm::SmallString<256> Input, Output;
490   int InputFD;
491   if (auto EC = llvm::sys::fs::createTemporaryFile("analysis", ".dot", InputFD,
492                                                    Input))
493     return llvm::createStringError(EC, "failed to create `dot` temp input");
494   llvm::raw_fd_ostream(InputFD, /*shouldClose=*/true) << DotGraph;
495   auto DeleteInput =
496       llvm::make_scope_exit([&] { llvm::sys::fs::remove(Input); });
497   if (auto EC = llvm::sys::fs::createTemporaryFile("analysis", ".svg", Output))
498     return llvm::createStringError(EC, "failed to create `dot` temp output");
499   auto DeleteOutput =
500       llvm::make_scope_exit([&] { llvm::sys::fs::remove(Output); });
501 
502   std::vector<std::optional<llvm::StringRef>> Redirects = {
503       Input, Output,
504       /*stderr=*/std::nullopt};
505   std::string ErrMsg;
506   int Code = llvm::sys::ExecuteAndWait(
507       DotPath, {"dot", "-Tsvg"}, /*Env=*/std::nullopt, Redirects,
508       /*SecondsToWait=*/0, /*MemoryLimit=*/0, &ErrMsg);
509   if (!ErrMsg.empty())
510     return llvm::createStringError(llvm::inconvertibleErrorCode(),
511                                    "'dot' failed: " + ErrMsg);
512   if (Code != 0)
513     return llvm::createStringError(llvm::inconvertibleErrorCode(),
514                                    "'dot' failed (" + llvm::Twine(Code) + ")");
515 
516   auto Buf = llvm::MemoryBuffer::getFile(Output);
517   if (!Buf)
518     return llvm::createStringError(Buf.getError(), "Can't read `dot` output");
519 
520   // Output has <?xml> prefix we don't want. Skip to <svg> tag.
521   llvm::StringRef Result = Buf.get()->getBuffer();
522   auto Pos = Result.find("<svg");
523   if (Pos == llvm::StringRef::npos)
524     return llvm::createStringError(llvm::inconvertibleErrorCode(),
525                                    "Can't find <svg> tag in `dot` output");
526   return Result.substr(Pos).str();
527 }
528 
529 } // namespace
530 
531 std::unique_ptr<Logger>
532 Logger::html(std::function<std::unique_ptr<llvm::raw_ostream>()> Streams) {
533   return std::make_unique<HTMLLogger>(std::move(Streams));
534 }
535 
536 } // namespace clang::dataflow
537