1 //===-- LLVMSymbolize.cpp -------------------------------------------------===//
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 // Implementation for LLVM symbolization library.
12 //===----------------------------------------------------------------------===//
14 #include "LLVMSymbolize.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/Config/config.h"
17 #include "llvm/Object/MachO.h"
18 #include "llvm/Support/Casting.h"
19 #include "llvm/Support/Compression.h"
20 #include "llvm/Support/DataExtractor.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/Path.h"
31 static bool error(error_code ec) {
34 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
39 getDILineInfoSpecifierFlags(const LLVMSymbolizer::Options &Opts) {
40 uint32_t Flags = llvm::DILineInfoSpecifier::FileLineInfo |
41 llvm::DILineInfoSpecifier::AbsoluteFilePath;
42 if (Opts.PrintFunctions)
43 Flags |= llvm::DILineInfoSpecifier::FunctionName;
47 static void patchFunctionNameInDILineInfo(const std::string &NewFunctionName,
48 DILineInfo &LineInfo) {
49 std::string FileName = LineInfo.getFileName();
50 LineInfo = DILineInfo(StringRef(FileName), StringRef(NewFunctionName),
51 LineInfo.getLine(), LineInfo.getColumn());
54 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
55 : Module(Obj), DebugInfoContext(DICtx) {
57 for (symbol_iterator si = Module->begin_symbols(), se = Module->end_symbols();
58 si != se; si.increment(ec)) {
61 SymbolRef::Type SymbolType;
62 if (error(si->getType(SymbolType)))
64 if (SymbolType != SymbolRef::ST_Function &&
65 SymbolType != SymbolRef::ST_Data)
67 uint64_t SymbolAddress;
68 if (error(si->getAddress(SymbolAddress)) ||
69 SymbolAddress == UnknownAddressOrSize)
72 // Getting symbol size is linear for Mach-O files, so assume that symbol
73 // occupies the memory range up to the following symbol.
74 if (isa<MachOObjectFile>(Obj))
76 else if (error(si->getSize(SymbolSize)) ||
77 SymbolSize == UnknownAddressOrSize)
80 if (error(si->getName(SymbolName)))
82 // Mach-O symbol table names have leading underscore, skip it.
83 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
84 SymbolName = SymbolName.drop_front();
85 // FIXME: If a function has alias, there are two entries in symbol table
86 // with same address size. Make sure we choose the correct one.
87 SymbolMapTy &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
88 SymbolDesc SD = { SymbolAddress, SymbolSize };
89 M.insert(std::make_pair(SD, SymbolName));
93 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
94 std::string &Name, uint64_t &Addr,
95 uint64_t &Size) const {
96 const SymbolMapTy &M = Type == SymbolRef::ST_Function ? Functions : Objects;
99 SymbolDesc SD = { Address, Address };
100 SymbolMapTy::const_iterator it = M.upper_bound(SD);
104 if (it->first.Size != 0 && it->first.Addr + it->first.Size <= Address)
106 Name = it->second.str();
107 Addr = it->first.Addr;
108 Size = it->first.Size;
112 DILineInfo ModuleInfo::symbolizeCode(
113 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
115 if (DebugInfoContext) {
116 LineInfo = DebugInfoContext->getLineInfoForAddress(
117 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
119 // Override function name from symbol table if necessary.
120 if (Opts.PrintFunctions && Opts.UseSymbolTable) {
121 std::string FunctionName;
122 uint64_t Start, Size;
123 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
124 FunctionName, Start, Size)) {
125 patchFunctionNameInDILineInfo(FunctionName, LineInfo);
131 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
132 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
133 DIInliningInfo InlinedContext;
134 if (DebugInfoContext) {
135 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
136 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
138 // Make sure there is at least one frame in context.
139 if (InlinedContext.getNumberOfFrames() == 0) {
140 InlinedContext.addFrame(DILineInfo());
142 // Override the function name in lower frame with name from symbol table.
143 if (Opts.PrintFunctions && Opts.UseSymbolTable) {
144 DIInliningInfo PatchedInlinedContext;
145 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
146 DILineInfo LineInfo = InlinedContext.getFrame(i);
148 std::string FunctionName;
149 uint64_t Start, Size;
150 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
151 FunctionName, Start, Size)) {
152 patchFunctionNameInDILineInfo(FunctionName, LineInfo);
155 PatchedInlinedContext.addFrame(LineInfo);
157 InlinedContext = PatchedInlinedContext;
159 return InlinedContext;
162 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
163 uint64_t &Start, uint64_t &Size) const {
164 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
168 const char LLVMSymbolizer::kBadString[] = "??";
170 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
171 uint64_t ModuleOffset) {
172 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
174 return printDILineInfo(DILineInfo());
175 if (Opts.PrintInlining) {
176 DIInliningInfo InlinedContext =
177 Info->symbolizeInlinedCode(ModuleOffset, Opts);
178 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
179 assert(FramesNum > 0);
181 for (uint32_t i = 0; i < FramesNum; i++) {
182 DILineInfo LineInfo = InlinedContext.getFrame(i);
183 Result += printDILineInfo(LineInfo);
187 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
188 return printDILineInfo(LineInfo);
191 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
192 uint64_t ModuleOffset) {
193 std::string Name = kBadString;
196 if (Opts.UseSymbolTable) {
197 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
198 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
199 Name = DemangleGlobalName(Name);
202 std::stringstream ss;
203 ss << Name << "\n" << Start << " " << Size << "\n";
207 void LLVMSymbolizer::flush() {
208 DeleteContainerSeconds(Modules);
209 DeleteContainerPointers(ParsedBinariesAndObjects);
210 BinaryForPath.clear();
211 ObjectFileForArch.clear();
214 static std::string getDarwinDWARFResourceForPath(const std::string &Path) {
215 StringRef Basename = sys::path::filename(Path);
216 const std::string &DSymDirectory = Path + ".dSYM";
217 SmallString<16> ResourceName = StringRef(DSymDirectory);
218 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
219 sys::path::append(ResourceName, Basename);
220 return ResourceName.str();
223 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
224 OwningPtr<MemoryBuffer> MB;
225 if (MemoryBuffer::getFileOrSTDIN(Path, MB))
227 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB->getBuffer());
230 static bool findDebugBinary(const std::string &OrigPath,
231 const std::string &DebuglinkName, uint32_t CRCHash,
232 std::string &Result) {
233 std::string OrigRealPath = OrigPath;
234 #if defined(HAVE_REALPATH)
235 if (char *RP = realpath(OrigPath.c_str(), NULL)) {
240 SmallString<16> OrigDir(OrigRealPath);
241 llvm::sys::path::remove_filename(OrigDir);
242 SmallString<16> DebugPath = OrigDir;
243 // Try /path/to/original_binary/debuglink_name
244 llvm::sys::path::append(DebugPath, DebuglinkName);
245 if (checkFileCRC(DebugPath, CRCHash)) {
246 Result = DebugPath.str();
249 // Try /path/to/original_binary/.debug/debuglink_name
250 DebugPath = OrigRealPath;
251 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
252 if (checkFileCRC(DebugPath, CRCHash)) {
253 Result = DebugPath.str();
256 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
257 DebugPath = "/usr/lib/debug";
258 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
260 if (checkFileCRC(DebugPath, CRCHash)) {
261 Result = DebugPath.str();
267 static bool getGNUDebuglinkContents(const Binary *Bin, std::string &DebugName,
269 const ObjectFile *Obj = dyn_cast<ObjectFile>(Bin);
273 for (section_iterator I = Obj->begin_sections(), E = Obj->end_sections();
274 I != E; I.increment(EC)) {
277 Name = Name.substr(Name.find_first_not_of("._"));
278 if (Name == "gnu_debuglink") {
280 I->getContents(Data);
281 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
283 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
284 // 4-byte align the offset.
285 Offset = (Offset + 3) & ~0x3;
286 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
287 DebugName = DebugNameStr;
288 CRCHash = DE.getU32(&Offset);
298 LLVMSymbolizer::BinaryPair
299 LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
300 BinaryMapTy::iterator I = BinaryForPath.find(Path);
301 if (I != BinaryForPath.end())
305 OwningPtr<Binary> ParsedBinary;
306 OwningPtr<Binary> ParsedDbgBinary;
307 if (!error(createBinary(Path, ParsedBinary))) {
308 // Check if it's a universal binary.
309 Bin = ParsedBinary.take();
310 ParsedBinariesAndObjects.push_back(Bin);
311 if (Bin->isMachO() || Bin->isMachOUniversalBinary()) {
312 // On Darwin we may find DWARF in separate object file in
313 // resource directory.
314 const std::string &ResourcePath =
315 getDarwinDWARFResourceForPath(Path);
316 bool ResourceFileExists = false;
317 if (!sys::fs::exists(ResourcePath, ResourceFileExists) &&
318 ResourceFileExists &&
319 !error(createBinary(ResourcePath, ParsedDbgBinary))) {
320 DbgBin = ParsedDbgBinary.take();
321 ParsedBinariesAndObjects.push_back(DbgBin);
324 // Try to locate the debug binary using .gnu_debuglink section.
326 std::string DebuglinkName;
328 std::string DebugBinaryPath;
329 if (getGNUDebuglinkContents(Bin, DebuglinkName, CRCHash) &&
330 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath) &&
331 !error(createBinary(DebugBinaryPath, ParsedDbgBinary))) {
332 DbgBin = ParsedDbgBinary.take();
333 ParsedBinariesAndObjects.push_back(DbgBin);
339 BinaryPair Res = std::make_pair(Bin, DbgBin);
340 BinaryForPath[Path] = Res;
345 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin, const std::string &ArchName) {
349 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
350 ObjectFileForArchMapTy::iterator I = ObjectFileForArch.find(
351 std::make_pair(UB, ArchName));
352 if (I != ObjectFileForArch.end())
354 OwningPtr<ObjectFile> ParsedObj;
355 if (!UB->getObjectForArch(Triple(ArchName).getArch(), ParsedObj)) {
356 Res = ParsedObj.take();
357 ParsedBinariesAndObjects.push_back(Res);
359 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
360 } else if (Bin->isObject()) {
361 Res = cast<ObjectFile>(Bin);
367 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
368 ModuleMapTy::iterator I = Modules.find(ModuleName);
369 if (I != Modules.end())
371 std::string BinaryName = ModuleName;
372 std::string ArchName = Opts.DefaultArch;
373 size_t ColonPos = ModuleName.find_last_of(':');
374 // Verify that substring after colon form a valid arch name.
375 if (ColonPos != std::string::npos) {
376 std::string ArchStr = ModuleName.substr(ColonPos + 1);
377 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
378 BinaryName = ModuleName.substr(0, ColonPos);
382 BinaryPair Binaries = getOrCreateBinary(BinaryName);
383 ObjectFile *Obj = getObjectFileFromBinary(Binaries.first, ArchName);
384 ObjectFile *DbgObj = getObjectFileFromBinary(Binaries.second, ArchName);
387 // Failed to find valid object file.
388 Modules.insert(make_pair(ModuleName, (ModuleInfo *)0));
391 DIContext *Context = DIContext::getDWARFContext(DbgObj);
393 ModuleInfo *Info = new ModuleInfo(Obj, Context);
394 Modules.insert(make_pair(ModuleName, Info));
398 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
399 // By default, DILineInfo contains "<invalid>" for function/filename it
400 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
401 static const std::string kDILineInfoBadString = "<invalid>";
402 std::stringstream Result;
403 if (Opts.PrintFunctions) {
404 std::string FunctionName = LineInfo.getFunctionName();
405 if (FunctionName == kDILineInfoBadString)
406 FunctionName = kBadString;
407 else if (Opts.Demangle)
408 FunctionName = DemangleName(FunctionName);
409 Result << FunctionName << "\n";
411 std::string Filename = LineInfo.getFileName();
412 if (Filename == kDILineInfoBadString)
413 Filename = kBadString;
414 Result << Filename << ":" << LineInfo.getLine() << ":" << LineInfo.getColumn()
419 #if !defined(_MSC_VER)
420 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
421 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
422 size_t *length, int *status);
425 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
426 #if !defined(_MSC_VER)
428 char *DemangledName = __cxa_demangle(Name.c_str(), 0, 0, &status);
431 std::string Result = DemangledName;
439 std::string LLVMSymbolizer::DemangleGlobalName(const std::string &Name) {
440 // We can spoil names of globals with C linkage, so use an heuristic
441 // approach to check if the name should be demangled.
442 return (Name.substr(0, 2) == "_Z") ? DemangleName(Name) : Name;
445 } // namespace symbolize