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/DebugInfo/PDB/PDB.h"
19 #include "llvm/DebugInfo/PDB/PDBContext.h"
20 #include "llvm/Object/ELFObjectFile.h"
21 #include "llvm/Object/MachO.h"
22 #include "llvm/Support/Casting.h"
23 #include "llvm/Support/Compression.h"
24 #include "llvm/Support/DataExtractor.h"
25 #include "llvm/Support/Errc.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Path.h"
35 static bool error(std::error_code ec) {
38 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
42 static DILineInfoSpecifier
43 getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
44 return DILineInfoSpecifier(
45 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
49 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
50 : Module(Obj), DebugInfoContext(DICtx) {
51 std::unique_ptr<DataExtractor> OpdExtractor;
52 uint64_t OpdAddress = 0;
53 // Find the .opd (function descriptor) section if any, for big-endian
55 if (Module->getArch() == Triple::ppc64) {
56 for (section_iterator Section : Module->sections()) {
58 if (!error(Section->getName(Name)) && Name == ".opd") {
60 if (!error(Section->getContents(Data))) {
61 OpdExtractor.reset(new DataExtractor(Data, Module->isLittleEndian(),
62 Module->getBytesInAddress()));
63 OpdAddress = Section->getAddress();
69 for (const SymbolRef &Symbol : Module->symbols()) {
70 addSymbol(Symbol, OpdExtractor.get(), OpdAddress);
72 bool NoSymbolTable = (Module->symbol_begin() == Module->symbol_end());
73 if (NoSymbolTable && Module->isELF()) {
74 // Fallback to dynamic symbol table, if regular symbol table is stripped.
75 std::pair<symbol_iterator, symbol_iterator> IDyn =
76 getELFDynamicSymbolIterators(Module);
77 for (symbol_iterator si = IDyn.first, se = IDyn.second; si != se; ++si) {
78 addSymbol(*si, OpdExtractor.get(), OpdAddress);
83 void ModuleInfo::addSymbol(const SymbolRef &Symbol, DataExtractor *OpdExtractor,
84 uint64_t OpdAddress) {
85 SymbolRef::Type SymbolType;
86 if (error(Symbol.getType(SymbolType)))
88 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
90 uint64_t SymbolAddress;
91 if (error(Symbol.getAddress(SymbolAddress)) ||
92 SymbolAddress == UnknownAddressOrSize)
95 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
96 // function descriptors. The first word of the descriptor is a pointer to
97 // the function's code.
98 // For the purposes of symbolization, pretend the symbol's address is that
99 // of the function's code, not the descriptor.
100 uint64_t OpdOffset = SymbolAddress - OpdAddress;
101 uint32_t OpdOffset32 = OpdOffset;
102 if (OpdOffset == OpdOffset32 &&
103 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
104 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
107 // Getting symbol size is linear for Mach-O files, so assume that symbol
108 // occupies the memory range up to the following symbol.
109 if (isa<MachOObjectFile>(Module))
111 else if (error(Symbol.getSize(SymbolSize)) ||
112 SymbolSize == UnknownAddressOrSize)
114 StringRef SymbolName;
115 if (error(Symbol.getName(SymbolName)))
117 // Mach-O symbol table names have leading underscore, skip it.
118 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
119 SymbolName = SymbolName.drop_front();
120 // FIXME: If a function has alias, there are two entries in symbol table
121 // with same address size. Make sure we choose the correct one.
122 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
123 SymbolDesc SD = { SymbolAddress, SymbolSize };
124 M.insert(std::make_pair(SD, SymbolName));
127 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
128 std::string &Name, uint64_t &Addr,
129 uint64_t &Size) const {
130 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
131 if (SymbolMap.empty())
133 SymbolDesc SD = { Address, Address };
134 auto SymbolIterator = SymbolMap.upper_bound(SD);
135 if (SymbolIterator == SymbolMap.begin())
138 if (SymbolIterator->first.Size != 0 &&
139 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
141 Name = SymbolIterator->second.str();
142 Addr = SymbolIterator->first.Addr;
143 Size = SymbolIterator->first.Size;
147 DILineInfo ModuleInfo::symbolizeCode(
148 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
150 if (DebugInfoContext) {
151 LineInfo = DebugInfoContext->getLineInfoForAddress(
152 ModuleOffset, getDILineInfoSpecifier(Opts));
154 // Override function name from symbol table if necessary.
155 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
156 std::string FunctionName;
157 uint64_t Start, Size;
158 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
159 FunctionName, Start, Size)) {
160 LineInfo.FunctionName = FunctionName;
166 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
167 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
168 DIInliningInfo InlinedContext;
170 if (DebugInfoContext) {
171 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
172 ModuleOffset, getDILineInfoSpecifier(Opts));
174 // Make sure there is at least one frame in context.
175 if (InlinedContext.getNumberOfFrames() == 0) {
176 InlinedContext.addFrame(DILineInfo());
178 // Override the function name in lower frame with name from symbol table.
179 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
180 DIInliningInfo PatchedInlinedContext;
181 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
182 DILineInfo LineInfo = InlinedContext.getFrame(i);
184 std::string FunctionName;
185 uint64_t Start, Size;
186 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
187 FunctionName, Start, Size)) {
188 LineInfo.FunctionName = FunctionName;
191 PatchedInlinedContext.addFrame(LineInfo);
193 InlinedContext = PatchedInlinedContext;
195 return InlinedContext;
198 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
199 uint64_t &Start, uint64_t &Size) const {
200 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
204 const char LLVMSymbolizer::kBadString[] = "??";
206 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
207 uint64_t ModuleOffset) {
208 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
210 return printDILineInfo(DILineInfo());
211 if (Opts.PrintInlining) {
212 DIInliningInfo InlinedContext =
213 Info->symbolizeInlinedCode(ModuleOffset, Opts);
214 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
215 assert(FramesNum > 0);
217 for (uint32_t i = 0; i < FramesNum; i++) {
218 DILineInfo LineInfo = InlinedContext.getFrame(i);
219 Result += printDILineInfo(LineInfo);
223 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
224 return printDILineInfo(LineInfo);
227 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
228 uint64_t ModuleOffset) {
229 std::string Name = kBadString;
232 if (Opts.UseSymbolTable) {
233 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
234 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
235 Name = DemangleName(Name);
238 std::stringstream ss;
239 ss << Name << "\n" << Start << " " << Size << "\n";
243 void LLVMSymbolizer::flush() {
244 DeleteContainerSeconds(Modules);
245 ObjectPairForPathArch.clear();
246 ObjectFileForArch.clear();
249 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
250 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
251 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
252 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
254 std::string getDarwinDWARFResourceForPath(
255 const std::string &Path, const std::string &Basename) {
256 SmallString<16> ResourceName = StringRef(Path);
257 if (sys::path::extension(Path) != ".dSYM") {
258 ResourceName += ".dSYM";
260 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
261 sys::path::append(ResourceName, Basename);
262 return ResourceName.str();
265 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
266 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
267 MemoryBuffer::getFileOrSTDIN(Path);
270 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
273 static bool findDebugBinary(const std::string &OrigPath,
274 const std::string &DebuglinkName, uint32_t CRCHash,
275 std::string &Result) {
276 std::string OrigRealPath = OrigPath;
277 #if defined(HAVE_REALPATH)
278 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
283 SmallString<16> OrigDir(OrigRealPath);
284 llvm::sys::path::remove_filename(OrigDir);
285 SmallString<16> DebugPath = OrigDir;
286 // Try /path/to/original_binary/debuglink_name
287 llvm::sys::path::append(DebugPath, DebuglinkName);
288 if (checkFileCRC(DebugPath, CRCHash)) {
289 Result = DebugPath.str();
292 // Try /path/to/original_binary/.debug/debuglink_name
293 DebugPath = OrigRealPath;
294 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
295 if (checkFileCRC(DebugPath, CRCHash)) {
296 Result = DebugPath.str();
299 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
300 DebugPath = "/usr/lib/debug";
301 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
303 if (checkFileCRC(DebugPath, CRCHash)) {
304 Result = DebugPath.str();
310 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
314 for (const SectionRef &Section : Obj->sections()) {
316 Section.getName(Name);
317 Name = Name.substr(Name.find_first_not_of("._"));
318 if (Name == "gnu_debuglink") {
320 Section.getContents(Data);
321 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
323 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
324 // 4-byte align the offset.
325 Offset = (Offset + 3) & ~0x3;
326 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
327 DebugName = DebugNameStr;
328 CRCHash = DE.getU32(&Offset);
339 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
340 const MachOObjectFile *Obj) {
341 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
342 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
343 if (dbg_uuid.empty() || bin_uuid.empty())
345 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
348 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
349 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
350 // On Darwin we may find DWARF in separate object file in
351 // resource directory.
352 std::vector<std::string> DsymPaths;
353 StringRef Filename = sys::path::filename(ExePath);
354 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
355 for (const auto &Path : Opts.DsymHints) {
356 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
358 for (const auto &path : DsymPaths) {
359 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
360 std::error_code EC = BinaryOrErr.getError();
361 if (EC != errc::no_such_file_or_directory && !error(EC)) {
362 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
364 getObjectFileFromBinary(B.getBinary(), ArchName);
365 const MachOObjectFile *MachDbgObj =
366 dyn_cast<const MachOObjectFile>(DbgObj);
367 if (!MachDbgObj) continue;
368 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
369 addOwningBinary(std::move(B));
377 LLVMSymbolizer::ObjectPair
378 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
379 const std::string &ArchName) {
380 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
381 if (I != ObjectPairForPathArch.end())
383 ObjectFile *Obj = nullptr;
384 ObjectFile *DbgObj = nullptr;
385 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
386 if (!error(BinaryOrErr.getError())) {
387 OwningBinary<Binary> &B = BinaryOrErr.get();
388 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
390 ObjectPair Res = std::make_pair(nullptr, nullptr);
391 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
394 addOwningBinary(std::move(B));
395 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
396 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
397 // Try to locate the debug binary using .gnu_debuglink section.
399 std::string DebuglinkName;
401 std::string DebugBinaryPath;
402 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
403 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
404 BinaryOrErr = createBinary(DebugBinaryPath);
405 if (!error(BinaryOrErr.getError())) {
406 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
407 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
408 addOwningBinary(std::move(B));
415 ObjectPair Res = std::make_pair(Obj, DbgObj);
416 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
421 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
422 const std::string &ArchName) {
425 ObjectFile *Res = nullptr;
426 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
427 const auto &I = ObjectFileForArch.find(
428 std::make_pair(UB, ArchName));
429 if (I != ObjectFileForArch.end())
431 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
432 UB->getObjectForArch(Triple(ArchName).getArch());
434 Res = ParsedObj.get().get();
435 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
437 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
438 } else if (Bin->isObject()) {
439 Res = cast<ObjectFile>(Bin);
445 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
446 const auto &I = Modules.find(ModuleName);
447 if (I != Modules.end())
449 std::string BinaryName = ModuleName;
450 std::string ArchName = Opts.DefaultArch;
451 size_t ColonPos = ModuleName.find_last_of(':');
452 // Verify that substring after colon form a valid arch name.
453 if (ColonPos != std::string::npos) {
454 std::string ArchStr = ModuleName.substr(ColonPos + 1);
455 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
456 BinaryName = ModuleName.substr(0, ColonPos);
460 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
462 if (!Objects.first) {
463 // Failed to find valid object file.
464 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
467 DIContext *Context = nullptr;
468 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
469 // If this is a COFF object, assume it contains PDB debug information. If
470 // we don't find any we will fall back to the DWARF case.
471 std::unique_ptr<IPDBSession> Session;
472 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
473 Objects.first->getFileName(), Session);
474 if (Error == PDB_ErrorCode::Success)
475 Context = new PDBContext(*CoffObject, std::move(Session));
478 Context = new DWARFContextInMemory(*Objects.second);
480 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
481 Modules.insert(make_pair(ModuleName, Info));
485 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
486 // By default, DILineInfo contains "<invalid>" for function/filename it
487 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
488 static const std::string kDILineInfoBadString = "<invalid>";
489 std::stringstream Result;
490 if (Opts.PrintFunctions != FunctionNameKind::None) {
491 std::string FunctionName = LineInfo.FunctionName;
492 if (FunctionName == kDILineInfoBadString)
493 FunctionName = kBadString;
494 else if (Opts.Demangle)
495 FunctionName = DemangleName(FunctionName);
496 Result << FunctionName << "\n";
498 std::string Filename = LineInfo.FileName;
499 if (Filename == kDILineInfoBadString)
500 Filename = kBadString;
501 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
505 #if !defined(_MSC_VER)
506 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
507 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
508 size_t *length, int *status);
511 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
512 #if !defined(_MSC_VER)
513 // We can spoil names of symbols with C linkage, so use an heuristic
514 // approach to check if the name should be demangled.
515 if (Name.substr(0, 2) != "_Z")
518 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
521 std::string Result = DemangledName;
529 } // namespace symbolize