llvm-symbolizer.cpp revision 341825
1//===-- llvm-symbolizer.cpp - Simple addr2line-like symbolizer ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This utility works much like "addr2line". It is able of transforming
11// tuples (module name, module offset) to code locations (function name,
12// file, line number, column number). It is targeted for compiler-rt tools
13// (especially AddressSanitizer and ThreadSanitizer) that can use it
14// to symbolize stack traces in their error reports.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/StringRef.h"
19#include "llvm/DebugInfo/Symbolize/DIPrinter.h"
20#include "llvm/DebugInfo/Symbolize/Symbolize.h"
21#include "llvm/Support/COM.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/InitLLVM.h"
26#include "llvm/Support/Path.h"
27#include "llvm/Support/raw_ostream.h"
28#include <cstdio>
29#include <cstring>
30#include <string>
31
32using namespace llvm;
33using namespace symbolize;
34
35static cl::opt<bool>
36ClUseSymbolTable("use-symbol-table", cl::init(true),
37                 cl::desc("Prefer names in symbol table to names "
38                          "in debug info"));
39
40static cl::opt<FunctionNameKind> ClPrintFunctions(
41    "functions", cl::init(FunctionNameKind::LinkageName),
42    cl::desc("Print function name for a given address:"),
43    cl::values(clEnumValN(FunctionNameKind::None, "none", "omit function name"),
44               clEnumValN(FunctionNameKind::ShortName, "short",
45                          "print short function name"),
46               clEnumValN(FunctionNameKind::LinkageName, "linkage",
47                          "print function linkage name")));
48
49static cl::opt<bool>
50    ClUseRelativeAddress("relative-address", cl::init(false),
51                         cl::desc("Interpret addresses as relative addresses"),
52                         cl::ReallyHidden);
53
54static cl::opt<bool>
55    ClPrintInlining("inlining", cl::init(true),
56                    cl::desc("Print all inlined frames for a given address"));
57
58static cl::opt<bool>
59ClDemangle("demangle", cl::init(true), cl::desc("Demangle function names"));
60
61static cl::opt<std::string> ClDefaultArch("default-arch", cl::init(""),
62                                          cl::desc("Default architecture "
63                                                   "(for multi-arch objects)"));
64
65static cl::opt<std::string>
66ClBinaryName("obj", cl::init(""),
67             cl::desc("Path to object file to be symbolized (if not provided, "
68                      "object file should be specified for each input line)"));
69
70static cl::opt<std::string>
71    ClDwpName("dwp", cl::init(""),
72              cl::desc("Path to DWP file to be use for any split CUs"));
73
74static cl::list<std::string>
75ClDsymHint("dsym-hint", cl::ZeroOrMore,
76           cl::desc("Path to .dSYM bundles to search for debug info for the "
77                    "object files"));
78static cl::opt<bool>
79    ClPrintAddress("print-address", cl::init(false),
80                   cl::desc("Show address before line information"));
81
82static cl::opt<bool>
83    ClPrettyPrint("pretty-print", cl::init(false),
84                  cl::desc("Make the output more human friendly"));
85
86static cl::opt<int> ClPrintSourceContextLines(
87    "print-source-context-lines", cl::init(0),
88    cl::desc("Print N number of source file context"));
89
90static cl::opt<bool> ClVerbose("verbose", cl::init(false),
91                               cl::desc("Print verbose line info"));
92
93template<typename T>
94static bool error(Expected<T> &ResOrErr) {
95  if (ResOrErr)
96    return false;
97  logAllUnhandledErrors(ResOrErr.takeError(), errs(),
98                        "LLVMSymbolizer: error reading file: ");
99  return true;
100}
101
102static bool parseCommand(StringRef InputString, bool &IsData,
103                         std::string &ModuleName, uint64_t &ModuleOffset) {
104  const char kDelimiters[] = " \n\r";
105  ModuleName = "";
106  if (InputString.consume_front("CODE ")) {
107    IsData = false;
108  } else if (InputString.consume_front("DATA ")) {
109    IsData = true;
110  } else {
111    // If no cmd, assume it's CODE.
112    IsData = false;
113  }
114  const char *pos = InputString.data();
115  // Skip delimiters and parse input filename (if needed).
116  if (ClBinaryName.empty()) {
117    pos += strspn(pos, kDelimiters);
118    if (*pos == '"' || *pos == '\'') {
119      char quote = *pos;
120      pos++;
121      const char *end = strchr(pos, quote);
122      if (!end)
123        return false;
124      ModuleName = std::string(pos, end - pos);
125      pos = end + 1;
126    } else {
127      int name_length = strcspn(pos, kDelimiters);
128      ModuleName = std::string(pos, name_length);
129      pos += name_length;
130    }
131  } else {
132    ModuleName = ClBinaryName;
133  }
134  // Skip delimiters and parse module offset.
135  pos += strspn(pos, kDelimiters);
136  int offset_length = strcspn(pos, kDelimiters);
137  return !StringRef(pos, offset_length).getAsInteger(0, ModuleOffset);
138}
139
140int main(int argc, char **argv) {
141  InitLLVM X(argc, argv);
142
143  llvm::sys::InitializeCOMRAII COM(llvm::sys::COMThreadingMode::MultiThreaded);
144
145  cl::ParseCommandLineOptions(argc, argv, "llvm-symbolizer\n");
146  LLVMSymbolizer::Options Opts(ClPrintFunctions, ClUseSymbolTable, ClDemangle,
147                               ClUseRelativeAddress, ClDefaultArch);
148
149  for (const auto &hint : ClDsymHint) {
150    if (sys::path::extension(hint) == ".dSYM") {
151      Opts.DsymHints.push_back(hint);
152    } else {
153      errs() << "Warning: invalid dSYM hint: \"" << hint <<
154                "\" (must have the '.dSYM' extension).\n";
155    }
156  }
157  LLVMSymbolizer Symbolizer(Opts);
158
159  DIPrinter Printer(outs(), ClPrintFunctions != FunctionNameKind::None,
160                    ClPrettyPrint, ClPrintSourceContextLines, ClVerbose);
161
162  const int kMaxInputStringLength = 1024;
163  char InputString[kMaxInputStringLength];
164
165  while (true) {
166    if (!fgets(InputString, sizeof(InputString), stdin))
167      break;
168
169    bool IsData = false;
170    std::string ModuleName;
171    uint64_t ModuleOffset = 0;
172    if (!parseCommand(StringRef(InputString), IsData, ModuleName,
173                      ModuleOffset)) {
174      outs() << InputString;
175      continue;
176    }
177
178    if (ClPrintAddress) {
179      outs() << "0x";
180      outs().write_hex(ModuleOffset);
181      StringRef Delimiter = ClPrettyPrint ? ": " : "\n";
182      outs() << Delimiter;
183    }
184    if (IsData) {
185      auto ResOrErr = Symbolizer.symbolizeData(ModuleName, ModuleOffset);
186      Printer << (error(ResOrErr) ? DIGlobal() : ResOrErr.get());
187    } else if (ClPrintInlining) {
188      auto ResOrErr =
189          Symbolizer.symbolizeInlinedCode(ModuleName, ModuleOffset, ClDwpName);
190      Printer << (error(ResOrErr) ? DIInliningInfo()
191                                             : ResOrErr.get());
192    } else {
193      auto ResOrErr =
194          Symbolizer.symbolizeCode(ModuleName, ModuleOffset, ClDwpName);
195      Printer << (error(ResOrErr) ? DILineInfo() : ResOrErr.get());
196    }
197    outs() << "\n";
198    outs().flush();
199  }
200
201  return 0;
202}
203