1 //===-- LLVMSymbolize.cpp -------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // Implementation for LLVM symbolization library.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/DebugInfo/Symbolize/Symbolize.h"
15 #include "SymbolizableObjectFile.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/BinaryFormat/COFF.h"
19 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
20 #include "llvm/DebugInfo/PDB/PDB.h"
21 #include "llvm/DebugInfo/PDB/PDBContext.h"
22 #include "llvm/Demangle/Demangle.h"
23 #include "llvm/Object/COFF.h"
24 #include "llvm/Object/MachO.h"
25 #include "llvm/Object/MachOUniversal.h"
26 #include "llvm/Support/CRC.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/Compression.h"
29 #include "llvm/Support/DataExtractor.h"
30 #include "llvm/Support/Errc.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/Path.h"
42 LLVMSymbolizer::symbolizeCodeCommon(SymbolizableModule *Info,
43 object::SectionedAddress ModuleOffset) {
44 // A null module means an error has already been reported. Return an empty
49 // If the user is giving us relative addresses, add the preferred base of the
50 // object to the offset before we do the query. It's what DIContext expects.
51 if (Opts.RelativeAddresses)
52 ModuleOffset.Address += Info->getModulePreferredBase();
54 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
57 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
62 LLVMSymbolizer::symbolizeCode(const ObjectFile &Obj,
63 object::SectionedAddress ModuleOffset) {
64 StringRef ModuleName = Obj.getFileName();
65 auto I = Modules.find(ModuleName);
66 if (I != Modules.end())
67 return symbolizeCodeCommon(I->second.get(), ModuleOffset);
69 std::unique_ptr<DIContext> Context =
70 DWARFContext::create(Obj, nullptr, DWARFContext::defaultErrorHandler);
71 Expected<SymbolizableModule *> InfoOrErr =
72 createModuleInfo(&Obj, std::move(Context), ModuleName);
74 return InfoOrErr.takeError();
75 return symbolizeCodeCommon(*InfoOrErr, ModuleOffset);
79 LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
80 object::SectionedAddress ModuleOffset) {
81 Expected<SymbolizableModule *> InfoOrErr = getOrCreateModuleInfo(ModuleName);
83 return InfoOrErr.takeError();
84 return symbolizeCodeCommon(*InfoOrErr, ModuleOffset);
87 Expected<DIInliningInfo>
88 LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
89 object::SectionedAddress ModuleOffset) {
90 SymbolizableModule *Info;
91 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
92 Info = InfoOrErr.get();
94 return InfoOrErr.takeError();
96 // A null module means an error has already been reported. Return an empty
99 return DIInliningInfo();
101 // If the user is giving us relative addresses, add the preferred base of the
102 // object to the offset before we do the query. It's what DIContext expects.
103 if (Opts.RelativeAddresses)
104 ModuleOffset.Address += Info->getModulePreferredBase();
106 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
107 ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
109 for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
110 auto *Frame = InlinedContext.getMutableFrame(i);
111 Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
114 return InlinedContext;
118 LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
119 object::SectionedAddress ModuleOffset) {
120 SymbolizableModule *Info;
121 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
122 Info = InfoOrErr.get();
124 return InfoOrErr.takeError();
126 // A null module means an error has already been reported. Return an empty
131 // If the user is giving us relative addresses, add the preferred base of
132 // the object to the offset before we do the query. It's what DIContext
134 if (Opts.RelativeAddresses)
135 ModuleOffset.Address += Info->getModulePreferredBase();
137 DIGlobal Global = Info->symbolizeData(ModuleOffset);
139 Global.Name = DemangleName(Global.Name, Info);
143 Expected<std::vector<DILocal>>
144 LLVMSymbolizer::symbolizeFrame(const std::string &ModuleName,
145 object::SectionedAddress ModuleOffset) {
146 SymbolizableModule *Info;
147 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
148 Info = InfoOrErr.get();
150 return InfoOrErr.takeError();
152 // A null module means an error has already been reported. Return an empty
155 return std::vector<DILocal>();
157 // If the user is giving us relative addresses, add the preferred base of
158 // the object to the offset before we do the query. It's what DIContext
160 if (Opts.RelativeAddresses)
161 ModuleOffset.Address += Info->getModulePreferredBase();
163 return Info->symbolizeFrame(ModuleOffset);
166 void LLVMSymbolizer::flush() {
167 ObjectForUBPathAndArch.clear();
168 BinaryForPath.clear();
169 ObjectPairForPathArch.clear();
175 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
176 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
177 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
178 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
179 std::string getDarwinDWARFResourceForPath(
180 const std::string &Path, const std::string &Basename) {
181 SmallString<16> ResourceName = StringRef(Path);
182 if (sys::path::extension(Path) != ".dSYM") {
183 ResourceName += ".dSYM";
185 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
186 sys::path::append(ResourceName, Basename);
187 return ResourceName.str();
190 bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
191 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
192 MemoryBuffer::getFileOrSTDIN(Path);
195 return CRCHash == llvm::crc32(arrayRefFromStringRef(MB.get()->getBuffer()));
198 bool findDebugBinary(const std::string &OrigPath,
199 const std::string &DebuglinkName, uint32_t CRCHash,
200 const std::string &FallbackDebugPath,
201 std::string &Result) {
202 SmallString<16> OrigDir(OrigPath);
203 llvm::sys::path::remove_filename(OrigDir);
204 SmallString<16> DebugPath = OrigDir;
205 // Try relative/path/to/original_binary/debuglink_name
206 llvm::sys::path::append(DebugPath, DebuglinkName);
207 if (checkFileCRC(DebugPath, CRCHash)) {
208 Result = DebugPath.str();
211 // Try relative/path/to/original_binary/.debug/debuglink_name
213 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
214 if (checkFileCRC(DebugPath, CRCHash)) {
215 Result = DebugPath.str();
218 // Make the path absolute so that lookups will go to
219 // "/usr/lib/debug/full/path/to/debug", not
220 // "/usr/lib/debug/to/debug"
221 llvm::sys::fs::make_absolute(OrigDir);
222 if (!FallbackDebugPath.empty()) {
223 // Try <FallbackDebugPath>/absolute/path/to/original_binary/debuglink_name
224 DebugPath = FallbackDebugPath;
226 #if defined(__NetBSD__)
227 // Try /usr/libdata/debug/absolute/path/to/original_binary/debuglink_name
228 DebugPath = "/usr/libdata/debug";
230 // Try /usr/lib/debug/absolute/path/to/original_binary/debuglink_name
231 DebugPath = "/usr/lib/debug";
234 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
236 if (checkFileCRC(DebugPath, CRCHash)) {
237 Result = DebugPath.str();
243 bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
247 for (const SectionRef &Section : Obj->sections()) {
249 if (Expected<StringRef> NameOrErr = Section.getName())
252 consumeError(NameOrErr.takeError());
254 Name = Name.substr(Name.find_first_not_of("._"));
255 if (Name == "gnu_debuglink") {
256 Expected<StringRef> ContentsOrErr = Section.getContents();
257 if (!ContentsOrErr) {
258 consumeError(ContentsOrErr.takeError());
261 DataExtractor DE(*ContentsOrErr, Obj->isLittleEndian(), 0);
263 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
264 // 4-byte align the offset.
265 Offset = (Offset + 3) & ~0x3;
266 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
267 DebugName = DebugNameStr;
268 CRCHash = DE.getU32(&Offset);
278 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
279 const MachOObjectFile *Obj) {
280 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
281 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
282 if (dbg_uuid.empty() || bin_uuid.empty())
284 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
287 template <typename ELFT>
288 Optional<ArrayRef<uint8_t>> getBuildID(const ELFFile<ELFT> *Obj) {
291 auto PhdrsOrErr = Obj->program_headers();
293 consumeError(PhdrsOrErr.takeError());
296 for (const auto &P : *PhdrsOrErr) {
297 if (P.p_type != ELF::PT_NOTE)
299 Error Err = Error::success();
300 for (auto N : Obj->notes(P, Err))
301 if (N.getType() == ELF::NT_GNU_BUILD_ID && N.getName() == ELF::ELF_NOTE_GNU)
307 Optional<ArrayRef<uint8_t>> getBuildID(const ELFObjectFileBase *Obj) {
308 Optional<ArrayRef<uint8_t>> BuildID;
309 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Obj))
310 BuildID = getBuildID(O->getELFFile());
311 else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Obj))
312 BuildID = getBuildID(O->getELFFile());
313 else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Obj))
314 BuildID = getBuildID(O->getELFFile());
315 else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Obj))
316 BuildID = getBuildID(O->getELFFile());
318 llvm_unreachable("unsupported file format");
322 bool findDebugBinary(const std::vector<std::string> &DebugFileDirectory,
323 const ArrayRef<uint8_t> BuildID,
324 std::string &Result) {
325 auto getDebugPath = [&](StringRef Directory) {
326 SmallString<128> Path{Directory};
327 sys::path::append(Path, ".build-id",
328 llvm::toHex(BuildID[0], /*LowerCase=*/true),
329 llvm::toHex(BuildID.slice(1), /*LowerCase=*/true));
333 if (DebugFileDirectory.empty()) {
334 SmallString<128> Path = getDebugPath(
335 #if defined(__NetBSD__)
336 // Try /usr/libdata/debug/.build-id/../...
339 // Try /usr/lib/debug/.build-id/../...
343 if (llvm::sys::fs::exists(Path)) {
348 for (const auto &Directory : DebugFileDirectory) {
349 // Try <debug-file-directory>/.build-id/../...
350 SmallString<128> Path = getDebugPath(Directory);
351 if (llvm::sys::fs::exists(Path)) {
360 } // end anonymous namespace
362 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
363 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
364 // On Darwin we may find DWARF in separate object file in
365 // resource directory.
366 std::vector<std::string> DsymPaths;
367 StringRef Filename = sys::path::filename(ExePath);
368 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
369 for (const auto &Path : Opts.DsymHints) {
370 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
372 for (const auto &Path : DsymPaths) {
373 auto DbgObjOrErr = getOrCreateObject(Path, ArchName);
375 // Ignore errors, the file might not exist.
376 consumeError(DbgObjOrErr.takeError());
379 ObjectFile *DbgObj = DbgObjOrErr.get();
382 const MachOObjectFile *MachDbgObj = dyn_cast<const MachOObjectFile>(DbgObj);
385 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj))
391 ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path,
392 const ObjectFile *Obj,
393 const std::string &ArchName) {
394 std::string DebuglinkName;
396 std::string DebugBinaryPath;
397 if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash))
399 if (!findDebugBinary(Path, DebuglinkName, CRCHash, Opts.FallbackDebugPath,
402 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
404 // Ignore errors, the file might not exist.
405 consumeError(DbgObjOrErr.takeError());
408 return DbgObjOrErr.get();
411 ObjectFile *LLVMSymbolizer::lookUpBuildIDObject(const std::string &Path,
412 const ELFObjectFileBase *Obj,
413 const std::string &ArchName) {
414 auto BuildID = getBuildID(Obj);
417 if (BuildID->size() < 2)
419 std::string DebugBinaryPath;
420 if (!findDebugBinary(Opts.DebugFileDirectory, *BuildID, DebugBinaryPath))
422 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
424 consumeError(DbgObjOrErr.takeError());
427 return DbgObjOrErr.get();
430 Expected<LLVMSymbolizer::ObjectPair>
431 LLVMSymbolizer::getOrCreateObjectPair(const std::string &Path,
432 const std::string &ArchName) {
433 auto I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
434 if (I != ObjectPairForPathArch.end())
437 auto ObjOrErr = getOrCreateObject(Path, ArchName);
439 ObjectPairForPathArch.emplace(std::make_pair(Path, ArchName),
440 ObjectPair(nullptr, nullptr));
441 return ObjOrErr.takeError();
444 ObjectFile *Obj = ObjOrErr.get();
445 assert(Obj != nullptr);
446 ObjectFile *DbgObj = nullptr;
448 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
449 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
450 else if (auto ELFObj = dyn_cast<const ELFObjectFileBase>(Obj))
451 DbgObj = lookUpBuildIDObject(Path, ELFObj, ArchName);
453 DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName);
456 ObjectPair Res = std::make_pair(Obj, DbgObj);
457 ObjectPairForPathArch.emplace(std::make_pair(Path, ArchName), Res);
461 Expected<ObjectFile *>
462 LLVMSymbolizer::getOrCreateObject(const std::string &Path,
463 const std::string &ArchName) {
465 auto Pair = BinaryForPath.emplace(Path, OwningBinary<Binary>());
467 Bin = Pair.first->second.getBinary();
469 Expected<OwningBinary<Binary>> BinOrErr = createBinary(Path);
471 return BinOrErr.takeError();
472 Pair.first->second = std::move(BinOrErr.get());
473 Bin = Pair.first->second.getBinary();
477 return static_cast<ObjectFile *>(nullptr);
479 if (MachOUniversalBinary *UB = dyn_cast_or_null<MachOUniversalBinary>(Bin)) {
480 auto I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName));
481 if (I != ObjectForUBPathAndArch.end())
482 return I->second.get();
484 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
485 UB->getMachOObjectForArch(ArchName);
487 ObjectForUBPathAndArch.emplace(std::make_pair(Path, ArchName),
488 std::unique_ptr<ObjectFile>());
489 return ObjOrErr.takeError();
491 ObjectFile *Res = ObjOrErr->get();
492 ObjectForUBPathAndArch.emplace(std::make_pair(Path, ArchName),
493 std::move(ObjOrErr.get()));
496 if (Bin->isObject()) {
497 return cast<ObjectFile>(Bin);
499 return errorCodeToError(object_error::arch_not_found);
502 Expected<SymbolizableModule *>
503 LLVMSymbolizer::createModuleInfo(const ObjectFile *Obj,
504 std::unique_ptr<DIContext> Context,
505 StringRef ModuleName) {
506 auto InfoOrErr = SymbolizableObjectFile::create(Obj, std::move(Context),
507 Opts.UntagAddresses);
508 std::unique_ptr<SymbolizableModule> SymMod;
510 SymMod = std::move(*InfoOrErr);
512 Modules.insert(std::make_pair(ModuleName, std::move(SymMod)));
513 assert(InsertResult.second);
514 if (std::error_code EC = InfoOrErr.getError())
515 return errorCodeToError(EC);
516 return InsertResult.first->second.get();
519 Expected<SymbolizableModule *>
520 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
521 auto I = Modules.find(ModuleName);
522 if (I != Modules.end())
523 return I->second.get();
525 std::string BinaryName = ModuleName;
526 std::string ArchName = Opts.DefaultArch;
527 size_t ColonPos = ModuleName.find_last_of(':');
528 // Verify that substring after colon form a valid arch name.
529 if (ColonPos != std::string::npos) {
530 std::string ArchStr = ModuleName.substr(ColonPos + 1);
531 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
532 BinaryName = ModuleName.substr(0, ColonPos);
536 auto ObjectsOrErr = getOrCreateObjectPair(BinaryName, ArchName);
538 // Failed to find valid object file.
539 Modules.emplace(ModuleName, std::unique_ptr<SymbolizableModule>());
540 return ObjectsOrErr.takeError();
542 ObjectPair Objects = ObjectsOrErr.get();
544 std::unique_ptr<DIContext> Context;
545 // If this is a COFF object containing PDB info, use a PDBContext to
546 // symbolize. Otherwise, use DWARF.
547 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
548 const codeview::DebugInfo *DebugInfo;
549 StringRef PDBFileName;
550 auto EC = CoffObject->getDebugPDBInfo(DebugInfo, PDBFileName);
551 if (!EC && DebugInfo != nullptr && !PDBFileName.empty()) {
554 std::unique_ptr<IPDBSession> Session;
555 if (auto Err = loadDataForEXE(PDB_ReaderType::DIA,
556 Objects.first->getFileName(), Session)) {
557 Modules.emplace(ModuleName, std::unique_ptr<SymbolizableModule>());
558 // Return along the PDB filename to provide more context
559 return createFileError(PDBFileName, std::move(Err));
561 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
563 return make_error<StringError>(
564 "PDB support not compiled in",
565 std::make_error_code(std::errc::not_supported));
571 DWARFContext::create(*Objects.second, nullptr,
572 DWARFContext::defaultErrorHandler, Opts.DWPName);
573 return createModuleInfo(Objects.first, std::move(Context), ModuleName);
578 // Undo these various manglings for Win32 extern "C" functions:
581 // fastcall - @foo@12
582 // vectorcall - foo@@12
583 // These are all different linkage names for 'foo'.
584 StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
585 // Remove any '_' or '@' prefix.
586 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
587 if (Front == '_' || Front == '@')
588 SymbolName = SymbolName.drop_front();
590 // Remove any '@[0-9]+' suffix.
592 size_t AtPos = SymbolName.rfind('@');
593 if (AtPos != StringRef::npos &&
594 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
595 [](char C) { return C >= '0' && C <= '9'; })) {
596 SymbolName = SymbolName.substr(0, AtPos);
600 // Remove any ending '@' for vectorcall.
601 if (SymbolName.endswith("@"))
602 SymbolName = SymbolName.drop_back();
607 } // end anonymous namespace
610 LLVMSymbolizer::DemangleName(const std::string &Name,
611 const SymbolizableModule *DbiModuleDescriptor) {
612 // We can spoil names of symbols with C linkage, so use an heuristic
613 // approach to check if the name should be demangled.
614 if (Name.substr(0, 2) == "_Z") {
616 char *DemangledName = itaniumDemangle(Name.c_str(), nullptr, nullptr, &status);
619 std::string Result = DemangledName;
624 if (!Name.empty() && Name.front() == '?') {
625 // Only do MSVC C++ demangling on symbols starting with '?'.
627 char *DemangledName = microsoftDemangle(
628 Name.c_str(), nullptr, nullptr, &status,
629 MSDemangleFlags(MSDF_NoAccessSpecifier | MSDF_NoCallingConvention |
630 MSDF_NoMemberType | MSDF_NoReturnType));
633 std::string Result = DemangledName;
638 if (DbiModuleDescriptor && DbiModuleDescriptor->isWin32Module())
639 return std::string(demanglePE32ExternCFunc(Name));
643 } // namespace symbolize