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/MemoryBuffer.h"
20#include "llvm/Support/raw_ostream.h"
21#include <algorithm>
22#include <cstddef>
23#include <cstdint>
24#include <memory>
25#include <string>
26
27namespace llvm {
28namespace symbolize {
29
30class SourceCode {
31 std::unique_ptr<MemoryBuffer> MemBuf;
32
33 std::optional<StringRef>
34 load(StringRef FileName, const std::optional<StringRef> &EmbeddedSource) {
35 if (Lines <= 0)
36 return std::nullopt;
37
38 if (EmbeddedSource)
39 return EmbeddedSource;
40 else {
41 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
42 MemoryBuffer::getFile(Filename: FileName);
43 if (!BufOrErr)
44 return std::nullopt;
45 MemBuf = std::move(*BufOrErr);
46 return MemBuf->getBuffer();
47 }
48 }
49
50 std::optional<StringRef> pruneSource(const std::optional<StringRef> &Source) {
51 if (!Source)
52 return std::nullopt;
53 size_t FirstLinePos = StringRef::npos, Pos = 0;
54 for (int64_t L = 1; L <= LastLine; ++L, ++Pos) {
55 if (L == FirstLine)
56 FirstLinePos = Pos;
57 Pos = Source->find(C: '\n', From: Pos);
58 if (Pos == StringRef::npos)
59 break;
60 }
61 if (FirstLinePos == StringRef::npos)
62 return std::nullopt;
63 return Source->substr(Start: FirstLinePos, N: (Pos == StringRef::npos)
64 ? StringRef::npos
65 : Pos - FirstLinePos);
66 }
67
68public:
69 const int64_t Line;
70 const int Lines;
71 const int64_t FirstLine;
72 const int64_t LastLine;
73 const std::optional<StringRef> PrunedSource;
74
75 SourceCode(StringRef FileName, int64_t Line, int Lines,
76 const std::optional<StringRef> &EmbeddedSource =
77 std::optional<StringRef>())
78 : Line(Line), Lines(Lines),
79 FirstLine(std::max(a: static_cast<int64_t>(1), b: Line - Lines / 2)),
80 LastLine(FirstLine + Lines - 1),
81 PrunedSource(pruneSource(Source: load(FileName, EmbeddedSource))) {}
82
83 void format(raw_ostream &OS) {
84 if (!PrunedSource)
85 return;
86 size_t MaxLineNumberWidth = NumDigitsBase10(X: LastLine);
87 int64_t L = FirstLine;
88 for (size_t Pos = 0; Pos < PrunedSource->size(); ++L) {
89 size_t PosEnd = PrunedSource->find(C: '\n', From: Pos);
90 StringRef String = PrunedSource->substr(
91 Start: Pos, N: (PosEnd == StringRef::npos) ? StringRef::npos : (PosEnd - Pos));
92 if (String.ends_with(Suffix: "\r"))
93 String = String.drop_back(N: 1);
94 OS << format_decimal(N: L, Width: MaxLineNumberWidth);
95 if (L == Line)
96 OS << " >: ";
97 else
98 OS << " : ";
99 OS << String << '\n';
100 if (PosEnd == StringRef::npos)
101 break;
102 Pos = PosEnd + 1;
103 }
104 }
105};
106
107void PlainPrinterBase::printHeader(std::optional<uint64_t> Address) {
108 if (Address.has_value() && Config.PrintAddress) {
109 OS << "0x";
110 OS.write_hex(N: *Address);
111 StringRef Delimiter = Config.Pretty ? ": " : "\n";
112 OS << Delimiter;
113 }
114}
115
116// Prints source code around in the FileName the Line.
117void PlainPrinterBase::printContext(SourceCode SourceCode) {
118 SourceCode.format(OS);
119}
120
121void 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
131void LLVMPrinter::printSimpleLocation(StringRef Filename,
132 const DILineInfo &Info) {
133 OS << Filename << ':' << Info.Line << ':' << Info.Column;
134 if (Info.IsApproximateLine)
135 OS << " " << Info.ApproxString;
136 OS << "\n";
137 printContext(
138 SourceCode: SourceCode(Filename, Info.Line, Config.SourceContextLines, Info.Source));
139}
140
141void GNUPrinter::printSimpleLocation(StringRef Filename,
142 const DILineInfo &Info) {
143 OS << Filename << ':' << Info.Line;
144 if (Info.IsApproximateLine)
145 OS << " " << Info.ApproxString;
146 if (Info.Discriminator)
147 OS << " (discriminator " << Info.Discriminator << ')';
148 OS << '\n';
149 printContext(
150 SourceCode: SourceCode(Filename, Info.Line, Config.SourceContextLines, Info.Source));
151}
152
153void PlainPrinterBase::printVerbose(StringRef Filename,
154 const DILineInfo &Info) {
155 OS << " Filename: " << Filename << '\n';
156 if (Info.StartLine) {
157 OS << " Function start filename: " << Info.StartFileName << '\n';
158 OS << " Function start line: " << Info.StartLine << '\n';
159 }
160 printStartAddress(Info);
161 OS << " Line: " << Info.Line << '\n';
162 OS << " Column: " << Info.Column << '\n';
163 if (Info.Discriminator)
164 OS << " Discriminator: " << Info.Discriminator << '\n';
165 if (Info.IsApproximateLine)
166 OS << " Approximate: true" << '\n';
167}
168
169void LLVMPrinter::printStartAddress(const DILineInfo &Info) {
170 if (Info.StartAddress) {
171 OS << " Function start address: 0x";
172 OS.write_hex(N: *Info.StartAddress);
173 OS << '\n';
174 }
175}
176
177void LLVMPrinter::printFooter() { OS << '\n'; }
178
179void PlainPrinterBase::print(const DILineInfo &Info, bool Inlined) {
180 printFunctionName(FunctionName: Info.FunctionName, Inlined);
181 StringRef Filename = Info.FileName;
182 if (Filename == DILineInfo::BadString)
183 Filename = DILineInfo::Addr2LineBadString;
184 if (Config.Verbose)
185 printVerbose(Filename, Info);
186 else
187 printSimpleLocation(Filename, Info);
188}
189
190void PlainPrinterBase::print(const Request &Request, const DILineInfo &Info) {
191 printHeader(Address: Request.Address);
192 print(Info, Inlined: false);
193 printFooter();
194}
195
196void PlainPrinterBase::print(const Request &Request,
197 const DIInliningInfo &Info) {
198 printHeader(Address: *Request.Address);
199 uint32_t FramesNum = Info.getNumberOfFrames();
200 if (FramesNum == 0)
201 print(Info: DILineInfo(), Inlined: false);
202 else
203 for (uint32_t I = 0; I < FramesNum; ++I)
204 print(Info: Info.getFrame(Index: I), Inlined: I > 0);
205 printFooter();
206}
207
208void PlainPrinterBase::print(const Request &Request, const DIGlobal &Global) {
209 printHeader(Address: *Request.Address);
210 StringRef Name = Global.Name;
211 if (Name == DILineInfo::BadString)
212 Name = DILineInfo::Addr2LineBadString;
213 OS << Name << "\n";
214 OS << Global.Start << " " << Global.Size << "\n";
215 if (Global.DeclFile.empty())
216 OS << "??:?\n";
217 else
218 OS << Global.DeclFile << ":" << Global.DeclLine << "\n";
219 printFooter();
220}
221
222void PlainPrinterBase::print(const Request &Request,
223 const std::vector<DILocal> &Locals) {
224 printHeader(Address: *Request.Address);
225 if (Locals.empty())
226 OS << DILineInfo::Addr2LineBadString << '\n';
227 else
228 for (const DILocal &L : Locals) {
229 if (L.FunctionName.empty())
230 OS << DILineInfo::Addr2LineBadString;
231 else
232 OS << L.FunctionName;
233 OS << '\n';
234
235 if (L.Name.empty())
236 OS << DILineInfo::Addr2LineBadString;
237 else
238 OS << L.Name;
239 OS << '\n';
240
241 if (L.DeclFile.empty())
242 OS << DILineInfo::Addr2LineBadString;
243 else
244 OS << L.DeclFile;
245
246 OS << ':' << L.DeclLine << '\n';
247
248 if (L.FrameOffset)
249 OS << *L.FrameOffset;
250 else
251 OS << DILineInfo::Addr2LineBadString;
252 OS << ' ';
253
254 if (L.Size)
255 OS << *L.Size;
256 else
257 OS << DILineInfo::Addr2LineBadString;
258 OS << ' ';
259
260 if (L.TagOffset)
261 OS << *L.TagOffset;
262 else
263 OS << DILineInfo::Addr2LineBadString;
264 OS << '\n';
265 }
266 printFooter();
267}
268
269void PlainPrinterBase::print(const Request &Request,
270 const std::vector<DILineInfo> &Locations) {
271 if (Locations.empty()) {
272 print(Request, Info: DILineInfo());
273 } else {
274 for (const DILineInfo &L : Locations)
275 print(Info: L, Inlined: false);
276 printFooter();
277 }
278}
279
280bool PlainPrinterBase::printError(const Request &Request,
281 const ErrorInfoBase &ErrorInfo) {
282 ErrHandler(ErrorInfo, Request.ModuleName);
283 // Print an empty struct too.
284 return true;
285}
286
287static std::string toHex(uint64_t V) {
288 return ("0x" + Twine::utohexstr(Val: V)).str();
289}
290
291static json::Object toJSON(const Request &Request, StringRef ErrorMsg = "") {
292 json::Object Json({{.K: "ModuleName", .V: Request.ModuleName.str()}});
293 if (!Request.Symbol.empty())
294 Json["SymName"] = Request.Symbol.str();
295 if (Request.Address)
296 Json["Address"] = toHex(V: *Request.Address);
297 if (!ErrorMsg.empty())
298 Json["Error"] = json::Object({{.K: "Message", .V: ErrorMsg.str()}});
299 return Json;
300}
301
302static json::Object toJSON(const DILineInfo &LineInfo) {
303 json::Object Obj = json::Object(
304 {{.K: "FunctionName", .V: LineInfo.FunctionName != DILineInfo::BadString
305 ? LineInfo.FunctionName
306 : ""},
307 {.K: "StartFileName", .V: LineInfo.StartFileName != DILineInfo::BadString
308 ? LineInfo.StartFileName
309 : ""},
310 {.K: "StartLine", .V: LineInfo.StartLine},
311 {.K: "StartAddress",
312 .V: LineInfo.StartAddress ? toHex(V: *LineInfo.StartAddress) : ""},
313 {.K: "FileName",
314 .V: LineInfo.FileName != DILineInfo::BadString ? LineInfo.FileName : ""},
315 {.K: "Line", .V: LineInfo.Line},
316 {.K: "Column", .V: LineInfo.Column},
317 {.K: "Discriminator", .V: LineInfo.Discriminator}});
318 if (LineInfo.IsApproximateLine)
319 Obj.insert(E: {.K: "Approximate", .V: LineInfo.IsApproximateLine});
320 return Obj;
321}
322
323void JSONPrinter::print(const Request &Request, const DILineInfo &Info) {
324 DIInliningInfo InliningInfo;
325 InliningInfo.addFrame(Frame: Info);
326 print(Request, Info: InliningInfo);
327}
328
329void JSONPrinter::print(const Request &Request, const DIInliningInfo &Info) {
330 json::Array Array;
331 for (uint32_t I = 0, N = Info.getNumberOfFrames(); I < N; ++I) {
332 const DILineInfo &LineInfo = Info.getFrame(Index: I);
333 json::Object Object = toJSON(LineInfo);
334 SourceCode SourceCode(LineInfo.FileName, LineInfo.Line,
335 Config.SourceContextLines, LineInfo.Source);
336 std::string FormattedSource;
337 raw_string_ostream Stream(FormattedSource);
338 SourceCode.format(OS&: Stream);
339 if (!FormattedSource.empty())
340 Object["Source"] = std::move(FormattedSource);
341 Array.push_back(E: std::move(Object));
342 }
343 json::Object Json = toJSON(Request);
344 Json["Symbol"] = std::move(Array);
345 if (ObjectList)
346 ObjectList->push_back(E: std::move(Json));
347 else
348 printJSON(V: std::move(Json));
349}
350
351void JSONPrinter::print(const Request &Request, const DIGlobal &Global) {
352 json::Object Data(
353 {{.K: "Name", .V: Global.Name != DILineInfo::BadString ? Global.Name : ""},
354 {.K: "Start", .V: toHex(V: Global.Start)},
355 {.K: "Size", .V: toHex(V: Global.Size)}});
356 json::Object Json = toJSON(Request);
357 Json["Data"] = std::move(Data);
358 if (ObjectList)
359 ObjectList->push_back(E: std::move(Json));
360 else
361 printJSON(V: std::move(Json));
362}
363
364void JSONPrinter::print(const Request &Request,
365 const std::vector<DILocal> &Locals) {
366 json::Array Frame;
367 for (const DILocal &Local : Locals) {
368 json::Object FrameObject(
369 {{.K: "FunctionName", .V: Local.FunctionName},
370 {.K: "Name", .V: Local.Name},
371 {.K: "DeclFile", .V: Local.DeclFile},
372 {.K: "DeclLine", .V: int64_t(Local.DeclLine)},
373 {.K: "Size", .V: Local.Size ? toHex(V: *Local.Size) : ""},
374 {.K: "TagOffset", .V: Local.TagOffset ? toHex(V: *Local.TagOffset) : ""}});
375 if (Local.FrameOffset)
376 FrameObject["FrameOffset"] = *Local.FrameOffset;
377 Frame.push_back(E: std::move(FrameObject));
378 }
379 json::Object Json = toJSON(Request);
380 Json["Frame"] = std::move(Frame);
381 if (ObjectList)
382 ObjectList->push_back(E: std::move(Json));
383 else
384 printJSON(V: std::move(Json));
385}
386
387void JSONPrinter::print(const Request &Request,
388 const std::vector<DILineInfo> &Locations) {
389 json::Array Definitions;
390 for (const DILineInfo &L : Locations)
391 Definitions.push_back(E: toJSON(LineInfo: L));
392 json::Object Json = toJSON(Request);
393 Json["Loc"] = std::move(Definitions);
394 if (ObjectList)
395 ObjectList->push_back(E: std::move(Json));
396 else
397 printJSON(V: std::move(Json));
398}
399
400bool JSONPrinter::printError(const Request &Request,
401 const ErrorInfoBase &ErrorInfo) {
402 json::Object Json = toJSON(Request, ErrorMsg: ErrorInfo.message());
403 if (ObjectList)
404 ObjectList->push_back(E: std::move(Json));
405 else
406 printJSON(V: std::move(Json));
407 return false;
408}
409
410void JSONPrinter::listBegin() {
411 assert(!ObjectList);
412 ObjectList = std::make_unique<json::Array>();
413}
414
415void JSONPrinter::listEnd() {
416 assert(ObjectList);
417 printJSON(V: std::move(*ObjectList));
418 ObjectList.reset();
419}
420
421} // end namespace symbolize
422} // end namespace llvm
423