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   printStartAddress(Info);
154   OS << "  Line: " << Info.Line << '\n';
155   OS << "  Column: " << Info.Column << '\n';
156   if (Info.Discriminator)
157     OS << "  Discriminator: " << Info.Discriminator << '\n';
158 }
159 
160 void LLVMPrinter::printStartAddress(const DILineInfo &Info) {
161   if (Info.StartAddress) {
162     OS << "  Function start address: 0x";
163     OS.write_hex(*Info.StartAddress);
164     OS << '\n';
165   }
166 }
167 
168 void LLVMPrinter::printFooter() { OS << '\n'; }
169 
170 void PlainPrinterBase::print(const DILineInfo &Info, bool Inlined) {
171   printFunctionName(Info.FunctionName, Inlined);
172   StringRef Filename = Info.FileName;
173   if (Filename == DILineInfo::BadString)
174     Filename = DILineInfo::Addr2LineBadString;
175   if (Config.Verbose)
176     printVerbose(Filename, Info);
177   else
178     printSimpleLocation(Filename, Info);
179 }
180 
181 void PlainPrinterBase::print(const Request &Request, const DILineInfo &Info) {
182   printHeader(*Request.Address);
183   print(Info, false);
184   printFooter();
185 }
186 
187 void PlainPrinterBase::print(const Request &Request,
188                              const DIInliningInfo &Info) {
189   printHeader(*Request.Address);
190   uint32_t FramesNum = Info.getNumberOfFrames();
191   if (FramesNum == 0)
192     print(DILineInfo(), false);
193   else
194     for (uint32_t I = 0; I < FramesNum; ++I)
195       print(Info.getFrame(I), I > 0);
196   printFooter();
197 }
198 
199 void PlainPrinterBase::print(const Request &Request, const DIGlobal &Global) {
200   printHeader(*Request.Address);
201   StringRef Name = Global.Name;
202   if (Name == DILineInfo::BadString)
203     Name = DILineInfo::Addr2LineBadString;
204   OS << Name << "\n";
205   OS << Global.Start << " " << Global.Size << "\n";
206   printFooter();
207 }
208 
209 void PlainPrinterBase::print(const Request &Request,
210                              const std::vector<DILocal> &Locals) {
211   printHeader(*Request.Address);
212   if (Locals.empty())
213     OS << DILineInfo::Addr2LineBadString << '\n';
214   else
215     for (const DILocal &L : Locals) {
216       if (L.FunctionName.empty())
217         OS << DILineInfo::Addr2LineBadString;
218       else
219         OS << L.FunctionName;
220       OS << '\n';
221 
222       if (L.Name.empty())
223         OS << DILineInfo::Addr2LineBadString;
224       else
225         OS << L.Name;
226       OS << '\n';
227 
228       if (L.DeclFile.empty())
229         OS << DILineInfo::Addr2LineBadString;
230       else
231         OS << L.DeclFile;
232 
233       OS << ':' << L.DeclLine << '\n';
234 
235       if (L.FrameOffset)
236         OS << *L.FrameOffset;
237       else
238         OS << DILineInfo::Addr2LineBadString;
239       OS << ' ';
240 
241       if (L.Size)
242         OS << *L.Size;
243       else
244         OS << DILineInfo::Addr2LineBadString;
245       OS << ' ';
246 
247       if (L.TagOffset)
248         OS << *L.TagOffset;
249       else
250         OS << DILineInfo::Addr2LineBadString;
251       OS << '\n';
252     }
253   printFooter();
254 }
255 
256 void PlainPrinterBase::printInvalidCommand(const Request &Request,
257                                            StringRef Command) {
258   OS << Command << '\n';
259 }
260 
261 bool PlainPrinterBase::printError(const Request &Request,
262                                   const ErrorInfoBase &ErrorInfo,
263                                   StringRef ErrorBanner) {
264   ES << ErrorBanner;
265   ErrorInfo.log(ES);
266   ES << '\n';
267   // Print an empty struct too.
268   return true;
269 }
270 
271 static std::string toHex(uint64_t V) {
272   return ("0x" + Twine::utohexstr(V)).str();
273 }
274 
275 static json::Object toJSON(const Request &Request, StringRef ErrorMsg = "") {
276   json::Object Json({{"ModuleName", Request.ModuleName.str()}});
277   if (Request.Address)
278     Json["Address"] = toHex(*Request.Address);
279   if (!ErrorMsg.empty())
280     Json["Error"] = json::Object({{"Message", ErrorMsg.str()}});
281   return Json;
282 }
283 
284 void JSONPrinter::print(const Request &Request, const DILineInfo &Info) {
285   DIInliningInfo InliningInfo;
286   InliningInfo.addFrame(Info);
287   print(Request, InliningInfo);
288 }
289 
290 void JSONPrinter::print(const Request &Request, const DIInliningInfo &Info) {
291   json::Array Array;
292   for (uint32_t I = 0, N = Info.getNumberOfFrames(); I < N; ++I) {
293     const DILineInfo &LineInfo = Info.getFrame(I);
294     Array.push_back(json::Object(
295         {{"FunctionName", LineInfo.FunctionName != DILineInfo::BadString
296                               ? LineInfo.FunctionName
297                               : ""},
298          {"StartFileName", LineInfo.StartFileName != DILineInfo::BadString
299                                ? LineInfo.StartFileName
300                                : ""},
301          {"StartLine", LineInfo.StartLine},
302          {"StartAddress",
303           LineInfo.StartAddress ? toHex(*LineInfo.StartAddress) : ""},
304          {"FileName",
305           LineInfo.FileName != DILineInfo::BadString ? LineInfo.FileName : ""},
306          {"Line", LineInfo.Line},
307          {"Column", LineInfo.Column},
308          {"Discriminator", LineInfo.Discriminator}}));
309   }
310   json::Object Json = toJSON(Request);
311   Json["Symbol"] = std::move(Array);
312   if (ObjectList)
313     ObjectList->push_back(std::move(Json));
314   else
315     printJSON(std::move(Json));
316 }
317 
318 void JSONPrinter::print(const Request &Request, const DIGlobal &Global) {
319   json::Object Data(
320       {{"Name", Global.Name != DILineInfo::BadString ? Global.Name : ""},
321        {"Start", toHex(Global.Start)},
322        {"Size", toHex(Global.Size)}});
323   json::Object Json = toJSON(Request);
324   Json["Data"] = std::move(Data);
325   if (ObjectList)
326     ObjectList->push_back(std::move(Json));
327   else
328     printJSON(std::move(Json));
329 }
330 
331 void JSONPrinter::print(const Request &Request,
332                         const std::vector<DILocal> &Locals) {
333   json::Array Frame;
334   for (const DILocal &Local : Locals) {
335     json::Object FrameObject(
336         {{"FunctionName", Local.FunctionName},
337          {"Name", Local.Name},
338          {"DeclFile", Local.DeclFile},
339          {"DeclLine", int64_t(Local.DeclLine)},
340          {"Size", Local.Size ? toHex(*Local.Size) : ""},
341          {"TagOffset", Local.TagOffset ? toHex(*Local.TagOffset) : ""}});
342     if (Local.FrameOffset)
343       FrameObject["FrameOffset"] = *Local.FrameOffset;
344     Frame.push_back(std::move(FrameObject));
345   }
346   json::Object Json = toJSON(Request);
347   Json["Frame"] = std::move(Frame);
348   if (ObjectList)
349     ObjectList->push_back(std::move(Json));
350   else
351     printJSON(std::move(Json));
352 }
353 
354 void JSONPrinter::printInvalidCommand(const Request &Request,
355                                       StringRef Command) {
356   printError(Request,
357              StringError("unable to parse arguments: " + Command,
358                          std::make_error_code(std::errc::invalid_argument)),
359              "");
360 }
361 
362 bool JSONPrinter::printError(const Request &Request,
363                              const ErrorInfoBase &ErrorInfo,
364                              StringRef ErrorBanner) {
365   json::Object Json = toJSON(Request, ErrorInfo.message());
366   if (ObjectList)
367     ObjectList->push_back(std::move(Json));
368   else
369     printJSON(std::move(Json));
370   return false;
371 }
372 
373 void JSONPrinter::listBegin() {
374   assert(!ObjectList);
375   ObjectList = std::make_unique<json::Array>();
376 }
377 
378 void JSONPrinter::listEnd() {
379   assert(ObjectList);
380   printJSON(std::move(*ObjectList));
381   ObjectList.reset();
382 }
383 
384 } // end namespace symbolize
385 } // end namespace llvm
386