1 //===-- llvm-symbolizer.cpp - Simple addr2line-like symbolizer ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
16 //===----------------------------------------------------------------------===//
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"
38 using namespace object;
41 UseSymbolTable("use-symbol-table", cl::init(true),
42 cl::desc("Prefer names in symbol table to names "
46 PrintFunctions("functions", cl::init(true),
47 cl::desc("Print function names as well as line "
48 "information for a given address"));
51 PrintInlining("inlining", cl::init(true),
52 cl::desc("Print all inlined frames for a given address"));
55 Demangle("demangle", cl::init(true),
56 cl::desc("Demangle function names"));
58 static StringRef ToolInvocationPath;
60 static bool error(error_code ec) {
61 if (!ec) return false;
62 errs() << ToolInvocationPath << ": error reading file: "
63 << ec.message() << ".\n";
67 static uint32_t getDILineInfoSpecifierFlags() {
68 uint32_t Flags = llvm::DILineInfoSpecifier::FileLineInfo |
69 llvm::DILineInfoSpecifier::AbsoluteFilePath;
71 Flags |= llvm::DILineInfoSpecifier::FunctionName;
75 static void patchFunctionNameInDILineInfo(const std::string &NewFunctionName,
76 DILineInfo &LineInfo) {
77 std::string FileName = LineInfo.getFileName();
78 LineInfo = DILineInfo(StringRef(FileName), StringRef(NewFunctionName),
79 LineInfo.getLine(), LineInfo.getColumn());
84 OwningPtr<ObjectFile> Module;
85 OwningPtr<DIContext> DebugInfoContext;
87 ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
88 : Module(Obj), DebugInfoContext(DICtx) {}
90 DILineInfo symbolizeCode(uint64_t ModuleOffset) const {
92 if (DebugInfoContext) {
93 LineInfo = DebugInfoContext->getLineInfoForAddress(
94 ModuleOffset, getDILineInfoSpecifierFlags());
96 // Override function name from symbol table if necessary.
97 if (PrintFunctions && UseSymbolTable) {
99 if (getFunctionNameFromSymbolTable(ModuleOffset, Function)) {
100 patchFunctionNameInDILineInfo(Function, LineInfo);
106 DIInliningInfo symbolizeInlinedCode(uint64_t ModuleOffset) const {
107 DIInliningInfo InlinedContext;
108 if (DebugInfoContext) {
109 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
110 ModuleOffset, getDILineInfoSpecifierFlags());
112 // Make sure there is at least one frame in context.
113 if (InlinedContext.getNumberOfFrames() == 0) {
114 InlinedContext.addFrame(DILineInfo());
116 // Override the function name in lower frame with name from symbol table.
117 if (PrintFunctions && UseSymbolTable) {
118 DIInliningInfo PatchedInlinedContext;
119 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames();
121 DILineInfo LineInfo = InlinedContext.getFrame(i);
123 std::string Function;
124 if (getFunctionNameFromSymbolTable(ModuleOffset, Function)) {
125 patchFunctionNameInDILineInfo(Function, LineInfo);
128 PatchedInlinedContext.addFrame(LineInfo);
130 InlinedContext = PatchedInlinedContext;
132 return InlinedContext;
136 bool getFunctionNameFromSymbolTable(uint64_t Address,
137 std::string &FunctionName) const {
140 for (symbol_iterator si = Module->begin_symbols(),
141 se = Module->end_symbols();
142 si != se; si.increment(ec)) {
143 if (error(ec)) return false;
144 uint64_t SymbolAddress;
146 SymbolRef::Type SymbolType;
147 if (error(si->getAddress(SymbolAddress)) ||
148 SymbolAddress == UnknownAddressOrSize) continue;
149 if (error(si->getSize(SymbolSize)) ||
150 SymbolSize == UnknownAddressOrSize) continue;
151 if (error(si->getType(SymbolType))) continue;
152 // FIXME: If a function has alias, there are two entries in symbol table
153 // with same address size. Make sure we choose the correct one.
154 if (SymbolAddress <= Address && Address < SymbolAddress + SymbolSize &&
155 SymbolType == SymbolRef::ST_Function) {
157 if (error(si->getName(Name))) continue;
158 FunctionName = Name.str();
166 typedef std::map<std::string, ModuleInfo*> ModuleMapTy;
167 typedef ModuleMapTy::iterator ModuleMapIter;
170 static ModuleMapTy Modules;
172 // Returns true if the object endianness is known.
173 static bool getObjectEndianness(const ObjectFile *Obj,
174 bool &IsLittleEndian) {
175 // FIXME: Implement this when libLLVMObject allows to do it easily.
176 IsLittleEndian = true;
180 static ObjectFile *getObjectFile(const std::string &Path) {
181 OwningPtr<MemoryBuffer> Buff;
182 MemoryBuffer::getFile(Path, Buff);
183 return ObjectFile::createObjectFile(Buff.take());
186 static std::string getDarwinDWARFResourceForModule(const std::string &Path) {
187 StringRef Basename = sys::path::filename(Path);
188 const std::string &DSymDirectory = Path + ".dSYM";
189 SmallString<16> ResourceName = StringRef(DSymDirectory);
190 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
191 sys::path::append(ResourceName, Basename);
192 return ResourceName.str();
195 static ModuleInfo *getOrCreateModuleInfo(const std::string &ModuleName) {
196 ModuleMapIter I = Modules.find(ModuleName);
197 if (I != Modules.end())
200 ObjectFile *Obj = getObjectFile(ModuleName);
201 ObjectFile *DbgObj = Obj;
203 // Module name doesn't point to a valid object file.
204 Modules.insert(make_pair(ModuleName, (ModuleInfo*)0));
208 DIContext *Context = 0;
210 if (getObjectEndianness(Obj, IsLittleEndian)) {
211 // On Darwin we may find DWARF in separate object file in
212 // resource directory.
213 if (isa<MachOObjectFile>(Obj)) {
214 const std::string &ResourceName = getDarwinDWARFResourceForModule(
216 ObjectFile *ResourceObj = getObjectFile(ResourceName);
217 if (ResourceObj != 0)
218 DbgObj = ResourceObj;
220 Context = DIContext::getDWARFContext(DbgObj);
224 ModuleInfo *Info = new ModuleInfo(Obj, Context);
225 Modules.insert(make_pair(ModuleName, Info));
229 #if !defined(_MSC_VER)
230 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
231 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
232 size_t *length, int *status);
235 static void printDILineInfo(DILineInfo LineInfo) {
236 // By default, DILineInfo contains "<invalid>" for function/filename it
237 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
238 static const std::string kDILineInfoBadString = "<invalid>";
239 static const std::string kSymbolizerBadString = "??";
240 if (PrintFunctions) {
241 std::string FunctionName = LineInfo.getFunctionName();
242 if (FunctionName == kDILineInfoBadString)
243 FunctionName = kSymbolizerBadString;
244 #if !defined(_MSC_VER)
247 char *DemangledName = __cxa_demangle(
248 FunctionName.c_str(), 0, 0, &status);
250 FunctionName = DemangledName;
255 outs() << FunctionName << "\n";
257 std::string Filename = LineInfo.getFileName();
258 if (Filename == kDILineInfoBadString)
259 Filename = kSymbolizerBadString;
260 outs() << Filename <<
261 ":" << LineInfo.getLine() <<
262 ":" << LineInfo.getColumn() <<
266 static void symbolize(std::string ModuleName, std::string ModuleOffsetStr) {
267 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
270 StringRef(ModuleOffsetStr).getAsInteger(0, Offset)) {
271 printDILineInfo(DILineInfo());
272 } else if (PrintInlining) {
273 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(Offset);
274 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
275 assert(FramesNum > 0);
276 for (uint32_t i = 0; i < FramesNum; i++) {
277 DILineInfo LineInfo = InlinedContext.getFrame(i);
278 printDILineInfo(LineInfo);
281 DILineInfo LineInfo = Info->symbolizeCode(Offset);
282 printDILineInfo(LineInfo);
285 outs() << "\n"; // Print extra empty line to mark the end of output.
289 static bool parseModuleNameAndOffset(std::string &ModuleName,
290 std::string &ModuleOffsetStr) {
291 static const int kMaxInputStringLength = 1024;
292 static const char kDelimiters[] = " \n";
293 char InputString[kMaxInputStringLength];
294 if (!fgets(InputString, sizeof(InputString), stdin))
297 ModuleOffsetStr = "";
298 // FIXME: Handle case when filename is given in quotes.
299 if (char *FilePath = strtok(InputString, kDelimiters)) {
300 ModuleName = FilePath;
301 if (char *OffsetStr = strtok((char*)0, kDelimiters))
302 ModuleOffsetStr = OffsetStr;
307 int main(int argc, char **argv) {
308 // Print stack trace if we signal out.
309 sys::PrintStackTraceOnErrorSignal();
310 PrettyStackTraceProgram X(argc, argv);
311 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
313 cl::ParseCommandLineOptions(argc, argv, "llvm symbolizer for compiler-rt\n");
314 ToolInvocationPath = argv[0];
316 std::string ModuleName;
317 std::string ModuleOffsetStr;
318 while (parseModuleNameAndOffset(ModuleName, ModuleOffsetStr)) {
319 symbolize(ModuleName, ModuleOffsetStr);