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"
39 using namespace object;
42 UseSymbolTable("use-symbol-table", cl::init(true),
43 cl::desc("Prefer names in symbol table to names "
47 PrintFunctions("functions", cl::init(true),
48 cl::desc("Print function names as well as line "
49 "information for a given address"));
52 PrintInlining("inlining", cl::init(true),
53 cl::desc("Print all inlined frames for a given address"));
56 Demangle("demangle", cl::init(true),
57 cl::desc("Demangle function names"));
59 static StringRef ToolInvocationPath;
61 static bool error(error_code ec) {
62 if (!ec) return false;
63 errs() << ToolInvocationPath << ": error reading file: "
64 << ec.message() << ".\n";
68 static uint32_t getDILineInfoSpecifierFlags() {
69 uint32_t Flags = llvm::DILineInfoSpecifier::FileLineInfo |
70 llvm::DILineInfoSpecifier::AbsoluteFilePath;
72 Flags |= llvm::DILineInfoSpecifier::FunctionName;
76 static 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());
85 OwningPtr<ObjectFile> Module;
86 OwningPtr<DIContext> DebugInfoContext;
88 ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
89 : Module(Obj), DebugInfoContext(DICtx) {}
91 DILineInfo symbolizeCode(uint64_t ModuleOffset) const {
93 if (DebugInfoContext) {
94 LineInfo = DebugInfoContext->getLineInfoForAddress(
95 ModuleOffset, getDILineInfoSpecifierFlags());
97 // Override function name from symbol table if necessary.
98 if (PrintFunctions && UseSymbolTable) {
100 if (getFunctionNameFromSymbolTable(ModuleOffset, Function)) {
101 patchFunctionNameInDILineInfo(Function, LineInfo);
107 DIInliningInfo symbolizeInlinedCode(uint64_t ModuleOffset) const {
108 DIInliningInfo InlinedContext;
109 if (DebugInfoContext) {
110 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
111 ModuleOffset, getDILineInfoSpecifierFlags());
113 // Make sure there is at least one frame in context.
114 if (InlinedContext.getNumberOfFrames() == 0) {
115 InlinedContext.addFrame(DILineInfo());
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();
122 DILineInfo LineInfo = InlinedContext.getFrame(i);
124 std::string Function;
125 if (getFunctionNameFromSymbolTable(ModuleOffset, Function)) {
126 patchFunctionNameInDILineInfo(Function, LineInfo);
129 PatchedInlinedContext.addFrame(LineInfo);
131 InlinedContext = PatchedInlinedContext;
133 return InlinedContext;
137 bool getFunctionNameFromSymbolTable(uint64_t Address,
138 std::string &FunctionName) const {
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;
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) {
158 if (error(si->getName(Name))) continue;
159 FunctionName = Name.str();
167 typedef std::map<std::string, ModuleInfo*> ModuleMapTy;
168 typedef ModuleMapTy::iterator ModuleMapIter;
171 static ModuleMapTy Modules;
173 static bool isFullNameOfDwarfSection(const StringRef &FullName,
174 const StringRef &ShortName) {
175 static const char kDwarfPrefix[] = "__DWARF,";
176 StringRef Name = FullName;
177 // Skip "__DWARF," prefix.
178 if (Name.startswith(kDwarfPrefix))
179 Name = Name.substr(strlen(kDwarfPrefix));
180 // Skip . and _ prefixes.
181 Name = Name.substr(Name.find_first_not_of("._"));
182 return (Name == ShortName);
185 // Returns true if the object endianness is known.
186 static bool getObjectEndianness(const ObjectFile *Obj,
187 bool &IsLittleEndian) {
188 // FIXME: Implement this when libLLVMObject allows to do it easily.
189 IsLittleEndian = true;
193 static void getDebugInfoSections(const ObjectFile *Obj,
194 StringRef &DebugInfoSection,
195 StringRef &DebugAbbrevSection,
196 StringRef &DebugLineSection,
197 StringRef &DebugArangesSection,
198 StringRef &DebugStringSection,
199 StringRef &DebugRangesSection) {
203 for (section_iterator i = Obj->begin_sections(),
204 e = Obj->end_sections();
205 i != e; i.increment(ec)) {
206 if (error(ec)) break;
208 if (error(i->getName(Name))) continue;
210 if (error(i->getContents(Data))) continue;
211 if (isFullNameOfDwarfSection(Name, "debug_info"))
212 DebugInfoSection = Data;
213 else if (isFullNameOfDwarfSection(Name, "debug_abbrev"))
214 DebugAbbrevSection = Data;
215 else if (isFullNameOfDwarfSection(Name, "debug_line"))
216 DebugLineSection = Data;
217 // Don't use debug_aranges for now, as address ranges contained
218 // there may not cover all instructions in the module
219 // else if (isFullNameOfDwarfSection(Name, "debug_aranges"))
220 // DebugArangesSection = Data;
221 else if (isFullNameOfDwarfSection(Name, "debug_str"))
222 DebugStringSection = Data;
223 else if (isFullNameOfDwarfSection(Name, "debug_ranges"))
224 DebugRangesSection = Data;
228 static ObjectFile *getObjectFile(const std::string &Path) {
229 OwningPtr<MemoryBuffer> Buff;
230 MemoryBuffer::getFile(Path, Buff);
231 return ObjectFile::createObjectFile(Buff.take());
234 static std::string getDarwinDWARFResourceForModule(const std::string &Path) {
235 StringRef Basename = sys::path::filename(Path);
236 const std::string &DSymDirectory = Path + ".dSYM";
237 SmallString<16> ResourceName = StringRef(DSymDirectory);
238 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
239 sys::path::append(ResourceName, Basename);
240 return ResourceName.str();
243 static ModuleInfo *getOrCreateModuleInfo(const std::string &ModuleName) {
244 ModuleMapIter I = Modules.find(ModuleName);
245 if (I != Modules.end())
248 ObjectFile *Obj = getObjectFile(ModuleName);
250 // Module name doesn't point to a valid object file.
251 Modules.insert(make_pair(ModuleName, (ModuleInfo*)0));
255 DIContext *Context = 0;
257 if (getObjectEndianness(Obj, IsLittleEndian)) {
259 StringRef DebugAbbrev;
261 StringRef DebugAranges;
262 StringRef DebugString;
263 StringRef DebugRanges;
264 getDebugInfoSections(Obj, DebugInfo, DebugAbbrev, DebugLine,
265 DebugAranges, DebugString, DebugRanges);
267 // On Darwin we may find DWARF in separate object file in
268 // resource directory.
269 if (isa<MachOObjectFile>(Obj)) {
270 const std::string &ResourceName = getDarwinDWARFResourceForModule(
272 ObjectFile *ResourceObj = getObjectFile(ResourceName);
273 if (ResourceObj != 0)
274 getDebugInfoSections(ResourceObj, DebugInfo, DebugAbbrev, DebugLine,
275 DebugAranges, DebugString, DebugRanges);
278 Context = DIContext::getDWARFContext(
279 IsLittleEndian, DebugInfo, DebugAbbrev,
280 DebugAranges, DebugLine, DebugString,
285 ModuleInfo *Info = new ModuleInfo(Obj, Context);
286 Modules.insert(make_pair(ModuleName, Info));
290 #if !defined(_MSC_VER)
291 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
292 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
293 size_t *length, int *status);
296 static void printDILineInfo(DILineInfo LineInfo) {
297 // By default, DILineInfo contains "<invalid>" for function/filename it
298 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
299 static const std::string kDILineInfoBadString = "<invalid>";
300 static const std::string kSymbolizerBadString = "??";
301 if (PrintFunctions) {
302 std::string FunctionName = LineInfo.getFunctionName();
303 if (FunctionName == kDILineInfoBadString)
304 FunctionName = kSymbolizerBadString;
305 #if !defined(_MSC_VER)
308 char *DemangledName = __cxa_demangle(
309 FunctionName.c_str(), 0, 0, &status);
311 FunctionName = DemangledName;
316 outs() << FunctionName << "\n";
318 std::string Filename = LineInfo.getFileName();
319 if (Filename == kDILineInfoBadString)
320 Filename = kSymbolizerBadString;
321 outs() << Filename <<
322 ":" << LineInfo.getLine() <<
323 ":" << LineInfo.getColumn() <<
327 static void symbolize(std::string ModuleName, std::string ModuleOffsetStr) {
328 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
331 StringRef(ModuleOffsetStr).getAsInteger(0, Offset)) {
332 printDILineInfo(DILineInfo());
333 } else if (PrintInlining) {
334 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(Offset);
335 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
336 assert(FramesNum > 0);
337 for (uint32_t i = 0; i < FramesNum; i++) {
338 DILineInfo LineInfo = InlinedContext.getFrame(i);
339 printDILineInfo(LineInfo);
342 DILineInfo LineInfo = Info->symbolizeCode(Offset);
343 printDILineInfo(LineInfo);
346 outs() << "\n"; // Print extra empty line to mark the end of output.
350 static bool parseModuleNameAndOffset(std::string &ModuleName,
351 std::string &ModuleOffsetStr) {
352 static const int kMaxInputStringLength = 1024;
353 static const char kDelimiters[] = " \n";
354 char InputString[kMaxInputStringLength];
355 if (!fgets(InputString, sizeof(InputString), stdin))
358 ModuleOffsetStr = "";
359 // FIXME: Handle case when filename is given in quotes.
360 if (char *FilePath = strtok(InputString, kDelimiters)) {
361 ModuleName = FilePath;
362 if (char *OffsetStr = strtok((char*)0, kDelimiters))
363 ModuleOffsetStr = OffsetStr;
368 int main(int argc, char **argv) {
369 // Print stack trace if we signal out.
370 sys::PrintStackTraceOnErrorSignal();
371 PrettyStackTraceProgram X(argc, argv);
372 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
374 cl::ParseCommandLineOptions(argc, argv, "llvm symbolizer for compiler-rt\n");
375 ToolInvocationPath = argv[0];
377 std::string ModuleName;
378 std::string ModuleOffsetStr;
379 while (parseModuleNameAndOffset(ModuleName, ModuleOffsetStr)) {
380 symbolize(ModuleName, ModuleOffsetStr);