1 //===- lib/DebugInfo/Symbolize/DIPrinter.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 defines the DIPrinter class, which is responsible for printing
10 // structures defined in DebugInfo/DIContext.h
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/DebugInfo/Symbolize/DIPrinter.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/DebugInfo/DIContext.h"
17 #include "llvm/Support/ErrorOr.h"
18 #include "llvm/Support/Format.h"
19 #include "llvm/Support/LineIterator.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <algorithm>
24 #include <cmath>
25 #include <cstddef>
26 #include <cstdint>
27 #include <memory>
28 #include <string>
29 
30 namespace llvm {
31 namespace symbolize {
32 
33 class SourceCode {
34   std::unique_ptr<MemoryBuffer> MemBuf;
35 
36   const Optional<StringRef> load(StringRef FileName,
37                                  const Optional<StringRef> &EmbeddedSource) {
38     if (Lines <= 0)
39       return None;
40 
41     if (EmbeddedSource)
42       return EmbeddedSource;
43     else {
44       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
45           MemoryBuffer::getFile(FileName);
46       if (!BufOrErr)
47         return None;
48       MemBuf = std::move(*BufOrErr);
49       return MemBuf->getBuffer();
50     }
51   }
52 
53   const Optional<StringRef> pruneSource(const Optional<StringRef> &Source) {
54     if (!Source)
55       return None;
56     size_t FirstLinePos = StringRef::npos, Pos = 0;
57     for (int64_t L = 1; L <= LastLine; ++L, ++Pos) {
58       if (L == FirstLine)
59         FirstLinePos = Pos;
60       Pos = Source->find('\n', Pos);
61       if (Pos == StringRef::npos)
62         break;
63     }
64     if (FirstLinePos == StringRef::npos)
65       return None;
66     return Source->substr(FirstLinePos, (Pos == StringRef::npos)
67                                             ? StringRef::npos
68                                             : Pos - FirstLinePos);
69   }
70 
71 public:
72   const int64_t Line;
73   const int Lines;
74   const int64_t FirstLine;
75   const int64_t LastLine;
76   const Optional<StringRef> PrunedSource;
77 
78   SourceCode(
79       StringRef FileName, int64_t Line, int Lines,
80       const Optional<StringRef> &EmbeddedSource = Optional<StringRef>(None))
81       : Line(Line), Lines(Lines),
82         FirstLine(std::max(static_cast<int64_t>(1), Line - Lines / 2)),
83         LastLine(FirstLine + Lines - 1),
84         PrunedSource(pruneSource(load(FileName, EmbeddedSource))) {}
85 };
86 
87 void PlainPrinterBase::printHeader(uint64_t Address) {
88   if (Config.PrintAddress) {
89     OS << "0x";
90     OS.write_hex(Address);
91     StringRef Delimiter = Config.Pretty ? ": " : "\n";
92     OS << Delimiter;
93   }
94 }
95 
96 // Prints source code around in the FileName the Line.
97 void PlainPrinterBase::printContext(SourceCode SourceCode) {
98   if (!SourceCode.PrunedSource)
99     return;
100 
101   StringRef Source = *SourceCode.PrunedSource;
102   std::string SourceCopy;
103   if (*Source.end() != '\0') {
104     SourceCopy = Source.str();
105     Source = SourceCopy;
106   }
107 
108   size_t MaxLineNumberWidth = std::ceil(std::log10(SourceCode.LastLine));
109   for (line_iterator I = line_iterator(MemoryBufferRef(Source, ""), false);
110        !I.is_at_eof(); ++I) {
111     int64_t L = SourceCode.FirstLine + I.line_number() - 1;
112     OS << format_decimal(L, MaxLineNumberWidth);
113     if (L == SourceCode.Line)
114       OS << " >: ";
115     else
116       OS << "  : ";
117     OS << *I << '\n';
118   }
119 }
120 
121 void PlainPrinterBase::printFunctionName(StringRef FunctionName, bool Inlined) {
122   if (Config.PrintFunctions) {
123     if (FunctionName == DILineInfo::BadString)
124       FunctionName = DILineInfo::Addr2LineBadString;
125     StringRef Delimiter = Config.Pretty ? " at " : "\n";
126     StringRef Prefix = (Config.Pretty && Inlined) ? " (inlined by) " : "";
127     OS << Prefix << FunctionName << Delimiter;
128   }
129 }
130 
131 void LLVMPrinter::printSimpleLocation(StringRef Filename,
132                                       const DILineInfo &Info) {
133   OS << Filename << ':' << Info.Line << ':' << Info.Column << '\n';
134   printContext(SourceCode(Filename, Info.Line, Config.SourceContextLines));
135 }
136 
137 void GNUPrinter::printSimpleLocation(StringRef Filename,
138                                      const DILineInfo &Info) {
139   OS << Filename << ':' << Info.Line;
140   if (Info.Discriminator)
141     OS << " (discriminator " << Info.Discriminator << ')';
142   OS << '\n';
143   printContext(SourceCode(Filename, Info.Line, Config.SourceContextLines));
144 }
145 
146 void PlainPrinterBase::printVerbose(StringRef Filename,
147                                     const DILineInfo &Info) {
148   OS << "  Filename: " << Filename << '\n';
149   if (Info.StartLine) {
150     OS << "  Function start filename: " << Info.StartFileName << '\n';
151     OS << "  Function start line: " << Info.StartLine << '\n';
152   }
153   OS << "  Line: " << Info.Line << '\n';
154   OS << "  Column: " << Info.Column << '\n';
155   if (Info.Discriminator)
156     OS << "  Discriminator: " << Info.Discriminator << '\n';
157 }
158 
159 void LLVMPrinter::printFooter() { OS << '\n'; }
160 
161 void PlainPrinterBase::print(const DILineInfo &Info, bool Inlined) {
162   printFunctionName(Info.FunctionName, Inlined);
163   StringRef Filename = Info.FileName;
164   if (Filename == DILineInfo::BadString)
165     Filename = DILineInfo::Addr2LineBadString;
166   if (Config.Verbose)
167     printVerbose(Filename, Info);
168   else
169     printSimpleLocation(Filename, Info);
170 }
171 
172 void PlainPrinterBase::print(const Request &Request, const DILineInfo &Info) {
173   printHeader(*Request.Address);
174   print(Info, false);
175   printFooter();
176 }
177 
178 void PlainPrinterBase::print(const Request &Request,
179                              const DIInliningInfo &Info) {
180   printHeader(*Request.Address);
181   uint32_t FramesNum = Info.getNumberOfFrames();
182   if (FramesNum == 0)
183     print(DILineInfo(), false);
184   else
185     for (uint32_t I = 0; I < FramesNum; ++I)
186       print(Info.getFrame(I), I > 0);
187   printFooter();
188 }
189 
190 void PlainPrinterBase::print(const Request &Request, const DIGlobal &Global) {
191   printHeader(*Request.Address);
192   StringRef Name = Global.Name;
193   if (Name == DILineInfo::BadString)
194     Name = DILineInfo::Addr2LineBadString;
195   OS << Name << "\n";
196   OS << Global.Start << " " << Global.Size << "\n";
197   printFooter();
198 }
199 
200 void PlainPrinterBase::print(const Request &Request,
201                              const std::vector<DILocal> &Locals) {
202   printHeader(*Request.Address);
203   if (Locals.empty())
204     OS << DILineInfo::Addr2LineBadString << '\n';
205   else
206     for (const DILocal &L : Locals) {
207       if (L.FunctionName.empty())
208         OS << DILineInfo::Addr2LineBadString;
209       else
210         OS << L.FunctionName;
211       OS << '\n';
212 
213       if (L.Name.empty())
214         OS << DILineInfo::Addr2LineBadString;
215       else
216         OS << L.Name;
217       OS << '\n';
218 
219       if (L.DeclFile.empty())
220         OS << DILineInfo::Addr2LineBadString;
221       else
222         OS << L.DeclFile;
223 
224       OS << ':' << L.DeclLine << '\n';
225 
226       if (L.FrameOffset)
227         OS << *L.FrameOffset;
228       else
229         OS << DILineInfo::Addr2LineBadString;
230       OS << ' ';
231 
232       if (L.Size)
233         OS << *L.Size;
234       else
235         OS << DILineInfo::Addr2LineBadString;
236       OS << ' ';
237 
238       if (L.TagOffset)
239         OS << *L.TagOffset;
240       else
241         OS << DILineInfo::Addr2LineBadString;
242       OS << '\n';
243     }
244   printFooter();
245 }
246 
247 void PlainPrinterBase::printInvalidCommand(const Request &Request,
248                                            StringRef Command) {
249   OS << Command << '\n';
250 }
251 
252 bool PlainPrinterBase::printError(const Request &Request,
253                                   const ErrorInfoBase &ErrorInfo,
254                                   StringRef ErrorBanner) {
255   ES << ErrorBanner;
256   ErrorInfo.log(ES);
257   ES << '\n';
258   // Print an empty struct too.
259   return true;
260 }
261 
262 static std::string toHex(uint64_t V) {
263   return ("0x" + Twine::utohexstr(V)).str();
264 }
265 
266 static json::Object toJSON(const Request &Request, StringRef ErrorMsg = "") {
267   json::Object Json({{"ModuleName", Request.ModuleName.str()}});
268   if (Request.Address)
269     Json["Address"] = toHex(*Request.Address);
270   if (!ErrorMsg.empty())
271     Json["Error"] = json::Object({{"Message", ErrorMsg.str()}});
272   return Json;
273 }
274 
275 void JSONPrinter::print(const Request &Request, const DILineInfo &Info) {
276   DIInliningInfo InliningInfo;
277   InliningInfo.addFrame(Info);
278   print(Request, InliningInfo);
279 }
280 
281 void JSONPrinter::print(const Request &Request, const DIInliningInfo &Info) {
282   json::Array Array;
283   for (uint32_t I = 0, N = Info.getNumberOfFrames(); I < N; ++I) {
284     const DILineInfo &LineInfo = Info.getFrame(I);
285     Array.push_back(json::Object(
286         {{"FunctionName", LineInfo.FunctionName != DILineInfo::BadString
287                               ? LineInfo.FunctionName
288                               : ""},
289          {"StartFileName", LineInfo.StartFileName != DILineInfo::BadString
290                                ? LineInfo.StartFileName
291                                : ""},
292          {"StartLine", LineInfo.StartLine},
293          {"FileName",
294           LineInfo.FileName != DILineInfo::BadString ? LineInfo.FileName : ""},
295          {"Line", LineInfo.Line},
296          {"Column", LineInfo.Column},
297          {"Discriminator", LineInfo.Discriminator}}));
298   }
299   json::Object Json = toJSON(Request);
300   Json["Symbol"] = std::move(Array);
301   if (ObjectList)
302     ObjectList->push_back(std::move(Json));
303   else
304     printJSON(std::move(Json));
305 }
306 
307 void JSONPrinter::print(const Request &Request, const DIGlobal &Global) {
308   json::Object Data(
309       {{"Name", Global.Name != DILineInfo::BadString ? Global.Name : ""},
310        {"Start", toHex(Global.Start)},
311        {"Size", toHex(Global.Size)}});
312   json::Object Json = toJSON(Request);
313   Json["Data"] = std::move(Data);
314   if (ObjectList)
315     ObjectList->push_back(std::move(Json));
316   else
317     printJSON(std::move(Json));
318 }
319 
320 void JSONPrinter::print(const Request &Request,
321                         const std::vector<DILocal> &Locals) {
322   json::Array Frame;
323   for (const DILocal &Local : Locals) {
324     json::Object FrameObject(
325         {{"FunctionName", Local.FunctionName},
326          {"Name", Local.Name},
327          {"DeclFile", Local.DeclFile},
328          {"DeclLine", int64_t(Local.DeclLine)},
329          {"Size", Local.Size ? toHex(*Local.Size) : ""},
330          {"TagOffset", Local.TagOffset ? toHex(*Local.TagOffset) : ""}});
331     if (Local.FrameOffset)
332       FrameObject["FrameOffset"] = *Local.FrameOffset;
333     Frame.push_back(std::move(FrameObject));
334   }
335   json::Object Json = toJSON(Request);
336   Json["Frame"] = std::move(Frame);
337   if (ObjectList)
338     ObjectList->push_back(std::move(Json));
339   else
340     printJSON(std::move(Json));
341 }
342 
343 void JSONPrinter::printInvalidCommand(const Request &Request,
344                                       StringRef Command) {
345   printError(Request,
346              StringError("unable to parse arguments: " + Command,
347                          std::make_error_code(std::errc::invalid_argument)),
348              "");
349 }
350 
351 bool JSONPrinter::printError(const Request &Request,
352                              const ErrorInfoBase &ErrorInfo,
353                              StringRef ErrorBanner) {
354   json::Object Json = toJSON(Request, ErrorInfo.message());
355   if (ObjectList)
356     ObjectList->push_back(std::move(Json));
357   else
358     printJSON(std::move(Json));
359   return false;
360 }
361 
362 void JSONPrinter::listBegin() {
363   assert(!ObjectList);
364   ObjectList = std::make_unique<json::Array>();
365 }
366 
367 void JSONPrinter::listEnd() {
368   assert(ObjectList);
369   printJSON(std::move(*ObjectList));
370   ObjectList.reset();
371 }
372 
373 } // end namespace symbolize
374 } // end namespace llvm
375