DIPrinter.cpp 12 KB

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