blob: f3335a3fc36c62ef24eb30c4ad6ef3e29ca78a18 [file] [log] [blame]
Alexander Potapenkof41954b2012-11-12 11:33:29 +00001//===-- 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/OwningPtr.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/DebugInfo/DIContext.h"
21#include "llvm/Object/MachO.h"
22#include "llvm/Object/ObjectFile.h"
23#include "llvm/Support/Casting.h"
24#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/ManagedStatic.h"
27#include "llvm/Support/MemoryBuffer.h"
28#include "llvm/Support/Path.h"
29#include "llvm/Support/PrettyStackTrace.h"
30#include "llvm/Support/Signals.h"
31#include "llvm/Support/raw_ostream.h"
32
33#include <cstdio>
34#include <cstring>
35#include <map>
36#include <string>
37
38using namespace llvm;
39using namespace object;
40
41static cl::opt<bool>
42UseSymbolTable("use-symbol-table", cl::init(true),
43 cl::desc("Prefer names in symbol table to names "
44 "in debug info"));
45
46static cl::opt<bool>
47PrintFunctions("functions", cl::init(true),
48 cl::desc("Print function names as well as line "
49 "information for a given address"));
50
51static cl::opt<bool>
52PrintInlining("inlining", cl::init(true),
53 cl::desc("Print all inlined frames for a given address"));
54
55static cl::opt<bool>
56Demangle("demangle", cl::init(true),
57 cl::desc("Demangle function names"));
58
59static StringRef ToolInvocationPath;
60
61static bool error(error_code ec) {
62 if (!ec) return false;
63 errs() << ToolInvocationPath << ": error reading file: "
64 << ec.message() << ".\n";
65 return true;
66}
67
68static uint32_t getDILineInfoSpecifierFlags() {
69 uint32_t Flags = llvm::DILineInfoSpecifier::FileLineInfo |
70 llvm::DILineInfoSpecifier::AbsoluteFilePath;
71 if (PrintFunctions)
72 Flags |= llvm::DILineInfoSpecifier::FunctionName;
73 return Flags;
74}
75
76static void patchFunctionNameInDILineInfo(const std::string &NewFunctionName,
77 DILineInfo &LineInfo) {
78 std::string FileName = LineInfo.getFileName();
79 LineInfo = DILineInfo(StringRef(FileName), StringRef(NewFunctionName),
80 LineInfo.getLine(), LineInfo.getColumn());
81}
82
83namespace {
84class ModuleInfo {
85 OwningPtr<ObjectFile> Module;
86 OwningPtr<DIContext> DebugInfoContext;
87 public:
88 ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
89 : Module(Obj), DebugInfoContext(DICtx) {}
90
91 DILineInfo symbolizeCode(uint64_t ModuleOffset) const {
92 DILineInfo LineInfo;
93 if (DebugInfoContext) {
94 LineInfo = DebugInfoContext->getLineInfoForAddress(
95 ModuleOffset, getDILineInfoSpecifierFlags());
96 }
97 // Override function name from symbol table if necessary.
98 if (PrintFunctions && UseSymbolTable) {
99 std::string Function;
100 if (getFunctionNameFromSymbolTable(ModuleOffset, Function)) {
101 patchFunctionNameInDILineInfo(Function, LineInfo);
102 }
103 }
104 return LineInfo;
105 }
106
107 DIInliningInfo symbolizeInlinedCode(uint64_t ModuleOffset) const {
108 DIInliningInfo InlinedContext;
109 if (DebugInfoContext) {
110 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
111 ModuleOffset, getDILineInfoSpecifierFlags());
112 }
113 // Make sure there is at least one frame in context.
114 if (InlinedContext.getNumberOfFrames() == 0) {
115 InlinedContext.addFrame(DILineInfo());
116 }
117 // Override the function name in lower frame with name from symbol table.
118 if (PrintFunctions && UseSymbolTable) {
119 DIInliningInfo PatchedInlinedContext;
120 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames();
121 i != n; i++) {
122 DILineInfo LineInfo = InlinedContext.getFrame(i);
123 if (i == n - 1) {
124 std::string Function;
125 if (getFunctionNameFromSymbolTable(ModuleOffset, Function)) {
126 patchFunctionNameInDILineInfo(Function, LineInfo);
127 }
128 }
129 PatchedInlinedContext.addFrame(LineInfo);
130 }
131 InlinedContext = PatchedInlinedContext;
132 }
133 return InlinedContext;
134 }
135
136 private:
137 bool getFunctionNameFromSymbolTable(uint64_t Address,
138 std::string &FunctionName) const {
139 assert(Module);
140 error_code ec;
141 for (symbol_iterator si = Module->begin_symbols(),
142 se = Module->end_symbols();
143 si != se; si.increment(ec)) {
144 if (error(ec)) return false;
145 uint64_t SymbolAddress;
146 uint64_t SymbolSize;
147 SymbolRef::Type SymbolType;
148 if (error(si->getAddress(SymbolAddress)) ||
149 SymbolAddress == UnknownAddressOrSize) continue;
150 if (error(si->getSize(SymbolSize)) ||
151 SymbolSize == UnknownAddressOrSize) continue;
152 if (error(si->getType(SymbolType))) continue;
153 // FIXME: If a function has alias, there are two entries in symbol table
154 // with same address size. Make sure we choose the correct one.
155 if (SymbolAddress <= Address && Address < SymbolAddress + SymbolSize &&
156 SymbolType == SymbolRef::ST_Function) {
157 StringRef Name;
158 if (error(si->getName(Name))) continue;
159 FunctionName = Name.str();
160 return true;
161 }
162 }
163 return false;
164 }
165};
166
167typedef std::map<std::string, ModuleInfo*> ModuleMapTy;
168typedef ModuleMapTy::iterator ModuleMapIter;
169} // namespace
170
171static ModuleMapTy Modules;
172
Alexander Potapenkof41954b2012-11-12 11:33:29 +0000173// Returns true if the object endianness is known.
174static bool getObjectEndianness(const ObjectFile *Obj,
175 bool &IsLittleEndian) {
176 // FIXME: Implement this when libLLVMObject allows to do it easily.
177 IsLittleEndian = true;
178 return true;
179}
180
Alexander Potapenkof41954b2012-11-12 11:33:29 +0000181static ObjectFile *getObjectFile(const std::string &Path) {
182 OwningPtr<MemoryBuffer> Buff;
183 MemoryBuffer::getFile(Path, Buff);
184 return ObjectFile::createObjectFile(Buff.take());
185}
186
187static std::string getDarwinDWARFResourceForModule(const std::string &Path) {
188 StringRef Basename = sys::path::filename(Path);
189 const std::string &DSymDirectory = Path + ".dSYM";
190 SmallString<16> ResourceName = StringRef(DSymDirectory);
191 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
192 sys::path::append(ResourceName, Basename);
193 return ResourceName.str();
194}
195
196static ModuleInfo *getOrCreateModuleInfo(const std::string &ModuleName) {
197 ModuleMapIter I = Modules.find(ModuleName);
198 if (I != Modules.end())
199 return I->second;
200
201 ObjectFile *Obj = getObjectFile(ModuleName);
Eric Christopherd1726a42012-11-12 21:40:38 +0000202 ObjectFile *DbgObj = Obj;
Alexander Potapenkof41954b2012-11-12 11:33:29 +0000203 if (Obj == 0) {
204 // Module name doesn't point to a valid object file.
205 Modules.insert(make_pair(ModuleName, (ModuleInfo*)0));
206 return 0;
207 }
208
209 DIContext *Context = 0;
210 bool IsLittleEndian;
211 if (getObjectEndianness(Obj, IsLittleEndian)) {
Alexander Potapenkof41954b2012-11-12 11:33:29 +0000212 // On Darwin we may find DWARF in separate object file in
213 // resource directory.
214 if (isa<MachOObjectFile>(Obj)) {
215 const std::string &ResourceName = getDarwinDWARFResourceForModule(
216 ModuleName);
217 ObjectFile *ResourceObj = getObjectFile(ResourceName);
218 if (ResourceObj != 0)
Eric Christopherd1726a42012-11-12 21:40:38 +0000219 DbgObj = ResourceObj;
Alexander Potapenkof41954b2012-11-12 11:33:29 +0000220 }
Eric Christopherd1726a42012-11-12 21:40:38 +0000221 Context = DIContext::getDWARFContext(DbgObj);
Alexander Potapenkof41954b2012-11-12 11:33:29 +0000222 assert(Context);
223 }
224
225 ModuleInfo *Info = new ModuleInfo(Obj, Context);
226 Modules.insert(make_pair(ModuleName, Info));
227 return Info;
228}
229
Alexander Potapenkodece7032012-11-12 14:49:58 +0000230#if !defined(_MSC_VER)
231// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
Alexander Potapenkof41954b2012-11-12 11:33:29 +0000232extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
233 size_t *length, int *status);
Alexander Potapenkodece7032012-11-12 14:49:58 +0000234#endif
Alexander Potapenkof41954b2012-11-12 11:33:29 +0000235
236static void printDILineInfo(DILineInfo LineInfo) {
237 // By default, DILineInfo contains "<invalid>" for function/filename it
238 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
239 static const std::string kDILineInfoBadString = "<invalid>";
240 static const std::string kSymbolizerBadString = "??";
241 if (PrintFunctions) {
242 std::string FunctionName = LineInfo.getFunctionName();
243 if (FunctionName == kDILineInfoBadString)
244 FunctionName = kSymbolizerBadString;
Alexander Potapenkodece7032012-11-12 14:49:58 +0000245#if !defined(_MSC_VER)
Alexander Potapenkof41954b2012-11-12 11:33:29 +0000246 if (Demangle) {
247 int status = 0;
248 char *DemangledName = __cxa_demangle(
249 FunctionName.c_str(), 0, 0, &status);
250 if (status == 0) {
251 FunctionName = DemangledName;
252 free(DemangledName);
253 }
254 }
Alexander Potapenkodece7032012-11-12 14:49:58 +0000255#endif
Alexander Potapenkof41954b2012-11-12 11:33:29 +0000256 outs() << FunctionName << "\n";
257 }
258 std::string Filename = LineInfo.getFileName();
259 if (Filename == kDILineInfoBadString)
260 Filename = kSymbolizerBadString;
261 outs() << Filename <<
262 ":" << LineInfo.getLine() <<
263 ":" << LineInfo.getColumn() <<
264 "\n";
265}
266
267static void symbolize(std::string ModuleName, std::string ModuleOffsetStr) {
268 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
269 uint64_t Offset = 0;
270 if (Info == 0 ||
271 StringRef(ModuleOffsetStr).getAsInteger(0, Offset)) {
272 printDILineInfo(DILineInfo());
273 } else if (PrintInlining) {
274 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(Offset);
275 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
276 assert(FramesNum > 0);
277 for (uint32_t i = 0; i < FramesNum; i++) {
278 DILineInfo LineInfo = InlinedContext.getFrame(i);
279 printDILineInfo(LineInfo);
280 }
281 } else {
282 DILineInfo LineInfo = Info->symbolizeCode(Offset);
283 printDILineInfo(LineInfo);
284 }
285
286 outs() << "\n"; // Print extra empty line to mark the end of output.
287 outs().flush();
288}
289
290static bool parseModuleNameAndOffset(std::string &ModuleName,
291 std::string &ModuleOffsetStr) {
292 static const int kMaxInputStringLength = 1024;
293 static const char kDelimiters[] = " \n";
294 char InputString[kMaxInputStringLength];
295 if (!fgets(InputString, sizeof(InputString), stdin))
296 return false;
297 ModuleName = "";
298 ModuleOffsetStr = "";
299 // FIXME: Handle case when filename is given in quotes.
300 if (char *FilePath = strtok(InputString, kDelimiters)) {
301 ModuleName = FilePath;
302 if (char *OffsetStr = strtok((char*)0, kDelimiters))
303 ModuleOffsetStr = OffsetStr;
304 }
305 return true;
306}
307
308int main(int argc, char **argv) {
309 // Print stack trace if we signal out.
310 sys::PrintStackTraceOnErrorSignal();
311 PrettyStackTraceProgram X(argc, argv);
312 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
313
314 cl::ParseCommandLineOptions(argc, argv, "llvm symbolizer for compiler-rt\n");
315 ToolInvocationPath = argv[0];
316
317 std::string ModuleName;
318 std::string ModuleOffsetStr;
319 while (parseModuleNameAndOffset(ModuleName, ModuleOffsetStr)) {
320 symbolize(ModuleName, ModuleOffsetStr);
321 }
322 return 0;
323}