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/ELFObjectFile.h"
18 #include "llvm/Object/MachO.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/Compression.h"
21 #include "llvm/Support/DataExtractor.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #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 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
48 : Module(Obj), DebugInfoContext(DICtx) {
49 for (const SymbolRef &Symbol : Module->symbols()) {
52 bool NoSymbolTable = (Module->symbol_begin() == Module->symbol_end());
53 if (NoSymbolTable && Module->isELF()) {
54 // Fallback to dynamic symbol table, if regular symbol table is stripped.
55 std::pair<symbol_iterator, symbol_iterator> IDyn =
56 getELFDynamicSymbolIterators(Module);
57 for (symbol_iterator si = IDyn.first, se = IDyn.second; si != se; ++si) {
63 void ModuleInfo::addSymbol(const SymbolRef &Symbol) {
64 SymbolRef::Type SymbolType;
65 if (error(Symbol.getType(SymbolType)))
67 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
69 uint64_t SymbolAddress;
70 if (error(Symbol.getAddress(SymbolAddress)) ||
71 SymbolAddress == UnknownAddressOrSize)
74 // Getting symbol size is linear for Mach-O files, so assume that symbol
75 // occupies the memory range up to the following symbol.
76 if (isa<MachOObjectFile>(Module))
78 else if (error(Symbol.getSize(SymbolSize)) ||
79 SymbolSize == UnknownAddressOrSize)
82 if (error(Symbol.getName(SymbolName)))
84 // Mach-O symbol table names have leading underscore, skip it.
85 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
86 SymbolName = SymbolName.drop_front();
87 // FIXME: If a function has alias, there are two entries in symbol table
88 // with same address size. Make sure we choose the correct one.
89 SymbolMapTy &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
90 SymbolDesc SD = { SymbolAddress, SymbolSize };
91 M.insert(std::make_pair(SD, SymbolName));
94 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
95 std::string &Name, uint64_t &Addr,
96 uint64_t &Size) const {
97 const SymbolMapTy &M = Type == SymbolRef::ST_Function ? Functions : Objects;
100 SymbolDesc SD = { Address, Address };
101 SymbolMapTy::const_iterator it = M.upper_bound(SD);
105 if (it->first.Size != 0 && it->first.Addr + it->first.Size <= Address)
107 Name = it->second.str();
108 Addr = it->first.Addr;
109 Size = it->first.Size;
113 DILineInfo ModuleInfo::symbolizeCode(
114 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
116 if (DebugInfoContext) {
117 LineInfo = DebugInfoContext->getLineInfoForAddress(
118 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
120 // Override function name from symbol table if necessary.
121 if (Opts.PrintFunctions && Opts.UseSymbolTable) {
122 std::string FunctionName;
123 uint64_t Start, Size;
124 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
125 FunctionName, Start, Size)) {
126 LineInfo.FunctionName = FunctionName;
132 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
133 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
134 DIInliningInfo InlinedContext;
135 if (DebugInfoContext) {
136 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
137 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
139 // Make sure there is at least one frame in context.
140 if (InlinedContext.getNumberOfFrames() == 0) {
141 InlinedContext.addFrame(DILineInfo());
143 // Override the function name in lower frame with name from symbol table.
144 if (Opts.PrintFunctions && Opts.UseSymbolTable) {
145 DIInliningInfo PatchedInlinedContext;
146 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
147 DILineInfo LineInfo = InlinedContext.getFrame(i);
149 std::string FunctionName;
150 uint64_t Start, Size;
151 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
152 FunctionName, Start, Size)) {
153 LineInfo.FunctionName = FunctionName;
156 PatchedInlinedContext.addFrame(LineInfo);
158 InlinedContext = PatchedInlinedContext;
160 return InlinedContext;
163 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
164 uint64_t &Start, uint64_t &Size) const {
165 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
169 const char LLVMSymbolizer::kBadString[] = "??";
171 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
172 uint64_t ModuleOffset) {
173 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
175 return printDILineInfo(DILineInfo());
176 if (Opts.PrintInlining) {
177 DIInliningInfo InlinedContext =
178 Info->symbolizeInlinedCode(ModuleOffset, Opts);
179 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
180 assert(FramesNum > 0);
182 for (uint32_t i = 0; i < FramesNum; i++) {
183 DILineInfo LineInfo = InlinedContext.getFrame(i);
184 Result += printDILineInfo(LineInfo);
188 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
189 return printDILineInfo(LineInfo);
192 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
193 uint64_t ModuleOffset) {
194 std::string Name = kBadString;
197 if (Opts.UseSymbolTable) {
198 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
199 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
200 Name = DemangleName(Name);
203 std::stringstream ss;
204 ss << Name << "\n" << Start << " " << Size << "\n";
208 void LLVMSymbolizer::flush() {
209 DeleteContainerSeconds(Modules);
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 std::unique_ptr<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);
272 for (const SectionRef &Section : Obj->sections()) {
274 Section.getName(Name);
275 Name = Name.substr(Name.find_first_not_of("._"));
276 if (Name == "gnu_debuglink") {
278 Section.getContents(Data);
279 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
281 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
282 // 4-byte align the offset.
283 Offset = (Offset + 3) & ~0x3;
284 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
285 DebugName = DebugNameStr;
286 CRCHash = DE.getU32(&Offset);
296 LLVMSymbolizer::BinaryPair
297 LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
298 BinaryMapTy::iterator I = BinaryForPath.find(Path);
299 if (I != BinaryForPath.end())
303 ErrorOr<Binary *> BinaryOrErr = createBinary(Path);
304 if (!error(BinaryOrErr.getError())) {
305 std::unique_ptr<Binary> ParsedBinary(BinaryOrErr.get());
306 // Check if it's a universal binary.
307 Bin = ParsedBinary.get();
308 ParsedBinariesAndObjects.push_back(std::move(ParsedBinary));
309 if (Bin->isMachO() || Bin->isMachOUniversalBinary()) {
310 // On Darwin we may find DWARF in separate object file in
311 // resource directory.
312 const std::string &ResourcePath =
313 getDarwinDWARFResourceForPath(Path);
314 BinaryOrErr = createBinary(ResourcePath);
315 error_code EC = BinaryOrErr.getError();
316 if (EC != errc::no_such_file_or_directory && !error(EC)) {
317 DbgBin = BinaryOrErr.get();
318 ParsedBinariesAndObjects.push_back(std::unique_ptr<Binary>(DbgBin));
321 // Try to locate the debug binary using .gnu_debuglink section.
323 std::string DebuglinkName;
325 std::string DebugBinaryPath;
326 if (getGNUDebuglinkContents(Bin, DebuglinkName, CRCHash) &&
327 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
328 BinaryOrErr = createBinary(DebugBinaryPath);
329 if (!error(BinaryOrErr.getError())) {
330 DbgBin = BinaryOrErr.get();
331 ParsedBinariesAndObjects.push_back(std::unique_ptr<Binary>(DbgBin));
338 BinaryPair Res = std::make_pair(Bin, DbgBin);
339 BinaryForPath[Path] = Res;
344 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin, const std::string &ArchName) {
348 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
349 ObjectFileForArchMapTy::iterator I = ObjectFileForArch.find(
350 std::make_pair(UB, ArchName));
351 if (I != ObjectFileForArch.end())
353 std::unique_ptr<ObjectFile> ParsedObj;
354 if (!UB->getObjectForArch(Triple(ArchName).getArch(), ParsedObj)) {
355 Res = ParsedObj.get();
356 ParsedBinariesAndObjects.push_back(std::move(ParsedObj));
358 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
359 } else if (Bin->isObject()) {
360 Res = cast<ObjectFile>(Bin);
366 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
367 ModuleMapTy::iterator I = Modules.find(ModuleName);
368 if (I != Modules.end())
370 std::string BinaryName = ModuleName;
371 std::string ArchName = Opts.DefaultArch;
372 size_t ColonPos = ModuleName.find_last_of(':');
373 // Verify that substring after colon form a valid arch name.
374 if (ColonPos != std::string::npos) {
375 std::string ArchStr = ModuleName.substr(ColonPos + 1);
376 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
377 BinaryName = ModuleName.substr(0, ColonPos);
381 BinaryPair Binaries = getOrCreateBinary(BinaryName);
382 ObjectFile *Obj = getObjectFileFromBinary(Binaries.first, ArchName);
383 ObjectFile *DbgObj = getObjectFileFromBinary(Binaries.second, ArchName);
386 // Failed to find valid object file.
387 Modules.insert(make_pair(ModuleName, (ModuleInfo *)0));
390 DIContext *Context = DIContext::getDWARFContext(DbgObj);
392 ModuleInfo *Info = new ModuleInfo(Obj, Context);
393 Modules.insert(make_pair(ModuleName, Info));
397 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
398 // By default, DILineInfo contains "<invalid>" for function/filename it
399 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
400 static const std::string kDILineInfoBadString = "<invalid>";
401 std::stringstream Result;
402 if (Opts.PrintFunctions) {
403 std::string FunctionName = LineInfo.FunctionName;
404 if (FunctionName == kDILineInfoBadString)
405 FunctionName = kBadString;
406 else if (Opts.Demangle)
407 FunctionName = DemangleName(FunctionName);
408 Result << FunctionName << "\n";
410 std::string Filename = LineInfo.FileName;
411 if (Filename == kDILineInfoBadString)
412 Filename = kBadString;
413 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
417 #if !defined(_MSC_VER)
418 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
419 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
420 size_t *length, int *status);
423 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
424 #if !defined(_MSC_VER)
425 // We can spoil names of symbols with C linkage, so use an heuristic
426 // approach to check if the name should be demangled.
427 if (Name.substr(0, 2) != "_Z")
430 char *DemangledName = __cxa_demangle(Name.c_str(), 0, 0, &status);
433 std::string Result = DemangledName;
441 } // namespace symbolize