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/DebugInfo/DWARF/DWARFContext.h"
18 #include "llvm/Object/ELFObjectFile.h"
19 #include "llvm/Object/MachO.h"
20 #include "llvm/Support/Casting.h"
21 #include "llvm/Support/Compression.h"
22 #include "llvm/Support/DataExtractor.h"
23 #include "llvm/Support/Errc.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/Path.h"
33 static bool error(std::error_code ec) {
36 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
40 static DILineInfoSpecifier
41 getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
42 return DILineInfoSpecifier(
43 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
47 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
48 : Module(Obj), DebugInfoContext(DICtx) {
49 std::unique_ptr<DataExtractor> OpdExtractor;
50 uint64_t OpdAddress = 0;
51 // Find the .opd (function descriptor) section if any, for big-endian
53 if (Module->getArch() == Triple::ppc64) {
54 for (section_iterator Section : Module->sections()) {
56 if (!error(Section->getName(Name)) && Name == ".opd") {
58 if (!error(Section->getContents(Data))) {
59 OpdExtractor.reset(new DataExtractor(Data, Module->isLittleEndian(),
60 Module->getBytesInAddress()));
61 OpdAddress = Section->getAddress();
67 for (const SymbolRef &Symbol : Module->symbols()) {
68 addSymbol(Symbol, OpdExtractor.get(), OpdAddress);
70 bool NoSymbolTable = (Module->symbol_begin() == Module->symbol_end());
71 if (NoSymbolTable && Module->isELF()) {
72 // Fallback to dynamic symbol table, if regular symbol table is stripped.
73 std::pair<symbol_iterator, symbol_iterator> IDyn =
74 getELFDynamicSymbolIterators(Module);
75 for (symbol_iterator si = IDyn.first, se = IDyn.second; si != se; ++si) {
76 addSymbol(*si, OpdExtractor.get(), OpdAddress);
81 void ModuleInfo::addSymbol(const SymbolRef &Symbol, DataExtractor *OpdExtractor,
82 uint64_t OpdAddress) {
83 SymbolRef::Type SymbolType;
84 if (error(Symbol.getType(SymbolType)))
86 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
88 uint64_t SymbolAddress;
89 if (error(Symbol.getAddress(SymbolAddress)) ||
90 SymbolAddress == UnknownAddressOrSize)
93 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
94 // function descriptors. The first word of the descriptor is a pointer to
95 // the function's code.
96 // For the purposes of symbolization, pretend the symbol's address is that
97 // of the function's code, not the descriptor.
98 uint64_t OpdOffset = SymbolAddress - OpdAddress;
99 uint32_t OpdOffset32 = OpdOffset;
100 if (OpdOffset == OpdOffset32 &&
101 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
102 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
105 // Getting symbol size is linear for Mach-O files, so assume that symbol
106 // occupies the memory range up to the following symbol.
107 if (isa<MachOObjectFile>(Module))
109 else if (error(Symbol.getSize(SymbolSize)) ||
110 SymbolSize == UnknownAddressOrSize)
112 StringRef SymbolName;
113 if (error(Symbol.getName(SymbolName)))
115 // Mach-O symbol table names have leading underscore, skip it.
116 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
117 SymbolName = SymbolName.drop_front();
118 // FIXME: If a function has alias, there are two entries in symbol table
119 // with same address size. Make sure we choose the correct one.
120 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
121 SymbolDesc SD = { SymbolAddress, SymbolSize };
122 M.insert(std::make_pair(SD, SymbolName));
125 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
126 std::string &Name, uint64_t &Addr,
127 uint64_t &Size) const {
128 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
129 if (SymbolMap.empty())
131 SymbolDesc SD = { Address, Address };
132 auto SymbolIterator = SymbolMap.upper_bound(SD);
133 if (SymbolIterator == SymbolMap.begin())
136 if (SymbolIterator->first.Size != 0 &&
137 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
139 Name = SymbolIterator->second.str();
140 Addr = SymbolIterator->first.Addr;
141 Size = SymbolIterator->first.Size;
145 DILineInfo ModuleInfo::symbolizeCode(
146 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
148 if (DebugInfoContext) {
149 LineInfo = DebugInfoContext->getLineInfoForAddress(
150 ModuleOffset, getDILineInfoSpecifier(Opts));
152 // Override function name from symbol table if necessary.
153 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
154 std::string FunctionName;
155 uint64_t Start, Size;
156 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
157 FunctionName, Start, Size)) {
158 LineInfo.FunctionName = FunctionName;
164 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
165 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
166 DIInliningInfo InlinedContext;
167 if (DebugInfoContext) {
168 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
169 ModuleOffset, getDILineInfoSpecifier(Opts));
171 // Make sure there is at least one frame in context.
172 if (InlinedContext.getNumberOfFrames() == 0) {
173 InlinedContext.addFrame(DILineInfo());
175 // Override the function name in lower frame with name from symbol table.
176 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
177 DIInliningInfo PatchedInlinedContext;
178 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
179 DILineInfo LineInfo = InlinedContext.getFrame(i);
181 std::string FunctionName;
182 uint64_t Start, Size;
183 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
184 FunctionName, Start, Size)) {
185 LineInfo.FunctionName = FunctionName;
188 PatchedInlinedContext.addFrame(LineInfo);
190 InlinedContext = PatchedInlinedContext;
192 return InlinedContext;
195 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
196 uint64_t &Start, uint64_t &Size) const {
197 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
201 const char LLVMSymbolizer::kBadString[] = "??";
203 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
204 uint64_t ModuleOffset) {
205 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
207 return printDILineInfo(DILineInfo());
208 if (Opts.PrintInlining) {
209 DIInliningInfo InlinedContext =
210 Info->symbolizeInlinedCode(ModuleOffset, Opts);
211 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
212 assert(FramesNum > 0);
214 for (uint32_t i = 0; i < FramesNum; i++) {
215 DILineInfo LineInfo = InlinedContext.getFrame(i);
216 Result += printDILineInfo(LineInfo);
220 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
221 return printDILineInfo(LineInfo);
224 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
225 uint64_t ModuleOffset) {
226 std::string Name = kBadString;
229 if (Opts.UseSymbolTable) {
230 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
231 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
232 Name = DemangleName(Name);
235 std::stringstream ss;
236 ss << Name << "\n" << Start << " " << Size << "\n";
240 void LLVMSymbolizer::flush() {
241 DeleteContainerSeconds(Modules);
242 ObjectPairForPathArch.clear();
243 ObjectFileForArch.clear();
246 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
247 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
248 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
249 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
251 std::string getDarwinDWARFResourceForPath(
252 const std::string &Path, const std::string &Basename) {
253 SmallString<16> ResourceName = StringRef(Path);
254 if (sys::path::extension(Path) != ".dSYM") {
255 ResourceName += ".dSYM";
257 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
258 sys::path::append(ResourceName, Basename);
259 return ResourceName.str();
262 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
263 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
264 MemoryBuffer::getFileOrSTDIN(Path);
267 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
270 static bool findDebugBinary(const std::string &OrigPath,
271 const std::string &DebuglinkName, uint32_t CRCHash,
272 std::string &Result) {
273 std::string OrigRealPath = OrigPath;
274 #if defined(HAVE_REALPATH)
275 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
280 SmallString<16> OrigDir(OrigRealPath);
281 llvm::sys::path::remove_filename(OrigDir);
282 SmallString<16> DebugPath = OrigDir;
283 // Try /path/to/original_binary/debuglink_name
284 llvm::sys::path::append(DebugPath, DebuglinkName);
285 if (checkFileCRC(DebugPath, CRCHash)) {
286 Result = DebugPath.str();
289 // Try /path/to/original_binary/.debug/debuglink_name
290 DebugPath = OrigRealPath;
291 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
292 if (checkFileCRC(DebugPath, CRCHash)) {
293 Result = DebugPath.str();
296 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
297 DebugPath = "/usr/lib/debug";
298 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
300 if (checkFileCRC(DebugPath, CRCHash)) {
301 Result = DebugPath.str();
307 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
311 for (const SectionRef &Section : Obj->sections()) {
313 Section.getName(Name);
314 Name = Name.substr(Name.find_first_not_of("._"));
315 if (Name == "gnu_debuglink") {
317 Section.getContents(Data);
318 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
320 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
321 // 4-byte align the offset.
322 Offset = (Offset + 3) & ~0x3;
323 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
324 DebugName = DebugNameStr;
325 CRCHash = DE.getU32(&Offset);
336 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
337 const MachOObjectFile *Obj) {
338 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
339 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
340 if (dbg_uuid.empty() || bin_uuid.empty())
342 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
345 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
346 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
347 // On Darwin we may find DWARF in separate object file in
348 // resource directory.
349 std::vector<std::string> DsymPaths;
350 StringRef Filename = sys::path::filename(ExePath);
351 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
352 for (const auto &Path : Opts.DsymHints) {
353 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
355 for (const auto &path : DsymPaths) {
356 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
357 std::error_code EC = BinaryOrErr.getError();
358 if (EC != errc::no_such_file_or_directory && !error(EC)) {
359 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
361 getObjectFileFromBinary(B.getBinary(), ArchName);
362 const MachOObjectFile *MachDbgObj =
363 dyn_cast<const MachOObjectFile>(DbgObj);
364 if (!MachDbgObj) continue;
365 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
366 addOwningBinary(std::move(B));
374 LLVMSymbolizer::ObjectPair
375 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
376 const std::string &ArchName) {
377 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
378 if (I != ObjectPairForPathArch.end())
380 ObjectFile *Obj = nullptr;
381 ObjectFile *DbgObj = nullptr;
382 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
383 if (!error(BinaryOrErr.getError())) {
384 OwningBinary<Binary> &B = BinaryOrErr.get();
385 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
387 ObjectPair Res = std::make_pair(nullptr, nullptr);
388 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
391 addOwningBinary(std::move(B));
392 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
393 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
394 // Try to locate the debug binary using .gnu_debuglink section.
396 std::string DebuglinkName;
398 std::string DebugBinaryPath;
399 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
400 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
401 BinaryOrErr = createBinary(DebugBinaryPath);
402 if (!error(BinaryOrErr.getError())) {
403 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
404 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
405 addOwningBinary(std::move(B));
412 ObjectPair Res = std::make_pair(Obj, DbgObj);
413 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
418 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
419 const std::string &ArchName) {
422 ObjectFile *Res = nullptr;
423 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
424 const auto &I = ObjectFileForArch.find(
425 std::make_pair(UB, ArchName));
426 if (I != ObjectFileForArch.end())
428 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
429 UB->getObjectForArch(Triple(ArchName).getArch());
431 Res = ParsedObj.get().get();
432 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
434 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
435 } else if (Bin->isObject()) {
436 Res = cast<ObjectFile>(Bin);
442 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
443 const auto &I = Modules.find(ModuleName);
444 if (I != Modules.end())
446 std::string BinaryName = ModuleName;
447 std::string ArchName = Opts.DefaultArch;
448 size_t ColonPos = ModuleName.find_last_of(':');
449 // Verify that substring after colon form a valid arch name.
450 if (ColonPos != std::string::npos) {
451 std::string ArchStr = ModuleName.substr(ColonPos + 1);
452 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
453 BinaryName = ModuleName.substr(0, ColonPos);
457 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
459 if (!Objects.first) {
460 // Failed to find valid object file.
461 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
464 DIContext *Context = new DWARFContextInMemory(*Objects.second);
466 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
467 Modules.insert(make_pair(ModuleName, Info));
471 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
472 // By default, DILineInfo contains "<invalid>" for function/filename it
473 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
474 static const std::string kDILineInfoBadString = "<invalid>";
475 std::stringstream Result;
476 if (Opts.PrintFunctions != FunctionNameKind::None) {
477 std::string FunctionName = LineInfo.FunctionName;
478 if (FunctionName == kDILineInfoBadString)
479 FunctionName = kBadString;
480 else if (Opts.Demangle)
481 FunctionName = DemangleName(FunctionName);
482 Result << FunctionName << "\n";
484 std::string Filename = LineInfo.FileName;
485 if (Filename == kDILineInfoBadString)
486 Filename = kBadString;
487 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
491 #if !defined(_MSC_VER)
492 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
493 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
494 size_t *length, int *status);
497 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
498 #if !defined(_MSC_VER)
499 // We can spoil names of symbols with C linkage, so use an heuristic
500 // approach to check if the name should be demangled.
501 if (Name.substr(0, 2) != "_Z")
504 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
507 std::string Result = DemangledName;
515 } // namespace symbolize