brintos

brintos / llvm-project-archived public Read only

0
0
Text · 148.7 KiB · 3968715 Raw
4104 lines · cpp
1//===-- ObjectFileELF.cpp -------------------------------------------------===//2//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-exception6//7//===----------------------------------------------------------------------===//8 9#include "ObjectFileELF.h"10 11#include <algorithm>12#include <cassert>13#include <optional>14#include <unordered_map>15 16#include "lldb/Core/Module.h"17#include "lldb/Core/ModuleSpec.h"18#include "lldb/Core/PluginManager.h"19#include "lldb/Core/Progress.h"20#include "lldb/Core/Section.h"21#include "lldb/Host/FileSystem.h"22#include "lldb/Host/LZMA.h"23#include "lldb/Symbol/DWARFCallFrameInfo.h"24#include "lldb/Symbol/SymbolContext.h"25#include "lldb/Target/Process.h"26#include "lldb/Target/SectionLoadList.h"27#include "lldb/Target/Target.h"28#include "lldb/Utility/ArchSpec.h"29#include "lldb/Utility/DataBufferHeap.h"30#include "lldb/Utility/FileSpecList.h"31#include "lldb/Utility/LLDBLog.h"32#include "lldb/Utility/Log.h"33#include "lldb/Utility/RangeMap.h"34#include "lldb/Utility/Status.h"35#include "lldb/Utility/Stream.h"36#include "lldb/Utility/Timer.h"37#include "llvm/ADT/IntervalMap.h"38#include "llvm/ADT/PointerUnion.h"39#include "llvm/ADT/StringRef.h"40#include "llvm/BinaryFormat/ELF.h"41#include "llvm/Object/Decompressor.h"42#include "llvm/Support/ARMBuildAttributes.h"43#include "llvm/Support/CRC.h"44#include "llvm/Support/FormatVariadic.h"45#include "llvm/Support/MathExtras.h"46#include "llvm/Support/MemoryBuffer.h"47#include "llvm/Support/MipsABIFlags.h"48 49#define CASE_AND_STREAM(s, def, width)                                         \50  case def:                                                                    \51    s->Printf("%-*s", width, #def);                                            \52    break;53 54using namespace lldb;55using namespace lldb_private;56using namespace elf;57using namespace llvm::ELF;58 59LLDB_PLUGIN_DEFINE(ObjectFileELF)60 61// ELF note owner definitions62static const char *const LLDB_NT_OWNER_FREEBSD = "FreeBSD";63static const char *const LLDB_NT_OWNER_GNU = "GNU";64static const char *const LLDB_NT_OWNER_NETBSD = "NetBSD";65static const char *const LLDB_NT_OWNER_NETBSDCORE = "NetBSD-CORE";66static const char *const LLDB_NT_OWNER_OPENBSD = "OpenBSD";67static const char *const LLDB_NT_OWNER_ANDROID = "Android";68static const char *const LLDB_NT_OWNER_CORE = "CORE";69static const char *const LLDB_NT_OWNER_LINUX = "LINUX";70 71// ELF note type definitions72static const elf_word LLDB_NT_FREEBSD_ABI_TAG = 0x01;73static const elf_word LLDB_NT_FREEBSD_ABI_SIZE = 4;74 75static const elf_word LLDB_NT_GNU_ABI_TAG = 0x01;76static const elf_word LLDB_NT_GNU_ABI_SIZE = 16;77 78static const elf_word LLDB_NT_GNU_BUILD_ID_TAG = 0x03;79 80static const elf_word LLDB_NT_NETBSD_IDENT_TAG = 1;81static const elf_word LLDB_NT_NETBSD_IDENT_DESCSZ = 4;82static const elf_word LLDB_NT_NETBSD_IDENT_NAMESZ = 7;83static const elf_word LLDB_NT_NETBSD_PROCINFO = 1;84 85// GNU ABI note OS constants86static const elf_word LLDB_NT_GNU_ABI_OS_LINUX = 0x00;87static const elf_word LLDB_NT_GNU_ABI_OS_HURD = 0x01;88static const elf_word LLDB_NT_GNU_ABI_OS_SOLARIS = 0x02;89 90namespace {91 92//===----------------------------------------------------------------------===//93/// \class ELFRelocation94/// Generic wrapper for ELFRel and ELFRela.95///96/// This helper class allows us to parse both ELFRel and ELFRela relocation97/// entries in a generic manner.98class ELFRelocation {99public:100  /// Constructs an ELFRelocation entry with a personality as given by @p101  /// type.102  ///103  /// \param type Either DT_REL or DT_RELA.  Any other value is invalid.104  ELFRelocation(unsigned type);105 106  ~ELFRelocation();107 108  bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset);109 110  static unsigned RelocType32(const ELFRelocation &rel);111 112  static unsigned RelocType64(const ELFRelocation &rel);113 114  static unsigned RelocSymbol32(const ELFRelocation &rel);115 116  static unsigned RelocSymbol64(const ELFRelocation &rel);117 118  static elf_addr RelocOffset32(const ELFRelocation &rel);119 120  static elf_addr RelocOffset64(const ELFRelocation &rel);121 122  static elf_sxword RelocAddend32(const ELFRelocation &rel);123 124  static elf_sxword RelocAddend64(const ELFRelocation &rel);125 126  bool IsRela() { return (llvm::isa<ELFRela *>(reloc)); }127 128private:129  typedef llvm::PointerUnion<ELFRel *, ELFRela *> RelocUnion;130 131  RelocUnion reloc;132};133 134lldb::SectionSP MergeSections(lldb::SectionSP lhs, lldb::SectionSP rhs) {135  assert(lhs && rhs);136 137  lldb::ModuleSP lhs_module_parent = lhs->GetModule();138  lldb::ModuleSP rhs_module_parent = rhs->GetModule();139  assert(lhs_module_parent && rhs_module_parent);140 141  // Do a sanity check, these should be the same.142  if (lhs->GetFileAddress() != rhs->GetFileAddress())143    lhs_module_parent->ReportWarning(144        "Mismatch addresses for section {0} when "145        "merging with {1}, expected: {2:x}, "146        "actual: {3:x}",147        lhs->GetTypeAsCString(),148        rhs_module_parent->GetFileSpec().GetPathAsConstString().GetCString(),149        lhs->GetByteSize(), rhs->GetByteSize());150 151  // We want to take the greater of two sections. If LHS and RHS are both152  // SHT_NOBITS, we should default to LHS. If RHS has a bigger section,153  // indicating it has data that wasn't stripped, we should take that instead.154  return rhs->GetFileSize() > lhs->GetFileSize() ? rhs : lhs;155}156} // end anonymous namespace157 158ELFRelocation::ELFRelocation(unsigned type) {159  if (type == DT_REL || type == SHT_REL)160    reloc = new ELFRel();161  else if (type == DT_RELA || type == SHT_RELA)162    reloc = new ELFRela();163  else {164    assert(false && "unexpected relocation type");165    reloc = static_cast<ELFRel *>(nullptr);166  }167}168 169ELFRelocation::~ELFRelocation() {170  if (auto *elfrel = llvm::dyn_cast<ELFRel *>(reloc))171    delete elfrel;172  else173    delete llvm::cast<ELFRela *>(reloc);174}175 176bool ELFRelocation::Parse(const lldb_private::DataExtractor &data,177                          lldb::offset_t *offset) {178  if (auto *elfrel = llvm::dyn_cast<ELFRel *>(reloc))179    return elfrel->Parse(data, offset);180  else181    return llvm::cast<ELFRela *>(reloc)->Parse(data, offset);182}183 184unsigned ELFRelocation::RelocType32(const ELFRelocation &rel) {185  if (auto *elfrel = llvm::dyn_cast<ELFRel *>(rel.reloc))186    return ELFRel::RelocType32(*elfrel);187  else188    return ELFRela::RelocType32(*llvm::cast<ELFRela *>(rel.reloc));189}190 191unsigned ELFRelocation::RelocType64(const ELFRelocation &rel) {192  if (auto *elfrel = llvm::dyn_cast<ELFRel *>(rel.reloc))193    return ELFRel::RelocType64(*elfrel);194  else195    return ELFRela::RelocType64(*llvm::cast<ELFRela *>(rel.reloc));196}197 198unsigned ELFRelocation::RelocSymbol32(const ELFRelocation &rel) {199  if (auto *elfrel = llvm::dyn_cast<ELFRel *>(rel.reloc))200    return ELFRel::RelocSymbol32(*elfrel);201  else202    return ELFRela::RelocSymbol32(*llvm::cast<ELFRela *>(rel.reloc));203}204 205unsigned ELFRelocation::RelocSymbol64(const ELFRelocation &rel) {206  if (auto *elfrel = llvm::dyn_cast<ELFRel *>(rel.reloc))207    return ELFRel::RelocSymbol64(*elfrel);208  else209    return ELFRela::RelocSymbol64(*llvm::cast<ELFRela *>(rel.reloc));210}211 212elf_addr ELFRelocation::RelocOffset32(const ELFRelocation &rel) {213  if (auto *elfrel = llvm::dyn_cast<ELFRel *>(rel.reloc))214    return elfrel->r_offset;215  else216    return llvm::cast<ELFRela *>(rel.reloc)->r_offset;217}218 219elf_addr ELFRelocation::RelocOffset64(const ELFRelocation &rel) {220  if (auto *elfrel = llvm::dyn_cast<ELFRel *>(rel.reloc))221    return elfrel->r_offset;222  else223    return llvm::cast<ELFRela *>(rel.reloc)->r_offset;224}225 226elf_sxword ELFRelocation::RelocAddend32(const ELFRelocation &rel) {227  if (llvm::isa<ELFRel *>(rel.reloc))228    return 0;229  else230    return llvm::cast<ELFRela *>(rel.reloc)->r_addend;231}232 233elf_sxword  ELFRelocation::RelocAddend64(const ELFRelocation &rel) {234  if (llvm::isa<ELFRel *>(rel.reloc))235    return 0;236  else237    return llvm::cast<ELFRela *>(rel.reloc)->r_addend;238}239 240static user_id_t SegmentID(size_t PHdrIndex) {241  return ~user_id_t(PHdrIndex);242}243 244bool ELFNote::Parse(const DataExtractor &data, lldb::offset_t *offset) {245  // Read all fields.246  if (data.GetU32(offset, &n_namesz, 3) == nullptr)247    return false;248 249  // The name field is required to be nul-terminated, and n_namesz includes the250  // terminating nul in observed implementations (contrary to the ELF-64 spec).251  // A special case is needed for cores generated by some older Linux versions,252  // which write a note named "CORE" without a nul terminator and n_namesz = 4.253  if (n_namesz == 4) {254    char buf[4];255    if (data.ExtractBytes(*offset, 4, data.GetByteOrder(), buf) != 4)256      return false;257    if (strncmp(buf, "CORE", 4) == 0) {258      n_name = "CORE";259      *offset += 4;260      return true;261    }262  }263 264  const char *cstr = data.GetCStr(offset, llvm::alignTo(n_namesz, 4));265  if (cstr == nullptr) {266    Log *log = GetLog(LLDBLog::Symbols);267    LLDB_LOGF(log, "Failed to parse note name lacking nul terminator");268 269    return false;270  }271  n_name = cstr;272  return true;273}274 275static uint32_t mipsVariantFromElfFlags (const elf::ELFHeader &header) {276  const uint32_t mips_arch = header.e_flags & llvm::ELF::EF_MIPS_ARCH;277  uint32_t endian = header.e_ident[EI_DATA];278  uint32_t arch_variant = ArchSpec::eMIPSSubType_unknown;279  uint32_t fileclass = header.e_ident[EI_CLASS];280 281  // If there aren't any elf flags available (e.g core elf file) then return282  // default283  // 32 or 64 bit arch (without any architecture revision) based on object file's class.284  if (header.e_type == ET_CORE) {285    switch (fileclass) {286    case llvm::ELF::ELFCLASS32:287      return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el288                                     : ArchSpec::eMIPSSubType_mips32;289    case llvm::ELF::ELFCLASS64:290      return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el291                                     : ArchSpec::eMIPSSubType_mips64;292    default:293      return arch_variant;294    }295  }296 297  switch (mips_arch) {298  case llvm::ELF::EF_MIPS_ARCH_1:299  case llvm::ELF::EF_MIPS_ARCH_2:300  case llvm::ELF::EF_MIPS_ARCH_32:301    return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el302                                   : ArchSpec::eMIPSSubType_mips32;303  case llvm::ELF::EF_MIPS_ARCH_32R2:304    return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r2el305                                   : ArchSpec::eMIPSSubType_mips32r2;306  case llvm::ELF::EF_MIPS_ARCH_32R6:307    return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r6el308                                   : ArchSpec::eMIPSSubType_mips32r6;309  case llvm::ELF::EF_MIPS_ARCH_3:310  case llvm::ELF::EF_MIPS_ARCH_4:311  case llvm::ELF::EF_MIPS_ARCH_5:312  case llvm::ELF::EF_MIPS_ARCH_64:313    return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el314                                   : ArchSpec::eMIPSSubType_mips64;315  case llvm::ELF::EF_MIPS_ARCH_64R2:316    return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r2el317                                   : ArchSpec::eMIPSSubType_mips64r2;318  case llvm::ELF::EF_MIPS_ARCH_64R6:319    return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r6el320                                   : ArchSpec::eMIPSSubType_mips64r6;321  default:322    break;323  }324 325  return arch_variant;326}327 328static uint32_t riscvVariantFromElfFlags(const elf::ELFHeader &header) {329  uint32_t fileclass = header.e_ident[EI_CLASS];330  switch (fileclass) {331  case llvm::ELF::ELFCLASS32:332    return ArchSpec::eRISCVSubType_riscv32;333  case llvm::ELF::ELFCLASS64:334    return ArchSpec::eRISCVSubType_riscv64;335  default:336    return ArchSpec::eRISCVSubType_unknown;337  }338}339 340static uint32_t ppc64VariantFromElfFlags(const elf::ELFHeader &header) {341  uint32_t endian = header.e_ident[EI_DATA];342  if (endian == ELFDATA2LSB)343    return ArchSpec::eCore_ppc64le_generic;344  else345    return ArchSpec::eCore_ppc64_generic;346}347 348static uint32_t loongarchVariantFromElfFlags(const elf::ELFHeader &header) {349  uint32_t fileclass = header.e_ident[EI_CLASS];350  switch (fileclass) {351  case llvm::ELF::ELFCLASS32:352    return ArchSpec::eLoongArchSubType_loongarch32;353  case llvm::ELF::ELFCLASS64:354    return ArchSpec::eLoongArchSubType_loongarch64;355  default:356    return ArchSpec::eLoongArchSubType_unknown;357  }358}359 360static uint32_t subTypeFromElfHeader(const elf::ELFHeader &header) {361  if (header.e_machine == llvm::ELF::EM_MIPS)362    return mipsVariantFromElfFlags(header);363  else if (header.e_machine == llvm::ELF::EM_PPC64)364    return ppc64VariantFromElfFlags(header);365  else if (header.e_machine == llvm::ELF::EM_RISCV)366    return riscvVariantFromElfFlags(header);367  else if (header.e_machine == llvm::ELF::EM_LOONGARCH)368    return loongarchVariantFromElfFlags(header);369 370  return LLDB_INVALID_CPUTYPE;371}372 373char ObjectFileELF::ID;374 375// Arbitrary constant used as UUID prefix for core files.376const uint32_t ObjectFileELF::g_core_uuid_magic(0xE210C);377 378// Static methods.379void ObjectFileELF::Initialize() {380  PluginManager::RegisterPlugin(GetPluginNameStatic(),381                                GetPluginDescriptionStatic(), CreateInstance,382                                CreateMemoryInstance, GetModuleSpecifications);383}384 385void ObjectFileELF::Terminate() {386  PluginManager::UnregisterPlugin(CreateInstance);387}388 389ObjectFile *ObjectFileELF::CreateInstance(const lldb::ModuleSP &module_sp,390                                          DataBufferSP data_sp,391                                          lldb::offset_t data_offset,392                                          const lldb_private::FileSpec *file,393                                          lldb::offset_t file_offset,394                                          lldb::offset_t length) {395  bool mapped_writable = false;396  if (!data_sp) {397    data_sp = MapFileDataWritable(*file, length, file_offset);398    if (!data_sp)399      return nullptr;400    data_offset = 0;401    mapped_writable = true;402  }403 404  assert(data_sp);405 406  if (data_sp->GetByteSize() <= (llvm::ELF::EI_NIDENT + data_offset))407    return nullptr;408 409  const uint8_t *magic = data_sp->GetBytes() + data_offset;410  if (!ELFHeader::MagicBytesMatch(magic))411    return nullptr;412 413  // Update the data to contain the entire file if it doesn't already414  if (data_sp->GetByteSize() < length) {415    data_sp = MapFileDataWritable(*file, length, file_offset);416    if (!data_sp)417      return nullptr;418    data_offset = 0;419    mapped_writable = true;420    magic = data_sp->GetBytes();421  }422 423  // If we didn't map the data as writable take ownership of the buffer.424  if (!mapped_writable) {425    data_sp = std::make_shared<DataBufferHeap>(data_sp->GetBytes(),426                                               data_sp->GetByteSize());427    data_offset = 0;428    magic = data_sp->GetBytes();429  }430 431  unsigned address_size = ELFHeader::AddressSizeInBytes(magic);432  if (address_size == 4 || address_size == 8) {433    std::unique_ptr<ObjectFileELF> objfile_up(new ObjectFileELF(434        module_sp, data_sp, data_offset, file, file_offset, length));435    ArchSpec spec = objfile_up->GetArchitecture();436    if (spec && objfile_up->SetModulesArchitecture(spec))437      return objfile_up.release();438  }439 440  return nullptr;441}442 443ObjectFile *ObjectFileELF::CreateMemoryInstance(444    const lldb::ModuleSP &module_sp, WritableDataBufferSP data_sp,445    const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {446  if (!data_sp || data_sp->GetByteSize() < (llvm::ELF::EI_NIDENT))447    return nullptr;448  const uint8_t *magic = data_sp->GetBytes();449  if (!ELFHeader::MagicBytesMatch(magic))450    return nullptr;451  // Read the ELF header first so we can figure out how many bytes we need452  // to read to get as least the ELF header + program headers.453  DataExtractor data;454  data.SetData(data_sp);455  elf::ELFHeader hdr;456  lldb::offset_t offset = 0;457  if (!hdr.Parse(data, &offset))458    return nullptr;459 460  // Make sure the address size is set correctly in the ELF header.461  if (!hdr.Is32Bit() && !hdr.Is64Bit())462    return nullptr;463  // Figure out where the program headers end and read enough bytes to get the464  // program headers in their entirety.465  lldb::offset_t end_phdrs = hdr.e_phoff + (hdr.e_phentsize * hdr.e_phnum);466  if (end_phdrs > data_sp->GetByteSize())467    data_sp = ReadMemory(process_sp, header_addr, end_phdrs);468 469  std::unique_ptr<ObjectFileELF> objfile_up(470      new ObjectFileELF(module_sp, data_sp, process_sp, header_addr));471  ArchSpec spec = objfile_up->GetArchitecture();472  if (spec && objfile_up->SetModulesArchitecture(spec))473    return objfile_up.release();474 475  return nullptr;476}477 478bool ObjectFileELF::MagicBytesMatch(DataBufferSP &data_sp,479                                    lldb::addr_t data_offset,480                                    lldb::addr_t data_length) {481  if (data_sp &&482      data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset)) {483    const uint8_t *magic = data_sp->GetBytes() + data_offset;484    return ELFHeader::MagicBytesMatch(magic);485  }486  return false;487}488 489static uint32_t calc_crc32(uint32_t init, const DataExtractor &data) {490  return llvm::crc32(init,491                     llvm::ArrayRef(data.GetDataStart(), data.GetByteSize()));492}493 494uint32_t ObjectFileELF::CalculateELFNotesSegmentsCRC32(495    const ProgramHeaderColl &program_headers, DataExtractor &object_data) {496 497  uint32_t core_notes_crc = 0;498 499  for (const ELFProgramHeader &H : program_headers) {500    if (H.p_type == llvm::ELF::PT_NOTE) {501      const elf_off ph_offset = H.p_offset;502      const size_t ph_size = H.p_filesz;503 504      DataExtractor segment_data;505      if (segment_data.SetData(object_data, ph_offset, ph_size) != ph_size) {506        // The ELF program header contained incorrect data, probably corefile507        // is incomplete or corrupted.508        break;509      }510 511      core_notes_crc = calc_crc32(core_notes_crc, segment_data);512    }513  }514 515  return core_notes_crc;516}517 518static const char *OSABIAsCString(unsigned char osabi_byte) {519#define _MAKE_OSABI_CASE(x)                                                    \520  case x:                                                                      \521    return #x522  switch (osabi_byte) {523    _MAKE_OSABI_CASE(ELFOSABI_NONE);524    _MAKE_OSABI_CASE(ELFOSABI_HPUX);525    _MAKE_OSABI_CASE(ELFOSABI_NETBSD);526    _MAKE_OSABI_CASE(ELFOSABI_GNU);527    _MAKE_OSABI_CASE(ELFOSABI_HURD);528    _MAKE_OSABI_CASE(ELFOSABI_SOLARIS);529    _MAKE_OSABI_CASE(ELFOSABI_AIX);530    _MAKE_OSABI_CASE(ELFOSABI_IRIX);531    _MAKE_OSABI_CASE(ELFOSABI_FREEBSD);532    _MAKE_OSABI_CASE(ELFOSABI_TRU64);533    _MAKE_OSABI_CASE(ELFOSABI_MODESTO);534    _MAKE_OSABI_CASE(ELFOSABI_OPENBSD);535    _MAKE_OSABI_CASE(ELFOSABI_OPENVMS);536    _MAKE_OSABI_CASE(ELFOSABI_NSK);537    _MAKE_OSABI_CASE(ELFOSABI_AROS);538    _MAKE_OSABI_CASE(ELFOSABI_FENIXOS);539    _MAKE_OSABI_CASE(ELFOSABI_C6000_ELFABI);540    _MAKE_OSABI_CASE(ELFOSABI_C6000_LINUX);541    _MAKE_OSABI_CASE(ELFOSABI_ARM);542    _MAKE_OSABI_CASE(ELFOSABI_STANDALONE);543  default:544    return "<unknown-osabi>";545  }546#undef _MAKE_OSABI_CASE547}548 549//550// WARNING : This function is being deprecated551// It's functionality has moved to ArchSpec::SetArchitecture This function is552// only being kept to validate the move.553//554// TODO : Remove this function555static bool GetOsFromOSABI(unsigned char osabi_byte,556                           llvm::Triple::OSType &ostype) {557  switch (osabi_byte) {558  case ELFOSABI_AIX:559    ostype = llvm::Triple::OSType::AIX;560    break;561  case ELFOSABI_FREEBSD:562    ostype = llvm::Triple::OSType::FreeBSD;563    break;564  case ELFOSABI_GNU:565    ostype = llvm::Triple::OSType::Linux;566    break;567  case ELFOSABI_NETBSD:568    ostype = llvm::Triple::OSType::NetBSD;569    break;570  case ELFOSABI_OPENBSD:571    ostype = llvm::Triple::OSType::OpenBSD;572    break;573  case ELFOSABI_SOLARIS:574    ostype = llvm::Triple::OSType::Solaris;575    break;576  default:577    ostype = llvm::Triple::OSType::UnknownOS;578  }579  return ostype != llvm::Triple::OSType::UnknownOS;580}581 582size_t ObjectFileELF::GetModuleSpecifications(583    const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,584    lldb::offset_t data_offset, lldb::offset_t file_offset,585    lldb::offset_t length, lldb_private::ModuleSpecList &specs) {586  Log *log = GetLog(LLDBLog::Modules);587 588  const size_t initial_count = specs.GetSize();589 590  if (ObjectFileELF::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {591    DataExtractor data;592    data.SetData(data_sp);593    elf::ELFHeader header;594    lldb::offset_t header_offset = data_offset;595    if (header.Parse(data, &header_offset)) {596      if (data_sp) {597        ModuleSpec spec(file);598        // In Android API level 23 and above, bionic dynamic linker is able to599        // load .so file directly from zip file. In that case, .so file is600        // page aligned and uncompressed, and this module spec should retain the601        // .so file offset and file size to pass through the information from602        // lldb-server to LLDB. For normal file, file_offset should be 0,603        // length should be the size of the file.604        spec.SetObjectOffset(file_offset);605        spec.SetObjectSize(length);606 607        const uint32_t sub_type = subTypeFromElfHeader(header);608        spec.GetArchitecture().SetArchitecture(609            eArchTypeELF, header.e_machine, sub_type, header.e_ident[EI_OSABI]);610 611        if (spec.GetArchitecture().IsValid()) {612          llvm::Triple::OSType ostype;613          llvm::Triple::VendorType vendor;614          llvm::Triple::OSType spec_ostype =615              spec.GetArchitecture().GetTriple().getOS();616 617          LLDB_LOGF(log, "ObjectFileELF::%s file '%s' module OSABI: %s",618                    __FUNCTION__, file.GetPath().c_str(),619                    OSABIAsCString(header.e_ident[EI_OSABI]));620 621          // SetArchitecture should have set the vendor to unknown622          vendor = spec.GetArchitecture().GetTriple().getVendor();623          assert(vendor == llvm::Triple::UnknownVendor);624          UNUSED_IF_ASSERT_DISABLED(vendor);625 626          //627          // Validate it is ok to remove GetOsFromOSABI628          GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);629          assert(spec_ostype == ostype);630          if (spec_ostype != llvm::Triple::OSType::UnknownOS) {631            LLDB_LOGF(log,632                      "ObjectFileELF::%s file '%s' set ELF module OS type "633                      "from ELF header OSABI.",634                      __FUNCTION__, file.GetPath().c_str());635          }636 637          // When ELF file does not contain GNU build ID, the later code will638          // calculate CRC32 with this data_sp file_offset and length. It is639          // important for Android zip .so file, which is a slice of a file,640          // to not access the outside of the file slice range.641          if (data_sp->GetByteSize() < length)642            data_sp = MapFileData(file, length, file_offset);643          if (data_sp)644            data.SetData(data_sp);645          // In case there is header extension in the section #0, the header we646          // parsed above could have sentinel values for e_phnum, e_shnum, and647          // e_shstrndx.  In this case we need to reparse the header with a648          // bigger data source to get the actual values.649          if (header.HasHeaderExtension()) {650            lldb::offset_t header_offset = data_offset;651            header.Parse(data, &header_offset);652          }653 654          uint32_t gnu_debuglink_crc = 0;655          std::string gnu_debuglink_file;656          SectionHeaderColl section_headers;657          lldb_private::UUID &uuid = spec.GetUUID();658 659          GetSectionHeaderInfo(section_headers, data, header, uuid,660                               gnu_debuglink_file, gnu_debuglink_crc,661                               spec.GetArchitecture());662 663          llvm::Triple &spec_triple = spec.GetArchitecture().GetTriple();664 665          LLDB_LOGF(log,666                    "ObjectFileELF::%s file '%s' module set to triple: %s "667                    "(architecture %s)",668                    __FUNCTION__, file.GetPath().c_str(),669                    spec_triple.getTriple().c_str(),670                    spec.GetArchitecture().GetArchitectureName());671 672          if (!uuid.IsValid()) {673            uint32_t core_notes_crc = 0;674 675            if (!gnu_debuglink_crc) {676              LLDB_SCOPED_TIMERF(677                  "Calculating module crc32 %s with size %" PRIu64 " KiB",678                  file.GetFilename().AsCString(),679                  (length - file_offset) / 1024);680 681              // For core files - which usually don't happen to have a682              // gnu_debuglink, and are pretty bulky - calculating whole683              // contents crc32 would be too much of luxury.  Thus we will need684              // to fallback to something simpler.685              if (header.e_type == llvm::ELF::ET_CORE) {686                ProgramHeaderColl program_headers;687                GetProgramHeaderInfo(program_headers, data, header);688 689                core_notes_crc =690                    CalculateELFNotesSegmentsCRC32(program_headers, data);691              } else {692                gnu_debuglink_crc = calc_crc32(0, data);693              }694            }695            using u32le = llvm::support::ulittle32_t;696            if (gnu_debuglink_crc) {697              // Use 4 bytes of crc from the .gnu_debuglink section.698              u32le data(gnu_debuglink_crc);699              uuid = UUID(&data, sizeof(data));700            } else if (core_notes_crc) {701              // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make702              // it look different form .gnu_debuglink crc followed by 4 bytes703              // of note segments crc.704              u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)};705              uuid = UUID(data, sizeof(data));706            }707          }708 709          specs.Append(spec);710        }711      }712    }713  }714 715  return specs.GetSize() - initial_count;716}717 718// ObjectFile protocol719 720ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,721                             DataBufferSP data_sp, lldb::offset_t data_offset,722                             const FileSpec *file, lldb::offset_t file_offset,723                             lldb::offset_t length)724    : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset) {725  if (file)726    m_file = *file;727}728 729ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,730                             DataBufferSP header_data_sp,731                             const lldb::ProcessSP &process_sp,732                             addr_t header_addr)733    : ObjectFile(module_sp, process_sp, header_addr, header_data_sp) {}734 735bool ObjectFileELF::IsExecutable() const {736  return ((m_header.e_type & ET_EXEC) != 0) || (m_header.e_entry != 0);737}738 739bool ObjectFileELF::SetLoadAddress(Target &target, lldb::addr_t value,740                                   bool value_is_offset) {741  ModuleSP module_sp = GetModule();742  if (module_sp) {743    size_t num_loaded_sections = 0;744    SectionList *section_list = GetSectionList();745    if (section_list) {746      if (!value_is_offset) {747        addr_t base = GetBaseAddress().GetFileAddress();748        if (base == LLDB_INVALID_ADDRESS)749          return false;750        value -= base;751      }752 753      const size_t num_sections = section_list->GetSize();754      size_t sect_idx = 0;755 756      for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {757        // Iterate through the object file sections to find all of the sections758        // that have SHF_ALLOC in their flag bits.759        SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));760 761        // PT_TLS segments can have the same p_vaddr and p_paddr as other762        // PT_LOAD segments so we shouldn't load them. If we do load them, then763        // the SectionLoadList will incorrectly fill in the instance variable764        // SectionLoadList::m_addr_to_sect with the same address as a PT_LOAD765        // segment and we won't be able to resolve addresses in the PT_LOAD766        // segment whose p_vaddr entry matches that of the PT_TLS. Any variables767        // that appear in the PT_TLS segments get resolved by the DWARF768        // expressions. If this ever changes we will need to fix all object769        // file plug-ins, but until then, we don't want PT_TLS segments to770        // remove the entry from SectionLoadList::m_addr_to_sect when we call771        // SetSectionLoadAddress() below.772        if (section_sp->IsThreadSpecific())773          continue;774        if (section_sp->Test(SHF_ALLOC) ||775            section_sp->GetType() == eSectionTypeContainer) {776          lldb::addr_t load_addr = section_sp->GetFileAddress();777          // We don't want to update the load address of a section with type778          // eSectionTypeAbsoluteAddress as they already have the absolute load779          // address already specified780          if (section_sp->GetType() != eSectionTypeAbsoluteAddress)781            load_addr += value;782 783          // On 32-bit systems the load address have to fit into 4 bytes. The784          // rest of the bytes are the overflow from the addition.785          if (GetAddressByteSize() == 4)786            load_addr &= 0xFFFFFFFF;787 788          if (target.SetSectionLoadAddress(section_sp, load_addr))789            ++num_loaded_sections;790        }791      }792      return num_loaded_sections > 0;793    }794  }795  return false;796}797 798ByteOrder ObjectFileELF::GetByteOrder() const {799  if (m_header.e_ident[EI_DATA] == ELFDATA2MSB)800    return eByteOrderBig;801  if (m_header.e_ident[EI_DATA] == ELFDATA2LSB)802    return eByteOrderLittle;803  return eByteOrderInvalid;804}805 806uint32_t ObjectFileELF::GetAddressByteSize() const {807  return m_data.GetAddressByteSize();808}809 810AddressClass ObjectFileELF::GetAddressClass(addr_t file_addr) {811  Symtab *symtab = GetSymtab();812  if (!symtab)813    return AddressClass::eUnknown;814 815  // The address class is determined based on the symtab. Ask it from the816  // object file what contains the symtab information.817  ObjectFile *symtab_objfile = symtab->GetObjectFile();818  if (symtab_objfile != nullptr && symtab_objfile != this)819    return symtab_objfile->GetAddressClass(file_addr);820 821  auto res = ObjectFile::GetAddressClass(file_addr);822  if (res != AddressClass::eCode)823    return res;824 825  auto ub = m_address_class_map.upper_bound(file_addr);826  if (ub == m_address_class_map.begin()) {827    // No entry in the address class map before the address. Return default828    // address class for an address in a code section.829    return AddressClass::eCode;830  }831 832  // Move iterator to the address class entry preceding address833  --ub;834 835  return ub->second;836}837 838size_t ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I) {839  return std::distance(m_section_headers.begin(), I);840}841 842size_t ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const {843  return std::distance(m_section_headers.begin(), I);844}845 846bool ObjectFileELF::ParseHeader() {847  lldb::offset_t offset = 0;848  return m_header.Parse(m_data, &offset);849}850 851UUID ObjectFileELF::GetUUID() {852  if (m_uuid)853    return m_uuid;854 855  // Try loading note info from any PT_NOTE program headers. This is more856  // friendly to ELF files that have no section headers, like ELF files that857  // are loaded from memory.858  for (const ELFProgramHeader &H : ProgramHeaders()) {859    if (H.p_type == llvm::ELF::PT_NOTE) {860      DataExtractor note_data = GetSegmentData(H);861      if (note_data.GetByteSize()) {862        lldb_private::ArchSpec arch_spec;863        RefineModuleDetailsFromNote(note_data, arch_spec, m_uuid);864        if (m_uuid)865          return m_uuid;866      }867    }868  }869 870  // Need to parse the section list to get the UUIDs, so make sure that's been871  // done.872  if (!ParseSectionHeaders() && GetType() != ObjectFile::eTypeCoreFile)873    return UUID();874 875  if (!m_uuid) {876    using u32le = llvm::support::ulittle32_t;877    if (GetType() == ObjectFile::eTypeCoreFile) {878      uint32_t core_notes_crc = 0;879 880      if (!ParseProgramHeaders())881        return UUID();882 883      core_notes_crc =884          CalculateELFNotesSegmentsCRC32(m_program_headers, m_data);885 886      if (core_notes_crc) {887        // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it888        // look different form .gnu_debuglink crc - followed by 4 bytes of note889        // segments crc.890        u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)};891        m_uuid = UUID(data, sizeof(data));892      }893    } else {894      if (!m_gnu_debuglink_crc)895        m_gnu_debuglink_crc = calc_crc32(0, m_data);896      if (m_gnu_debuglink_crc) {897        // Use 4 bytes of crc from the .gnu_debuglink section.898        u32le data(m_gnu_debuglink_crc);899        m_uuid = UUID(&data, sizeof(data));900      }901    }902  }903 904  return m_uuid;905}906 907std::optional<FileSpec> ObjectFileELF::GetDebugLink() {908  if (m_gnu_debuglink_file.empty())909    return std::nullopt;910  return FileSpec(m_gnu_debuglink_file);911}912 913uint32_t ObjectFileELF::GetDependentModules(FileSpecList &files) {914  size_t num_modules = ParseDependentModules();915  uint32_t num_specs = 0;916 917  for (unsigned i = 0; i < num_modules; ++i) {918    if (files.AppendIfUnique(m_filespec_up->GetFileSpecAtIndex(i)))919      num_specs++;920  }921 922  return num_specs;923}924 925Address ObjectFileELF::GetImageInfoAddress(Target *target) {926  if (!ParseDynamicSymbols())927    return Address();928 929  SectionList *section_list = GetSectionList();930  if (!section_list)931    return Address();932 933  for (size_t i = 0; i < m_dynamic_symbols.size(); ++i) {934    const ELFDynamic &symbol = m_dynamic_symbols[i].symbol;935 936    if (symbol.d_tag != DT_DEBUG && symbol.d_tag != DT_MIPS_RLD_MAP &&937        symbol.d_tag != DT_MIPS_RLD_MAP_REL)938      continue;939 940    // Compute the offset as the number of previous entries plus the size of941    // d_tag.942    const addr_t offset = (i * 2 + 1) * GetAddressByteSize();943    const addr_t d_file_addr = m_dynamic_base_addr + offset;944    Address d_addr;945    if (!d_addr.ResolveAddressUsingFileSections(d_file_addr, GetSectionList()))946      return Address();947    if (symbol.d_tag == DT_DEBUG)948      return d_addr;949 950    // MIPS executables uses DT_MIPS_RLD_MAP_REL to support PIE. DT_MIPS_RLD_MAP951    // exists in non-PIE.952    if ((symbol.d_tag == DT_MIPS_RLD_MAP ||953         symbol.d_tag == DT_MIPS_RLD_MAP_REL) &&954        target) {955      const addr_t d_load_addr = d_addr.GetLoadAddress(target);956      if (d_load_addr == LLDB_INVALID_ADDRESS)957        return Address();958 959      Status error;960      if (symbol.d_tag == DT_MIPS_RLD_MAP) {961        // DT_MIPS_RLD_MAP tag stores an absolute address of the debug pointer.962        Address addr;963        if (target->ReadPointerFromMemory(d_load_addr, error, addr, true))964          return addr;965      }966      if (symbol.d_tag == DT_MIPS_RLD_MAP_REL) {967        // DT_MIPS_RLD_MAP_REL tag stores the offset to the debug pointer,968        // relative to the address of the tag.969        uint64_t rel_offset;970        rel_offset = target->ReadUnsignedIntegerFromMemory(971            d_load_addr, GetAddressByteSize(), UINT64_MAX, error, true);972        if (error.Success() && rel_offset != UINT64_MAX) {973          Address addr;974          addr_t debug_ptr_address =975              d_load_addr - GetAddressByteSize() + rel_offset;976          addr.SetOffset(debug_ptr_address);977          return addr;978        }979      }980    }981  }982  return Address();983}984 985lldb_private::Address ObjectFileELF::GetEntryPointAddress() {986  if (m_entry_point_address.IsValid())987    return m_entry_point_address;988 989  if (!ParseHeader() || !IsExecutable())990    return m_entry_point_address;991 992  SectionList *section_list = GetSectionList();993  addr_t offset = m_header.e_entry;994 995  if (!section_list)996    m_entry_point_address.SetOffset(offset);997  else998    m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list);999  return m_entry_point_address;1000}1001 1002Address ObjectFileELF::GetBaseAddress() {1003  if (GetType() == ObjectFile::eTypeObjectFile) {1004    for (SectionHeaderCollIter I = std::next(m_section_headers.begin());1005         I != m_section_headers.end(); ++I) {1006      const ELFSectionHeaderInfo &header = *I;1007      if (header.sh_flags & SHF_ALLOC)1008        return Address(GetSectionList()->FindSectionByID(SectionIndex(I)), 0);1009    }1010    return LLDB_INVALID_ADDRESS;1011  }1012 1013  for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {1014    const ELFProgramHeader &H = EnumPHdr.value();1015    if (H.p_type != PT_LOAD)1016      continue;1017 1018    return Address(1019        GetSectionList()->FindSectionByID(SegmentID(EnumPHdr.index())), 0);1020  }1021  return LLDB_INVALID_ADDRESS;1022}1023 1024size_t ObjectFileELF::ParseDependentModules() {1025  if (m_filespec_up)1026    return m_filespec_up->GetSize();1027 1028  m_filespec_up = std::make_unique<FileSpecList>();1029 1030  if (ParseDynamicSymbols()) {1031    for (const auto &entry : m_dynamic_symbols) {1032      if (entry.symbol.d_tag != DT_NEEDED)1033        continue;1034      if (!entry.name.empty()) {1035        FileSpec file_spec(entry.name);1036        FileSystem::Instance().Resolve(file_spec);1037        m_filespec_up->Append(file_spec);1038      }1039    }1040  }1041  return m_filespec_up->GetSize();1042}1043 1044// GetProgramHeaderInfo1045size_t ObjectFileELF::GetProgramHeaderInfo(ProgramHeaderColl &program_headers,1046                                           DataExtractor &object_data,1047                                           const ELFHeader &header) {1048  // We have already parsed the program headers1049  if (!program_headers.empty())1050    return program_headers.size();1051 1052  // If there are no program headers to read we are done.1053  if (header.e_phnum == 0)1054    return 0;1055 1056  program_headers.resize(header.e_phnum);1057  if (program_headers.size() != header.e_phnum)1058    return 0;1059 1060  const size_t ph_size = header.e_phnum * header.e_phentsize;1061  const elf_off ph_offset = header.e_phoff;1062  DataExtractor data;1063  if (data.SetData(object_data, ph_offset, ph_size) != ph_size)1064    return 0;1065 1066  uint32_t idx;1067  lldb::offset_t offset;1068  for (idx = 0, offset = 0; idx < header.e_phnum; ++idx) {1069    if (!program_headers[idx].Parse(data, &offset))1070      break;1071  }1072 1073  if (idx < program_headers.size())1074    program_headers.resize(idx);1075 1076  return program_headers.size();1077}1078 1079// ParseProgramHeaders1080bool ObjectFileELF::ParseProgramHeaders() {1081  return GetProgramHeaderInfo(m_program_headers, m_data, m_header) != 0;1082}1083 1084lldb_private::Status1085ObjectFileELF::RefineModuleDetailsFromNote(lldb_private::DataExtractor &data,1086                                           lldb_private::ArchSpec &arch_spec,1087                                           lldb_private::UUID &uuid) {1088  Log *log = GetLog(LLDBLog::Modules);1089  Status error;1090 1091  lldb::offset_t offset = 0;1092 1093  while (true) {1094    // Parse the note header.  If this fails, bail out.1095    const lldb::offset_t note_offset = offset;1096    ELFNote note = ELFNote();1097    if (!note.Parse(data, &offset)) {1098      // We're done.1099      return error;1100    }1101 1102    LLDB_LOGF(log, "ObjectFileELF::%s parsing note name='%s', type=%" PRIu32,1103              __FUNCTION__, note.n_name.c_str(), note.n_type);1104 1105    // Process FreeBSD ELF notes.1106    if ((note.n_name == LLDB_NT_OWNER_FREEBSD) &&1107        (note.n_type == LLDB_NT_FREEBSD_ABI_TAG) &&1108        (note.n_descsz == LLDB_NT_FREEBSD_ABI_SIZE)) {1109      // Pull out the min version info.1110      uint32_t version_info;1111      if (data.GetU32(&offset, &version_info, 1) == nullptr) {1112        error =1113            Status::FromErrorString("failed to read FreeBSD ABI note payload");1114        return error;1115      }1116 1117      // Convert the version info into a major/minor number.1118      const uint32_t version_major = version_info / 100000;1119      const uint32_t version_minor = (version_info / 1000) % 100;1120 1121      char os_name[32];1122      snprintf(os_name, sizeof(os_name), "freebsd%" PRIu32 ".%" PRIu32,1123               version_major, version_minor);1124 1125      // Set the elf OS version to FreeBSD.  Also clear the vendor.1126      arch_spec.GetTriple().setOSName(os_name);1127      arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);1128 1129      LLDB_LOGF(log,1130                "ObjectFileELF::%s detected FreeBSD %" PRIu32 ".%" PRIu321131                ".%" PRIu32,1132                __FUNCTION__, version_major, version_minor,1133                static_cast<uint32_t>(version_info % 1000));1134    }1135    // Process GNU ELF notes.1136    else if (note.n_name == LLDB_NT_OWNER_GNU) {1137      switch (note.n_type) {1138      case LLDB_NT_GNU_ABI_TAG:1139        if (note.n_descsz == LLDB_NT_GNU_ABI_SIZE) {1140          // Pull out the min OS version supporting the ABI.1141          uint32_t version_info[4];1142          if (data.GetU32(&offset, &version_info[0], note.n_descsz / 4) ==1143              nullptr) {1144            error =1145                Status::FromErrorString("failed to read GNU ABI note payload");1146            return error;1147          }1148 1149          // Set the OS per the OS field.1150          switch (version_info[0]) {1151          case LLDB_NT_GNU_ABI_OS_LINUX:1152            arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);1153            arch_spec.GetTriple().setVendor(1154                llvm::Triple::VendorType::UnknownVendor);1155            LLDB_LOGF(log,1156                      "ObjectFileELF::%s detected Linux, min version %" PRIu321157                      ".%" PRIu32 ".%" PRIu32,1158                      __FUNCTION__, version_info[1], version_info[2],1159                      version_info[3]);1160            // FIXME we have the minimal version number, we could be propagating1161            // that.  version_info[1] = OS Major, version_info[2] = OS Minor,1162            // version_info[3] = Revision.1163            break;1164          case LLDB_NT_GNU_ABI_OS_HURD:1165            arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);1166            arch_spec.GetTriple().setVendor(1167                llvm::Triple::VendorType::UnknownVendor);1168            LLDB_LOGF(log,1169                      "ObjectFileELF::%s detected Hurd (unsupported), min "1170                      "version %" PRIu32 ".%" PRIu32 ".%" PRIu32,1171                      __FUNCTION__, version_info[1], version_info[2],1172                      version_info[3]);1173            break;1174          case LLDB_NT_GNU_ABI_OS_SOLARIS:1175            arch_spec.GetTriple().setOS(llvm::Triple::OSType::Solaris);1176            arch_spec.GetTriple().setVendor(1177                llvm::Triple::VendorType::UnknownVendor);1178            LLDB_LOGF(log,1179                      "ObjectFileELF::%s detected Solaris, min version %" PRIu321180                      ".%" PRIu32 ".%" PRIu32,1181                      __FUNCTION__, version_info[1], version_info[2],1182                      version_info[3]);1183            break;1184          default:1185            LLDB_LOGF(log,1186                      "ObjectFileELF::%s unrecognized OS in note, id %" PRIu321187                      ", min version %" PRIu32 ".%" PRIu32 ".%" PRIu32,1188                      __FUNCTION__, version_info[0], version_info[1],1189                      version_info[2], version_info[3]);1190            break;1191          }1192        }1193        break;1194 1195      case LLDB_NT_GNU_BUILD_ID_TAG:1196        // Only bother processing this if we don't already have the uuid set.1197        if (!uuid.IsValid()) {1198          // 16 bytes is UUID|MD5, 20 bytes is SHA1. Other linkers may produce a1199          // build-id of a different length. Accept it as long as it's at least1200          // 4 bytes as it will be better than our own crc32.1201          if (note.n_descsz >= 4) {1202            if (const uint8_t *buf = data.PeekData(offset, note.n_descsz)) {1203              // Save the build id as the UUID for the module.1204              uuid = UUID(buf, note.n_descsz);1205            } else {1206              error = Status::FromErrorString(1207                  "failed to read GNU_BUILD_ID note payload");1208              return error;1209            }1210          }1211        }1212        break;1213      }1214      if (arch_spec.IsMIPS() &&1215          arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)1216        // The note.n_name == LLDB_NT_OWNER_GNU is valid for Linux platform1217        arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);1218    }1219    // Process NetBSD ELF executables and shared libraries1220    else if ((note.n_name == LLDB_NT_OWNER_NETBSD) &&1221             (note.n_type == LLDB_NT_NETBSD_IDENT_TAG) &&1222             (note.n_descsz == LLDB_NT_NETBSD_IDENT_DESCSZ) &&1223             (note.n_namesz == LLDB_NT_NETBSD_IDENT_NAMESZ)) {1224      // Pull out the version info.1225      uint32_t version_info;1226      if (data.GetU32(&offset, &version_info, 1) == nullptr) {1227        error =1228            Status::FromErrorString("failed to read NetBSD ABI note payload");1229        return error;1230      }1231      // Convert the version info into a major/minor/patch number.1232      //     #define __NetBSD_Version__ MMmmrrpp001233      //1234      //     M = major version1235      //     m = minor version; a minor number of 99 indicates current.1236      //     r = 0 (since NetBSD 3.0 not used)1237      //     p = patchlevel1238      const uint32_t version_major = version_info / 100000000;1239      const uint32_t version_minor = (version_info % 100000000) / 1000000;1240      const uint32_t version_patch = (version_info % 10000) / 100;1241      // Set the elf OS version to NetBSD.  Also clear the vendor.1242      arch_spec.GetTriple().setOSName(1243          llvm::formatv("netbsd{0}.{1}.{2}", version_major, version_minor,1244                        version_patch).str());1245      arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);1246    }1247    // Process NetBSD ELF core(5) notes1248    else if ((note.n_name == LLDB_NT_OWNER_NETBSDCORE) &&1249             (note.n_type == LLDB_NT_NETBSD_PROCINFO)) {1250      // Set the elf OS version to NetBSD.  Also clear the vendor.1251      arch_spec.GetTriple().setOS(llvm::Triple::OSType::NetBSD);1252      arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);1253    }1254    // Process OpenBSD ELF notes.1255    else if (note.n_name == LLDB_NT_OWNER_OPENBSD) {1256      // Set the elf OS version to OpenBSD.  Also clear the vendor.1257      arch_spec.GetTriple().setOS(llvm::Triple::OSType::OpenBSD);1258      arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);1259    } else if (note.n_name == LLDB_NT_OWNER_ANDROID) {1260      arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);1261      arch_spec.GetTriple().setEnvironment(1262          llvm::Triple::EnvironmentType::Android);1263    } else if (note.n_name == LLDB_NT_OWNER_LINUX) {1264      // This is sometimes found in core files and usually contains extended1265      // register info1266      arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);1267    } else if (note.n_name == LLDB_NT_OWNER_CORE) {1268      // Parse the NT_FILE to look for stuff in paths to shared libraries1269      // The contents look like this in a 64 bit ELF core file:1270      //1271      // count     = 0x000000000000000a (10)1272      // page_size = 0x0000000000001000 (4096)1273      // Index start              end                file_ofs           path1274      // ===== ------------------ ------------------ ------------------ -------------------------------------1275      // [  0] 0x0000000000401000 0x0000000000000000                    /tmp/a.out1276      // [  1] 0x0000000000600000 0x0000000000601000 0x0000000000000000 /tmp/a.out1277      // [  2] 0x0000000000601000 0x0000000000602000 0x0000000000000001 /tmp/a.out1278      // [  3] 0x00007fa79c9ed000 0x00007fa79cba8000 0x0000000000000000 /lib/x86_64-linux-gnu/libc-2.19.so1279      // [  4] 0x00007fa79cba8000 0x00007fa79cda7000 0x00000000000001bb /lib/x86_64-linux-gnu/libc-2.19.so1280      // [  5] 0x00007fa79cda7000 0x00007fa79cdab000 0x00000000000001ba /lib/x86_64-linux-gnu/libc-2.19.so1281      // [  6] 0x00007fa79cdab000 0x00007fa79cdad000 0x00000000000001be /lib/x86_64-linux-gnu/libc-2.19.so1282      // [  7] 0x00007fa79cdb2000 0x00007fa79cdd5000 0x0000000000000000 /lib/x86_64-linux-gnu/ld-2.19.so1283      // [  8] 0x00007fa79cfd4000 0x00007fa79cfd5000 0x0000000000000022 /lib/x86_64-linux-gnu/ld-2.19.so1284      // [  9] 0x00007fa79cfd5000 0x00007fa79cfd6000 0x0000000000000023 /lib/x86_64-linux-gnu/ld-2.19.so1285      //1286      // In the 32 bit ELFs the count, page_size, start, end, file_ofs are1287      // uint32_t.1288      //1289      // For reference: see readelf source code (in binutils).1290      if (note.n_type == NT_FILE) {1291        uint64_t count = data.GetAddress(&offset);1292        const char *cstr;1293        data.GetAddress(&offset); // Skip page size1294        offset += count * 3 *1295                  data.GetAddressByteSize(); // Skip all start/end/file_ofs1296        for (size_t i = 0; i < count; ++i) {1297          cstr = data.GetCStr(&offset);1298          if (cstr == nullptr) {1299            error = Status::FromErrorStringWithFormat(1300                "ObjectFileELF::%s trying to read "1301                "at an offset after the end "1302                "(GetCStr returned nullptr)",1303                __FUNCTION__);1304            return error;1305          }1306          llvm::StringRef path(cstr);1307          if (path.contains("/lib/x86_64-linux-gnu") || path.contains("/lib/i386-linux-gnu")) {1308            arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);1309            break;1310          }1311        }1312        if (arch_spec.IsMIPS() &&1313            arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)1314          // In case of MIPSR6, the LLDB_NT_OWNER_GNU note is missing for some1315          // cases (e.g. compile with -nostdlib) Hence set OS to Linux1316          arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);1317      }1318    }1319 1320    // Calculate the offset of the next note just in case "offset" has been1321    // used to poke at the contents of the note data1322    offset = note_offset + note.GetByteSize();1323  }1324 1325  return error;1326}1327 1328void ObjectFileELF::ParseARMAttributes(DataExtractor &data, uint64_t length,1329                                       ArchSpec &arch_spec) {1330  lldb::offset_t Offset = 0;1331 1332  uint8_t FormatVersion = data.GetU8(&Offset);1333  if (FormatVersion != llvm::ELFAttrs::Format_Version)1334    return;1335 1336  Offset = Offset + sizeof(uint32_t); // Section Length1337  llvm::StringRef VendorName = data.GetCStr(&Offset);1338 1339  if (VendorName != "aeabi")1340    return;1341 1342  if (arch_spec.GetTriple().getEnvironment() ==1343      llvm::Triple::UnknownEnvironment)1344    arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);1345 1346  while (Offset < length) {1347    uint8_t Tag = data.GetU8(&Offset);1348    uint32_t Size = data.GetU32(&Offset);1349 1350    if (Tag != llvm::ARMBuildAttrs::File || Size == 0)1351      continue;1352 1353    while (Offset < length) {1354      uint64_t Tag = data.GetULEB128(&Offset);1355      switch (Tag) {1356      default:1357        if (Tag < 32)1358          data.GetULEB128(&Offset);1359        else if (Tag % 2 == 0)1360          data.GetULEB128(&Offset);1361        else1362          data.GetCStr(&Offset);1363 1364        break;1365 1366      case llvm::ARMBuildAttrs::CPU_raw_name:1367      case llvm::ARMBuildAttrs::CPU_name:1368        data.GetCStr(&Offset);1369 1370        break;1371 1372      case llvm::ARMBuildAttrs::ABI_VFP_args: {1373        uint64_t VFPArgs = data.GetULEB128(&Offset);1374 1375        if (VFPArgs == llvm::ARMBuildAttrs::BaseAAPCS) {1376          if (arch_spec.GetTriple().getEnvironment() ==1377                  llvm::Triple::UnknownEnvironment ||1378              arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABIHF)1379            arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);1380 1381          arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);1382        } else if (VFPArgs == llvm::ARMBuildAttrs::HardFPAAPCS) {1383          if (arch_spec.GetTriple().getEnvironment() ==1384                  llvm::Triple::UnknownEnvironment ||1385              arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABI)1386            arch_spec.GetTriple().setEnvironment(llvm::Triple::EABIHF);1387 1388          arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);1389        }1390 1391        break;1392      }1393      }1394    }1395  }1396}1397 1398// GetSectionHeaderInfo1399size_t ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl &section_headers,1400                                           DataExtractor &object_data,1401                                           const elf::ELFHeader &header,1402                                           lldb_private::UUID &uuid,1403                                           std::string &gnu_debuglink_file,1404                                           uint32_t &gnu_debuglink_crc,1405                                           ArchSpec &arch_spec) {1406  // Don't reparse the section headers if we already did that.1407  if (!section_headers.empty())1408    return section_headers.size();1409 1410  // Only initialize the arch_spec to okay defaults if they're not already set.1411  // We'll refine this with note data as we parse the notes.1412  if (arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) {1413    llvm::Triple::OSType ostype;1414    llvm::Triple::OSType spec_ostype;1415    const uint32_t sub_type = subTypeFromElfHeader(header);1416    arch_spec.SetArchitecture(eArchTypeELF, header.e_machine, sub_type,1417                              header.e_ident[EI_OSABI]);1418 1419    // Validate if it is ok to remove GetOsFromOSABI. Note, that now the OS is1420    // determined based on EI_OSABI flag and the info extracted from ELF notes1421    // (see RefineModuleDetailsFromNote). However in some cases that still1422    // might be not enough: for example a shared library might not have any1423    // notes at all and have EI_OSABI flag set to System V, as result the OS1424    // will be set to UnknownOS.1425    GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);1426    spec_ostype = arch_spec.GetTriple().getOS();1427    assert(spec_ostype == ostype);1428    UNUSED_IF_ASSERT_DISABLED(spec_ostype);1429  }1430 1431  if (arch_spec.GetMachine() == llvm::Triple::mips ||1432      arch_spec.GetMachine() == llvm::Triple::mipsel ||1433      arch_spec.GetMachine() == llvm::Triple::mips64 ||1434      arch_spec.GetMachine() == llvm::Triple::mips64el) {1435    switch (header.e_flags & llvm::ELF::EF_MIPS_ARCH_ASE) {1436    case llvm::ELF::EF_MIPS_MICROMIPS:1437      arch_spec.SetFlags(ArchSpec::eMIPSAse_micromips);1438      break;1439    case llvm::ELF::EF_MIPS_ARCH_ASE_M16:1440      arch_spec.SetFlags(ArchSpec::eMIPSAse_mips16);1441      break;1442    case llvm::ELF::EF_MIPS_ARCH_ASE_MDMX:1443      arch_spec.SetFlags(ArchSpec::eMIPSAse_mdmx);1444      break;1445    default:1446      break;1447    }1448  }1449 1450  if (arch_spec.GetMachine() == llvm::Triple::arm ||1451      arch_spec.GetMachine() == llvm::Triple::thumb) {1452    if (header.e_flags & llvm::ELF::EF_ARM_SOFT_FLOAT)1453      arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);1454    else if (header.e_flags & llvm::ELF::EF_ARM_VFP_FLOAT)1455      arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);1456  }1457 1458  if (arch_spec.GetMachine() == llvm::Triple::riscv32 ||1459      arch_spec.GetMachine() == llvm::Triple::riscv64) {1460    uint32_t flags = arch_spec.GetFlags();1461 1462    if (header.e_flags & llvm::ELF::EF_RISCV_RVC)1463      flags |= ArchSpec::eRISCV_rvc;1464    if (header.e_flags & llvm::ELF::EF_RISCV_RVE)1465      flags |= ArchSpec::eRISCV_rve;1466 1467    if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_SINGLE) ==1468        llvm::ELF::EF_RISCV_FLOAT_ABI_SINGLE)1469      flags |= ArchSpec::eRISCV_float_abi_single;1470    else if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_DOUBLE) ==1471             llvm::ELF::EF_RISCV_FLOAT_ABI_DOUBLE)1472      flags |= ArchSpec::eRISCV_float_abi_double;1473    else if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_QUAD) ==1474             llvm::ELF::EF_RISCV_FLOAT_ABI_QUAD)1475      flags |= ArchSpec::eRISCV_float_abi_quad;1476 1477    arch_spec.SetFlags(flags);1478  }1479 1480  if (arch_spec.GetMachine() == llvm::Triple::loongarch32 ||1481      arch_spec.GetMachine() == llvm::Triple::loongarch64) {1482    uint32_t flags = arch_spec.GetFlags();1483    switch (header.e_flags & llvm::ELF::EF_LOONGARCH_ABI_MODIFIER_MASK) {1484    case llvm::ELF::EF_LOONGARCH_ABI_SINGLE_FLOAT:1485      flags |= ArchSpec::eLoongArch_abi_single_float;1486      break;1487    case llvm::ELF::EF_LOONGARCH_ABI_DOUBLE_FLOAT:1488      flags |= ArchSpec::eLoongArch_abi_double_float;1489      break;1490    case llvm::ELF::EF_LOONGARCH_ABI_SOFT_FLOAT:1491      break;1492    }1493 1494    arch_spec.SetFlags(flags);1495  }1496 1497  // If there are no section headers we are done.1498  if (header.e_shnum == 0)1499    return 0;1500 1501  Log *log = GetLog(LLDBLog::Modules);1502 1503  section_headers.resize(header.e_shnum);1504  if (section_headers.size() != header.e_shnum)1505    return 0;1506 1507  const size_t sh_size = header.e_shnum * header.e_shentsize;1508  const elf_off sh_offset = header.e_shoff;1509  DataExtractor sh_data;1510  if (sh_data.SetData(object_data, sh_offset, sh_size) != sh_size)1511    return 0;1512 1513  uint32_t idx;1514  lldb::offset_t offset;1515  for (idx = 0, offset = 0; idx < header.e_shnum; ++idx) {1516    if (!section_headers[idx].Parse(sh_data, &offset))1517      break;1518  }1519  if (idx < section_headers.size())1520    section_headers.resize(idx);1521 1522  const unsigned strtab_idx = header.e_shstrndx;1523  if (strtab_idx && strtab_idx < section_headers.size()) {1524    const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];1525    const size_t byte_size = sheader.sh_size;1526    const Elf64_Off offset = sheader.sh_offset;1527    lldb_private::DataExtractor shstr_data;1528 1529    if (shstr_data.SetData(object_data, offset, byte_size) == byte_size) {1530      for (SectionHeaderCollIter I = section_headers.begin();1531           I != section_headers.end(); ++I) {1532        static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");1533        const ELFSectionHeaderInfo &sheader = *I;1534        const uint64_t section_size =1535            sheader.sh_type == SHT_NOBITS ? 0 : sheader.sh_size;1536        ConstString name(shstr_data.PeekCStr(I->sh_name));1537 1538        I->section_name = name;1539 1540        if (arch_spec.IsMIPS()) {1541          uint32_t arch_flags = arch_spec.GetFlags();1542          DataExtractor data;1543          if (sheader.sh_type == SHT_MIPS_ABIFLAGS) {1544 1545            if (section_size && (data.SetData(object_data, sheader.sh_offset,1546                                              section_size) == section_size)) {1547              // MIPS ASE Mask is at offset 12 in MIPS.abiflags section1548              lldb::offset_t offset = 12; // MIPS ABI Flags Version: 01549              arch_flags |= data.GetU32(&offset);1550 1551              // The floating point ABI is at offset 71552              offset = 7;1553              switch (data.GetU8(&offset)) {1554              case llvm::Mips::Val_GNU_MIPS_ABI_FP_ANY:1555                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_ANY;1556                break;1557              case llvm::Mips::Val_GNU_MIPS_ABI_FP_DOUBLE:1558                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_DOUBLE;1559                break;1560              case llvm::Mips::Val_GNU_MIPS_ABI_FP_SINGLE:1561                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SINGLE;1562                break;1563              case llvm::Mips::Val_GNU_MIPS_ABI_FP_SOFT:1564                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SOFT;1565                break;1566              case llvm::Mips::Val_GNU_MIPS_ABI_FP_OLD_64:1567                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_OLD_64;1568                break;1569              case llvm::Mips::Val_GNU_MIPS_ABI_FP_XX:1570                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_XX;1571                break;1572              case llvm::Mips::Val_GNU_MIPS_ABI_FP_64:1573                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64;1574                break;1575              case llvm::Mips::Val_GNU_MIPS_ABI_FP_64A:1576                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64A;1577                break;1578              }1579            }1580          }1581          // Settings appropriate ArchSpec ABI Flags1582          switch (header.e_flags & llvm::ELF::EF_MIPS_ABI) {1583          case llvm::ELF::EF_MIPS_ABI_O32:1584            arch_flags |= lldb_private::ArchSpec::eMIPSABI_O32;1585            break;1586          case EF_MIPS_ABI_O64:1587            arch_flags |= lldb_private::ArchSpec::eMIPSABI_O64;1588            break;1589          case EF_MIPS_ABI_EABI32:1590            arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI32;1591            break;1592          case EF_MIPS_ABI_EABI64:1593            arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI64;1594            break;1595          default:1596            // ABI Mask doesn't cover N32 and N64 ABI.1597            if (header.e_ident[EI_CLASS] == llvm::ELF::ELFCLASS64)1598              arch_flags |= lldb_private::ArchSpec::eMIPSABI_N64;1599            else if (header.e_flags & llvm::ELF::EF_MIPS_ABI2)1600              arch_flags |= lldb_private::ArchSpec::eMIPSABI_N32;1601            break;1602          }1603          arch_spec.SetFlags(arch_flags);1604        }1605 1606        if (arch_spec.GetMachine() == llvm::Triple::arm ||1607            arch_spec.GetMachine() == llvm::Triple::thumb) {1608          DataExtractor data;1609 1610          if (sheader.sh_type == SHT_ARM_ATTRIBUTES && section_size != 0 &&1611              data.SetData(object_data, sheader.sh_offset, section_size) == section_size)1612            ParseARMAttributes(data, section_size, arch_spec);1613        }1614 1615        if (name == g_sect_name_gnu_debuglink) {1616          DataExtractor data;1617          if (section_size && (data.SetData(object_data, sheader.sh_offset,1618                                            section_size) == section_size)) {1619            lldb::offset_t gnu_debuglink_offset = 0;1620            gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);1621            gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);1622            data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);1623          }1624        }1625 1626        // Process ELF note section entries.1627        bool is_note_header = (sheader.sh_type == SHT_NOTE);1628 1629        // The section header ".note.android.ident" is stored as a1630        // PROGBITS type header but it is actually a note header.1631        static ConstString g_sect_name_android_ident(".note.android.ident");1632        if (!is_note_header && name == g_sect_name_android_ident)1633          is_note_header = true;1634 1635        if (is_note_header) {1636          // Allow notes to refine module info.1637          DataExtractor data;1638          if (section_size && (data.SetData(object_data, sheader.sh_offset,1639                                            section_size) == section_size)) {1640            Status error = RefineModuleDetailsFromNote(data, arch_spec, uuid);1641            if (error.Fail()) {1642              LLDB_LOGF(log, "ObjectFileELF::%s ELF note processing failed: %s",1643                        __FUNCTION__, error.AsCString());1644            }1645          }1646        }1647      }1648 1649      // Make any unknown triple components to be unspecified unknowns.1650      if (arch_spec.GetTriple().getVendor() == llvm::Triple::UnknownVendor)1651        arch_spec.GetTriple().setVendorName(llvm::StringRef());1652      if (arch_spec.GetTriple().getOS() == llvm::Triple::UnknownOS)1653        arch_spec.GetTriple().setOSName(llvm::StringRef());1654 1655      return section_headers.size();1656    }1657  }1658 1659  section_headers.clear();1660  return 0;1661}1662 1663llvm::StringRef1664ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const {1665  size_t pos = symbol_name.find('@');1666  return symbol_name.substr(0, pos);1667}1668 1669// ParseSectionHeaders1670size_t ObjectFileELF::ParseSectionHeaders() {1671  return GetSectionHeaderInfo(m_section_headers, m_data, m_header, m_uuid,1672                              m_gnu_debuglink_file, m_gnu_debuglink_crc,1673                              m_arch_spec);1674}1675 1676const ObjectFileELF::ELFSectionHeaderInfo *1677ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id) {1678  if (!ParseSectionHeaders())1679    return nullptr;1680 1681  if (id < m_section_headers.size())1682    return &m_section_headers[id];1683 1684  return nullptr;1685}1686 1687lldb::user_id_t ObjectFileELF::GetSectionIndexByName(const char *name) {1688  if (!name || !name[0] || !ParseSectionHeaders())1689    return 0;1690  for (size_t i = 1; i < m_section_headers.size(); ++i)1691    if (m_section_headers[i].section_name == ConstString(name))1692      return i;1693  return 0;1694}1695 1696static SectionType GetSectionTypeFromName(llvm::StringRef Name) {1697  if (Name.consume_front(".debug_"))1698    return ObjectFile::GetDWARFSectionTypeFromName(Name);1699 1700  return llvm::StringSwitch<SectionType>(Name)1701      .Case(".ARM.exidx", eSectionTypeARMexidx)1702      .Case(".ARM.extab", eSectionTypeARMextab)1703      .Case(".ctf", eSectionTypeDebug)1704      .Cases({".data", ".tdata"}, eSectionTypeData)1705      .Case(".eh_frame", eSectionTypeEHFrame)1706      .Case(".gnu_debugaltlink", eSectionTypeDWARFGNUDebugAltLink)1707      .Case(".gosymtab", eSectionTypeGoSymtab)1708      .Case(".text", eSectionTypeCode)1709      .Case(".lldbsummaries", lldb::eSectionTypeLLDBTypeSummaries)1710      .Case(".lldbformatters", lldb::eSectionTypeLLDBFormatters)1711      .Case(".swift_ast", eSectionTypeSwiftModules)1712      .Default(eSectionTypeOther);1713}1714 1715SectionType ObjectFileELF::GetSectionType(const ELFSectionHeaderInfo &H) const {1716  switch (H.sh_type) {1717  case SHT_PROGBITS:1718    if (H.sh_flags & SHF_EXECINSTR)1719      return eSectionTypeCode;1720    break;1721  case SHT_NOBITS:1722    if (H.sh_flags & SHF_ALLOC)1723      return eSectionTypeZeroFill;1724    break;1725  case SHT_SYMTAB:1726    return eSectionTypeELFSymbolTable;1727  case SHT_DYNSYM:1728    return eSectionTypeELFDynamicSymbols;1729  case SHT_RELA:1730  case SHT_REL:1731    return eSectionTypeELFRelocationEntries;1732  case SHT_DYNAMIC:1733    return eSectionTypeELFDynamicLinkInfo;1734  }1735  return GetSectionTypeFromName(H.section_name.GetStringRef());1736}1737 1738static uint32_t GetTargetByteSize(SectionType Type, const ArchSpec &arch) {1739  switch (Type) {1740  case eSectionTypeData:1741  case eSectionTypeZeroFill:1742    return arch.GetDataByteSize();1743  case eSectionTypeCode:1744    return arch.GetCodeByteSize();1745  default:1746    return 1;1747  }1748}1749 1750static Permissions GetPermissions(const ELFSectionHeader &H) {1751  Permissions Perm = Permissions(0);1752  if (H.sh_flags & SHF_ALLOC)1753    Perm |= ePermissionsReadable;1754  if (H.sh_flags & SHF_WRITE)1755    Perm |= ePermissionsWritable;1756  if (H.sh_flags & SHF_EXECINSTR)1757    Perm |= ePermissionsExecutable;1758  return Perm;1759}1760 1761static Permissions GetPermissions(const ELFProgramHeader &H) {1762  Permissions Perm = Permissions(0);1763  if (H.p_flags & PF_R)1764    Perm |= ePermissionsReadable;1765  if (H.p_flags & PF_W)1766    Perm |= ePermissionsWritable;1767  if (H.p_flags & PF_X)1768    Perm |= ePermissionsExecutable;1769  return Perm;1770}1771 1772namespace {1773 1774using VMRange = lldb_private::Range<addr_t, addr_t>;1775 1776struct SectionAddressInfo {1777  SectionSP Segment;1778  VMRange Range;1779};1780 1781// (Unlinked) ELF object files usually have 0 for every section address, meaning1782// we need to compute synthetic addresses in order for "file addresses" from1783// different sections to not overlap. This class handles that logic.1784class VMAddressProvider {1785  using VMMap = llvm::IntervalMap<addr_t, SectionSP, 4,1786                                       llvm::IntervalMapHalfOpenInfo<addr_t>>;1787 1788  ObjectFile::Type ObjectType;1789  addr_t NextVMAddress = 0;1790  VMMap::Allocator Alloc;1791  VMMap Segments{Alloc};1792  VMMap Sections{Alloc};1793  lldb_private::Log *Log = GetLog(LLDBLog::Modules);1794  size_t SegmentCount = 0;1795  std::string SegmentName;1796 1797  VMRange GetVMRange(const ELFSectionHeader &H) {1798    addr_t Address = H.sh_addr;1799    addr_t Size = H.sh_flags & SHF_ALLOC ? H.sh_size : 0;1800 1801    // When this is a debug file for relocatable file, the address is all zero1802    // and thus needs to use accumulate method1803    if ((ObjectType == ObjectFile::Type::eTypeObjectFile ||1804         (ObjectType == ObjectFile::Type::eTypeDebugInfo && H.sh_addr == 0)) &&1805        Segments.empty() && (H.sh_flags & SHF_ALLOC)) {1806      NextVMAddress =1807          llvm::alignTo(NextVMAddress, std::max<addr_t>(H.sh_addralign, 1));1808      Address = NextVMAddress;1809      NextVMAddress += Size;1810    }1811    return VMRange(Address, Size);1812  }1813 1814public:1815  VMAddressProvider(ObjectFile::Type Type, llvm::StringRef SegmentName)1816      : ObjectType(Type), SegmentName(std::string(SegmentName)) {}1817 1818  std::string GetNextSegmentName() const {1819    return llvm::formatv("{0}[{1}]", SegmentName, SegmentCount).str();1820  }1821 1822  std::optional<VMRange> GetAddressInfo(const ELFProgramHeader &H) {1823    if (H.p_memsz == 0) {1824      LLDB_LOG(Log, "Ignoring zero-sized {0} segment. Corrupt object file?",1825               SegmentName);1826      return std::nullopt;1827    }1828 1829    if (Segments.overlaps(H.p_vaddr, H.p_vaddr + H.p_memsz)) {1830      LLDB_LOG(Log, "Ignoring overlapping {0} segment. Corrupt object file?",1831               SegmentName);1832      return std::nullopt;1833    }1834    return VMRange(H.p_vaddr, H.p_memsz);1835  }1836 1837  std::optional<SectionAddressInfo> GetAddressInfo(const ELFSectionHeader &H) {1838    VMRange Range = GetVMRange(H);1839    SectionSP Segment;1840    auto It = Segments.find(Range.GetRangeBase());1841    if ((H.sh_flags & SHF_ALLOC) && It.valid()) {1842      addr_t MaxSize;1843      if (It.start() <= Range.GetRangeBase()) {1844        MaxSize = It.stop() - Range.GetRangeBase();1845        Segment = *It;1846      } else1847        MaxSize = It.start() - Range.GetRangeBase();1848      if (Range.GetByteSize() > MaxSize) {1849        LLDB_LOG(Log, "Shortening section crossing segment boundaries. "1850                      "Corrupt object file?");1851        Range.SetByteSize(MaxSize);1852      }1853    }1854    if (Range.GetByteSize() > 0 &&1855        Sections.overlaps(Range.GetRangeBase(), Range.GetRangeEnd())) {1856      LLDB_LOG(Log, "Ignoring overlapping section. Corrupt object file?");1857      return std::nullopt;1858    }1859    if (Segment)1860      Range.Slide(-Segment->GetFileAddress());1861    return SectionAddressInfo{Segment, Range};1862  }1863 1864  void AddSegment(const VMRange &Range, SectionSP Seg) {1865    Segments.insert(Range.GetRangeBase(), Range.GetRangeEnd(), std::move(Seg));1866    ++SegmentCount;1867  }1868 1869  void AddSection(SectionAddressInfo Info, SectionSP Sect) {1870    if (Info.Range.GetByteSize() == 0)1871      return;1872    if (Info.Segment)1873      Info.Range.Slide(Info.Segment->GetFileAddress());1874    Sections.insert(Info.Range.GetRangeBase(), Info.Range.GetRangeEnd(),1875                    std::move(Sect));1876  }1877};1878}1879 1880// We have to do this because ELF doesn't have section IDs, and also1881// doesn't require section names to be unique.  (We use the section index1882// for section IDs, but that isn't guaranteed to be the same in separate1883// debug images.)1884static SectionSP FindMatchingSection(const SectionList &section_list,1885                                     SectionSP section) {1886  SectionSP sect_sp;1887 1888  addr_t vm_addr = section->GetFileAddress();1889  ConstString name = section->GetName();1890  offset_t byte_size = section->GetByteSize();1891  bool thread_specific = section->IsThreadSpecific();1892  uint32_t permissions = section->GetPermissions();1893  uint32_t alignment = section->GetLog2Align();1894 1895  for (auto sect : section_list) {1896    if (sect->GetName() == name &&1897        sect->IsThreadSpecific() == thread_specific &&1898        sect->GetPermissions() == permissions &&1899        sect->GetByteSize() == byte_size && sect->GetFileAddress() == vm_addr &&1900        sect->GetLog2Align() == alignment) {1901      sect_sp = sect;1902      break;1903    } else {1904      sect_sp = FindMatchingSection(sect->GetChildren(), section);1905      if (sect_sp)1906        break;1907    }1908  }1909 1910  return sect_sp;1911}1912 1913void ObjectFileELF::CreateSections(SectionList &unified_section_list) {1914  if (m_sections_up)1915    return;1916 1917  m_sections_up = std::make_unique<SectionList>();1918  VMAddressProvider regular_provider(GetType(), "PT_LOAD");1919  VMAddressProvider tls_provider(GetType(), "PT_TLS");1920 1921  for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {1922    const ELFProgramHeader &PHdr = EnumPHdr.value();1923    if (PHdr.p_type != PT_LOAD && PHdr.p_type != PT_TLS)1924      continue;1925 1926    VMAddressProvider &provider =1927        PHdr.p_type == PT_TLS ? tls_provider : regular_provider;1928    auto InfoOr = provider.GetAddressInfo(PHdr);1929    if (!InfoOr)1930      continue;1931 1932    uint32_t Log2Align = llvm::Log2_64(std::max<elf_xword>(PHdr.p_align, 1));1933    SectionSP Segment = std::make_shared<Section>(1934        GetModule(), this, SegmentID(EnumPHdr.index()),1935        ConstString(provider.GetNextSegmentName()), eSectionTypeContainer,1936        InfoOr->GetRangeBase(), InfoOr->GetByteSize(), PHdr.p_offset,1937        PHdr.p_filesz, Log2Align, /*flags*/ 0);1938    Segment->SetPermissions(GetPermissions(PHdr));1939    Segment->SetIsThreadSpecific(PHdr.p_type == PT_TLS);1940    m_sections_up->AddSection(Segment);1941 1942    provider.AddSegment(*InfoOr, std::move(Segment));1943  }1944 1945  ParseSectionHeaders();1946  if (m_section_headers.empty())1947    return;1948 1949  for (SectionHeaderCollIter I = std::next(m_section_headers.begin());1950       I != m_section_headers.end(); ++I) {1951    const ELFSectionHeaderInfo &header = *I;1952 1953    ConstString &name = I->section_name;1954    const uint64_t file_size =1955        header.sh_type == SHT_NOBITS ? 0 : header.sh_size;1956 1957    VMAddressProvider &provider =1958        header.sh_flags & SHF_TLS ? tls_provider : regular_provider;1959    auto InfoOr = provider.GetAddressInfo(header);1960    if (!InfoOr)1961      continue;1962 1963    SectionType sect_type = GetSectionType(header);1964 1965    const uint32_t target_bytes_size =1966        GetTargetByteSize(sect_type, m_arch_spec);1967 1968    elf::elf_xword log2align =1969        (header.sh_addralign == 0) ? 0 : llvm::Log2_64(header.sh_addralign);1970 1971    SectionSP section_sp(new Section(1972        InfoOr->Segment, GetModule(), // Module to which this section belongs.1973        this,            // ObjectFile to which this section belongs and should1974                         // read section data from.1975        SectionIndex(I), // Section ID.1976        name,            // Section name.1977        sect_type,       // Section type.1978        InfoOr->Range.GetRangeBase(), // VM address.1979        InfoOr->Range.GetByteSize(),  // VM size in bytes of this section.1980        header.sh_offset,             // Offset of this section in the file.1981        file_size,           // Size of the section as found in the file.1982        log2align,           // Alignment of the section1983        header.sh_flags,     // Flags for this section.1984        target_bytes_size)); // Number of host bytes per target byte1985 1986    section_sp->SetPermissions(GetPermissions(header));1987    section_sp->SetIsThreadSpecific(header.sh_flags & SHF_TLS);1988    (InfoOr->Segment ? InfoOr->Segment->GetChildren() : *m_sections_up)1989        .AddSection(section_sp);1990    provider.AddSection(std::move(*InfoOr), std::move(section_sp));1991  }1992 1993  // Merge the two adding any new sections, and overwriting any existing1994  // sections that are SHT_NOBITS1995  unified_section_list =1996      SectionList::Merge(unified_section_list, *m_sections_up, MergeSections);1997 1998  // If there's a .gnu_debugdata section, we'll try to read the .symtab that's1999  // embedded in there and replace the one in the original object file (if any).2000  // If there's none in the orignal object file, we add it to it.2001  if (auto gdd_obj_file = GetGnuDebugDataObjectFile()) {2002    if (auto gdd_objfile_section_list = gdd_obj_file->GetSectionList()) {2003      if (SectionSP symtab_section_sp =2004              gdd_objfile_section_list->FindSectionByType(2005                  eSectionTypeELFSymbolTable, true)) {2006        SectionSP module_section_sp = unified_section_list.FindSectionByType(2007            eSectionTypeELFSymbolTable, true);2008        if (module_section_sp)2009          unified_section_list.ReplaceSection(module_section_sp->GetID(),2010                                              symtab_section_sp);2011        else2012          unified_section_list.AddSection(symtab_section_sp);2013      }2014    }2015  }2016}2017 2018std::shared_ptr<ObjectFileELF> ObjectFileELF::GetGnuDebugDataObjectFile() {2019  if (m_gnu_debug_data_object_file != nullptr)2020    return m_gnu_debug_data_object_file;2021 2022  SectionSP section =2023      GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata"));2024  if (!section)2025    return nullptr;2026 2027  if (!lldb_private::lzma::isAvailable()) {2028    GetModule()->ReportWarning(2029        "No LZMA support found for reading .gnu_debugdata section");2030    return nullptr;2031  }2032 2033  // Uncompress the data2034  DataExtractor data;2035  section->GetSectionData(data);2036  llvm::SmallVector<uint8_t, 0> uncompressedData;2037  auto err = lldb_private::lzma::uncompress(data.GetData(), uncompressedData);2038  if (err) {2039    GetModule()->ReportWarning(2040        "An error occurred while decompression the section {0}: {1}",2041        section->GetName().AsCString(), llvm::toString(std::move(err)).c_str());2042    return nullptr;2043  }2044 2045  // Construct ObjectFileELF object from decompressed buffer2046  DataBufferSP gdd_data_buf(2047      new DataBufferHeap(uncompressedData.data(), uncompressedData.size()));2048  auto fspec = GetFileSpec().CopyByAppendingPathComponent(2049      llvm::StringRef("gnu_debugdata"));2050  m_gnu_debug_data_object_file.reset(new ObjectFileELF(2051      GetModule(), gdd_data_buf, 0, &fspec, 0, gdd_data_buf->GetByteSize()));2052 2053  // This line is essential; otherwise a breakpoint can be set but not hit.2054  m_gnu_debug_data_object_file->SetType(ObjectFile::eTypeDebugInfo);2055 2056  ArchSpec spec = m_gnu_debug_data_object_file->GetArchitecture();2057  if (spec && m_gnu_debug_data_object_file->SetModulesArchitecture(spec))2058    return m_gnu_debug_data_object_file;2059 2060  return nullptr;2061}2062 2063// Find the arm/aarch64 mapping symbol character in the given symbol name.2064// Mapping symbols have the form of "$<char>[.<any>]*". Additionally we2065// recognize cases when the mapping symbol prefixed by an arbitrary string2066// because if a symbol prefix added to each symbol in the object file with2067// objcopy then the mapping symbols are also prefixed.2068static char FindArmAarch64MappingSymbol(const char *symbol_name) {2069  if (!symbol_name)2070    return '\0';2071 2072  const char *dollar_pos = ::strchr(symbol_name, '$');2073  if (!dollar_pos || dollar_pos[1] == '\0')2074    return '\0';2075 2076  if (dollar_pos[2] == '\0' || dollar_pos[2] == '.')2077    return dollar_pos[1];2078  return '\0';2079}2080 2081static char FindRISCVMappingSymbol(const char *symbol_name) {2082  if (!symbol_name)2083    return '\0';2084 2085  if (strcmp(symbol_name, "$d") == 0) {2086    return 'd';2087  }2088  if (strcmp(symbol_name, "$x") == 0) {2089    return 'x';2090  }2091  return '\0';2092}2093 2094#define STO_MIPS_ISA (3 << 6)2095#define STO_MICROMIPS (2 << 6)2096#define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS)2097 2098// private2099std::pair<unsigned, ObjectFileELF::FileAddressToAddressClassMap>2100ObjectFileELF::ParseSymbols(Symtab *symtab, user_id_t start_id,2101                            SectionList *section_list, const size_t num_symbols,2102                            const DataExtractor &symtab_data,2103                            const DataExtractor &strtab_data) {2104  ELFSymbol symbol;2105  lldb::offset_t offset = 0;2106  // The changes these symbols would make to the class map. We will also update2107  // m_address_class_map but need to tell the caller what changed because the2108  // caller may be another object file.2109  FileAddressToAddressClassMap address_class_map;2110 2111  static ConstString text_section_name(".text");2112  static ConstString init_section_name(".init");2113  static ConstString fini_section_name(".fini");2114  static ConstString ctors_section_name(".ctors");2115  static ConstString dtors_section_name(".dtors");2116 2117  static ConstString data_section_name(".data");2118  static ConstString rodata_section_name(".rodata");2119  static ConstString rodata1_section_name(".rodata1");2120  static ConstString data2_section_name(".data1");2121  static ConstString bss_section_name(".bss");2122  static ConstString opd_section_name(".opd"); // For ppc642123 2124  // On Android the oatdata and the oatexec symbols in the oat and odex files2125  // covers the full .text section what causes issues with displaying unusable2126  // symbol name to the user and very slow unwinding speed because the2127  // instruction emulation based unwind plans try to emulate all instructions2128  // in these symbols. Don't add these symbols to the symbol list as they have2129  // no use for the debugger and they are causing a lot of trouble. Filtering2130  // can't be restricted to Android because this special object file don't2131  // contain the note section specifying the environment to Android but the2132  // custom extension and file name makes it highly unlikely that this will2133  // collide with anything else.2134  llvm::StringRef file_extension = m_file.GetFileNameExtension();2135  bool skip_oatdata_oatexec =2136      file_extension == ".oat" || file_extension == ".odex";2137 2138  ArchSpec arch = GetArchitecture();2139  ModuleSP module_sp(GetModule());2140  SectionList *module_section_list =2141      module_sp ? module_sp->GetSectionList() : nullptr;2142 2143  // We might have debug information in a separate object, in which case2144  // we need to map the sections from that object to the sections in the2145  // main object during symbol lookup.  If we had to compare the sections2146  // for every single symbol, that would be expensive, so this map is2147  // used to accelerate the process.2148  std::unordered_map<lldb::SectionSP, lldb::SectionSP> section_map;2149 2150  unsigned i;2151  for (i = 0; i < num_symbols; ++i) {2152    if (!symbol.Parse(symtab_data, &offset))2153      break;2154 2155    const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);2156    if (!symbol_name)2157      symbol_name = "";2158 2159    // Skip local symbols starting with ".L" because these are compiler2160    // generated local labels used for internal purposes (e.g. debugging,2161    // optimization) and are not relevant for symbol resolution or external2162    // linkage.2163    if (llvm::StringRef(symbol_name).starts_with(".L"))2164      continue;2165    // No need to add non-section symbols that have no names2166    if (symbol.getType() != STT_SECTION &&2167        (symbol_name == nullptr || symbol_name[0] == '\0'))2168      continue;2169 2170    // Skipping oatdata and oatexec sections if it is requested. See details2171    // above the definition of skip_oatdata_oatexec for the reasons.2172    if (skip_oatdata_oatexec && (::strcmp(symbol_name, "oatdata") == 0 ||2173                                 ::strcmp(symbol_name, "oatexec") == 0))2174      continue;2175 2176    SectionSP symbol_section_sp;2177    SymbolType symbol_type = eSymbolTypeInvalid;2178    Elf64_Half shndx = symbol.st_shndx;2179 2180    switch (shndx) {2181    case SHN_ABS:2182      symbol_type = eSymbolTypeAbsolute;2183      break;2184    case SHN_UNDEF:2185      symbol_type = eSymbolTypeUndefined;2186      break;2187    default:2188      symbol_section_sp = section_list->FindSectionByID(shndx);2189      break;2190    }2191 2192    // If a symbol is undefined do not process it further even if it has a STT2193    // type2194    if (symbol_type != eSymbolTypeUndefined) {2195      switch (symbol.getType()) {2196      default:2197      case STT_NOTYPE:2198        // The symbol's type is not specified.2199        break;2200 2201      case STT_OBJECT:2202        // The symbol is associated with a data object, such as a variable, an2203        // array, etc.2204        symbol_type = eSymbolTypeData;2205        break;2206 2207      case STT_FUNC:2208        // The symbol is associated with a function or other executable code.2209        symbol_type = eSymbolTypeCode;2210        break;2211 2212      case STT_SECTION:2213        // The symbol is associated with a section. Symbol table entries of2214        // this type exist primarily for relocation and normally have STB_LOCAL2215        // binding.2216        break;2217 2218      case STT_FILE:2219        // Conventionally, the symbol's name gives the name of the source file2220        // associated with the object file. A file symbol has STB_LOCAL2221        // binding, its section index is SHN_ABS, and it precedes the other2222        // STB_LOCAL symbols for the file, if it is present.2223        symbol_type = eSymbolTypeSourceFile;2224        break;2225 2226      case STT_GNU_IFUNC:2227        // The symbol is associated with an indirect function. The actual2228        // function will be resolved if it is referenced.2229        symbol_type = eSymbolTypeResolver;2230        break;2231      }2232    }2233 2234    if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) {2235      if (symbol_section_sp) {2236        ConstString sect_name = symbol_section_sp->GetName();2237        if (sect_name == text_section_name || sect_name == init_section_name ||2238            sect_name == fini_section_name || sect_name == ctors_section_name ||2239            sect_name == dtors_section_name) {2240          symbol_type = eSymbolTypeCode;2241        } else if (sect_name == data_section_name ||2242                   sect_name == data2_section_name ||2243                   sect_name == rodata_section_name ||2244                   sect_name == rodata1_section_name ||2245                   sect_name == bss_section_name) {2246          symbol_type = eSymbolTypeData;2247        }2248      }2249    }2250 2251    int64_t symbol_value_offset = 0;2252    uint32_t additional_flags = 0;2253    if (arch.IsValid()) {2254      if (arch.GetMachine() == llvm::Triple::arm) {2255        if (symbol.getBinding() == STB_LOCAL) {2256          char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);2257          if (symbol_type == eSymbolTypeCode) {2258            switch (mapping_symbol) {2259            case 'a':2260              // $a[.<any>]* - marks an ARM instruction sequence2261              address_class_map[symbol.st_value] = AddressClass::eCode;2262              break;2263            case 'b':2264            case 't':2265              // $b[.<any>]* - marks a THUMB BL instruction sequence2266              // $t[.<any>]* - marks a THUMB instruction sequence2267              address_class_map[symbol.st_value] =2268                  AddressClass::eCodeAlternateISA;2269              break;2270            case 'd':2271              // $d[.<any>]* - marks a data item sequence (e.g. lit pool)2272              address_class_map[symbol.st_value] = AddressClass::eData;2273              break;2274            }2275          }2276          if (mapping_symbol)2277            continue;2278        }2279      } else if (arch.GetMachine() == llvm::Triple::aarch64) {2280        if (symbol.getBinding() == STB_LOCAL) {2281          char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);2282          if (symbol_type == eSymbolTypeCode) {2283            switch (mapping_symbol) {2284            case 'x':2285              // $x[.<any>]* - marks an A64 instruction sequence2286              address_class_map[symbol.st_value] = AddressClass::eCode;2287              break;2288            case 'd':2289              // $d[.<any>]* - marks a data item sequence (e.g. lit pool)2290              address_class_map[symbol.st_value] = AddressClass::eData;2291              break;2292            }2293          }2294          if (mapping_symbol)2295            continue;2296        }2297      } else if (arch.GetTriple().isRISCV()) {2298        if (symbol.getBinding() == STB_LOCAL) {2299          char mapping_symbol = FindRISCVMappingSymbol(symbol_name);2300          if (symbol_type == eSymbolTypeCode) {2301            // Only handle $d and $x mapping symbols.2302            // Other mapping symbols are ignored as they don't affect address2303            // classification.2304            switch (mapping_symbol) {2305            case 'x':2306              // $x - marks a RISCV instruction sequence2307              address_class_map[symbol.st_value] = AddressClass::eCode;2308              break;2309            case 'd':2310              // $d - marks a RISCV data item sequence2311              address_class_map[symbol.st_value] = AddressClass::eData;2312              break;2313            }2314          }2315          if (mapping_symbol)2316            continue;2317        }2318      }2319 2320      if (arch.GetMachine() == llvm::Triple::arm) {2321        if (symbol_type == eSymbolTypeCode) {2322          if (symbol.st_value & 1) {2323            // Subtracting 1 from the address effectively unsets the low order2324            // bit, which results in the address actually pointing to the2325            // beginning of the symbol. This delta will be used below in2326            // conjunction with symbol.st_value to produce the final2327            // symbol_value that we store in the symtab.2328            symbol_value_offset = -1;2329            address_class_map[symbol.st_value ^ 1] =2330                AddressClass::eCodeAlternateISA;2331          } else {2332            // This address is ARM2333            address_class_map[symbol.st_value] = AddressClass::eCode;2334          }2335        }2336      }2337 2338      /*2339       * MIPS:2340       * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for2341       * MIPS).2342       * This allows processor to switch between microMIPS and MIPS without any2343       * need2344       * for special mode-control register. However, apart from .debug_line,2345       * none of2346       * the ELF/DWARF sections set the ISA bit (for symbol or section). Use2347       * st_other2348       * flag to check whether the symbol is microMIPS and then set the address2349       * class2350       * accordingly.2351      */2352      if (arch.IsMIPS()) {2353        if (IS_MICROMIPS(symbol.st_other))2354          address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;2355        else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) {2356          symbol.st_value = symbol.st_value & (~1ull);2357          address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;2358        } else {2359          if (symbol_type == eSymbolTypeCode)2360            address_class_map[symbol.st_value] = AddressClass::eCode;2361          else if (symbol_type == eSymbolTypeData)2362            address_class_map[symbol.st_value] = AddressClass::eData;2363          else2364            address_class_map[symbol.st_value] = AddressClass::eUnknown;2365        }2366      }2367    }2368 2369    // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB2370    // symbols. See above for more details.2371    uint64_t symbol_value = symbol.st_value + symbol_value_offset;2372 2373    if (symbol_section_sp &&2374        CalculateType() != ObjectFile::Type::eTypeObjectFile)2375      symbol_value -= symbol_section_sp->GetFileAddress();2376 2377    if (symbol_section_sp && module_section_list &&2378        module_section_list != section_list) {2379      auto section_it = section_map.find(symbol_section_sp);2380      if (section_it == section_map.end()) {2381        section_it = section_map2382                         .emplace(symbol_section_sp,2383                                  FindMatchingSection(*module_section_list,2384                                                      symbol_section_sp))2385                         .first;2386      }2387      if (section_it->second)2388        symbol_section_sp = section_it->second;2389    }2390 2391    bool is_global = symbol.getBinding() == STB_GLOBAL;2392    uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags;2393    llvm::StringRef symbol_ref(symbol_name);2394 2395    // Symbol names may contain @VERSION suffixes. Find those and strip them2396    // temporarily.2397    size_t version_pos = symbol_ref.find('@');2398    bool has_suffix = version_pos != llvm::StringRef::npos;2399    llvm::StringRef symbol_bare = symbol_ref.substr(0, version_pos);2400    Mangled mangled(symbol_bare);2401 2402    // Now append the suffix back to mangled and unmangled names. Only do it if2403    // the demangling was successful (string is not empty).2404    if (has_suffix) {2405      llvm::StringRef suffix = symbol_ref.substr(version_pos);2406 2407      llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef();2408      if (!mangled_name.empty())2409        mangled.SetMangledName(ConstString((mangled_name + suffix).str()));2410 2411      ConstString demangled = mangled.GetDemangledName();2412      llvm::StringRef demangled_name = demangled.GetStringRef();2413      if (!demangled_name.empty())2414        mangled.SetDemangledName(ConstString((demangled_name + suffix).str()));2415    }2416 2417    // In ELF all symbol should have a valid size but it is not true for some2418    // function symbols coming from hand written assembly. As none of the2419    // function symbol should have 0 size we try to calculate the size for2420    // these symbols in the symtab with saying that their original size is not2421    // valid.2422    bool symbol_size_valid =2423        symbol.st_size != 0 || symbol.getType() != STT_FUNC;2424 2425    bool is_trampoline = false;2426    if (arch.IsValid() && (arch.GetMachine() == llvm::Triple::aarch64)) {2427      // On AArch64, trampolines are registered as code.2428      // If we detect a trampoline (which starts with __AArch64ADRPThunk_ or2429      // __AArch64AbsLongThunk_) we register the symbol as a trampoline. This2430      // way we will be able to detect the trampoline when we step in a function2431      // and step through the trampoline.2432      if (symbol_type == eSymbolTypeCode) {2433        llvm::StringRef trampoline_name = mangled.GetName().GetStringRef();2434        if (trampoline_name.starts_with("__AArch64ADRPThunk_") ||2435            trampoline_name.starts_with("__AArch64AbsLongThunk_")) {2436          symbol_type = eSymbolTypeTrampoline;2437          is_trampoline = true;2438        }2439      }2440    }2441 2442    Symbol dc_symbol(2443        i + start_id, // ID is the original symbol table index.2444        mangled,2445        symbol_type,                    // Type of this symbol2446        is_global,                      // Is this globally visible?2447        false,                          // Is this symbol debug info?2448        is_trampoline,                  // Is this symbol a trampoline?2449        false,                          // Is this symbol artificial?2450        AddressRange(symbol_section_sp, // Section in which this symbol is2451                                        // defined or null.2452                     symbol_value,      // Offset in section or symbol value.2453                     symbol.st_size),   // Size in bytes of this symbol.2454        symbol_size_valid,              // Symbol size is valid2455        has_suffix,                     // Contains linker annotations?2456        flags);                         // Symbol flags.2457    if (symbol.getBinding() == STB_WEAK)2458      dc_symbol.SetIsWeak(true);2459    symtab->AddSymbol(dc_symbol);2460  }2461 2462  m_address_class_map.merge(address_class_map);2463  return {i, address_class_map};2464}2465 2466std::pair<unsigned, ObjectFileELF::FileAddressToAddressClassMap>2467ObjectFileELF::ParseSymbolTable(Symtab *symbol_table, user_id_t start_id,2468                                lldb_private::Section *symtab) {2469  if (symtab->GetObjectFile() != this) {2470    // If the symbol table section is owned by a different object file, have it2471    // do the parsing.2472    ObjectFileELF *obj_file_elf =2473        static_cast<ObjectFileELF *>(symtab->GetObjectFile());2474    auto [num_symbols, address_class_map] =2475        obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab);2476 2477    // The other object file returned the changes it made to its address2478    // class map, make the same changes to ours.2479    m_address_class_map.merge(address_class_map);2480 2481    return {num_symbols, address_class_map};2482  }2483 2484  // Get section list for this object file.2485  SectionList *section_list = m_sections_up.get();2486  if (!section_list)2487    return {};2488 2489  user_id_t symtab_id = symtab->GetID();2490  const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);2491  assert(symtab_hdr->sh_type == SHT_SYMTAB ||2492         symtab_hdr->sh_type == SHT_DYNSYM);2493 2494  // sh_link: section header index of associated string table.2495  user_id_t strtab_id = symtab_hdr->sh_link;2496  Section *strtab = section_list->FindSectionByID(strtab_id).get();2497 2498  if (symtab && strtab) {2499    assert(symtab->GetObjectFile() == this);2500    assert(strtab->GetObjectFile() == this);2501 2502    DataExtractor symtab_data;2503    DataExtractor strtab_data;2504    if (ReadSectionData(symtab, symtab_data) &&2505        ReadSectionData(strtab, strtab_data)) {2506      size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;2507 2508      return ParseSymbols(symbol_table, start_id, section_list, num_symbols,2509                          symtab_data, strtab_data);2510    }2511  }2512 2513  return {0, {}};2514}2515 2516size_t ObjectFileELF::ParseDynamicSymbols() {2517  if (m_dynamic_symbols.size())2518    return m_dynamic_symbols.size();2519 2520  std::optional<DataExtractor> dynamic_data = GetDynamicData();2521  if (!dynamic_data)2522    return 0;2523 2524  ELFDynamicWithName e;2525  lldb::offset_t cursor = 0;2526  while (e.symbol.Parse(*dynamic_data, &cursor)) {2527    m_dynamic_symbols.push_back(e);2528    if (e.symbol.d_tag == DT_NULL)2529      break;2530  }2531  if (std::optional<DataExtractor> dynstr_data = GetDynstrData()) {2532    for (ELFDynamicWithName &entry : m_dynamic_symbols) {2533      switch (entry.symbol.d_tag) {2534      case DT_NEEDED:2535      case DT_SONAME:2536      case DT_RPATH:2537      case DT_RUNPATH:2538      case DT_AUXILIARY:2539      case DT_FILTER: {2540        lldb::offset_t cursor = entry.symbol.d_val;2541        const char *name = dynstr_data->GetCStr(&cursor);2542        if (name)2543          entry.name = std::string(name);2544        break;2545      }2546      default:2547        break;2548      }2549    }2550  }2551  return m_dynamic_symbols.size();2552}2553 2554const ELFDynamic *ObjectFileELF::FindDynamicSymbol(unsigned tag) {2555  if (!ParseDynamicSymbols())2556    return nullptr;2557  for (const auto &entry : m_dynamic_symbols) {2558    if (entry.symbol.d_tag == tag)2559      return &entry.symbol;2560  }2561  return nullptr;2562}2563 2564unsigned ObjectFileELF::PLTRelocationType() {2565  // DT_PLTREL2566  //  This member specifies the type of relocation entry to which the2567  //  procedure linkage table refers. The d_val member holds DT_REL or2568  //  DT_RELA, as appropriate. All relocations in a procedure linkage table2569  //  must use the same relocation.2570  const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);2571 2572  if (symbol)2573    return symbol->d_val;2574 2575  return 0;2576}2577 2578// Returns the size of the normal plt entries and the offset of the first2579// normal plt entry. The 0th entry in the plt table is usually a resolution2580// entry which have different size in some architectures then the rest of the2581// plt entries.2582static std::pair<uint64_t, uint64_t>2583GetPltEntrySizeAndOffset(const ELFSectionHeader *rel_hdr,2584                         const ELFSectionHeader *plt_hdr) {2585  const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;2586 2587  // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are2588  // 16 bytes. So round the entsize up by the alignment if addralign is set.2589  elf_xword plt_entsize =2590      plt_hdr->sh_addralign2591          ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign)2592          : plt_hdr->sh_entsize;2593 2594  // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly.2595  // PLT entries relocation code in general requires multiple instruction and2596  // should be greater than 4 bytes in most cases. Try to guess correct size2597  // just in case.2598  if (plt_entsize <= 4) {2599    // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the2600    // size of the plt entries based on the number of entries and the size of2601    // the plt section with the assumption that the size of the 0th entry is at2602    // least as big as the size of the normal entries and it isn't much bigger2603    // then that.2604    if (plt_hdr->sh_addralign)2605      plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign /2606                    (num_relocations + 1) * plt_hdr->sh_addralign;2607    else2608      plt_entsize = plt_hdr->sh_size / (num_relocations + 1);2609  }2610 2611  elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize;2612 2613  return std::make_pair(plt_entsize, plt_offset);2614}2615 2616static unsigned ParsePLTRelocations(2617    Symtab *symbol_table, user_id_t start_id, unsigned rel_type,2618    const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,2619    const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr,2620    const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data,2621    DataExtractor &symtab_data, DataExtractor &strtab_data) {2622  ELFRelocation rel(rel_type);2623  ELFSymbol symbol;2624  lldb::offset_t offset = 0;2625 2626  uint64_t plt_offset, plt_entsize;2627  std::tie(plt_entsize, plt_offset) =2628      GetPltEntrySizeAndOffset(rel_hdr, plt_hdr);2629  const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;2630 2631  typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);2632  reloc_info_fn reloc_type;2633  reloc_info_fn reloc_symbol;2634 2635  if (hdr->Is32Bit()) {2636    reloc_type = ELFRelocation::RelocType32;2637    reloc_symbol = ELFRelocation::RelocSymbol32;2638  } else {2639    reloc_type = ELFRelocation::RelocType64;2640    reloc_symbol = ELFRelocation::RelocSymbol64;2641  }2642 2643  unsigned slot_type = hdr->GetRelocationJumpSlotType();2644  unsigned i;2645  for (i = 0; i < num_relocations; ++i) {2646    if (!rel.Parse(rel_data, &offset))2647      break;2648 2649    if (reloc_type(rel) != slot_type)2650      continue;2651 2652    lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;2653    if (!symbol.Parse(symtab_data, &symbol_offset))2654      break;2655 2656    const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);2657    uint64_t plt_index = plt_offset + i * plt_entsize;2658 2659    Symbol jump_symbol(2660        i + start_id,          // Symbol table index2661        symbol_name,           // symbol name.2662        eSymbolTypeTrampoline, // Type of this symbol2663        false,                 // Is this globally visible?2664        false,                 // Is this symbol debug info?2665        true,                  // Is this symbol a trampoline?2666        true,                  // Is this symbol artificial?2667        plt_section_sp, // Section in which this symbol is defined or null.2668        plt_index,      // Offset in section or symbol value.2669        plt_entsize,    // Size in bytes of this symbol.2670        true,           // Size is valid2671        false,          // Contains linker annotations?2672        0);             // Symbol flags.2673 2674    symbol_table->AddSymbol(jump_symbol);2675  }2676 2677  return i;2678}2679 2680unsigned2681ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table, user_id_t start_id,2682                                      const ELFSectionHeaderInfo *rel_hdr,2683                                      user_id_t rel_id) {2684  assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);2685 2686  // The link field points to the associated symbol table.2687  user_id_t symtab_id = rel_hdr->sh_link;2688 2689  // If the link field doesn't point to the appropriate symbol name table then2690  // try to find it by name as some compiler don't fill in the link fields.2691  if (!symtab_id)2692    symtab_id = GetSectionIndexByName(".dynsym");2693 2694  // Get PLT section.  We cannot use rel_hdr->sh_info, since current linkers2695  // point that to the .got.plt or .got section instead of .plt.2696  user_id_t plt_id = GetSectionIndexByName(".plt");2697 2698  if (!symtab_id || !plt_id)2699    return 0;2700 2701  const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);2702  if (!plt_hdr)2703    return 0;2704 2705  const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);2706  if (!sym_hdr)2707    return 0;2708 2709  SectionList *section_list = m_sections_up.get();2710  if (!section_list)2711    return 0;2712 2713  Section *rel_section = section_list->FindSectionByID(rel_id).get();2714  if (!rel_section)2715    return 0;2716 2717  SectionSP plt_section_sp(section_list->FindSectionByID(plt_id));2718  if (!plt_section_sp)2719    return 0;2720 2721  Section *symtab = section_list->FindSectionByID(symtab_id).get();2722  if (!symtab)2723    return 0;2724 2725  // sh_link points to associated string table.2726  Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link).get();2727  if (!strtab)2728    return 0;2729 2730  DataExtractor rel_data;2731  if (!ReadSectionData(rel_section, rel_data))2732    return 0;2733 2734  DataExtractor symtab_data;2735  if (!ReadSectionData(symtab, symtab_data))2736    return 0;2737 2738  DataExtractor strtab_data;2739  if (!ReadSectionData(strtab, strtab_data))2740    return 0;2741 2742  unsigned rel_type = PLTRelocationType();2743  if (!rel_type)2744    return 0;2745 2746  return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header,2747                             rel_hdr, plt_hdr, sym_hdr, plt_section_sp,2748                             rel_data, symtab_data, strtab_data);2749}2750 2751static void ApplyELF64ABS64Relocation(Symtab *symtab, ELFRelocation &rel,2752                                      DataExtractor &debug_data,2753                                      Section *rel_section) {2754  Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol64(rel));2755  if (symbol) {2756    addr_t value = symbol->GetAddressRef().GetFileAddress();2757    DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();2758    // ObjectFileELF creates a WritableDataBuffer in CreateInstance.2759    WritableDataBuffer *data_buffer =2760        llvm::cast<WritableDataBuffer>(data_buffer_sp.get());2761    void *const dst = data_buffer->GetBytes() + rel_section->GetFileOffset() +2762                      ELFRelocation::RelocOffset64(rel);2763    uint64_t val_offset = value + ELFRelocation::RelocAddend64(rel);2764    memcpy(dst, &val_offset, sizeof(uint64_t));2765  }2766}2767 2768static void ApplyELF64ABS32Relocation(Symtab *symtab, ELFRelocation &rel,2769                                      DataExtractor &debug_data,2770                                      Section *rel_section, bool is_signed) {2771  Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol64(rel));2772  if (symbol) {2773    addr_t value = symbol->GetAddressRef().GetFileAddress();2774    value += ELFRelocation::RelocAddend32(rel);2775    if ((!is_signed && (value > UINT32_MAX)) ||2776        (is_signed &&2777         ((int64_t)value > INT32_MAX || (int64_t)value < INT32_MIN))) {2778      Log *log = GetLog(LLDBLog::Modules);2779      LLDB_LOGF(log, "Failed to apply debug info relocations");2780      return;2781    }2782    uint32_t truncated_addr = (value & 0xFFFFFFFF);2783    DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();2784    // ObjectFileELF creates a WritableDataBuffer in CreateInstance.2785    WritableDataBuffer *data_buffer =2786        llvm::cast<WritableDataBuffer>(data_buffer_sp.get());2787    void *const dst = data_buffer->GetBytes() + rel_section->GetFileOffset() +2788                      ELFRelocation::RelocOffset32(rel);2789    memcpy(dst, &truncated_addr, sizeof(uint32_t));2790  }2791}2792 2793static void ApplyELF32ABS32RelRelocation(Symtab *symtab, ELFRelocation &rel,2794                                         DataExtractor &debug_data,2795                                         Section *rel_section) {2796  Log *log = GetLog(LLDBLog::Modules);2797  Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol32(rel));2798  if (symbol) {2799    addr_t value = symbol->GetAddressRef().GetFileAddress();2800    if (value == LLDB_INVALID_ADDRESS) {2801      const char *name = symbol->GetName().GetCString();2802      LLDB_LOGF(log, "Debug info symbol invalid: %s", name);2803      return;2804    }2805    assert(llvm::isUInt<32>(value) && "Valid addresses are 32-bit");2806    DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();2807    // ObjectFileELF creates a WritableDataBuffer in CreateInstance.2808    WritableDataBuffer *data_buffer =2809        llvm::cast<WritableDataBuffer>(data_buffer_sp.get());2810    uint8_t *dst = data_buffer->GetBytes() + rel_section->GetFileOffset() +2811                   ELFRelocation::RelocOffset32(rel);2812    // Implicit addend is stored inline as a signed value.2813    int32_t addend;2814    memcpy(&addend, dst, sizeof(int32_t));2815    // The sum must be positive. This extra check prevents UB from overflow in2816    // the actual range check below.2817    if (addend < 0 && static_cast<uint32_t>(-addend) > value) {2818      LLDB_LOGF(log, "Debug info relocation overflow: 0x%" PRIx64,2819                static_cast<int64_t>(value) + addend);2820      return;2821    }2822    if (!llvm::isUInt<32>(value + addend)) {2823      LLDB_LOGF(log, "Debug info relocation out of range: 0x%" PRIx64, value);2824      return;2825    }2826    uint32_t addr = value + addend;2827    memcpy(dst, &addr, sizeof(uint32_t));2828  }2829}2830 2831unsigned ObjectFileELF::ApplyRelocations(2832    Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,2833    const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr,2834    DataExtractor &rel_data, DataExtractor &symtab_data,2835    DataExtractor &debug_data, Section *rel_section) {2836  ELFRelocation rel(rel_hdr->sh_type);2837  lldb::addr_t offset = 0;2838  const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;2839  typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);2840  reloc_info_fn reloc_type;2841  reloc_info_fn reloc_symbol;2842 2843  if (hdr->Is32Bit()) {2844    reloc_type = ELFRelocation::RelocType32;2845    reloc_symbol = ELFRelocation::RelocSymbol32;2846  } else {2847    reloc_type = ELFRelocation::RelocType64;2848    reloc_symbol = ELFRelocation::RelocSymbol64;2849  }2850 2851  for (unsigned i = 0; i < num_relocations; ++i) {2852    if (!rel.Parse(rel_data, &offset)) {2853      GetModule()->ReportError(".rel{0}[{1:d}] failed to parse relocation",2854                               rel_section->GetName().AsCString(), i);2855      break;2856    }2857    Symbol *symbol = nullptr;2858 2859    if (hdr->Is32Bit()) {2860      switch (hdr->e_machine) {2861      case llvm::ELF::EM_ARM:2862        switch (reloc_type(rel)) {2863        case R_ARM_ABS32:2864          ApplyELF32ABS32RelRelocation(symtab, rel, debug_data, rel_section);2865          break;2866        case R_ARM_REL32:2867          GetModule()->ReportError("unsupported AArch32 relocation:"2868                                   " .rel{0}[{1}], type {2}",2869                                   rel_section->GetName().AsCString(), i,2870                                   reloc_type(rel));2871          break;2872        default:2873          assert(false && "unexpected relocation type");2874        }2875        break;2876      case llvm::ELF::EM_386:2877        switch (reloc_type(rel)) {2878        case R_386_32:2879          symbol = symtab->FindSymbolByID(reloc_symbol(rel));2880          if (symbol) {2881            addr_t f_offset =2882                rel_section->GetFileOffset() + ELFRelocation::RelocOffset32(rel);2883            DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();2884            // ObjectFileELF creates a WritableDataBuffer in CreateInstance.2885            WritableDataBuffer *data_buffer =2886                llvm::cast<WritableDataBuffer>(data_buffer_sp.get());2887            uint32_t *dst = reinterpret_cast<uint32_t *>(2888                data_buffer->GetBytes() + f_offset);2889 2890            addr_t value = symbol->GetAddressRef().GetFileAddress();2891            if (rel.IsRela()) {2892              value += ELFRelocation::RelocAddend32(rel);2893            } else {2894              value += *dst;2895            }2896            *dst = value;2897          } else {2898            GetModule()->ReportError(".rel{0}[{1}] unknown symbol id: {2:d}",2899                                    rel_section->GetName().AsCString(), i,2900                                    reloc_symbol(rel));2901          }2902          break;2903        case R_386_NONE:2904        case R_386_PC32:2905          GetModule()->ReportError("unsupported i386 relocation:"2906                                   " .rel{0}[{1}], type {2}",2907                                   rel_section->GetName().AsCString(), i,2908                                   reloc_type(rel));2909          break;2910        default:2911          assert(false && "unexpected relocation type");2912          break;2913        }2914        break;2915      default:2916        GetModule()->ReportError("unsupported 32-bit ELF machine arch: {0}", hdr->e_machine);2917        break;2918      }2919    } else {2920      switch (hdr->e_machine) {2921      case llvm::ELF::EM_AARCH64:2922        switch (reloc_type(rel)) {2923        case R_AARCH64_ABS64:2924          ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);2925          break;2926        case R_AARCH64_ABS32:2927          ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);2928          break;2929        default:2930          assert(false && "unexpected relocation type");2931        }2932        break;2933      case llvm::ELF::EM_LOONGARCH:2934        switch (reloc_type(rel)) {2935        case R_LARCH_64:2936          ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);2937          break;2938        case R_LARCH_32:2939          ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);2940          break;2941        default:2942          assert(false && "unexpected relocation type");2943        }2944        break;2945      case llvm::ELF::EM_X86_64:2946        switch (reloc_type(rel)) {2947        case R_X86_64_64:2948          ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);2949          break;2950        case R_X86_64_32:2951          ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section,2952                                    false);2953          break;2954        case R_X86_64_32S:2955          ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);2956          break;2957        case R_X86_64_PC32:2958        default:2959          assert(false && "unexpected relocation type");2960        }2961        break;2962      default:2963        GetModule()->ReportError("unsupported 64-bit ELF machine arch: {0}", hdr->e_machine);2964        break;2965      }2966    }2967  }2968 2969  return 0;2970}2971 2972unsigned ObjectFileELF::RelocateDebugSections(const ELFSectionHeader *rel_hdr,2973                                              user_id_t rel_id,2974                                              lldb_private::Symtab *thetab) {2975  assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);2976 2977  // Parse in the section list if needed.2978  SectionList *section_list = GetSectionList();2979  if (!section_list)2980    return 0;2981 2982  user_id_t symtab_id = rel_hdr->sh_link;2983  user_id_t debug_id = rel_hdr->sh_info;2984 2985  const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id);2986  if (!symtab_hdr)2987    return 0;2988 2989  const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id);2990  if (!debug_hdr)2991    return 0;2992 2993  Section *rel = section_list->FindSectionByID(rel_id).get();2994  if (!rel)2995    return 0;2996 2997  Section *symtab = section_list->FindSectionByID(symtab_id).get();2998  if (!symtab)2999    return 0;3000 3001  Section *debug = section_list->FindSectionByID(debug_id).get();3002  if (!debug)3003    return 0;3004 3005  DataExtractor rel_data;3006  DataExtractor symtab_data;3007  DataExtractor debug_data;3008 3009  if (GetData(rel->GetFileOffset(), rel->GetFileSize(), rel_data) &&3010      GetData(symtab->GetFileOffset(), symtab->GetFileSize(), symtab_data) &&3011      GetData(debug->GetFileOffset(), debug->GetFileSize(), debug_data)) {3012    ApplyRelocations(thetab, &m_header, rel_hdr, symtab_hdr, debug_hdr,3013                     rel_data, symtab_data, debug_data, debug);3014  }3015 3016  return 0;3017}3018 3019void ObjectFileELF::ParseSymtab(Symtab &lldb_symtab) {3020  ModuleSP module_sp(GetModule());3021  if (!module_sp)3022    return;3023 3024  Progress progress("Parsing symbol table",3025                    m_file.GetFilename().AsCString("<Unknown>"));3026  ElapsedTime elapsed(module_sp->GetSymtabParseTime());3027 3028  // We always want to use the main object file so we (hopefully) only have one3029  // cached copy of our symtab, dynamic sections, etc.3030  ObjectFile *module_obj_file = module_sp->GetObjectFile();3031  if (module_obj_file && module_obj_file != this)3032    return module_obj_file->ParseSymtab(lldb_symtab);3033 3034  SectionList *section_list = module_sp->GetSectionList();3035  if (!section_list)3036    return;3037 3038  uint64_t symbol_id = 0;3039 3040  // Sharable objects and dynamic executables usually have 2 distinct symbol3041  // tables, one named ".symtab", and the other ".dynsym". The dynsym is a3042  // smaller version of the symtab that only contains global symbols. The3043  // information found in the dynsym is therefore also found in the symtab,3044  // while the reverse is not necessarily true.3045  Section *symtab =3046      section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get();3047  if (symtab) {3048    auto [num_symbols, address_class_map] =3049        ParseSymbolTable(&lldb_symtab, symbol_id, symtab);3050    m_address_class_map.merge(address_class_map);3051    symbol_id += num_symbols;3052  }3053 3054  // The symtab section is non-allocable and can be stripped, while the3055  // .dynsym section which should always be always be there. To support the3056  // minidebuginfo case we parse .dynsym when there's a .gnu_debuginfo3057  // section, nomatter if .symtab was already parsed or not. This is because3058  // minidebuginfo normally removes the .symtab symbols which have their3059  // matching .dynsym counterparts.3060  if (!symtab ||3061      GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata"))) {3062    Section *dynsym =3063        section_list->FindSectionByType(eSectionTypeELFDynamicSymbols, true)3064            .get();3065    if (dynsym) {3066      auto [num_symbols, address_class_map] =3067          ParseSymbolTable(&lldb_symtab, symbol_id, dynsym);3068      symbol_id += num_symbols;3069      m_address_class_map.merge(address_class_map);3070    } else {3071      // Try and read the dynamic symbol table from the .dynamic section.3072      uint32_t dynamic_num_symbols = 0;3073      std::optional<DataExtractor> symtab_data =3074          GetDynsymDataFromDynamic(dynamic_num_symbols);3075      std::optional<DataExtractor> strtab_data = GetDynstrData();3076      if (symtab_data && strtab_data) {3077        auto [num_symbols_parsed, address_class_map] = ParseSymbols(3078            &lldb_symtab, symbol_id, section_list, dynamic_num_symbols,3079            symtab_data.value(), strtab_data.value());3080        symbol_id += num_symbols_parsed;3081        m_address_class_map.merge(address_class_map);3082      }3083    }3084  }3085 3086  // DT_JMPREL3087  //      If present, this entry's d_ptr member holds the address of3088  //      relocation3089  //      entries associated solely with the procedure linkage table.3090  //      Separating3091  //      these relocation entries lets the dynamic linker ignore them during3092  //      process initialization, if lazy binding is enabled. If this entry is3093  //      present, the related entries of types DT_PLTRELSZ and DT_PLTREL must3094  //      also be present.3095  const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);3096  if (symbol) {3097    // Synthesize trampoline symbols to help navigate the PLT.3098    addr_t addr = symbol->d_ptr;3099    Section *reloc_section =3100        section_list->FindSectionContainingFileAddress(addr).get();3101    if (reloc_section) {3102      user_id_t reloc_id = reloc_section->GetID();3103      const ELFSectionHeaderInfo *reloc_header =3104          GetSectionHeaderByIndex(reloc_id);3105      if (reloc_header)3106        ParseTrampolineSymbols(&lldb_symtab, symbol_id, reloc_header, reloc_id);3107    }3108  }3109 3110  if (DWARFCallFrameInfo *eh_frame =3111          GetModule()->GetUnwindTable().GetEHFrameInfo()) {3112    ParseUnwindSymbols(&lldb_symtab, eh_frame);3113  }3114 3115  // In the event that there's no symbol entry for the entry point we'll3116  // artificially create one. We delegate to the symtab object the figuring3117  // out of the proper size, this will usually make it span til the next3118  // symbol it finds in the section. This means that if there are missing3119  // symbols the entry point might span beyond its function definition.3120  // We're fine with this as it doesn't make it worse than not having a3121  // symbol entry at all.3122  if (CalculateType() == eTypeExecutable) {3123    ArchSpec arch = GetArchitecture();3124    auto entry_point_addr = GetEntryPointAddress();3125    bool is_valid_entry_point =3126        entry_point_addr.IsValid() && entry_point_addr.IsSectionOffset();3127    addr_t entry_point_file_addr = entry_point_addr.GetFileAddress();3128    if (is_valid_entry_point && !lldb_symtab.FindSymbolContainingFileAddress(3129                                    entry_point_file_addr)) {3130      uint64_t symbol_id = lldb_symtab.GetNumSymbols();3131      // Don't set the name for any synthetic symbols, the Symbol3132      // object will generate one if needed when the name is accessed3133      // via accessors.3134      SectionSP section_sp = entry_point_addr.GetSection();3135      Symbol symbol(3136          /*symID=*/symbol_id,3137          /*name=*/llvm::StringRef(), // Name will be auto generated.3138          /*type=*/eSymbolTypeCode,3139          /*external=*/true,3140          /*is_debug=*/false,3141          /*is_trampoline=*/false,3142          /*is_artificial=*/true,3143          /*section_sp=*/section_sp,3144          /*offset=*/0,3145          /*size=*/0, // FDE can span multiple symbols so don't use its size.3146          /*size_is_valid=*/false,3147          /*contains_linker_annotations=*/false,3148          /*flags=*/0);3149      // When the entry point is arm thumb we need to explicitly set its3150      // class address to reflect that. This is important because expression3151      // evaluation relies on correctly setting a breakpoint at this3152      // address.3153      if (arch.GetMachine() == llvm::Triple::arm &&3154          (entry_point_file_addr & 1)) {3155        symbol.GetAddressRef().SetOffset(entry_point_addr.GetOffset() ^ 1);3156        m_address_class_map[entry_point_file_addr ^ 1] =3157            AddressClass::eCodeAlternateISA;3158      } else {3159        m_address_class_map[entry_point_file_addr] = AddressClass::eCode;3160      }3161      lldb_symtab.AddSymbol(symbol);3162    }3163  }3164}3165 3166void ObjectFileELF::RelocateSection(lldb_private::Section *section)3167{3168  static const char *debug_prefix = ".debug";3169 3170  // Set relocated bit so we stop getting called, regardless of whether we3171  // actually relocate.3172  section->SetIsRelocated(true);3173 3174  // We only relocate in ELF relocatable files3175  if (CalculateType() != eTypeObjectFile)3176    return;3177 3178  const char *section_name = section->GetName().GetCString();3179  // Can't relocate that which can't be named3180  if (section_name == nullptr)3181    return;3182 3183  // We don't relocate non-debug sections at the moment3184  if (strncmp(section_name, debug_prefix, strlen(debug_prefix)))3185    return;3186 3187  // Relocation section names to look for3188  std::string needle = std::string(".rel") + section_name;3189  std::string needlea = std::string(".rela") + section_name;3190 3191  for (SectionHeaderCollIter I = m_section_headers.begin();3192       I != m_section_headers.end(); ++I) {3193    if (I->sh_type == SHT_RELA || I->sh_type == SHT_REL) {3194      const char *hay_name = I->section_name.GetCString();3195      if (hay_name == nullptr)3196        continue;3197      if (needle == hay_name || needlea == hay_name) {3198        const ELFSectionHeader &reloc_header = *I;3199        user_id_t reloc_id = SectionIndex(I);3200        RelocateDebugSections(&reloc_header, reloc_id, GetSymtab());3201        break;3202      }3203    }3204  }3205}3206 3207void ObjectFileELF::ParseUnwindSymbols(Symtab *symbol_table,3208                                       DWARFCallFrameInfo *eh_frame) {3209  SectionList *section_list = GetSectionList();3210  if (!section_list)3211    return;3212 3213  // First we save the new symbols into a separate list and add them to the3214  // symbol table after we collected all symbols we want to add. This is3215  // neccessary because adding a new symbol invalidates the internal index of3216  // the symtab what causing the next lookup to be slow because it have to3217  // recalculate the index first.3218  std::vector<Symbol> new_symbols;3219 3220  size_t num_symbols = symbol_table->GetNumSymbols();3221  uint64_t last_symbol_id =3222      num_symbols ? symbol_table->SymbolAtIndex(num_symbols - 1)->GetID() : 0;3223  eh_frame->ForEachFDEEntries([&](lldb::addr_t file_addr, uint32_t size,3224                                  dw_offset_t) {3225    Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr);3226    if (symbol) {3227      if (!symbol->GetByteSizeIsValid()) {3228        symbol->SetByteSize(size);3229        symbol->SetSizeIsSynthesized(true);3230      }3231    } else {3232      SectionSP section_sp =3233          section_list->FindSectionContainingFileAddress(file_addr);3234      if (section_sp) {3235        addr_t offset = file_addr - section_sp->GetFileAddress();3236        uint64_t symbol_id = ++last_symbol_id;3237        // Don't set the name for any synthetic symbols, the Symbol3238        // object will generate one if needed when the name is accessed3239        // via accessors.3240        Symbol eh_symbol(3241            /*symID=*/symbol_id,3242            /*name=*/llvm::StringRef(), // Name will be auto generated.3243            /*type=*/eSymbolTypeCode,3244            /*external=*/true,3245            /*is_debug=*/false,3246            /*is_trampoline=*/false,3247            /*is_artificial=*/true,3248            /*section_sp=*/section_sp,3249            /*offset=*/offset,3250            /*size=*/0, // FDE can span multiple symbols so don't use its size.3251            /*size_is_valid=*/false,3252            /*contains_linker_annotations=*/false,3253            /*flags=*/0);3254        new_symbols.push_back(eh_symbol);3255      }3256    }3257    return true;3258  });3259 3260  for (const Symbol &s : new_symbols)3261    symbol_table->AddSymbol(s);3262}3263 3264bool ObjectFileELF::IsStripped() {3265  // TODO: determine this for ELF3266  return false;3267}3268 3269//===----------------------------------------------------------------------===//3270// Dump3271//3272// Dump the specifics of the runtime file container (such as any headers3273// segments, sections, etc).3274void ObjectFileELF::Dump(Stream *s) {3275  ModuleSP module_sp(GetModule());3276  if (!module_sp) {3277    return;3278  }3279 3280  std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());3281  s->Printf("%p: ", static_cast<void *>(this));3282  s->Indent();3283  s->PutCString("ObjectFileELF");3284 3285  ArchSpec header_arch = GetArchitecture();3286 3287  *s << ", file = '" << m_file3288     << "', arch = " << header_arch.GetArchitectureName();3289  if (m_memory_addr != LLDB_INVALID_ADDRESS)3290    s->Printf(", addr = %#16.16" PRIx64, m_memory_addr);3291  s->EOL();3292 3293  DumpELFHeader(s, m_header);3294  s->EOL();3295  DumpELFProgramHeaders(s);3296  s->EOL();3297  DumpELFSectionHeaders(s);3298  s->EOL();3299  SectionList *section_list = GetSectionList();3300  if (section_list)3301    section_list->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,3302                       UINT32_MAX);3303  Symtab *symtab = GetSymtab();3304  if (symtab)3305    symtab->Dump(s, nullptr, eSortOrderNone);3306  s->EOL();3307  DumpDependentModules(s);3308  s->EOL();3309  DumpELFDynamic(s);3310  s->EOL();3311  Address image_info_addr = GetImageInfoAddress(nullptr);3312  if (image_info_addr.IsValid())3313    s->Printf("image_info_address = %#16.16" PRIx64 "\n",3314              image_info_addr.GetFileAddress());3315}3316 3317// DumpELFHeader3318//3319// Dump the ELF header to the specified output stream3320void ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header) {3321  s->PutCString("ELF Header\n");3322  s->Printf("e_ident[EI_MAG0   ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);3323  s->Printf("e_ident[EI_MAG1   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG1],3324            header.e_ident[EI_MAG1]);3325  s->Printf("e_ident[EI_MAG2   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG2],3326            header.e_ident[EI_MAG2]);3327  s->Printf("e_ident[EI_MAG3   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG3],3328            header.e_ident[EI_MAG3]);3329 3330  s->Printf("e_ident[EI_CLASS  ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);3331  s->Printf("e_ident[EI_DATA   ] = 0x%2.2x ", header.e_ident[EI_DATA]);3332  DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);3333  s->Printf("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);3334  s->Printf("e_ident[EI_PAD    ] = 0x%2.2x\n", header.e_ident[EI_PAD]);3335 3336  s->Printf("e_type      = 0x%4.4x ", header.e_type);3337  DumpELFHeader_e_type(s, header.e_type);3338  s->Printf("\ne_machine   = 0x%4.4x\n", header.e_machine);3339  s->Printf("e_version   = 0x%8.8x\n", header.e_version);3340  s->Printf("e_entry     = 0x%8.8" PRIx64 "\n", header.e_entry);3341  s->Printf("e_phoff     = 0x%8.8" PRIx64 "\n", header.e_phoff);3342  s->Printf("e_shoff     = 0x%8.8" PRIx64 "\n", header.e_shoff);3343  s->Printf("e_flags     = 0x%8.8x\n", header.e_flags);3344  s->Printf("e_ehsize    = 0x%4.4x\n", header.e_ehsize);3345  s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);3346  s->Printf("e_phnum     = 0x%8.8x\n", header.e_phnum);3347  s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);3348  s->Printf("e_shnum     = 0x%8.8x\n", header.e_shnum);3349  s->Printf("e_shstrndx  = 0x%8.8x\n", header.e_shstrndx);3350}3351 3352// DumpELFHeader_e_type3353//3354// Dump an token value for the ELF header member e_type3355void ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type) {3356  switch (e_type) {3357  case ET_NONE:3358    *s << "ET_NONE";3359    break;3360  case ET_REL:3361    *s << "ET_REL";3362    break;3363  case ET_EXEC:3364    *s << "ET_EXEC";3365    break;3366  case ET_DYN:3367    *s << "ET_DYN";3368    break;3369  case ET_CORE:3370    *s << "ET_CORE";3371    break;3372  default:3373    break;3374  }3375}3376 3377// DumpELFHeader_e_ident_EI_DATA3378//3379// Dump an token value for the ELF header member e_ident[EI_DATA]3380void ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s,3381                                                  unsigned char ei_data) {3382  switch (ei_data) {3383  case ELFDATANONE:3384    *s << "ELFDATANONE";3385    break;3386  case ELFDATA2LSB:3387    *s << "ELFDATA2LSB - Little Endian";3388    break;3389  case ELFDATA2MSB:3390    *s << "ELFDATA2MSB - Big Endian";3391    break;3392  default:3393    break;3394  }3395}3396 3397// DumpELFProgramHeader3398//3399// Dump a single ELF program header to the specified output stream3400void ObjectFileELF::DumpELFProgramHeader(Stream *s,3401                                         const ELFProgramHeader &ph) {3402  DumpELFProgramHeader_p_type(s, ph.p_type);3403  s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset,3404            ph.p_vaddr, ph.p_paddr);3405  s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz,3406            ph.p_flags);3407 3408  DumpELFProgramHeader_p_flags(s, ph.p_flags);3409  s->Printf(") %8.8" PRIx64, ph.p_align);3410}3411 3412// DumpELFProgramHeader_p_type3413//3414// Dump an token value for the ELF program header member p_type which describes3415// the type of the program header3416void ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type) {3417  const int kStrWidth = 15;3418  switch (p_type) {3419    CASE_AND_STREAM(s, PT_NULL, kStrWidth);3420    CASE_AND_STREAM(s, PT_LOAD, kStrWidth);3421    CASE_AND_STREAM(s, PT_DYNAMIC, kStrWidth);3422    CASE_AND_STREAM(s, PT_INTERP, kStrWidth);3423    CASE_AND_STREAM(s, PT_NOTE, kStrWidth);3424    CASE_AND_STREAM(s, PT_SHLIB, kStrWidth);3425    CASE_AND_STREAM(s, PT_PHDR, kStrWidth);3426    CASE_AND_STREAM(s, PT_TLS, kStrWidth);3427    CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);3428  default:3429    s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");3430    break;3431  }3432}3433 3434// DumpELFProgramHeader_p_flags3435//3436// Dump an token value for the ELF program header member p_flags3437void ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags) {3438  *s << ((p_flags & PF_X) ? "PF_X" : "    ")3439     << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')3440     << ((p_flags & PF_W) ? "PF_W" : "    ")3441     << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')3442     << ((p_flags & PF_R) ? "PF_R" : "    ");3443}3444 3445// DumpELFProgramHeaders3446//3447// Dump all of the ELF program header to the specified output stream3448void ObjectFileELF::DumpELFProgramHeaders(Stream *s) {3449  if (!ParseProgramHeaders())3450    return;3451 3452  s->PutCString("Program Headers\n");3453  s->PutCString("IDX  p_type          p_offset p_vaddr  p_paddr  "3454                "p_filesz p_memsz  p_flags                   p_align\n");3455  s->PutCString("==== --------------- -------- -------- -------- "3456                "-------- -------- ------------------------- --------\n");3457 3458  for (const auto &H : llvm::enumerate(m_program_headers)) {3459    s->Format("[{0,2}] ", H.index());3460    ObjectFileELF::DumpELFProgramHeader(s, H.value());3461    s->EOL();3462  }3463}3464 3465// DumpELFSectionHeader3466//3467// Dump a single ELF section header to the specified output stream3468void ObjectFileELF::DumpELFSectionHeader(Stream *s,3469                                         const ELFSectionHeaderInfo &sh) {3470  s->Printf("%8.8x ", sh.sh_name);3471  DumpELFSectionHeader_sh_type(s, sh.sh_type);3472  s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);3473  DumpELFSectionHeader_sh_flags(s, sh.sh_flags);3474  s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr,3475            sh.sh_offset, sh.sh_size);3476  s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);3477  s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);3478}3479 3480// DumpELFSectionHeader_sh_type3481//3482// Dump an token value for the ELF section header member sh_type which3483// describes the type of the section3484void ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type) {3485  const int kStrWidth = 12;3486  switch (sh_type) {3487    CASE_AND_STREAM(s, SHT_NULL, kStrWidth);3488    CASE_AND_STREAM(s, SHT_PROGBITS, kStrWidth);3489    CASE_AND_STREAM(s, SHT_SYMTAB, kStrWidth);3490    CASE_AND_STREAM(s, SHT_STRTAB, kStrWidth);3491    CASE_AND_STREAM(s, SHT_RELA, kStrWidth);3492    CASE_AND_STREAM(s, SHT_HASH, kStrWidth);3493    CASE_AND_STREAM(s, SHT_DYNAMIC, kStrWidth);3494    CASE_AND_STREAM(s, SHT_NOTE, kStrWidth);3495    CASE_AND_STREAM(s, SHT_NOBITS, kStrWidth);3496    CASE_AND_STREAM(s, SHT_REL, kStrWidth);3497    CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth);3498    CASE_AND_STREAM(s, SHT_DYNSYM, kStrWidth);3499    CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth);3500    CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth);3501    CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth);3502    CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth);3503  default:3504    s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");3505    break;3506  }3507}3508 3509// DumpELFSectionHeader_sh_flags3510//3511// Dump an token value for the ELF section header member sh_flags3512void ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s,3513                                                  elf_xword sh_flags) {3514  *s << ((sh_flags & SHF_WRITE) ? "WRITE" : "     ")3515     << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')3516     << ((sh_flags & SHF_ALLOC) ? "ALLOC" : "     ")3517     << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')3518     << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : "         ");3519}3520 3521// DumpELFSectionHeaders3522//3523// Dump all of the ELF section header to the specified output stream3524void ObjectFileELF::DumpELFSectionHeaders(Stream *s) {3525  if (!ParseSectionHeaders())3526    return;3527 3528  s->PutCString("Section Headers\n");3529  s->PutCString("IDX  name     type         flags                            "3530                "addr     offset   size     link     info     addralgn "3531                "entsize  Name\n");3532  s->PutCString("==== -------- ------------ -------------------------------- "3533                "-------- -------- -------- -------- -------- -------- "3534                "-------- ====================\n");3535 3536  uint32_t idx = 0;3537  for (SectionHeaderCollConstIter I = m_section_headers.begin();3538       I != m_section_headers.end(); ++I, ++idx) {3539    s->Printf("[%2u] ", idx);3540    ObjectFileELF::DumpELFSectionHeader(s, *I);3541    const char *section_name = I->section_name.AsCString("");3542    if (section_name)3543      *s << ' ' << section_name << "\n";3544  }3545}3546 3547void ObjectFileELF::DumpDependentModules(lldb_private::Stream *s) {3548  size_t num_modules = ParseDependentModules();3549 3550  if (num_modules > 0) {3551    s->PutCString("Dependent Modules:\n");3552    for (unsigned i = 0; i < num_modules; ++i) {3553      const FileSpec &spec = m_filespec_up->GetFileSpecAtIndex(i);3554      s->Printf("   %s\n", spec.GetFilename().GetCString());3555    }3556  }3557}3558 3559std::string static getDynamicTagAsString(uint16_t Arch, uint64_t Type) {3560#define DYNAMIC_STRINGIFY_ENUM(tag, value)                                     \3561  case value:                                                                  \3562    return #tag;3563 3564#define DYNAMIC_TAG(n, v)3565  switch (Arch) {3566  case llvm::ELF::EM_AARCH64:3567    switch (Type) {3568#define AARCH64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)3569#include "llvm/BinaryFormat/DynamicTags.def"3570#undef AARCH64_DYNAMIC_TAG3571    }3572    break;3573 3574  case llvm::ELF::EM_HEXAGON:3575    switch (Type) {3576#define HEXAGON_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)3577#include "llvm/BinaryFormat/DynamicTags.def"3578#undef HEXAGON_DYNAMIC_TAG3579    }3580    break;3581 3582  case llvm::ELF::EM_MIPS:3583    switch (Type) {3584#define MIPS_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)3585#include "llvm/BinaryFormat/DynamicTags.def"3586#undef MIPS_DYNAMIC_TAG3587    }3588    break;3589 3590  case llvm::ELF::EM_PPC:3591    switch (Type) {3592#define PPC_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)3593#include "llvm/BinaryFormat/DynamicTags.def"3594#undef PPC_DYNAMIC_TAG3595    }3596    break;3597 3598  case llvm::ELF::EM_PPC64:3599    switch (Type) {3600#define PPC64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)3601#include "llvm/BinaryFormat/DynamicTags.def"3602#undef PPC64_DYNAMIC_TAG3603    }3604    break;3605 3606  case llvm::ELF::EM_RISCV:3607    switch (Type) {3608#define RISCV_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)3609#include "llvm/BinaryFormat/DynamicTags.def"3610#undef RISCV_DYNAMIC_TAG3611    }3612    break;3613  }3614#undef DYNAMIC_TAG3615  switch (Type) {3616// Now handle all dynamic tags except the architecture specific ones3617#define AARCH64_DYNAMIC_TAG(name, value)3618#define MIPS_DYNAMIC_TAG(name, value)3619#define HEXAGON_DYNAMIC_TAG(name, value)3620#define PPC_DYNAMIC_TAG(name, value)3621#define PPC64_DYNAMIC_TAG(name, value)3622#define RISCV_DYNAMIC_TAG(name, value)3623// Also ignore marker tags such as DT_HIOS (maps to DT_VERNEEDNUM), etc.3624#define DYNAMIC_TAG_MARKER(name, value)3625#define DYNAMIC_TAG(name, value)                                               \3626  case value:                                                                  \3627    return #name;3628#include "llvm/BinaryFormat/DynamicTags.def"3629#undef DYNAMIC_TAG3630#undef AARCH64_DYNAMIC_TAG3631#undef MIPS_DYNAMIC_TAG3632#undef HEXAGON_DYNAMIC_TAG3633#undef PPC_DYNAMIC_TAG3634#undef PPC64_DYNAMIC_TAG3635#undef RISCV_DYNAMIC_TAG3636#undef DYNAMIC_TAG_MARKER3637#undef DYNAMIC_STRINGIFY_ENUM3638  default:3639    return "<unknown:>0x" + llvm::utohexstr(Type, true);3640  }3641}3642 3643void ObjectFileELF::DumpELFDynamic(lldb_private::Stream *s) {3644  ParseDynamicSymbols();3645  if (m_dynamic_symbols.empty())3646    return;3647 3648  s->PutCString(".dynamic:\n");3649  s->PutCString("IDX  d_tag            d_val/d_ptr\n");3650  s->PutCString("==== ---------------- ------------------\n");3651  uint32_t idx = 0;3652  for (const auto &entry : m_dynamic_symbols) {3653    s->Printf("[%2u] ", idx++);3654    s->Printf(3655        "%-16s 0x%16.16" PRIx64,3656        getDynamicTagAsString(m_header.e_machine, entry.symbol.d_tag).c_str(),3657        entry.symbol.d_ptr);3658    if (!entry.name.empty())3659      s->Printf(" \"%s\"", entry.name.c_str());3660    s->EOL();3661  }3662}3663 3664ArchSpec ObjectFileELF::GetArchitecture() {3665  if (!ParseHeader())3666    return ArchSpec();3667 3668  if (m_section_headers.empty()) {3669    // Allow elf notes to be parsed which may affect the detected architecture.3670    ParseSectionHeaders();3671  }3672 3673  if (CalculateType() == eTypeCoreFile &&3674      !m_arch_spec.TripleOSWasSpecified()) {3675    // Core files don't have section headers yet they have PT_NOTE program3676    // headers that might shed more light on the architecture3677    for (const elf::ELFProgramHeader &H : ProgramHeaders()) {3678      if (H.p_type != PT_NOTE || H.p_offset == 0 || H.p_filesz == 0)3679        continue;3680      DataExtractor data;3681      if (data.SetData(m_data, H.p_offset, H.p_filesz) == H.p_filesz) {3682        UUID uuid;3683        RefineModuleDetailsFromNote(data, m_arch_spec, uuid);3684      }3685    }3686  }3687  return m_arch_spec;3688}3689 3690ObjectFile::Type ObjectFileELF::CalculateType() {3691  switch (m_header.e_type) {3692  case llvm::ELF::ET_NONE:3693    // 0 - No file type3694    return eTypeUnknown;3695 3696  case llvm::ELF::ET_REL:3697    // 1 - Relocatable file3698    return eTypeObjectFile;3699 3700  case llvm::ELF::ET_EXEC:3701    // 2 - Executable file3702    return eTypeExecutable;3703 3704  case llvm::ELF::ET_DYN:3705    // 3 - Shared object file3706    return eTypeSharedLibrary;3707 3708  case ET_CORE:3709    // 4 - Core file3710    return eTypeCoreFile;3711 3712  default:3713    break;3714  }3715  return eTypeUnknown;3716}3717 3718ObjectFile::Strata ObjectFileELF::CalculateStrata() {3719  switch (m_header.e_type) {3720  case llvm::ELF::ET_NONE:3721    // 0 - No file type3722    return eStrataUnknown;3723 3724  case llvm::ELF::ET_REL:3725    // 1 - Relocatable file3726    return eStrataUnknown;3727 3728  case llvm::ELF::ET_EXEC:3729    // 2 - Executable file3730    {3731      SectionList *section_list = GetSectionList();3732      if (section_list) {3733        static ConstString loader_section_name(".interp");3734        SectionSP loader_section =3735            section_list->FindSectionByName(loader_section_name);3736        if (loader_section) {3737          char buffer[256];3738          size_t read_size =3739              ReadSectionData(loader_section.get(), 0, buffer, sizeof(buffer));3740 3741          // We compare the content of .interp section3742          // It will contains \0 when counting read_size, so the size needs to3743          // decrease by one3744          llvm::StringRef loader_name(buffer, read_size - 1);3745          llvm::StringRef freebsd_kernel_loader_name("/red/herring");3746          if (loader_name == freebsd_kernel_loader_name)3747            return eStrataKernel;3748        }3749      }3750      return eStrataUser;3751    }3752 3753  case llvm::ELF::ET_DYN:3754    // 3 - Shared object file3755    // TODO: is there any way to detect that an shared library is a kernel3756    // related executable by inspecting the program headers, section headers,3757    // symbols, or any other flag bits???3758    return eStrataUnknown;3759 3760  case ET_CORE:3761    // 4 - Core file3762    // TODO: is there any way to detect that an core file is a kernel3763    // related executable by inspecting the program headers, section headers,3764    // symbols, or any other flag bits???3765    return eStrataUnknown;3766 3767  default:3768    break;3769  }3770  return eStrataUnknown;3771}3772 3773size_t ObjectFileELF::ReadSectionData(Section *section,3774                       lldb::offset_t section_offset, void *dst,3775                       size_t dst_len) {3776  // If some other objectfile owns this data, pass this to them.3777  if (section->GetObjectFile() != this)3778    return section->GetObjectFile()->ReadSectionData(section, section_offset,3779                                                     dst, dst_len);3780 3781  if (!section->Test(SHF_COMPRESSED))3782    return ObjectFile::ReadSectionData(section, section_offset, dst, dst_len);3783 3784  // For compressed sections we need to read to full data to be able to3785  // decompress.3786  DataExtractor data;3787  ReadSectionData(section, data);3788  return data.CopyData(section_offset, dst_len, dst);3789}3790 3791size_t ObjectFileELF::ReadSectionData(Section *section,3792                                      DataExtractor &section_data) {3793  // If some other objectfile owns this data, pass this to them.3794  if (section->GetObjectFile() != this)3795    return section->GetObjectFile()->ReadSectionData(section, section_data);3796 3797  size_t result = ObjectFile::ReadSectionData(section, section_data);3798  if (result == 0 || !(section->Get() & llvm::ELF::SHF_COMPRESSED))3799    return result;3800 3801  auto Decompressor = llvm::object::Decompressor::create(3802      section->GetName().GetStringRef(),3803      {reinterpret_cast<const char *>(section_data.GetDataStart()),3804       size_t(section_data.GetByteSize())},3805      GetByteOrder() == eByteOrderLittle, GetAddressByteSize() == 8);3806  if (!Decompressor) {3807    GetModule()->ReportWarning(3808        "Unable to initialize decompressor for section '{0}': {1}",3809        section->GetName().GetCString(),3810        llvm::toString(Decompressor.takeError()).c_str());3811    section_data.Clear();3812    return 0;3813  }3814 3815  auto buffer_sp =3816      std::make_shared<DataBufferHeap>(Decompressor->getDecompressedSize(), 0);3817  if (auto error = Decompressor->decompress(3818          {buffer_sp->GetBytes(), size_t(buffer_sp->GetByteSize())})) {3819    GetModule()->ReportWarning("Decompression of section '{0}' failed: {1}",3820                               section->GetName().GetCString(),3821                               llvm::toString(std::move(error)).c_str());3822    section_data.Clear();3823    return 0;3824  }3825 3826  section_data.SetData(buffer_sp);3827  return buffer_sp->GetByteSize();3828}3829 3830llvm::ArrayRef<ELFProgramHeader> ObjectFileELF::ProgramHeaders() {3831  ParseProgramHeaders();3832  return m_program_headers;3833}3834 3835DataExtractor ObjectFileELF::GetSegmentData(const ELFProgramHeader &H) {3836  // Try and read the program header from our cached m_data which can come from3837  // the file on disk being mmap'ed or from the initial part of the ELF file we3838  // read from memory and cached.3839  DataExtractor data = DataExtractor(m_data, H.p_offset, H.p_filesz);3840  if (data.GetByteSize() == H.p_filesz)3841    return data;3842  if (IsInMemory()) {3843    // We have a ELF file in process memory, read the program header data from3844    // the process.3845    if (ProcessSP process_sp = m_process_wp.lock()) {3846      const lldb::offset_t base_file_addr = GetBaseAddress().GetFileAddress();3847      const addr_t load_bias = m_memory_addr - base_file_addr;3848      const addr_t data_addr = H.p_vaddr + load_bias;3849      if (DataBufferSP data_sp = ReadMemory(process_sp, data_addr, H.p_memsz))3850        return DataExtractor(data_sp, GetByteOrder(), GetAddressByteSize());3851    }3852  }3853  return DataExtractor();3854}3855 3856bool ObjectFileELF::AnySegmentHasPhysicalAddress() {3857  for (const ELFProgramHeader &H : ProgramHeaders()) {3858    if (H.p_paddr != 0)3859      return true;3860  }3861  return false;3862}3863 3864std::vector<ObjectFile::LoadableData>3865ObjectFileELF::GetLoadableData(Target &target) {3866  // Create a list of loadable data from loadable segments, using physical3867  // addresses if they aren't all null3868  std::vector<LoadableData> loadables;3869  bool should_use_paddr = AnySegmentHasPhysicalAddress();3870  for (const ELFProgramHeader &H : ProgramHeaders()) {3871    LoadableData loadable;3872    if (H.p_type != llvm::ELF::PT_LOAD)3873      continue;3874    loadable.Dest = should_use_paddr ? H.p_paddr : H.p_vaddr;3875    if (loadable.Dest == LLDB_INVALID_ADDRESS)3876      continue;3877    if (H.p_filesz == 0)3878      continue;3879    auto segment_data = GetSegmentData(H);3880    loadable.Contents = llvm::ArrayRef<uint8_t>(segment_data.GetDataStart(),3881                                                segment_data.GetByteSize());3882    loadables.push_back(loadable);3883  }3884  return loadables;3885}3886 3887lldb::WritableDataBufferSP3888ObjectFileELF::MapFileDataWritable(const FileSpec &file, uint64_t Size,3889                                   uint64_t Offset) {3890  return FileSystem::Instance().CreateWritableDataBuffer(file.GetPath(), Size,3891                                                         Offset);3892}3893 3894std::optional<DataExtractor>3895ObjectFileELF::ReadDataFromDynamic(const ELFDynamic *dyn, uint64_t length,3896                                   uint64_t offset) {3897  // ELFDynamic values contain a "d_ptr" member that will be a load address if3898  // we have an ELF file read from memory, or it will be a file address if it3899  // was read from a ELF file. This function will correctly fetch data pointed3900  // to by the ELFDynamic::d_ptr, or return std::nullopt if the data isn't3901  // available.3902  const lldb::addr_t d_ptr_addr = dyn->d_ptr + offset;3903  if (ProcessSP process_sp = m_process_wp.lock()) {3904    if (DataBufferSP data_sp = ReadMemory(process_sp, d_ptr_addr, length))3905      return DataExtractor(data_sp, GetByteOrder(), GetAddressByteSize());3906  } else {3907    // We have an ELF file with no section headers or we didn't find the3908    // .dynamic section. Try and find the .dynstr section.3909    Address addr;3910    if (!addr.ResolveAddressUsingFileSections(d_ptr_addr, GetSectionList()))3911      return std::nullopt;3912    DataExtractor data;3913    addr.GetSection()->GetSectionData(data);3914    return DataExtractor(data, d_ptr_addr - addr.GetSection()->GetFileAddress(),3915                         length);3916  }3917  return std::nullopt;3918}3919 3920std::optional<DataExtractor> ObjectFileELF::GetDynstrData() {3921  if (SectionList *section_list = GetSectionList()) {3922    // Find the SHT_DYNAMIC section.3923    if (Section *dynamic =3924            section_list3925                ->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)3926                .get()) {3927      assert(dynamic->GetObjectFile() == this);3928      if (const ELFSectionHeaderInfo *header =3929              GetSectionHeaderByIndex(dynamic->GetID())) {3930        // sh_link: section header index of string table used by entries in3931        // the section.3932        if (Section *dynstr =3933                section_list->FindSectionByID(header->sh_link).get()) {3934          DataExtractor data;3935          if (ReadSectionData(dynstr, data))3936            return data;3937        }3938      }3939    }3940  }3941 3942  // Every ELF file which represents an executable or shared library has3943  // mandatory .dynamic entries. Two of these values are DT_STRTAB and DT_STRSZ3944  // and represent the dynamic symbol tables's string table. These are needed3945  // by the dynamic loader and we can read them from a process' address space.3946  //3947  // When loading and ELF file from memory, only the program headers are3948  // guaranteed end up being mapped into memory, and we can find these values in3949  // the PT_DYNAMIC segment.3950  const ELFDynamic *strtab = FindDynamicSymbol(DT_STRTAB);3951  const ELFDynamic *strsz = FindDynamicSymbol(DT_STRSZ);3952  if (strtab == nullptr || strsz == nullptr)3953    return std::nullopt;3954 3955  return ReadDataFromDynamic(strtab, strsz->d_val, /*offset=*/0);3956}3957 3958std::optional<lldb_private::DataExtractor> ObjectFileELF::GetDynamicData() {3959  DataExtractor data;3960  // The PT_DYNAMIC program header describes where the .dynamic section is and3961  // doesn't require parsing section headers. The PT_DYNAMIC is required by3962  // executables and shared libraries so it will always be available.3963  for (const ELFProgramHeader &H : ProgramHeaders()) {3964    if (H.p_type == llvm::ELF::PT_DYNAMIC) {3965      data = GetSegmentData(H);3966      if (data.GetByteSize() > 0) {3967        m_dynamic_base_addr = H.p_vaddr;3968        return data;3969      }3970    }3971  }3972  // Fall back to using section headers.3973  if (SectionList *section_list = GetSectionList()) {3974    // Find the SHT_DYNAMIC section.3975    if (Section *dynamic =3976            section_list3977                ->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)3978                .get()) {3979      assert(dynamic->GetObjectFile() == this);3980      if (ReadSectionData(dynamic, data)) {3981        m_dynamic_base_addr = dynamic->GetFileAddress();3982        return data;3983      }3984    }3985  }3986  return std::nullopt;3987}3988 3989std::optional<uint32_t> ObjectFileELF::GetNumSymbolsFromDynamicHash() {3990  const ELFDynamic *hash = FindDynamicSymbol(DT_HASH);3991  if (hash == nullptr)3992    return std::nullopt;3993 3994  // The DT_HASH header looks like this:3995  struct DtHashHeader {3996    uint32_t nbucket;3997    uint32_t nchain;3998  };3999  if (auto data = ReadDataFromDynamic(hash, 8)) {4000    // We don't need the number of buckets value "nbucket", we just need the4001    // "nchain" value which contains the number of symbols.4002    offset_t offset = offsetof(DtHashHeader, nchain);4003    return data->GetU32(&offset);4004  }4005 4006  return std::nullopt;4007}4008 4009std::optional<uint32_t> ObjectFileELF::GetNumSymbolsFromDynamicGnuHash() {4010  const ELFDynamic *gnu_hash = FindDynamicSymbol(DT_GNU_HASH);4011  if (gnu_hash == nullptr)4012    return std::nullopt;4013 4014  // Create a DT_GNU_HASH header4015  // https://flapenguin.me/elf-dt-gnu-hash4016  struct DtGnuHashHeader {4017    uint32_t nbuckets = 0;4018    uint32_t symoffset = 0;4019    uint32_t bloom_size = 0;4020    uint32_t bloom_shift = 0;4021  };4022  uint32_t num_symbols = 0;4023  // Read enogh data for the DT_GNU_HASH header so we can extract the values.4024  if (auto data = ReadDataFromDynamic(gnu_hash, sizeof(DtGnuHashHeader))) {4025    offset_t offset = 0;4026    DtGnuHashHeader header;4027    header.nbuckets = data->GetU32(&offset);4028    header.symoffset = data->GetU32(&offset);4029    header.bloom_size = data->GetU32(&offset);4030    header.bloom_shift = data->GetU32(&offset);4031    const size_t addr_size = GetAddressByteSize();4032    const addr_t buckets_offset =4033        sizeof(DtGnuHashHeader) + addr_size * header.bloom_size;4034    std::vector<uint32_t> buckets;4035    if (auto bucket_data = ReadDataFromDynamic(gnu_hash, header.nbuckets * 4,4036                                               buckets_offset)) {4037      offset = 0;4038      for (uint32_t i = 0; i < header.nbuckets; ++i)4039        buckets.push_back(bucket_data->GetU32(&offset));4040      // Locate the chain that handles the largest index bucket.4041      uint32_t last_symbol = 0;4042      for (uint32_t bucket_value : buckets)4043        last_symbol = std::max(bucket_value, last_symbol);4044      if (last_symbol < header.symoffset) {4045        num_symbols = header.symoffset;4046      } else {4047        // Walk the bucket's chain to add the chain length to the total.4048        const addr_t chains_base_offset = buckets_offset + header.nbuckets * 4;4049        for (;;) {4050          if (auto chain_entry_data = ReadDataFromDynamic(4051                  gnu_hash, 4,4052                  chains_base_offset + (last_symbol - header.symoffset) * 4)) {4053            offset = 0;4054            uint32_t chain_entry = chain_entry_data->GetU32(&offset);4055            ++last_symbol;4056            // If the low bit is set, this entry is the end of the chain.4057            if (chain_entry & 1)4058              break;4059          } else {4060            break;4061          }4062        }4063        num_symbols = last_symbol;4064      }4065    }4066  }4067  if (num_symbols > 0)4068    return num_symbols;4069 4070  return std::nullopt;4071}4072 4073std::optional<DataExtractor>4074ObjectFileELF::GetDynsymDataFromDynamic(uint32_t &num_symbols) {4075  // Every ELF file which represents an executable or shared library has4076  // mandatory .dynamic entries. The DT_SYMTAB value contains a pointer to the4077  // symbol table, and DT_SYMENT contains the size of a symbol table entry.4078  // We then can use either the DT_HASH or DT_GNU_HASH to find the number of4079  // symbols in the symbol table as the symbol count is not stored in the4080  // .dynamic section as a key/value pair.4081  //4082  // When loading and ELF file from memory, only the program headers end up4083  // being mapped into memory, and we can find these values in the PT_DYNAMIC4084  // segment.4085  num_symbols = 0;4086  // Get the process in case this is an in memory ELF file.4087  ProcessSP process_sp(m_process_wp.lock());4088  const ELFDynamic *symtab = FindDynamicSymbol(DT_SYMTAB);4089  const ELFDynamic *syment = FindDynamicSymbol(DT_SYMENT);4090  // DT_SYMTAB and DT_SYMENT are mandatory.4091  if (symtab == nullptr || syment == nullptr)4092    return std::nullopt;4093 4094  if (std::optional<uint32_t> syms = GetNumSymbolsFromDynamicHash())4095    num_symbols = *syms;4096  else if (std::optional<uint32_t> syms = GetNumSymbolsFromDynamicGnuHash())4097    num_symbols = *syms;4098  else4099    return std::nullopt;4100  if (num_symbols == 0)4101    return std::nullopt;4102  return ReadDataFromDynamic(symtab, syment->d_val * num_symbols);4103}4104