15ffd83dbSDimitry Andric //===-- ObjectFileELF.cpp -------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "ObjectFileELF.h"
100b57cec5SDimitry Andric 
110b57cec5SDimitry Andric #include <algorithm>
120b57cec5SDimitry Andric #include <cassert>
13bdd1243dSDimitry Andric #include <optional>
140b57cec5SDimitry Andric #include <unordered_map>
150b57cec5SDimitry Andric 
160b57cec5SDimitry Andric #include "lldb/Core/Module.h"
170b57cec5SDimitry Andric #include "lldb/Core/ModuleSpec.h"
180b57cec5SDimitry Andric #include "lldb/Core/PluginManager.h"
19fe6060f1SDimitry Andric #include "lldb/Core/Progress.h"
200b57cec5SDimitry Andric #include "lldb/Core/Section.h"
210b57cec5SDimitry Andric #include "lldb/Host/FileSystem.h"
229dba64beSDimitry Andric #include "lldb/Host/LZMA.h"
230b57cec5SDimitry Andric #include "lldb/Symbol/DWARFCallFrameInfo.h"
240b57cec5SDimitry Andric #include "lldb/Symbol/SymbolContext.h"
250b57cec5SDimitry Andric #include "lldb/Target/SectionLoadList.h"
260b57cec5SDimitry Andric #include "lldb/Target/Target.h"
270b57cec5SDimitry Andric #include "lldb/Utility/ArchSpec.h"
280b57cec5SDimitry Andric #include "lldb/Utility/DataBufferHeap.h"
29*fe013be4SDimitry Andric #include "lldb/Utility/FileSpecList.h"
3081ad6265SDimitry Andric #include "lldb/Utility/LLDBLog.h"
310b57cec5SDimitry Andric #include "lldb/Utility/Log.h"
320b57cec5SDimitry Andric #include "lldb/Utility/RangeMap.h"
330b57cec5SDimitry Andric #include "lldb/Utility/Status.h"
340b57cec5SDimitry Andric #include "lldb/Utility/Stream.h"
350b57cec5SDimitry Andric #include "lldb/Utility/Timer.h"
360b57cec5SDimitry Andric #include "llvm/ADT/IntervalMap.h"
370b57cec5SDimitry Andric #include "llvm/ADT/PointerUnion.h"
380b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
399dba64beSDimitry Andric #include "llvm/BinaryFormat/ELF.h"
400b57cec5SDimitry Andric #include "llvm/Object/Decompressor.h"
410b57cec5SDimitry Andric #include "llvm/Support/ARMBuildAttributes.h"
429dba64beSDimitry Andric #include "llvm/Support/CRC.h"
43fe6060f1SDimitry Andric #include "llvm/Support/FormatVariadic.h"
440b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
450b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
460b57cec5SDimitry Andric #include "llvm/Support/MipsABIFlags.h"
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric #define CASE_AND_STREAM(s, def, width)                                         \
490b57cec5SDimitry Andric   case def:                                                                    \
500b57cec5SDimitry Andric     s->Printf("%-*s", width, #def);                                            \
510b57cec5SDimitry Andric     break;
520b57cec5SDimitry Andric 
530b57cec5SDimitry Andric using namespace lldb;
540b57cec5SDimitry Andric using namespace lldb_private;
550b57cec5SDimitry Andric using namespace elf;
560b57cec5SDimitry Andric using namespace llvm::ELF;
570b57cec5SDimitry Andric 
585ffd83dbSDimitry Andric LLDB_PLUGIN_DEFINE(ObjectFileELF)
595ffd83dbSDimitry Andric 
600b57cec5SDimitry Andric // ELF note owner definitions
61349cc55cSDimitry Andric static const char *const LLDB_NT_OWNER_FREEBSD = "FreeBSD";
62349cc55cSDimitry Andric static const char *const LLDB_NT_OWNER_GNU = "GNU";
63349cc55cSDimitry Andric static const char *const LLDB_NT_OWNER_NETBSD = "NetBSD";
64349cc55cSDimitry Andric static const char *const LLDB_NT_OWNER_NETBSDCORE = "NetBSD-CORE";
65349cc55cSDimitry Andric static const char *const LLDB_NT_OWNER_OPENBSD = "OpenBSD";
66349cc55cSDimitry Andric static const char *const LLDB_NT_OWNER_ANDROID = "Android";
67349cc55cSDimitry Andric static const char *const LLDB_NT_OWNER_CORE = "CORE";
68349cc55cSDimitry Andric static const char *const LLDB_NT_OWNER_LINUX = "LINUX";
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric // ELF note type definitions
71349cc55cSDimitry Andric static const elf_word LLDB_NT_FREEBSD_ABI_TAG = 0x01;
72349cc55cSDimitry Andric static const elf_word LLDB_NT_FREEBSD_ABI_SIZE = 4;
730b57cec5SDimitry Andric 
74349cc55cSDimitry Andric static const elf_word LLDB_NT_GNU_ABI_TAG = 0x01;
75349cc55cSDimitry Andric static const elf_word LLDB_NT_GNU_ABI_SIZE = 16;
760b57cec5SDimitry Andric 
77349cc55cSDimitry Andric static const elf_word LLDB_NT_GNU_BUILD_ID_TAG = 0x03;
780b57cec5SDimitry Andric 
79349cc55cSDimitry Andric static const elf_word LLDB_NT_NETBSD_IDENT_TAG = 1;
80349cc55cSDimitry Andric static const elf_word LLDB_NT_NETBSD_IDENT_DESCSZ = 4;
81349cc55cSDimitry Andric static const elf_word LLDB_NT_NETBSD_IDENT_NAMESZ = 7;
82349cc55cSDimitry Andric static const elf_word LLDB_NT_NETBSD_PROCINFO = 1;
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric // GNU ABI note OS constants
85349cc55cSDimitry Andric static const elf_word LLDB_NT_GNU_ABI_OS_LINUX = 0x00;
86349cc55cSDimitry Andric static const elf_word LLDB_NT_GNU_ABI_OS_HURD = 0x01;
87349cc55cSDimitry Andric static const elf_word LLDB_NT_GNU_ABI_OS_SOLARIS = 0x02;
88349cc55cSDimitry Andric 
89349cc55cSDimitry Andric namespace {
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
920b57cec5SDimitry Andric /// \class ELFRelocation
930b57cec5SDimitry Andric /// Generic wrapper for ELFRel and ELFRela.
940b57cec5SDimitry Andric ///
950b57cec5SDimitry Andric /// This helper class allows us to parse both ELFRel and ELFRela relocation
960b57cec5SDimitry Andric /// entries in a generic manner.
970b57cec5SDimitry Andric class ELFRelocation {
980b57cec5SDimitry Andric public:
990b57cec5SDimitry Andric   /// Constructs an ELFRelocation entry with a personality as given by @p
1000b57cec5SDimitry Andric   /// type.
1010b57cec5SDimitry Andric   ///
1020b57cec5SDimitry Andric   /// \param type Either DT_REL or DT_RELA.  Any other value is invalid.
1030b57cec5SDimitry Andric   ELFRelocation(unsigned type);
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric   ~ELFRelocation();
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric   bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset);
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric   static unsigned RelocType32(const ELFRelocation &rel);
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric   static unsigned RelocType64(const ELFRelocation &rel);
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric   static unsigned RelocSymbol32(const ELFRelocation &rel);
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric   static unsigned RelocSymbol64(const ELFRelocation &rel);
1160b57cec5SDimitry Andric 
1171ac55f4cSDimitry Andric   static elf_addr RelocOffset32(const ELFRelocation &rel);
1180b57cec5SDimitry Andric 
1191ac55f4cSDimitry Andric   static elf_addr RelocOffset64(const ELFRelocation &rel);
1200b57cec5SDimitry Andric 
1211ac55f4cSDimitry Andric   static elf_sxword RelocAddend32(const ELFRelocation &rel);
1220b57cec5SDimitry Andric 
1231ac55f4cSDimitry Andric   static elf_sxword RelocAddend64(const ELFRelocation &rel);
1240b57cec5SDimitry Andric 
125bdd1243dSDimitry Andric   bool IsRela() { return (reloc.is<ELFRela *>()); }
126bdd1243dSDimitry Andric 
1270b57cec5SDimitry Andric private:
1280b57cec5SDimitry Andric   typedef llvm::PointerUnion<ELFRel *, ELFRela *> RelocUnion;
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric   RelocUnion reloc;
1310b57cec5SDimitry Andric };
132349cc55cSDimitry Andric } // end anonymous namespace
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric ELFRelocation::ELFRelocation(unsigned type) {
1350b57cec5SDimitry Andric   if (type == DT_REL || type == SHT_REL)
1360b57cec5SDimitry Andric     reloc = new ELFRel();
1370b57cec5SDimitry Andric   else if (type == DT_RELA || type == SHT_RELA)
1380b57cec5SDimitry Andric     reloc = new ELFRela();
1390b57cec5SDimitry Andric   else {
1400b57cec5SDimitry Andric     assert(false && "unexpected relocation type");
1410b57cec5SDimitry Andric     reloc = static_cast<ELFRel *>(nullptr);
1420b57cec5SDimitry Andric   }
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric 
1450b57cec5SDimitry Andric ELFRelocation::~ELFRelocation() {
1460b57cec5SDimitry Andric   if (reloc.is<ELFRel *>())
1470b57cec5SDimitry Andric     delete reloc.get<ELFRel *>();
1480b57cec5SDimitry Andric   else
1490b57cec5SDimitry Andric     delete reloc.get<ELFRela *>();
1500b57cec5SDimitry Andric }
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric bool ELFRelocation::Parse(const lldb_private::DataExtractor &data,
1530b57cec5SDimitry Andric                           lldb::offset_t *offset) {
1540b57cec5SDimitry Andric   if (reloc.is<ELFRel *>())
1550b57cec5SDimitry Andric     return reloc.get<ELFRel *>()->Parse(data, offset);
1560b57cec5SDimitry Andric   else
1570b57cec5SDimitry Andric     return reloc.get<ELFRela *>()->Parse(data, offset);
1580b57cec5SDimitry Andric }
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric unsigned ELFRelocation::RelocType32(const ELFRelocation &rel) {
1610b57cec5SDimitry Andric   if (rel.reloc.is<ELFRel *>())
1620b57cec5SDimitry Andric     return ELFRel::RelocType32(*rel.reloc.get<ELFRel *>());
1630b57cec5SDimitry Andric   else
1640b57cec5SDimitry Andric     return ELFRela::RelocType32(*rel.reloc.get<ELFRela *>());
1650b57cec5SDimitry Andric }
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric unsigned ELFRelocation::RelocType64(const ELFRelocation &rel) {
1680b57cec5SDimitry Andric   if (rel.reloc.is<ELFRel *>())
1690b57cec5SDimitry Andric     return ELFRel::RelocType64(*rel.reloc.get<ELFRel *>());
1700b57cec5SDimitry Andric   else
1710b57cec5SDimitry Andric     return ELFRela::RelocType64(*rel.reloc.get<ELFRela *>());
1720b57cec5SDimitry Andric }
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric unsigned ELFRelocation::RelocSymbol32(const ELFRelocation &rel) {
1750b57cec5SDimitry Andric   if (rel.reloc.is<ELFRel *>())
1760b57cec5SDimitry Andric     return ELFRel::RelocSymbol32(*rel.reloc.get<ELFRel *>());
1770b57cec5SDimitry Andric   else
1780b57cec5SDimitry Andric     return ELFRela::RelocSymbol32(*rel.reloc.get<ELFRela *>());
1790b57cec5SDimitry Andric }
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric unsigned ELFRelocation::RelocSymbol64(const ELFRelocation &rel) {
1820b57cec5SDimitry Andric   if (rel.reloc.is<ELFRel *>())
1830b57cec5SDimitry Andric     return ELFRel::RelocSymbol64(*rel.reloc.get<ELFRel *>());
1840b57cec5SDimitry Andric   else
1850b57cec5SDimitry Andric     return ELFRela::RelocSymbol64(*rel.reloc.get<ELFRela *>());
1860b57cec5SDimitry Andric }
1870b57cec5SDimitry Andric 
1881ac55f4cSDimitry Andric elf_addr ELFRelocation::RelocOffset32(const ELFRelocation &rel) {
1890b57cec5SDimitry Andric   if (rel.reloc.is<ELFRel *>())
1900b57cec5SDimitry Andric     return rel.reloc.get<ELFRel *>()->r_offset;
1910b57cec5SDimitry Andric   else
1920b57cec5SDimitry Andric     return rel.reloc.get<ELFRela *>()->r_offset;
1930b57cec5SDimitry Andric }
1940b57cec5SDimitry Andric 
1951ac55f4cSDimitry Andric elf_addr ELFRelocation::RelocOffset64(const ELFRelocation &rel) {
1960b57cec5SDimitry Andric   if (rel.reloc.is<ELFRel *>())
1970b57cec5SDimitry Andric     return rel.reloc.get<ELFRel *>()->r_offset;
1980b57cec5SDimitry Andric   else
1990b57cec5SDimitry Andric     return rel.reloc.get<ELFRela *>()->r_offset;
2000b57cec5SDimitry Andric }
2010b57cec5SDimitry Andric 
2021ac55f4cSDimitry Andric elf_sxword ELFRelocation::RelocAddend32(const ELFRelocation &rel) {
2030b57cec5SDimitry Andric   if (rel.reloc.is<ELFRel *>())
2040b57cec5SDimitry Andric     return 0;
2050b57cec5SDimitry Andric   else
2060b57cec5SDimitry Andric     return rel.reloc.get<ELFRela *>()->r_addend;
2070b57cec5SDimitry Andric }
2080b57cec5SDimitry Andric 
2091ac55f4cSDimitry Andric elf_sxword  ELFRelocation::RelocAddend64(const ELFRelocation &rel) {
2100b57cec5SDimitry Andric   if (rel.reloc.is<ELFRel *>())
2110b57cec5SDimitry Andric     return 0;
2120b57cec5SDimitry Andric   else
2130b57cec5SDimitry Andric     return rel.reloc.get<ELFRela *>()->r_addend;
2140b57cec5SDimitry Andric }
2150b57cec5SDimitry Andric 
2165ffd83dbSDimitry Andric static user_id_t SegmentID(size_t PHdrIndex) {
2175ffd83dbSDimitry Andric   return ~user_id_t(PHdrIndex);
2185ffd83dbSDimitry Andric }
2190b57cec5SDimitry Andric 
2200b57cec5SDimitry Andric bool ELFNote::Parse(const DataExtractor &data, lldb::offset_t *offset) {
2210b57cec5SDimitry Andric   // Read all fields.
2220b57cec5SDimitry Andric   if (data.GetU32(offset, &n_namesz, 3) == nullptr)
2230b57cec5SDimitry Andric     return false;
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric   // The name field is required to be nul-terminated, and n_namesz includes the
2260b57cec5SDimitry Andric   // terminating nul in observed implementations (contrary to the ELF-64 spec).
2270b57cec5SDimitry Andric   // A special case is needed for cores generated by some older Linux versions,
2280b57cec5SDimitry Andric   // which write a note named "CORE" without a nul terminator and n_namesz = 4.
2290b57cec5SDimitry Andric   if (n_namesz == 4) {
2300b57cec5SDimitry Andric     char buf[4];
2310b57cec5SDimitry Andric     if (data.ExtractBytes(*offset, 4, data.GetByteOrder(), buf) != 4)
2320b57cec5SDimitry Andric       return false;
2330b57cec5SDimitry Andric     if (strncmp(buf, "CORE", 4) == 0) {
2340b57cec5SDimitry Andric       n_name = "CORE";
2350b57cec5SDimitry Andric       *offset += 4;
2360b57cec5SDimitry Andric       return true;
2370b57cec5SDimitry Andric     }
2380b57cec5SDimitry Andric   }
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric   const char *cstr = data.GetCStr(offset, llvm::alignTo(n_namesz, 4));
2410b57cec5SDimitry Andric   if (cstr == nullptr) {
24281ad6265SDimitry Andric     Log *log = GetLog(LLDBLog::Symbols);
2439dba64beSDimitry Andric     LLDB_LOGF(log, "Failed to parse note name lacking nul terminator");
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric     return false;
2460b57cec5SDimitry Andric   }
2470b57cec5SDimitry Andric   n_name = cstr;
2480b57cec5SDimitry Andric   return true;
2490b57cec5SDimitry Andric }
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric static uint32_t mipsVariantFromElfFlags (const elf::ELFHeader &header) {
2520b57cec5SDimitry Andric   const uint32_t mips_arch = header.e_flags & llvm::ELF::EF_MIPS_ARCH;
2530b57cec5SDimitry Andric   uint32_t endian = header.e_ident[EI_DATA];
2540b57cec5SDimitry Andric   uint32_t arch_variant = ArchSpec::eMIPSSubType_unknown;
2550b57cec5SDimitry Andric   uint32_t fileclass = header.e_ident[EI_CLASS];
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric   // If there aren't any elf flags available (e.g core elf file) then return
2580b57cec5SDimitry Andric   // default
2590b57cec5SDimitry Andric   // 32 or 64 bit arch (without any architecture revision) based on object file's class.
2600b57cec5SDimitry Andric   if (header.e_type == ET_CORE) {
2610b57cec5SDimitry Andric     switch (fileclass) {
2620b57cec5SDimitry Andric     case llvm::ELF::ELFCLASS32:
2630b57cec5SDimitry Andric       return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el
2640b57cec5SDimitry Andric                                      : ArchSpec::eMIPSSubType_mips32;
2650b57cec5SDimitry Andric     case llvm::ELF::ELFCLASS64:
2660b57cec5SDimitry Andric       return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el
2670b57cec5SDimitry Andric                                      : ArchSpec::eMIPSSubType_mips64;
2680b57cec5SDimitry Andric     default:
2690b57cec5SDimitry Andric       return arch_variant;
2700b57cec5SDimitry Andric     }
2710b57cec5SDimitry Andric   }
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   switch (mips_arch) {
2740b57cec5SDimitry Andric   case llvm::ELF::EF_MIPS_ARCH_1:
2750b57cec5SDimitry Andric   case llvm::ELF::EF_MIPS_ARCH_2:
2760b57cec5SDimitry Andric   case llvm::ELF::EF_MIPS_ARCH_32:
2770b57cec5SDimitry Andric     return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el
2780b57cec5SDimitry Andric                                    : ArchSpec::eMIPSSubType_mips32;
2790b57cec5SDimitry Andric   case llvm::ELF::EF_MIPS_ARCH_32R2:
2800b57cec5SDimitry Andric     return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r2el
2810b57cec5SDimitry Andric                                    : ArchSpec::eMIPSSubType_mips32r2;
2820b57cec5SDimitry Andric   case llvm::ELF::EF_MIPS_ARCH_32R6:
2830b57cec5SDimitry Andric     return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r6el
2840b57cec5SDimitry Andric                                    : ArchSpec::eMIPSSubType_mips32r6;
2850b57cec5SDimitry Andric   case llvm::ELF::EF_MIPS_ARCH_3:
2860b57cec5SDimitry Andric   case llvm::ELF::EF_MIPS_ARCH_4:
2870b57cec5SDimitry Andric   case llvm::ELF::EF_MIPS_ARCH_5:
2880b57cec5SDimitry Andric   case llvm::ELF::EF_MIPS_ARCH_64:
2890b57cec5SDimitry Andric     return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el
2900b57cec5SDimitry Andric                                    : ArchSpec::eMIPSSubType_mips64;
2910b57cec5SDimitry Andric   case llvm::ELF::EF_MIPS_ARCH_64R2:
2920b57cec5SDimitry Andric     return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r2el
2930b57cec5SDimitry Andric                                    : ArchSpec::eMIPSSubType_mips64r2;
2940b57cec5SDimitry Andric   case llvm::ELF::EF_MIPS_ARCH_64R6:
2950b57cec5SDimitry Andric     return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r6el
2960b57cec5SDimitry Andric                                    : ArchSpec::eMIPSSubType_mips64r6;
2970b57cec5SDimitry Andric   default:
2980b57cec5SDimitry Andric     break;
2990b57cec5SDimitry Andric   }
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric   return arch_variant;
3020b57cec5SDimitry Andric }
3030b57cec5SDimitry Andric 
304e8d8bef9SDimitry Andric static uint32_t riscvVariantFromElfFlags(const elf::ELFHeader &header) {
305e8d8bef9SDimitry Andric   uint32_t fileclass = header.e_ident[EI_CLASS];
306e8d8bef9SDimitry Andric   switch (fileclass) {
307e8d8bef9SDimitry Andric   case llvm::ELF::ELFCLASS32:
308e8d8bef9SDimitry Andric     return ArchSpec::eRISCVSubType_riscv32;
309e8d8bef9SDimitry Andric   case llvm::ELF::ELFCLASS64:
310e8d8bef9SDimitry Andric     return ArchSpec::eRISCVSubType_riscv64;
311e8d8bef9SDimitry Andric   default:
312e8d8bef9SDimitry Andric     return ArchSpec::eRISCVSubType_unknown;
313e8d8bef9SDimitry Andric   }
314e8d8bef9SDimitry Andric }
315e8d8bef9SDimitry Andric 
31681ad6265SDimitry Andric static uint32_t ppc64VariantFromElfFlags(const elf::ELFHeader &header) {
31781ad6265SDimitry Andric   uint32_t endian = header.e_ident[EI_DATA];
31881ad6265SDimitry Andric   if (endian == ELFDATA2LSB)
31981ad6265SDimitry Andric     return ArchSpec::eCore_ppc64le_generic;
32081ad6265SDimitry Andric   else
32181ad6265SDimitry Andric     return ArchSpec::eCore_ppc64_generic;
32281ad6265SDimitry Andric }
32381ad6265SDimitry Andric 
324bdd1243dSDimitry Andric static uint32_t loongarchVariantFromElfFlags(const elf::ELFHeader &header) {
325bdd1243dSDimitry Andric   uint32_t fileclass = header.e_ident[EI_CLASS];
326bdd1243dSDimitry Andric   switch (fileclass) {
327bdd1243dSDimitry Andric   case llvm::ELF::ELFCLASS32:
328bdd1243dSDimitry Andric     return ArchSpec::eLoongArchSubType_loongarch32;
329bdd1243dSDimitry Andric   case llvm::ELF::ELFCLASS64:
330bdd1243dSDimitry Andric     return ArchSpec::eLoongArchSubType_loongarch64;
331bdd1243dSDimitry Andric   default:
332bdd1243dSDimitry Andric     return ArchSpec::eLoongArchSubType_unknown;
333bdd1243dSDimitry Andric   }
334bdd1243dSDimitry Andric }
335bdd1243dSDimitry Andric 
3360b57cec5SDimitry Andric static uint32_t subTypeFromElfHeader(const elf::ELFHeader &header) {
3370b57cec5SDimitry Andric   if (header.e_machine == llvm::ELF::EM_MIPS)
3380b57cec5SDimitry Andric     return mipsVariantFromElfFlags(header);
33981ad6265SDimitry Andric   else if (header.e_machine == llvm::ELF::EM_PPC64)
34081ad6265SDimitry Andric     return ppc64VariantFromElfFlags(header);
341e8d8bef9SDimitry Andric   else if (header.e_machine == llvm::ELF::EM_RISCV)
342e8d8bef9SDimitry Andric     return riscvVariantFromElfFlags(header);
343bdd1243dSDimitry Andric   else if (header.e_machine == llvm::ELF::EM_LOONGARCH)
344bdd1243dSDimitry Andric     return loongarchVariantFromElfFlags(header);
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric   return LLDB_INVALID_CPUTYPE;
3470b57cec5SDimitry Andric }
3480b57cec5SDimitry Andric 
3499dba64beSDimitry Andric char ObjectFileELF::ID;
3509dba64beSDimitry Andric 
3510b57cec5SDimitry Andric // Arbitrary constant used as UUID prefix for core files.
3520b57cec5SDimitry Andric const uint32_t ObjectFileELF::g_core_uuid_magic(0xE210C);
3530b57cec5SDimitry Andric 
3540b57cec5SDimitry Andric // Static methods.
3550b57cec5SDimitry Andric void ObjectFileELF::Initialize() {
3560b57cec5SDimitry Andric   PluginManager::RegisterPlugin(GetPluginNameStatic(),
3570b57cec5SDimitry Andric                                 GetPluginDescriptionStatic(), CreateInstance,
3580b57cec5SDimitry Andric                                 CreateMemoryInstance, GetModuleSpecifications);
3590b57cec5SDimitry Andric }
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric void ObjectFileELF::Terminate() {
3620b57cec5SDimitry Andric   PluginManager::UnregisterPlugin(CreateInstance);
3630b57cec5SDimitry Andric }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric ObjectFile *ObjectFileELF::CreateInstance(const lldb::ModuleSP &module_sp,
36681ad6265SDimitry Andric                                           DataBufferSP data_sp,
3670b57cec5SDimitry Andric                                           lldb::offset_t data_offset,
3680b57cec5SDimitry Andric                                           const lldb_private::FileSpec *file,
3690b57cec5SDimitry Andric                                           lldb::offset_t file_offset,
3700b57cec5SDimitry Andric                                           lldb::offset_t length) {
37181ad6265SDimitry Andric   bool mapped_writable = false;
3720b57cec5SDimitry Andric   if (!data_sp) {
37381ad6265SDimitry Andric     data_sp = MapFileDataWritable(*file, length, file_offset);
3740b57cec5SDimitry Andric     if (!data_sp)
3750b57cec5SDimitry Andric       return nullptr;
3760b57cec5SDimitry Andric     data_offset = 0;
37781ad6265SDimitry Andric     mapped_writable = true;
3780b57cec5SDimitry Andric   }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric   assert(data_sp);
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric   if (data_sp->GetByteSize() <= (llvm::ELF::EI_NIDENT + data_offset))
3830b57cec5SDimitry Andric     return nullptr;
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric   const uint8_t *magic = data_sp->GetBytes() + data_offset;
3860b57cec5SDimitry Andric   if (!ELFHeader::MagicBytesMatch(magic))
3870b57cec5SDimitry Andric     return nullptr;
3880b57cec5SDimitry Andric 
3890b57cec5SDimitry Andric   // Update the data to contain the entire file if it doesn't already
3900b57cec5SDimitry Andric   if (data_sp->GetByteSize() < length) {
39181ad6265SDimitry Andric     data_sp = MapFileDataWritable(*file, length, file_offset);
3920b57cec5SDimitry Andric     if (!data_sp)
3930b57cec5SDimitry Andric       return nullptr;
3940b57cec5SDimitry Andric     data_offset = 0;
39581ad6265SDimitry Andric     mapped_writable = true;
39681ad6265SDimitry Andric     magic = data_sp->GetBytes();
39781ad6265SDimitry Andric   }
39881ad6265SDimitry Andric 
39981ad6265SDimitry Andric   // If we didn't map the data as writable take ownership of the buffer.
40081ad6265SDimitry Andric   if (!mapped_writable) {
40181ad6265SDimitry Andric     data_sp = std::make_shared<DataBufferHeap>(data_sp->GetBytes(),
40281ad6265SDimitry Andric                                                data_sp->GetByteSize());
40381ad6265SDimitry Andric     data_offset = 0;
4040b57cec5SDimitry Andric     magic = data_sp->GetBytes();
4050b57cec5SDimitry Andric   }
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric   unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
4080b57cec5SDimitry Andric   if (address_size == 4 || address_size == 8) {
4090b57cec5SDimitry Andric     std::unique_ptr<ObjectFileELF> objfile_up(new ObjectFileELF(
4100b57cec5SDimitry Andric         module_sp, data_sp, data_offset, file, file_offset, length));
4110b57cec5SDimitry Andric     ArchSpec spec = objfile_up->GetArchitecture();
4120b57cec5SDimitry Andric     if (spec && objfile_up->SetModulesArchitecture(spec))
4130b57cec5SDimitry Andric       return objfile_up.release();
4140b57cec5SDimitry Andric   }
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric   return nullptr;
4170b57cec5SDimitry Andric }
4180b57cec5SDimitry Andric 
4190b57cec5SDimitry Andric ObjectFile *ObjectFileELF::CreateMemoryInstance(
42081ad6265SDimitry Andric     const lldb::ModuleSP &module_sp, WritableDataBufferSP data_sp,
4210b57cec5SDimitry Andric     const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {
4220b57cec5SDimitry Andric   if (data_sp && data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT)) {
4230b57cec5SDimitry Andric     const uint8_t *magic = data_sp->GetBytes();
4240b57cec5SDimitry Andric     if (ELFHeader::MagicBytesMatch(magic)) {
4250b57cec5SDimitry Andric       unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
4260b57cec5SDimitry Andric       if (address_size == 4 || address_size == 8) {
4270b57cec5SDimitry Andric         std::unique_ptr<ObjectFileELF> objfile_up(
4280b57cec5SDimitry Andric             new ObjectFileELF(module_sp, data_sp, process_sp, header_addr));
4290b57cec5SDimitry Andric         ArchSpec spec = objfile_up->GetArchitecture();
4300b57cec5SDimitry Andric         if (spec && objfile_up->SetModulesArchitecture(spec))
4310b57cec5SDimitry Andric           return objfile_up.release();
4320b57cec5SDimitry Andric       }
4330b57cec5SDimitry Andric     }
4340b57cec5SDimitry Andric   }
4350b57cec5SDimitry Andric   return nullptr;
4360b57cec5SDimitry Andric }
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric bool ObjectFileELF::MagicBytesMatch(DataBufferSP &data_sp,
4390b57cec5SDimitry Andric                                     lldb::addr_t data_offset,
4400b57cec5SDimitry Andric                                     lldb::addr_t data_length) {
4410b57cec5SDimitry Andric   if (data_sp &&
4420b57cec5SDimitry Andric       data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset)) {
4430b57cec5SDimitry Andric     const uint8_t *magic = data_sp->GetBytes() + data_offset;
4440b57cec5SDimitry Andric     return ELFHeader::MagicBytesMatch(magic);
4450b57cec5SDimitry Andric   }
4460b57cec5SDimitry Andric   return false;
4470b57cec5SDimitry Andric }
4480b57cec5SDimitry Andric 
4499dba64beSDimitry Andric static uint32_t calc_crc32(uint32_t init, const DataExtractor &data) {
450bdd1243dSDimitry Andric   return llvm::crc32(init,
451bdd1243dSDimitry Andric                      llvm::ArrayRef(data.GetDataStart(), data.GetByteSize()));
4520b57cec5SDimitry Andric }
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric uint32_t ObjectFileELF::CalculateELFNotesSegmentsCRC32(
4550b57cec5SDimitry Andric     const ProgramHeaderColl &program_headers, DataExtractor &object_data) {
4560b57cec5SDimitry Andric 
4570b57cec5SDimitry Andric   uint32_t core_notes_crc = 0;
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric   for (const ELFProgramHeader &H : program_headers) {
4600b57cec5SDimitry Andric     if (H.p_type == llvm::ELF::PT_NOTE) {
4610b57cec5SDimitry Andric       const elf_off ph_offset = H.p_offset;
4620b57cec5SDimitry Andric       const size_t ph_size = H.p_filesz;
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric       DataExtractor segment_data;
4650b57cec5SDimitry Andric       if (segment_data.SetData(object_data, ph_offset, ph_size) != ph_size) {
4660b57cec5SDimitry Andric         // The ELF program header contained incorrect data, probably corefile
4670b57cec5SDimitry Andric         // is incomplete or corrupted.
4680b57cec5SDimitry Andric         break;
4690b57cec5SDimitry Andric       }
4700b57cec5SDimitry Andric 
4719dba64beSDimitry Andric       core_notes_crc = calc_crc32(core_notes_crc, segment_data);
4720b57cec5SDimitry Andric     }
4730b57cec5SDimitry Andric   }
4740b57cec5SDimitry Andric 
4750b57cec5SDimitry Andric   return core_notes_crc;
4760b57cec5SDimitry Andric }
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric static const char *OSABIAsCString(unsigned char osabi_byte) {
4790b57cec5SDimitry Andric #define _MAKE_OSABI_CASE(x)                                                    \
4800b57cec5SDimitry Andric   case x:                                                                      \
4810b57cec5SDimitry Andric     return #x
4820b57cec5SDimitry Andric   switch (osabi_byte) {
4830b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_NONE);
4840b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_HPUX);
4850b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_NETBSD);
4860b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_GNU);
4870b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_HURD);
4880b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_SOLARIS);
4890b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_AIX);
4900b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_IRIX);
4910b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_FREEBSD);
4920b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_TRU64);
4930b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_MODESTO);
4940b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_OPENBSD);
4950b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_OPENVMS);
4960b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_NSK);
4970b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_AROS);
4980b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_FENIXOS);
4990b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_C6000_ELFABI);
5000b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_C6000_LINUX);
5010b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_ARM);
5020b57cec5SDimitry Andric     _MAKE_OSABI_CASE(ELFOSABI_STANDALONE);
5030b57cec5SDimitry Andric   default:
5040b57cec5SDimitry Andric     return "<unknown-osabi>";
5050b57cec5SDimitry Andric   }
5060b57cec5SDimitry Andric #undef _MAKE_OSABI_CASE
5070b57cec5SDimitry Andric }
5080b57cec5SDimitry Andric 
5090b57cec5SDimitry Andric //
5100b57cec5SDimitry Andric // WARNING : This function is being deprecated
5110b57cec5SDimitry Andric // It's functionality has moved to ArchSpec::SetArchitecture This function is
5120b57cec5SDimitry Andric // only being kept to validate the move.
5130b57cec5SDimitry Andric //
5140b57cec5SDimitry Andric // TODO : Remove this function
5150b57cec5SDimitry Andric static bool GetOsFromOSABI(unsigned char osabi_byte,
5160b57cec5SDimitry Andric                            llvm::Triple::OSType &ostype) {
5170b57cec5SDimitry Andric   switch (osabi_byte) {
5180b57cec5SDimitry Andric   case ELFOSABI_AIX:
5190b57cec5SDimitry Andric     ostype = llvm::Triple::OSType::AIX;
5200b57cec5SDimitry Andric     break;
5210b57cec5SDimitry Andric   case ELFOSABI_FREEBSD:
5220b57cec5SDimitry Andric     ostype = llvm::Triple::OSType::FreeBSD;
5230b57cec5SDimitry Andric     break;
5240b57cec5SDimitry Andric   case ELFOSABI_GNU:
5250b57cec5SDimitry Andric     ostype = llvm::Triple::OSType::Linux;
5260b57cec5SDimitry Andric     break;
5270b57cec5SDimitry Andric   case ELFOSABI_NETBSD:
5280b57cec5SDimitry Andric     ostype = llvm::Triple::OSType::NetBSD;
5290b57cec5SDimitry Andric     break;
5300b57cec5SDimitry Andric   case ELFOSABI_OPENBSD:
5310b57cec5SDimitry Andric     ostype = llvm::Triple::OSType::OpenBSD;
5320b57cec5SDimitry Andric     break;
5330b57cec5SDimitry Andric   case ELFOSABI_SOLARIS:
5340b57cec5SDimitry Andric     ostype = llvm::Triple::OSType::Solaris;
5350b57cec5SDimitry Andric     break;
5360b57cec5SDimitry Andric   default:
5370b57cec5SDimitry Andric     ostype = llvm::Triple::OSType::UnknownOS;
5380b57cec5SDimitry Andric   }
5390b57cec5SDimitry Andric   return ostype != llvm::Triple::OSType::UnknownOS;
5400b57cec5SDimitry Andric }
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric size_t ObjectFileELF::GetModuleSpecifications(
5430b57cec5SDimitry Andric     const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
5440b57cec5SDimitry Andric     lldb::offset_t data_offset, lldb::offset_t file_offset,
5450b57cec5SDimitry Andric     lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
54681ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Modules);
5470b57cec5SDimitry Andric 
5480b57cec5SDimitry Andric   const size_t initial_count = specs.GetSize();
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric   if (ObjectFileELF::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
5510b57cec5SDimitry Andric     DataExtractor data;
5520b57cec5SDimitry Andric     data.SetData(data_sp);
5530b57cec5SDimitry Andric     elf::ELFHeader header;
5540b57cec5SDimitry Andric     lldb::offset_t header_offset = data_offset;
5550b57cec5SDimitry Andric     if (header.Parse(data, &header_offset)) {
5560b57cec5SDimitry Andric       if (data_sp) {
5570b57cec5SDimitry Andric         ModuleSpec spec(file);
558*fe013be4SDimitry Andric         // In Android API level 23 and above, bionic dynamic linker is able to
559*fe013be4SDimitry Andric         // load .so file directly from zip file. In that case, .so file is
560*fe013be4SDimitry Andric         // page aligned and uncompressed, and this module spec should retain the
561*fe013be4SDimitry Andric         // .so file offset and file size to pass through the information from
562*fe013be4SDimitry Andric         // lldb-server to LLDB. For normal file, file_offset should be 0,
563*fe013be4SDimitry Andric         // length should be the size of the file.
564*fe013be4SDimitry Andric         spec.SetObjectOffset(file_offset);
565*fe013be4SDimitry Andric         spec.SetObjectSize(length);
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric         const uint32_t sub_type = subTypeFromElfHeader(header);
5680b57cec5SDimitry Andric         spec.GetArchitecture().SetArchitecture(
5690b57cec5SDimitry Andric             eArchTypeELF, header.e_machine, sub_type, header.e_ident[EI_OSABI]);
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric         if (spec.GetArchitecture().IsValid()) {
5720b57cec5SDimitry Andric           llvm::Triple::OSType ostype;
5730b57cec5SDimitry Andric           llvm::Triple::VendorType vendor;
5740b57cec5SDimitry Andric           llvm::Triple::OSType spec_ostype =
5750b57cec5SDimitry Andric               spec.GetArchitecture().GetTriple().getOS();
5760b57cec5SDimitry Andric 
5779dba64beSDimitry Andric           LLDB_LOGF(log, "ObjectFileELF::%s file '%s' module OSABI: %s",
5780b57cec5SDimitry Andric                     __FUNCTION__, file.GetPath().c_str(),
5790b57cec5SDimitry Andric                     OSABIAsCString(header.e_ident[EI_OSABI]));
5800b57cec5SDimitry Andric 
5810b57cec5SDimitry Andric           // SetArchitecture should have set the vendor to unknown
5820b57cec5SDimitry Andric           vendor = spec.GetArchitecture().GetTriple().getVendor();
5830b57cec5SDimitry Andric           assert(vendor == llvm::Triple::UnknownVendor);
5840b57cec5SDimitry Andric           UNUSED_IF_ASSERT_DISABLED(vendor);
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric           //
5870b57cec5SDimitry Andric           // Validate it is ok to remove GetOsFromOSABI
5880b57cec5SDimitry Andric           GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
5890b57cec5SDimitry Andric           assert(spec_ostype == ostype);
5900b57cec5SDimitry Andric           if (spec_ostype != llvm::Triple::OSType::UnknownOS) {
5919dba64beSDimitry Andric             LLDB_LOGF(log,
5929dba64beSDimitry Andric                       "ObjectFileELF::%s file '%s' set ELF module OS type "
5930b57cec5SDimitry Andric                       "from ELF header OSABI.",
5940b57cec5SDimitry Andric                       __FUNCTION__, file.GetPath().c_str());
5950b57cec5SDimitry Andric           }
5960b57cec5SDimitry Andric 
597*fe013be4SDimitry Andric           // When ELF file does not contain GNU build ID, the later code will
598*fe013be4SDimitry Andric           // calculate CRC32 with this data_sp file_offset and length. It is
599*fe013be4SDimitry Andric           // important for Android zip .so file, which is a slice of a file,
600*fe013be4SDimitry Andric           // to not access the outside of the file slice range.
6015ffd83dbSDimitry Andric           if (data_sp->GetByteSize() < length)
602*fe013be4SDimitry Andric             data_sp = MapFileData(file, length, file_offset);
6030b57cec5SDimitry Andric           if (data_sp)
6040b57cec5SDimitry Andric             data.SetData(data_sp);
6050b57cec5SDimitry Andric           // In case there is header extension in the section #0, the header we
6060b57cec5SDimitry Andric           // parsed above could have sentinel values for e_phnum, e_shnum, and
6070b57cec5SDimitry Andric           // e_shstrndx.  In this case we need to reparse the header with a
6080b57cec5SDimitry Andric           // bigger data source to get the actual values.
6090b57cec5SDimitry Andric           if (header.HasHeaderExtension()) {
6100b57cec5SDimitry Andric             lldb::offset_t header_offset = data_offset;
6110b57cec5SDimitry Andric             header.Parse(data, &header_offset);
6120b57cec5SDimitry Andric           }
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric           uint32_t gnu_debuglink_crc = 0;
6150b57cec5SDimitry Andric           std::string gnu_debuglink_file;
6160b57cec5SDimitry Andric           SectionHeaderColl section_headers;
6170b57cec5SDimitry Andric           lldb_private::UUID &uuid = spec.GetUUID();
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric           GetSectionHeaderInfo(section_headers, data, header, uuid,
6200b57cec5SDimitry Andric                                gnu_debuglink_file, gnu_debuglink_crc,
6210b57cec5SDimitry Andric                                spec.GetArchitecture());
6220b57cec5SDimitry Andric 
6230b57cec5SDimitry Andric           llvm::Triple &spec_triple = spec.GetArchitecture().GetTriple();
6240b57cec5SDimitry Andric 
6259dba64beSDimitry Andric           LLDB_LOGF(log,
6269dba64beSDimitry Andric                     "ObjectFileELF::%s file '%s' module set to triple: %s "
6270b57cec5SDimitry Andric                     "(architecture %s)",
6280b57cec5SDimitry Andric                     __FUNCTION__, file.GetPath().c_str(),
6290b57cec5SDimitry Andric                     spec_triple.getTriple().c_str(),
6300b57cec5SDimitry Andric                     spec.GetArchitecture().GetArchitectureName());
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric           if (!uuid.IsValid()) {
6330b57cec5SDimitry Andric             uint32_t core_notes_crc = 0;
6340b57cec5SDimitry Andric 
6350b57cec5SDimitry Andric             if (!gnu_debuglink_crc) {
636e8d8bef9SDimitry Andric               LLDB_SCOPED_TIMERF(
6370b57cec5SDimitry Andric                   "Calculating module crc32 %s with size %" PRIu64 " KiB",
638*fe013be4SDimitry Andric                   file.GetFilename().AsCString(),
6395ffd83dbSDimitry Andric                   (length - file_offset) / 1024);
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric               // For core files - which usually don't happen to have a
6420b57cec5SDimitry Andric               // gnu_debuglink, and are pretty bulky - calculating whole
6430b57cec5SDimitry Andric               // contents crc32 would be too much of luxury.  Thus we will need
6440b57cec5SDimitry Andric               // to fallback to something simpler.
6450b57cec5SDimitry Andric               if (header.e_type == llvm::ELF::ET_CORE) {
6460b57cec5SDimitry Andric                 ProgramHeaderColl program_headers;
6470b57cec5SDimitry Andric                 GetProgramHeaderInfo(program_headers, data, header);
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric                 core_notes_crc =
6500b57cec5SDimitry Andric                     CalculateELFNotesSegmentsCRC32(program_headers, data);
6510b57cec5SDimitry Andric               } else {
6529dba64beSDimitry Andric                 gnu_debuglink_crc = calc_crc32(0, data);
6530b57cec5SDimitry Andric               }
6540b57cec5SDimitry Andric             }
6550b57cec5SDimitry Andric             using u32le = llvm::support::ulittle32_t;
6560b57cec5SDimitry Andric             if (gnu_debuglink_crc) {
6570b57cec5SDimitry Andric               // Use 4 bytes of crc from the .gnu_debuglink section.
6580b57cec5SDimitry Andric               u32le data(gnu_debuglink_crc);
659bdd1243dSDimitry Andric               uuid = UUID(&data, sizeof(data));
6600b57cec5SDimitry Andric             } else if (core_notes_crc) {
6610b57cec5SDimitry Andric               // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make
6620b57cec5SDimitry Andric               // it look different form .gnu_debuglink crc followed by 4 bytes
6630b57cec5SDimitry Andric               // of note segments crc.
6640b57cec5SDimitry Andric               u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)};
665bdd1243dSDimitry Andric               uuid = UUID(data, sizeof(data));
6660b57cec5SDimitry Andric             }
6670b57cec5SDimitry Andric           }
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric           specs.Append(spec);
6700b57cec5SDimitry Andric         }
6710b57cec5SDimitry Andric       }
6720b57cec5SDimitry Andric     }
6730b57cec5SDimitry Andric   }
6740b57cec5SDimitry Andric 
6750b57cec5SDimitry Andric   return specs.GetSize() - initial_count;
6760b57cec5SDimitry Andric }
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric // ObjectFile protocol
6790b57cec5SDimitry Andric 
6800b57cec5SDimitry Andric ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,
68181ad6265SDimitry Andric                              DataBufferSP data_sp, lldb::offset_t data_offset,
6820b57cec5SDimitry Andric                              const FileSpec *file, lldb::offset_t file_offset,
6830b57cec5SDimitry Andric                              lldb::offset_t length)
6849dba64beSDimitry Andric     : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset) {
6850b57cec5SDimitry Andric   if (file)
6860b57cec5SDimitry Andric     m_file = *file;
6870b57cec5SDimitry Andric }
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,
69081ad6265SDimitry Andric                              DataBufferSP header_data_sp,
6910b57cec5SDimitry Andric                              const lldb::ProcessSP &process_sp,
6920b57cec5SDimitry Andric                              addr_t header_addr)
6939dba64beSDimitry Andric     : ObjectFile(module_sp, process_sp, header_addr, header_data_sp) {}
6940b57cec5SDimitry Andric 
6950b57cec5SDimitry Andric bool ObjectFileELF::IsExecutable() const {
6960b57cec5SDimitry Andric   return ((m_header.e_type & ET_EXEC) != 0) || (m_header.e_entry != 0);
6970b57cec5SDimitry Andric }
6980b57cec5SDimitry Andric 
6990b57cec5SDimitry Andric bool ObjectFileELF::SetLoadAddress(Target &target, lldb::addr_t value,
7000b57cec5SDimitry Andric                                    bool value_is_offset) {
7010b57cec5SDimitry Andric   ModuleSP module_sp = GetModule();
7020b57cec5SDimitry Andric   if (module_sp) {
7030b57cec5SDimitry Andric     size_t num_loaded_sections = 0;
7040b57cec5SDimitry Andric     SectionList *section_list = GetSectionList();
7050b57cec5SDimitry Andric     if (section_list) {
7060b57cec5SDimitry Andric       if (!value_is_offset) {
7070b57cec5SDimitry Andric         addr_t base = GetBaseAddress().GetFileAddress();
7080b57cec5SDimitry Andric         if (base == LLDB_INVALID_ADDRESS)
7090b57cec5SDimitry Andric           return false;
7100b57cec5SDimitry Andric         value -= base;
7110b57cec5SDimitry Andric       }
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric       const size_t num_sections = section_list->GetSize();
7140b57cec5SDimitry Andric       size_t sect_idx = 0;
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric       for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
7170b57cec5SDimitry Andric         // Iterate through the object file sections to find all of the sections
7180b57cec5SDimitry Andric         // that have SHF_ALLOC in their flag bits.
7190b57cec5SDimitry Andric         SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
7200b57cec5SDimitry Andric         if (section_sp->Test(SHF_ALLOC) ||
7210b57cec5SDimitry Andric             section_sp->GetType() == eSectionTypeContainer) {
7220b57cec5SDimitry Andric           lldb::addr_t load_addr = section_sp->GetFileAddress();
7230b57cec5SDimitry Andric           // We don't want to update the load address of a section with type
7240b57cec5SDimitry Andric           // eSectionTypeAbsoluteAddress as they already have the absolute load
7250b57cec5SDimitry Andric           // address already specified
7260b57cec5SDimitry Andric           if (section_sp->GetType() != eSectionTypeAbsoluteAddress)
7270b57cec5SDimitry Andric             load_addr += value;
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric           // On 32-bit systems the load address have to fit into 4 bytes. The
7300b57cec5SDimitry Andric           // rest of the bytes are the overflow from the addition.
7310b57cec5SDimitry Andric           if (GetAddressByteSize() == 4)
7320b57cec5SDimitry Andric             load_addr &= 0xFFFFFFFF;
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric           if (target.GetSectionLoadList().SetSectionLoadAddress(section_sp,
7350b57cec5SDimitry Andric                                                                 load_addr))
7360b57cec5SDimitry Andric             ++num_loaded_sections;
7370b57cec5SDimitry Andric         }
7380b57cec5SDimitry Andric       }
7390b57cec5SDimitry Andric       return num_loaded_sections > 0;
7400b57cec5SDimitry Andric     }
7410b57cec5SDimitry Andric   }
7420b57cec5SDimitry Andric   return false;
7430b57cec5SDimitry Andric }
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric ByteOrder ObjectFileELF::GetByteOrder() const {
7460b57cec5SDimitry Andric   if (m_header.e_ident[EI_DATA] == ELFDATA2MSB)
7470b57cec5SDimitry Andric     return eByteOrderBig;
7480b57cec5SDimitry Andric   if (m_header.e_ident[EI_DATA] == ELFDATA2LSB)
7490b57cec5SDimitry Andric     return eByteOrderLittle;
7500b57cec5SDimitry Andric   return eByteOrderInvalid;
7510b57cec5SDimitry Andric }
7520b57cec5SDimitry Andric 
7530b57cec5SDimitry Andric uint32_t ObjectFileELF::GetAddressByteSize() const {
7540b57cec5SDimitry Andric   return m_data.GetAddressByteSize();
7550b57cec5SDimitry Andric }
7560b57cec5SDimitry Andric 
7570b57cec5SDimitry Andric AddressClass ObjectFileELF::GetAddressClass(addr_t file_addr) {
7580b57cec5SDimitry Andric   Symtab *symtab = GetSymtab();
7590b57cec5SDimitry Andric   if (!symtab)
7600b57cec5SDimitry Andric     return AddressClass::eUnknown;
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric   // The address class is determined based on the symtab. Ask it from the
7630b57cec5SDimitry Andric   // object file what contains the symtab information.
7640b57cec5SDimitry Andric   ObjectFile *symtab_objfile = symtab->GetObjectFile();
7650b57cec5SDimitry Andric   if (symtab_objfile != nullptr && symtab_objfile != this)
7660b57cec5SDimitry Andric     return symtab_objfile->GetAddressClass(file_addr);
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric   auto res = ObjectFile::GetAddressClass(file_addr);
7690b57cec5SDimitry Andric   if (res != AddressClass::eCode)
7700b57cec5SDimitry Andric     return res;
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric   auto ub = m_address_class_map.upper_bound(file_addr);
7730b57cec5SDimitry Andric   if (ub == m_address_class_map.begin()) {
7740b57cec5SDimitry Andric     // No entry in the address class map before the address. Return default
7750b57cec5SDimitry Andric     // address class for an address in a code section.
7760b57cec5SDimitry Andric     return AddressClass::eCode;
7770b57cec5SDimitry Andric   }
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric   // Move iterator to the address class entry preceding address
7800b57cec5SDimitry Andric   --ub;
7810b57cec5SDimitry Andric 
7820b57cec5SDimitry Andric   return ub->second;
7830b57cec5SDimitry Andric }
7840b57cec5SDimitry Andric 
7850b57cec5SDimitry Andric size_t ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I) {
7860b57cec5SDimitry Andric   return std::distance(m_section_headers.begin(), I);
7870b57cec5SDimitry Andric }
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric size_t ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const {
7900b57cec5SDimitry Andric   return std::distance(m_section_headers.begin(), I);
7910b57cec5SDimitry Andric }
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric bool ObjectFileELF::ParseHeader() {
7940b57cec5SDimitry Andric   lldb::offset_t offset = 0;
7950b57cec5SDimitry Andric   return m_header.Parse(m_data, &offset);
7960b57cec5SDimitry Andric }
7970b57cec5SDimitry Andric 
7980b57cec5SDimitry Andric UUID ObjectFileELF::GetUUID() {
7990b57cec5SDimitry Andric   // Need to parse the section list to get the UUIDs, so make sure that's been
8000b57cec5SDimitry Andric   // done.
8010b57cec5SDimitry Andric   if (!ParseSectionHeaders() && GetType() != ObjectFile::eTypeCoreFile)
8020b57cec5SDimitry Andric     return UUID();
8030b57cec5SDimitry Andric 
8040b57cec5SDimitry Andric   if (!m_uuid) {
8050b57cec5SDimitry Andric     using u32le = llvm::support::ulittle32_t;
8060b57cec5SDimitry Andric     if (GetType() == ObjectFile::eTypeCoreFile) {
8070b57cec5SDimitry Andric       uint32_t core_notes_crc = 0;
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric       if (!ParseProgramHeaders())
8100b57cec5SDimitry Andric         return UUID();
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric       core_notes_crc =
8130b57cec5SDimitry Andric           CalculateELFNotesSegmentsCRC32(m_program_headers, m_data);
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric       if (core_notes_crc) {
8160b57cec5SDimitry Andric         // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it
8170b57cec5SDimitry Andric         // look different form .gnu_debuglink crc - followed by 4 bytes of note
8180b57cec5SDimitry Andric         // segments crc.
8190b57cec5SDimitry Andric         u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)};
820bdd1243dSDimitry Andric         m_uuid = UUID(data, sizeof(data));
8210b57cec5SDimitry Andric       }
8220b57cec5SDimitry Andric     } else {
8230b57cec5SDimitry Andric       if (!m_gnu_debuglink_crc)
8249dba64beSDimitry Andric         m_gnu_debuglink_crc = calc_crc32(0, m_data);
8250b57cec5SDimitry Andric       if (m_gnu_debuglink_crc) {
8260b57cec5SDimitry Andric         // Use 4 bytes of crc from the .gnu_debuglink section.
8270b57cec5SDimitry Andric         u32le data(m_gnu_debuglink_crc);
828bdd1243dSDimitry Andric         m_uuid = UUID(&data, sizeof(data));
8290b57cec5SDimitry Andric       }
8300b57cec5SDimitry Andric     }
8310b57cec5SDimitry Andric   }
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric   return m_uuid;
8340b57cec5SDimitry Andric }
8350b57cec5SDimitry Andric 
836bdd1243dSDimitry Andric std::optional<FileSpec> ObjectFileELF::GetDebugLink() {
8379dba64beSDimitry Andric   if (m_gnu_debuglink_file.empty())
838bdd1243dSDimitry Andric     return std::nullopt;
8399dba64beSDimitry Andric   return FileSpec(m_gnu_debuglink_file);
8400b57cec5SDimitry Andric }
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric uint32_t ObjectFileELF::GetDependentModules(FileSpecList &files) {
8430b57cec5SDimitry Andric   size_t num_modules = ParseDependentModules();
8440b57cec5SDimitry Andric   uint32_t num_specs = 0;
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric   for (unsigned i = 0; i < num_modules; ++i) {
8470b57cec5SDimitry Andric     if (files.AppendIfUnique(m_filespec_up->GetFileSpecAtIndex(i)))
8480b57cec5SDimitry Andric       num_specs++;
8490b57cec5SDimitry Andric   }
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric   return num_specs;
8520b57cec5SDimitry Andric }
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric Address ObjectFileELF::GetImageInfoAddress(Target *target) {
8550b57cec5SDimitry Andric   if (!ParseDynamicSymbols())
8560b57cec5SDimitry Andric     return Address();
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
8590b57cec5SDimitry Andric   if (!section_list)
8600b57cec5SDimitry Andric     return Address();
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric   // Find the SHT_DYNAMIC (.dynamic) section.
8630b57cec5SDimitry Andric   SectionSP dynsym_section_sp(
8640b57cec5SDimitry Andric       section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true));
8650b57cec5SDimitry Andric   if (!dynsym_section_sp)
8660b57cec5SDimitry Andric     return Address();
8670b57cec5SDimitry Andric   assert(dynsym_section_sp->GetObjectFile() == this);
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric   user_id_t dynsym_id = dynsym_section_sp->GetID();
8700b57cec5SDimitry Andric   const ELFSectionHeaderInfo *dynsym_hdr = GetSectionHeaderByIndex(dynsym_id);
8710b57cec5SDimitry Andric   if (!dynsym_hdr)
8720b57cec5SDimitry Andric     return Address();
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric   for (size_t i = 0; i < m_dynamic_symbols.size(); ++i) {
8750b57cec5SDimitry Andric     ELFDynamic &symbol = m_dynamic_symbols[i];
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric     if (symbol.d_tag == DT_DEBUG) {
8780b57cec5SDimitry Andric       // Compute the offset as the number of previous entries plus the size of
8790b57cec5SDimitry Andric       // d_tag.
8800b57cec5SDimitry Andric       addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
8810b57cec5SDimitry Andric       return Address(dynsym_section_sp, offset);
8820b57cec5SDimitry Andric     }
8830b57cec5SDimitry Andric     // MIPS executables uses DT_MIPS_RLD_MAP_REL to support PIE. DT_MIPS_RLD_MAP
8840b57cec5SDimitry Andric     // exists in non-PIE.
8850b57cec5SDimitry Andric     else if ((symbol.d_tag == DT_MIPS_RLD_MAP ||
8860b57cec5SDimitry Andric               symbol.d_tag == DT_MIPS_RLD_MAP_REL) &&
8870b57cec5SDimitry Andric              target) {
8880b57cec5SDimitry Andric       addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
8890b57cec5SDimitry Andric       addr_t dyn_base = dynsym_section_sp->GetLoadBaseAddress(target);
8900b57cec5SDimitry Andric       if (dyn_base == LLDB_INVALID_ADDRESS)
8910b57cec5SDimitry Andric         return Address();
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric       Status error;
8940b57cec5SDimitry Andric       if (symbol.d_tag == DT_MIPS_RLD_MAP) {
8950b57cec5SDimitry Andric         // DT_MIPS_RLD_MAP tag stores an absolute address of the debug pointer.
8960b57cec5SDimitry Andric         Address addr;
897fe6060f1SDimitry Andric         if (target->ReadPointerFromMemory(dyn_base + offset, error, addr, true))
8980b57cec5SDimitry Andric           return addr;
8990b57cec5SDimitry Andric       }
9000b57cec5SDimitry Andric       if (symbol.d_tag == DT_MIPS_RLD_MAP_REL) {
9010b57cec5SDimitry Andric         // DT_MIPS_RLD_MAP_REL tag stores the offset to the debug pointer,
9020b57cec5SDimitry Andric         // relative to the address of the tag.
9030b57cec5SDimitry Andric         uint64_t rel_offset;
9040b57cec5SDimitry Andric         rel_offset = target->ReadUnsignedIntegerFromMemory(
905fe6060f1SDimitry Andric             dyn_base + offset, GetAddressByteSize(), UINT64_MAX, error, true);
9060b57cec5SDimitry Andric         if (error.Success() && rel_offset != UINT64_MAX) {
9070b57cec5SDimitry Andric           Address addr;
9080b57cec5SDimitry Andric           addr_t debug_ptr_address =
9090b57cec5SDimitry Andric               dyn_base + (offset - GetAddressByteSize()) + rel_offset;
9100b57cec5SDimitry Andric           addr.SetOffset(debug_ptr_address);
9110b57cec5SDimitry Andric           return addr;
9120b57cec5SDimitry Andric         }
9130b57cec5SDimitry Andric       }
9140b57cec5SDimitry Andric     }
9150b57cec5SDimitry Andric   }
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric   return Address();
9180b57cec5SDimitry Andric }
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric lldb_private::Address ObjectFileELF::GetEntryPointAddress() {
9210b57cec5SDimitry Andric   if (m_entry_point_address.IsValid())
9220b57cec5SDimitry Andric     return m_entry_point_address;
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric   if (!ParseHeader() || !IsExecutable())
9250b57cec5SDimitry Andric     return m_entry_point_address;
9260b57cec5SDimitry Andric 
9270b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
9280b57cec5SDimitry Andric   addr_t offset = m_header.e_entry;
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric   if (!section_list)
9310b57cec5SDimitry Andric     m_entry_point_address.SetOffset(offset);
9320b57cec5SDimitry Andric   else
9330b57cec5SDimitry Andric     m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list);
9340b57cec5SDimitry Andric   return m_entry_point_address;
9350b57cec5SDimitry Andric }
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric Address ObjectFileELF::GetBaseAddress() {
9380b57cec5SDimitry Andric   for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {
9390b57cec5SDimitry Andric     const ELFProgramHeader &H = EnumPHdr.value();
9400b57cec5SDimitry Andric     if (H.p_type != PT_LOAD)
9410b57cec5SDimitry Andric       continue;
9420b57cec5SDimitry Andric 
9430b57cec5SDimitry Andric     return Address(
9440b57cec5SDimitry Andric         GetSectionList()->FindSectionByID(SegmentID(EnumPHdr.index())), 0);
9450b57cec5SDimitry Andric   }
9460b57cec5SDimitry Andric   return LLDB_INVALID_ADDRESS;
9470b57cec5SDimitry Andric }
9480b57cec5SDimitry Andric 
9490b57cec5SDimitry Andric // ParseDependentModules
9500b57cec5SDimitry Andric size_t ObjectFileELF::ParseDependentModules() {
9510b57cec5SDimitry Andric   if (m_filespec_up)
9520b57cec5SDimitry Andric     return m_filespec_up->GetSize();
9530b57cec5SDimitry Andric 
9545ffd83dbSDimitry Andric   m_filespec_up = std::make_unique<FileSpecList>();
9550b57cec5SDimitry Andric 
9560b57cec5SDimitry Andric   if (!ParseSectionHeaders())
9570b57cec5SDimitry Andric     return 0;
9580b57cec5SDimitry Andric 
9590b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
9600b57cec5SDimitry Andric   if (!section_list)
9610b57cec5SDimitry Andric     return 0;
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric   // Find the SHT_DYNAMIC section.
9640b57cec5SDimitry Andric   Section *dynsym =
9650b57cec5SDimitry Andric       section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
9660b57cec5SDimitry Andric           .get();
9670b57cec5SDimitry Andric   if (!dynsym)
9680b57cec5SDimitry Andric     return 0;
9690b57cec5SDimitry Andric   assert(dynsym->GetObjectFile() == this);
9700b57cec5SDimitry Andric 
9710b57cec5SDimitry Andric   const ELFSectionHeaderInfo *header = GetSectionHeaderByIndex(dynsym->GetID());
9720b57cec5SDimitry Andric   if (!header)
9730b57cec5SDimitry Andric     return 0;
9740b57cec5SDimitry Andric   // sh_link: section header index of string table used by entries in the
9750b57cec5SDimitry Andric   // section.
9760b57cec5SDimitry Andric   Section *dynstr = section_list->FindSectionByID(header->sh_link).get();
9770b57cec5SDimitry Andric   if (!dynstr)
9780b57cec5SDimitry Andric     return 0;
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric   DataExtractor dynsym_data;
9810b57cec5SDimitry Andric   DataExtractor dynstr_data;
9820b57cec5SDimitry Andric   if (ReadSectionData(dynsym, dynsym_data) &&
9830b57cec5SDimitry Andric       ReadSectionData(dynstr, dynstr_data)) {
9840b57cec5SDimitry Andric     ELFDynamic symbol;
9850b57cec5SDimitry Andric     const lldb::offset_t section_size = dynsym_data.GetByteSize();
9860b57cec5SDimitry Andric     lldb::offset_t offset = 0;
9870b57cec5SDimitry Andric 
9880b57cec5SDimitry Andric     // The only type of entries we are concerned with are tagged DT_NEEDED,
9890b57cec5SDimitry Andric     // yielding the name of a required library.
9900b57cec5SDimitry Andric     while (offset < section_size) {
9910b57cec5SDimitry Andric       if (!symbol.Parse(dynsym_data, &offset))
9920b57cec5SDimitry Andric         break;
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric       if (symbol.d_tag != DT_NEEDED)
9950b57cec5SDimitry Andric         continue;
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric       uint32_t str_index = static_cast<uint32_t>(symbol.d_val);
9980b57cec5SDimitry Andric       const char *lib_name = dynstr_data.PeekCStr(str_index);
9990b57cec5SDimitry Andric       FileSpec file_spec(lib_name);
10000b57cec5SDimitry Andric       FileSystem::Instance().Resolve(file_spec);
10010b57cec5SDimitry Andric       m_filespec_up->Append(file_spec);
10020b57cec5SDimitry Andric     }
10030b57cec5SDimitry Andric   }
10040b57cec5SDimitry Andric 
10050b57cec5SDimitry Andric   return m_filespec_up->GetSize();
10060b57cec5SDimitry Andric }
10070b57cec5SDimitry Andric 
10080b57cec5SDimitry Andric // GetProgramHeaderInfo
10090b57cec5SDimitry Andric size_t ObjectFileELF::GetProgramHeaderInfo(ProgramHeaderColl &program_headers,
10100b57cec5SDimitry Andric                                            DataExtractor &object_data,
10110b57cec5SDimitry Andric                                            const ELFHeader &header) {
10120b57cec5SDimitry Andric   // We have already parsed the program headers
10130b57cec5SDimitry Andric   if (!program_headers.empty())
10140b57cec5SDimitry Andric     return program_headers.size();
10150b57cec5SDimitry Andric 
10160b57cec5SDimitry Andric   // If there are no program headers to read we are done.
10170b57cec5SDimitry Andric   if (header.e_phnum == 0)
10180b57cec5SDimitry Andric     return 0;
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric   program_headers.resize(header.e_phnum);
10210b57cec5SDimitry Andric   if (program_headers.size() != header.e_phnum)
10220b57cec5SDimitry Andric     return 0;
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric   const size_t ph_size = header.e_phnum * header.e_phentsize;
10250b57cec5SDimitry Andric   const elf_off ph_offset = header.e_phoff;
10260b57cec5SDimitry Andric   DataExtractor data;
10270b57cec5SDimitry Andric   if (data.SetData(object_data, ph_offset, ph_size) != ph_size)
10280b57cec5SDimitry Andric     return 0;
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric   uint32_t idx;
10310b57cec5SDimitry Andric   lldb::offset_t offset;
10320b57cec5SDimitry Andric   for (idx = 0, offset = 0; idx < header.e_phnum; ++idx) {
10330b57cec5SDimitry Andric     if (!program_headers[idx].Parse(data, &offset))
10340b57cec5SDimitry Andric       break;
10350b57cec5SDimitry Andric   }
10360b57cec5SDimitry Andric 
10370b57cec5SDimitry Andric   if (idx < program_headers.size())
10380b57cec5SDimitry Andric     program_headers.resize(idx);
10390b57cec5SDimitry Andric 
10400b57cec5SDimitry Andric   return program_headers.size();
10410b57cec5SDimitry Andric }
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric // ParseProgramHeaders
10440b57cec5SDimitry Andric bool ObjectFileELF::ParseProgramHeaders() {
10450b57cec5SDimitry Andric   return GetProgramHeaderInfo(m_program_headers, m_data, m_header) != 0;
10460b57cec5SDimitry Andric }
10470b57cec5SDimitry Andric 
10480b57cec5SDimitry Andric lldb_private::Status
10490b57cec5SDimitry Andric ObjectFileELF::RefineModuleDetailsFromNote(lldb_private::DataExtractor &data,
10500b57cec5SDimitry Andric                                            lldb_private::ArchSpec &arch_spec,
10510b57cec5SDimitry Andric                                            lldb_private::UUID &uuid) {
105281ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Modules);
10530b57cec5SDimitry Andric   Status error;
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric   lldb::offset_t offset = 0;
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric   while (true) {
10580b57cec5SDimitry Andric     // Parse the note header.  If this fails, bail out.
10590b57cec5SDimitry Andric     const lldb::offset_t note_offset = offset;
10600b57cec5SDimitry Andric     ELFNote note = ELFNote();
10610b57cec5SDimitry Andric     if (!note.Parse(data, &offset)) {
10620b57cec5SDimitry Andric       // We're done.
10630b57cec5SDimitry Andric       return error;
10640b57cec5SDimitry Andric     }
10650b57cec5SDimitry Andric 
10669dba64beSDimitry Andric     LLDB_LOGF(log, "ObjectFileELF::%s parsing note name='%s', type=%" PRIu32,
10670b57cec5SDimitry Andric               __FUNCTION__, note.n_name.c_str(), note.n_type);
10680b57cec5SDimitry Andric 
10690b57cec5SDimitry Andric     // Process FreeBSD ELF notes.
10700b57cec5SDimitry Andric     if ((note.n_name == LLDB_NT_OWNER_FREEBSD) &&
10710b57cec5SDimitry Andric         (note.n_type == LLDB_NT_FREEBSD_ABI_TAG) &&
10720b57cec5SDimitry Andric         (note.n_descsz == LLDB_NT_FREEBSD_ABI_SIZE)) {
10730b57cec5SDimitry Andric       // Pull out the min version info.
10740b57cec5SDimitry Andric       uint32_t version_info;
10750b57cec5SDimitry Andric       if (data.GetU32(&offset, &version_info, 1) == nullptr) {
10760b57cec5SDimitry Andric         error.SetErrorString("failed to read FreeBSD ABI note payload");
10770b57cec5SDimitry Andric         return error;
10780b57cec5SDimitry Andric       }
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric       // Convert the version info into a major/minor number.
10810b57cec5SDimitry Andric       const uint32_t version_major = version_info / 100000;
10820b57cec5SDimitry Andric       const uint32_t version_minor = (version_info / 1000) % 100;
10830b57cec5SDimitry Andric 
10840b57cec5SDimitry Andric       char os_name[32];
10850b57cec5SDimitry Andric       snprintf(os_name, sizeof(os_name), "freebsd%" PRIu32 ".%" PRIu32,
10860b57cec5SDimitry Andric                version_major, version_minor);
10870b57cec5SDimitry Andric 
10880b57cec5SDimitry Andric       // Set the elf OS version to FreeBSD.  Also clear the vendor.
10890b57cec5SDimitry Andric       arch_spec.GetTriple().setOSName(os_name);
10900b57cec5SDimitry Andric       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
10910b57cec5SDimitry Andric 
10929dba64beSDimitry Andric       LLDB_LOGF(log,
10939dba64beSDimitry Andric                 "ObjectFileELF::%s detected FreeBSD %" PRIu32 ".%" PRIu32
10940b57cec5SDimitry Andric                 ".%" PRIu32,
10950b57cec5SDimitry Andric                 __FUNCTION__, version_major, version_minor,
10960b57cec5SDimitry Andric                 static_cast<uint32_t>(version_info % 1000));
10970b57cec5SDimitry Andric     }
10980b57cec5SDimitry Andric     // Process GNU ELF notes.
10990b57cec5SDimitry Andric     else if (note.n_name == LLDB_NT_OWNER_GNU) {
11000b57cec5SDimitry Andric       switch (note.n_type) {
11010b57cec5SDimitry Andric       case LLDB_NT_GNU_ABI_TAG:
11020b57cec5SDimitry Andric         if (note.n_descsz == LLDB_NT_GNU_ABI_SIZE) {
11030b57cec5SDimitry Andric           // Pull out the min OS version supporting the ABI.
11040b57cec5SDimitry Andric           uint32_t version_info[4];
11050b57cec5SDimitry Andric           if (data.GetU32(&offset, &version_info[0], note.n_descsz / 4) ==
11060b57cec5SDimitry Andric               nullptr) {
11070b57cec5SDimitry Andric             error.SetErrorString("failed to read GNU ABI note payload");
11080b57cec5SDimitry Andric             return error;
11090b57cec5SDimitry Andric           }
11100b57cec5SDimitry Andric 
11110b57cec5SDimitry Andric           // Set the OS per the OS field.
11120b57cec5SDimitry Andric           switch (version_info[0]) {
11130b57cec5SDimitry Andric           case LLDB_NT_GNU_ABI_OS_LINUX:
11140b57cec5SDimitry Andric             arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
11150b57cec5SDimitry Andric             arch_spec.GetTriple().setVendor(
11160b57cec5SDimitry Andric                 llvm::Triple::VendorType::UnknownVendor);
11179dba64beSDimitry Andric             LLDB_LOGF(log,
11180b57cec5SDimitry Andric                       "ObjectFileELF::%s detected Linux, min version %" PRIu32
11190b57cec5SDimitry Andric                       ".%" PRIu32 ".%" PRIu32,
11200b57cec5SDimitry Andric                       __FUNCTION__, version_info[1], version_info[2],
11210b57cec5SDimitry Andric                       version_info[3]);
11220b57cec5SDimitry Andric             // FIXME we have the minimal version number, we could be propagating
11230b57cec5SDimitry Andric             // that.  version_info[1] = OS Major, version_info[2] = OS Minor,
11240b57cec5SDimitry Andric             // version_info[3] = Revision.
11250b57cec5SDimitry Andric             break;
11260b57cec5SDimitry Andric           case LLDB_NT_GNU_ABI_OS_HURD:
11270b57cec5SDimitry Andric             arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
11280b57cec5SDimitry Andric             arch_spec.GetTriple().setVendor(
11290b57cec5SDimitry Andric                 llvm::Triple::VendorType::UnknownVendor);
11309dba64beSDimitry Andric             LLDB_LOGF(log,
11319dba64beSDimitry Andric                       "ObjectFileELF::%s detected Hurd (unsupported), min "
11320b57cec5SDimitry Andric                       "version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
11330b57cec5SDimitry Andric                       __FUNCTION__, version_info[1], version_info[2],
11340b57cec5SDimitry Andric                       version_info[3]);
11350b57cec5SDimitry Andric             break;
11360b57cec5SDimitry Andric           case LLDB_NT_GNU_ABI_OS_SOLARIS:
11370b57cec5SDimitry Andric             arch_spec.GetTriple().setOS(llvm::Triple::OSType::Solaris);
11380b57cec5SDimitry Andric             arch_spec.GetTriple().setVendor(
11390b57cec5SDimitry Andric                 llvm::Triple::VendorType::UnknownVendor);
11409dba64beSDimitry Andric             LLDB_LOGF(log,
11410b57cec5SDimitry Andric                       "ObjectFileELF::%s detected Solaris, min version %" PRIu32
11420b57cec5SDimitry Andric                       ".%" PRIu32 ".%" PRIu32,
11430b57cec5SDimitry Andric                       __FUNCTION__, version_info[1], version_info[2],
11440b57cec5SDimitry Andric                       version_info[3]);
11450b57cec5SDimitry Andric             break;
11460b57cec5SDimitry Andric           default:
11479dba64beSDimitry Andric             LLDB_LOGF(log,
11480b57cec5SDimitry Andric                       "ObjectFileELF::%s unrecognized OS in note, id %" PRIu32
11490b57cec5SDimitry Andric                       ", min version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
11500b57cec5SDimitry Andric                       __FUNCTION__, version_info[0], version_info[1],
11510b57cec5SDimitry Andric                       version_info[2], version_info[3]);
11520b57cec5SDimitry Andric             break;
11530b57cec5SDimitry Andric           }
11540b57cec5SDimitry Andric         }
11550b57cec5SDimitry Andric         break;
11560b57cec5SDimitry Andric 
11570b57cec5SDimitry Andric       case LLDB_NT_GNU_BUILD_ID_TAG:
11580b57cec5SDimitry Andric         // Only bother processing this if we don't already have the uuid set.
11590b57cec5SDimitry Andric         if (!uuid.IsValid()) {
11600b57cec5SDimitry Andric           // 16 bytes is UUID|MD5, 20 bytes is SHA1. Other linkers may produce a
11610b57cec5SDimitry Andric           // build-id of a different length. Accept it as long as it's at least
11620b57cec5SDimitry Andric           // 4 bytes as it will be better than our own crc32.
11630b57cec5SDimitry Andric           if (note.n_descsz >= 4) {
11640b57cec5SDimitry Andric             if (const uint8_t *buf = data.PeekData(offset, note.n_descsz)) {
11650b57cec5SDimitry Andric               // Save the build id as the UUID for the module.
1166bdd1243dSDimitry Andric               uuid = UUID(buf, note.n_descsz);
11670b57cec5SDimitry Andric             } else {
11680b57cec5SDimitry Andric               error.SetErrorString("failed to read GNU_BUILD_ID note payload");
11690b57cec5SDimitry Andric               return error;
11700b57cec5SDimitry Andric             }
11710b57cec5SDimitry Andric           }
11720b57cec5SDimitry Andric         }
11730b57cec5SDimitry Andric         break;
11740b57cec5SDimitry Andric       }
11750b57cec5SDimitry Andric       if (arch_spec.IsMIPS() &&
11760b57cec5SDimitry Andric           arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)
11770b57cec5SDimitry Andric         // The note.n_name == LLDB_NT_OWNER_GNU is valid for Linux platform
11780b57cec5SDimitry Andric         arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
11790b57cec5SDimitry Andric     }
11800b57cec5SDimitry Andric     // Process NetBSD ELF executables and shared libraries
11810b57cec5SDimitry Andric     else if ((note.n_name == LLDB_NT_OWNER_NETBSD) &&
11820b57cec5SDimitry Andric              (note.n_type == LLDB_NT_NETBSD_IDENT_TAG) &&
11830b57cec5SDimitry Andric              (note.n_descsz == LLDB_NT_NETBSD_IDENT_DESCSZ) &&
11840b57cec5SDimitry Andric              (note.n_namesz == LLDB_NT_NETBSD_IDENT_NAMESZ)) {
11850b57cec5SDimitry Andric       // Pull out the version info.
11860b57cec5SDimitry Andric       uint32_t version_info;
11870b57cec5SDimitry Andric       if (data.GetU32(&offset, &version_info, 1) == nullptr) {
11880b57cec5SDimitry Andric         error.SetErrorString("failed to read NetBSD ABI note payload");
11890b57cec5SDimitry Andric         return error;
11900b57cec5SDimitry Andric       }
11910b57cec5SDimitry Andric       // Convert the version info into a major/minor/patch number.
11920b57cec5SDimitry Andric       //     #define __NetBSD_Version__ MMmmrrpp00
11930b57cec5SDimitry Andric       //
11940b57cec5SDimitry Andric       //     M = major version
11950b57cec5SDimitry Andric       //     m = minor version; a minor number of 99 indicates current.
11960b57cec5SDimitry Andric       //     r = 0 (since NetBSD 3.0 not used)
11970b57cec5SDimitry Andric       //     p = patchlevel
11980b57cec5SDimitry Andric       const uint32_t version_major = version_info / 100000000;
11990b57cec5SDimitry Andric       const uint32_t version_minor = (version_info % 100000000) / 1000000;
12000b57cec5SDimitry Andric       const uint32_t version_patch = (version_info % 10000) / 100;
12010b57cec5SDimitry Andric       // Set the elf OS version to NetBSD.  Also clear the vendor.
12020b57cec5SDimitry Andric       arch_spec.GetTriple().setOSName(
12030b57cec5SDimitry Andric           llvm::formatv("netbsd{0}.{1}.{2}", version_major, version_minor,
12040b57cec5SDimitry Andric                         version_patch).str());
12050b57cec5SDimitry Andric       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
12060b57cec5SDimitry Andric     }
12070b57cec5SDimitry Andric     // Process NetBSD ELF core(5) notes
12080b57cec5SDimitry Andric     else if ((note.n_name == LLDB_NT_OWNER_NETBSDCORE) &&
12090b57cec5SDimitry Andric              (note.n_type == LLDB_NT_NETBSD_PROCINFO)) {
12100b57cec5SDimitry Andric       // Set the elf OS version to NetBSD.  Also clear the vendor.
12110b57cec5SDimitry Andric       arch_spec.GetTriple().setOS(llvm::Triple::OSType::NetBSD);
12120b57cec5SDimitry Andric       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
12130b57cec5SDimitry Andric     }
12140b57cec5SDimitry Andric     // Process OpenBSD ELF notes.
12150b57cec5SDimitry Andric     else if (note.n_name == LLDB_NT_OWNER_OPENBSD) {
12160b57cec5SDimitry Andric       // Set the elf OS version to OpenBSD.  Also clear the vendor.
12170b57cec5SDimitry Andric       arch_spec.GetTriple().setOS(llvm::Triple::OSType::OpenBSD);
12180b57cec5SDimitry Andric       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
12190b57cec5SDimitry Andric     } else if (note.n_name == LLDB_NT_OWNER_ANDROID) {
12200b57cec5SDimitry Andric       arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
12210b57cec5SDimitry Andric       arch_spec.GetTriple().setEnvironment(
12220b57cec5SDimitry Andric           llvm::Triple::EnvironmentType::Android);
12230b57cec5SDimitry Andric     } else if (note.n_name == LLDB_NT_OWNER_LINUX) {
12240b57cec5SDimitry Andric       // This is sometimes found in core files and usually contains extended
12250b57cec5SDimitry Andric       // register info
12260b57cec5SDimitry Andric       arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
12270b57cec5SDimitry Andric     } else if (note.n_name == LLDB_NT_OWNER_CORE) {
122881ad6265SDimitry Andric       // Parse the NT_FILE to look for stuff in paths to shared libraries
122981ad6265SDimitry Andric       // The contents look like this in a 64 bit ELF core file:
123081ad6265SDimitry Andric       //
123181ad6265SDimitry Andric       // count     = 0x000000000000000a (10)
123281ad6265SDimitry Andric       // page_size = 0x0000000000001000 (4096)
123381ad6265SDimitry Andric       // Index start              end                file_ofs           path
123481ad6265SDimitry Andric       // ===== ------------------ ------------------ ------------------ -------------------------------------
123581ad6265SDimitry Andric       // [  0] 0x0000000000401000 0x0000000000000000                    /tmp/a.out
123681ad6265SDimitry Andric       // [  1] 0x0000000000600000 0x0000000000601000 0x0000000000000000 /tmp/a.out
123781ad6265SDimitry Andric       // [  2] 0x0000000000601000 0x0000000000602000 0x0000000000000001 /tmp/a.out
123881ad6265SDimitry Andric       // [  3] 0x00007fa79c9ed000 0x00007fa79cba8000 0x0000000000000000 /lib/x86_64-linux-gnu/libc-2.19.so
123981ad6265SDimitry Andric       // [  4] 0x00007fa79cba8000 0x00007fa79cda7000 0x00000000000001bb /lib/x86_64-linux-gnu/libc-2.19.so
124081ad6265SDimitry Andric       // [  5] 0x00007fa79cda7000 0x00007fa79cdab000 0x00000000000001ba /lib/x86_64-linux-gnu/libc-2.19.so
124181ad6265SDimitry Andric       // [  6] 0x00007fa79cdab000 0x00007fa79cdad000 0x00000000000001be /lib/x86_64-linux-gnu/libc-2.19.so
124281ad6265SDimitry Andric       // [  7] 0x00007fa79cdb2000 0x00007fa79cdd5000 0x0000000000000000 /lib/x86_64-linux-gnu/ld-2.19.so
124381ad6265SDimitry Andric       // [  8] 0x00007fa79cfd4000 0x00007fa79cfd5000 0x0000000000000022 /lib/x86_64-linux-gnu/ld-2.19.so
124481ad6265SDimitry Andric       // [  9] 0x00007fa79cfd5000 0x00007fa79cfd6000 0x0000000000000023 /lib/x86_64-linux-gnu/ld-2.19.so
124581ad6265SDimitry Andric       //
124681ad6265SDimitry Andric       // In the 32 bit ELFs the count, page_size, start, end, file_ofs are
124781ad6265SDimitry Andric       // uint32_t.
124881ad6265SDimitry Andric       //
124981ad6265SDimitry Andric       // For reference: see readelf source code (in binutils).
12500b57cec5SDimitry Andric       if (note.n_type == NT_FILE) {
12510b57cec5SDimitry Andric         uint64_t count = data.GetAddress(&offset);
12520b57cec5SDimitry Andric         const char *cstr;
12530b57cec5SDimitry Andric         data.GetAddress(&offset); // Skip page size
12540b57cec5SDimitry Andric         offset += count * 3 *
12550b57cec5SDimitry Andric                   data.GetAddressByteSize(); // Skip all start/end/file_ofs
12560b57cec5SDimitry Andric         for (size_t i = 0; i < count; ++i) {
12570b57cec5SDimitry Andric           cstr = data.GetCStr(&offset);
12580b57cec5SDimitry Andric           if (cstr == nullptr) {
12590b57cec5SDimitry Andric             error.SetErrorStringWithFormat("ObjectFileELF::%s trying to read "
12600b57cec5SDimitry Andric                                            "at an offset after the end "
12610b57cec5SDimitry Andric                                            "(GetCStr returned nullptr)",
12620b57cec5SDimitry Andric                                            __FUNCTION__);
12630b57cec5SDimitry Andric             return error;
12640b57cec5SDimitry Andric           }
12650b57cec5SDimitry Andric           llvm::StringRef path(cstr);
12660b57cec5SDimitry Andric           if (path.contains("/lib/x86_64-linux-gnu") || path.contains("/lib/i386-linux-gnu")) {
12670b57cec5SDimitry Andric             arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
12680b57cec5SDimitry Andric             break;
12690b57cec5SDimitry Andric           }
12700b57cec5SDimitry Andric         }
12710b57cec5SDimitry Andric         if (arch_spec.IsMIPS() &&
12720b57cec5SDimitry Andric             arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)
12730b57cec5SDimitry Andric           // In case of MIPSR6, the LLDB_NT_OWNER_GNU note is missing for some
12740b57cec5SDimitry Andric           // cases (e.g. compile with -nostdlib) Hence set OS to Linux
12750b57cec5SDimitry Andric           arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
12760b57cec5SDimitry Andric       }
12770b57cec5SDimitry Andric     }
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric     // Calculate the offset of the next note just in case "offset" has been
12800b57cec5SDimitry Andric     // used to poke at the contents of the note data
12810b57cec5SDimitry Andric     offset = note_offset + note.GetByteSize();
12820b57cec5SDimitry Andric   }
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric   return error;
12850b57cec5SDimitry Andric }
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric void ObjectFileELF::ParseARMAttributes(DataExtractor &data, uint64_t length,
12880b57cec5SDimitry Andric                                        ArchSpec &arch_spec) {
12890b57cec5SDimitry Andric   lldb::offset_t Offset = 0;
12900b57cec5SDimitry Andric 
12910b57cec5SDimitry Andric   uint8_t FormatVersion = data.GetU8(&Offset);
12925ffd83dbSDimitry Andric   if (FormatVersion != llvm::ELFAttrs::Format_Version)
12930b57cec5SDimitry Andric     return;
12940b57cec5SDimitry Andric 
12950b57cec5SDimitry Andric   Offset = Offset + sizeof(uint32_t); // Section Length
12960b57cec5SDimitry Andric   llvm::StringRef VendorName = data.GetCStr(&Offset);
12970b57cec5SDimitry Andric 
12980b57cec5SDimitry Andric   if (VendorName != "aeabi")
12990b57cec5SDimitry Andric     return;
13000b57cec5SDimitry Andric 
13010b57cec5SDimitry Andric   if (arch_spec.GetTriple().getEnvironment() ==
13020b57cec5SDimitry Andric       llvm::Triple::UnknownEnvironment)
13030b57cec5SDimitry Andric     arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric   while (Offset < length) {
13060b57cec5SDimitry Andric     uint8_t Tag = data.GetU8(&Offset);
13070b57cec5SDimitry Andric     uint32_t Size = data.GetU32(&Offset);
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric     if (Tag != llvm::ARMBuildAttrs::File || Size == 0)
13100b57cec5SDimitry Andric       continue;
13110b57cec5SDimitry Andric 
13120b57cec5SDimitry Andric     while (Offset < length) {
13130b57cec5SDimitry Andric       uint64_t Tag = data.GetULEB128(&Offset);
13140b57cec5SDimitry Andric       switch (Tag) {
13150b57cec5SDimitry Andric       default:
13160b57cec5SDimitry Andric         if (Tag < 32)
13170b57cec5SDimitry Andric           data.GetULEB128(&Offset);
13180b57cec5SDimitry Andric         else if (Tag % 2 == 0)
13190b57cec5SDimitry Andric           data.GetULEB128(&Offset);
13200b57cec5SDimitry Andric         else
13210b57cec5SDimitry Andric           data.GetCStr(&Offset);
13220b57cec5SDimitry Andric 
13230b57cec5SDimitry Andric         break;
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric       case llvm::ARMBuildAttrs::CPU_raw_name:
13260b57cec5SDimitry Andric       case llvm::ARMBuildAttrs::CPU_name:
13270b57cec5SDimitry Andric         data.GetCStr(&Offset);
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric         break;
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric       case llvm::ARMBuildAttrs::ABI_VFP_args: {
13320b57cec5SDimitry Andric         uint64_t VFPArgs = data.GetULEB128(&Offset);
13330b57cec5SDimitry Andric 
13340b57cec5SDimitry Andric         if (VFPArgs == llvm::ARMBuildAttrs::BaseAAPCS) {
13350b57cec5SDimitry Andric           if (arch_spec.GetTriple().getEnvironment() ==
13360b57cec5SDimitry Andric                   llvm::Triple::UnknownEnvironment ||
13370b57cec5SDimitry Andric               arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABIHF)
13380b57cec5SDimitry Andric             arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
13390b57cec5SDimitry Andric 
13400b57cec5SDimitry Andric           arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
13410b57cec5SDimitry Andric         } else if (VFPArgs == llvm::ARMBuildAttrs::HardFPAAPCS) {
13420b57cec5SDimitry Andric           if (arch_spec.GetTriple().getEnvironment() ==
13430b57cec5SDimitry Andric                   llvm::Triple::UnknownEnvironment ||
13440b57cec5SDimitry Andric               arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABI)
13450b57cec5SDimitry Andric             arch_spec.GetTriple().setEnvironment(llvm::Triple::EABIHF);
13460b57cec5SDimitry Andric 
13470b57cec5SDimitry Andric           arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
13480b57cec5SDimitry Andric         }
13490b57cec5SDimitry Andric 
13500b57cec5SDimitry Andric         break;
13510b57cec5SDimitry Andric       }
13520b57cec5SDimitry Andric       }
13530b57cec5SDimitry Andric     }
13540b57cec5SDimitry Andric   }
13550b57cec5SDimitry Andric }
13560b57cec5SDimitry Andric 
13570b57cec5SDimitry Andric // GetSectionHeaderInfo
13580b57cec5SDimitry Andric size_t ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl &section_headers,
13590b57cec5SDimitry Andric                                            DataExtractor &object_data,
13600b57cec5SDimitry Andric                                            const elf::ELFHeader &header,
13610b57cec5SDimitry Andric                                            lldb_private::UUID &uuid,
13620b57cec5SDimitry Andric                                            std::string &gnu_debuglink_file,
13630b57cec5SDimitry Andric                                            uint32_t &gnu_debuglink_crc,
13640b57cec5SDimitry Andric                                            ArchSpec &arch_spec) {
13650b57cec5SDimitry Andric   // Don't reparse the section headers if we already did that.
13660b57cec5SDimitry Andric   if (!section_headers.empty())
13670b57cec5SDimitry Andric     return section_headers.size();
13680b57cec5SDimitry Andric 
13690b57cec5SDimitry Andric   // Only initialize the arch_spec to okay defaults if they're not already set.
13700b57cec5SDimitry Andric   // We'll refine this with note data as we parse the notes.
13710b57cec5SDimitry Andric   if (arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) {
13720b57cec5SDimitry Andric     llvm::Triple::OSType ostype;
13730b57cec5SDimitry Andric     llvm::Triple::OSType spec_ostype;
13740b57cec5SDimitry Andric     const uint32_t sub_type = subTypeFromElfHeader(header);
13750b57cec5SDimitry Andric     arch_spec.SetArchitecture(eArchTypeELF, header.e_machine, sub_type,
13760b57cec5SDimitry Andric                               header.e_ident[EI_OSABI]);
13770b57cec5SDimitry Andric 
13780b57cec5SDimitry Andric     // Validate if it is ok to remove GetOsFromOSABI. Note, that now the OS is
13790b57cec5SDimitry Andric     // determined based on EI_OSABI flag and the info extracted from ELF notes
13800b57cec5SDimitry Andric     // (see RefineModuleDetailsFromNote). However in some cases that still
13810b57cec5SDimitry Andric     // might be not enough: for example a shared library might not have any
13820b57cec5SDimitry Andric     // notes at all and have EI_OSABI flag set to System V, as result the OS
13830b57cec5SDimitry Andric     // will be set to UnknownOS.
13840b57cec5SDimitry Andric     GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
13850b57cec5SDimitry Andric     spec_ostype = arch_spec.GetTriple().getOS();
13860b57cec5SDimitry Andric     assert(spec_ostype == ostype);
13870b57cec5SDimitry Andric     UNUSED_IF_ASSERT_DISABLED(spec_ostype);
13880b57cec5SDimitry Andric   }
13890b57cec5SDimitry Andric 
13900b57cec5SDimitry Andric   if (arch_spec.GetMachine() == llvm::Triple::mips ||
13910b57cec5SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::mipsel ||
13920b57cec5SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::mips64 ||
13930b57cec5SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::mips64el) {
13940b57cec5SDimitry Andric     switch (header.e_flags & llvm::ELF::EF_MIPS_ARCH_ASE) {
13950b57cec5SDimitry Andric     case llvm::ELF::EF_MIPS_MICROMIPS:
13960b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eMIPSAse_micromips);
13970b57cec5SDimitry Andric       break;
13980b57cec5SDimitry Andric     case llvm::ELF::EF_MIPS_ARCH_ASE_M16:
13990b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eMIPSAse_mips16);
14000b57cec5SDimitry Andric       break;
14010b57cec5SDimitry Andric     case llvm::ELF::EF_MIPS_ARCH_ASE_MDMX:
14020b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eMIPSAse_mdmx);
14030b57cec5SDimitry Andric       break;
14040b57cec5SDimitry Andric     default:
14050b57cec5SDimitry Andric       break;
14060b57cec5SDimitry Andric     }
14070b57cec5SDimitry Andric   }
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric   if (arch_spec.GetMachine() == llvm::Triple::arm ||
14100b57cec5SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::thumb) {
14110b57cec5SDimitry Andric     if (header.e_flags & llvm::ELF::EF_ARM_SOFT_FLOAT)
14120b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
14130b57cec5SDimitry Andric     else if (header.e_flags & llvm::ELF::EF_ARM_VFP_FLOAT)
14140b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
14150b57cec5SDimitry Andric   }
14160b57cec5SDimitry Andric 
141781ad6265SDimitry Andric   if (arch_spec.GetMachine() == llvm::Triple::riscv32 ||
141881ad6265SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::riscv64) {
141981ad6265SDimitry Andric     uint32_t flags = arch_spec.GetFlags();
142081ad6265SDimitry Andric 
142181ad6265SDimitry Andric     if (header.e_flags & llvm::ELF::EF_RISCV_RVC)
142281ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_rvc;
142381ad6265SDimitry Andric     if (header.e_flags & llvm::ELF::EF_RISCV_RVE)
142481ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_rve;
142581ad6265SDimitry Andric 
142681ad6265SDimitry Andric     if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_SINGLE) ==
142781ad6265SDimitry Andric         llvm::ELF::EF_RISCV_FLOAT_ABI_SINGLE)
142881ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_float_abi_single;
142981ad6265SDimitry Andric     else if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_DOUBLE) ==
143081ad6265SDimitry Andric              llvm::ELF::EF_RISCV_FLOAT_ABI_DOUBLE)
143181ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_float_abi_double;
143281ad6265SDimitry Andric     else if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_QUAD) ==
143381ad6265SDimitry Andric              llvm::ELF::EF_RISCV_FLOAT_ABI_QUAD)
143481ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_float_abi_quad;
143581ad6265SDimitry Andric 
143681ad6265SDimitry Andric     arch_spec.SetFlags(flags);
143781ad6265SDimitry Andric   }
143881ad6265SDimitry Andric 
14390b57cec5SDimitry Andric   // If there are no section headers we are done.
14400b57cec5SDimitry Andric   if (header.e_shnum == 0)
14410b57cec5SDimitry Andric     return 0;
14420b57cec5SDimitry Andric 
144381ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Modules);
14440b57cec5SDimitry Andric 
14450b57cec5SDimitry Andric   section_headers.resize(header.e_shnum);
14460b57cec5SDimitry Andric   if (section_headers.size() != header.e_shnum)
14470b57cec5SDimitry Andric     return 0;
14480b57cec5SDimitry Andric 
14490b57cec5SDimitry Andric   const size_t sh_size = header.e_shnum * header.e_shentsize;
14500b57cec5SDimitry Andric   const elf_off sh_offset = header.e_shoff;
14510b57cec5SDimitry Andric   DataExtractor sh_data;
14520b57cec5SDimitry Andric   if (sh_data.SetData(object_data, sh_offset, sh_size) != sh_size)
14530b57cec5SDimitry Andric     return 0;
14540b57cec5SDimitry Andric 
14550b57cec5SDimitry Andric   uint32_t idx;
14560b57cec5SDimitry Andric   lldb::offset_t offset;
14570b57cec5SDimitry Andric   for (idx = 0, offset = 0; idx < header.e_shnum; ++idx) {
14580b57cec5SDimitry Andric     if (!section_headers[idx].Parse(sh_data, &offset))
14590b57cec5SDimitry Andric       break;
14600b57cec5SDimitry Andric   }
14610b57cec5SDimitry Andric   if (idx < section_headers.size())
14620b57cec5SDimitry Andric     section_headers.resize(idx);
14630b57cec5SDimitry Andric 
14640b57cec5SDimitry Andric   const unsigned strtab_idx = header.e_shstrndx;
14650b57cec5SDimitry Andric   if (strtab_idx && strtab_idx < section_headers.size()) {
14660b57cec5SDimitry Andric     const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];
14670b57cec5SDimitry Andric     const size_t byte_size = sheader.sh_size;
14680b57cec5SDimitry Andric     const Elf64_Off offset = sheader.sh_offset;
14690b57cec5SDimitry Andric     lldb_private::DataExtractor shstr_data;
14700b57cec5SDimitry Andric 
14710b57cec5SDimitry Andric     if (shstr_data.SetData(object_data, offset, byte_size) == byte_size) {
14720b57cec5SDimitry Andric       for (SectionHeaderCollIter I = section_headers.begin();
14730b57cec5SDimitry Andric            I != section_headers.end(); ++I) {
14740b57cec5SDimitry Andric         static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");
14750b57cec5SDimitry Andric         const ELFSectionHeaderInfo &sheader = *I;
14760b57cec5SDimitry Andric         const uint64_t section_size =
14770b57cec5SDimitry Andric             sheader.sh_type == SHT_NOBITS ? 0 : sheader.sh_size;
14780b57cec5SDimitry Andric         ConstString name(shstr_data.PeekCStr(I->sh_name));
14790b57cec5SDimitry Andric 
14800b57cec5SDimitry Andric         I->section_name = name;
14810b57cec5SDimitry Andric 
14820b57cec5SDimitry Andric         if (arch_spec.IsMIPS()) {
14830b57cec5SDimitry Andric           uint32_t arch_flags = arch_spec.GetFlags();
14840b57cec5SDimitry Andric           DataExtractor data;
14850b57cec5SDimitry Andric           if (sheader.sh_type == SHT_MIPS_ABIFLAGS) {
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric             if (section_size && (data.SetData(object_data, sheader.sh_offset,
14880b57cec5SDimitry Andric                                               section_size) == section_size)) {
14890b57cec5SDimitry Andric               // MIPS ASE Mask is at offset 12 in MIPS.abiflags section
14900b57cec5SDimitry Andric               lldb::offset_t offset = 12; // MIPS ABI Flags Version: 0
14910b57cec5SDimitry Andric               arch_flags |= data.GetU32(&offset);
14920b57cec5SDimitry Andric 
14930b57cec5SDimitry Andric               // The floating point ABI is at offset 7
14940b57cec5SDimitry Andric               offset = 7;
14950b57cec5SDimitry Andric               switch (data.GetU8(&offset)) {
14960b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_ANY:
14970b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_ANY;
14980b57cec5SDimitry Andric                 break;
14990b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_DOUBLE:
15000b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_DOUBLE;
15010b57cec5SDimitry Andric                 break;
15020b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_SINGLE:
15030b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SINGLE;
15040b57cec5SDimitry Andric                 break;
15050b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_SOFT:
15060b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SOFT;
15070b57cec5SDimitry Andric                 break;
15080b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_OLD_64:
15090b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_OLD_64;
15100b57cec5SDimitry Andric                 break;
15110b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_XX:
15120b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_XX;
15130b57cec5SDimitry Andric                 break;
15140b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_64:
15150b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64;
15160b57cec5SDimitry Andric                 break;
15170b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_64A:
15180b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64A;
15190b57cec5SDimitry Andric                 break;
15200b57cec5SDimitry Andric               }
15210b57cec5SDimitry Andric             }
15220b57cec5SDimitry Andric           }
15230b57cec5SDimitry Andric           // Settings appropriate ArchSpec ABI Flags
15240b57cec5SDimitry Andric           switch (header.e_flags & llvm::ELF::EF_MIPS_ABI) {
15250b57cec5SDimitry Andric           case llvm::ELF::EF_MIPS_ABI_O32:
15260b57cec5SDimitry Andric             arch_flags |= lldb_private::ArchSpec::eMIPSABI_O32;
15270b57cec5SDimitry Andric             break;
15280b57cec5SDimitry Andric           case EF_MIPS_ABI_O64:
15290b57cec5SDimitry Andric             arch_flags |= lldb_private::ArchSpec::eMIPSABI_O64;
15300b57cec5SDimitry Andric             break;
15310b57cec5SDimitry Andric           case EF_MIPS_ABI_EABI32:
15320b57cec5SDimitry Andric             arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI32;
15330b57cec5SDimitry Andric             break;
15340b57cec5SDimitry Andric           case EF_MIPS_ABI_EABI64:
15350b57cec5SDimitry Andric             arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI64;
15360b57cec5SDimitry Andric             break;
15370b57cec5SDimitry Andric           default:
15380b57cec5SDimitry Andric             // ABI Mask doesn't cover N32 and N64 ABI.
15390b57cec5SDimitry Andric             if (header.e_ident[EI_CLASS] == llvm::ELF::ELFCLASS64)
15400b57cec5SDimitry Andric               arch_flags |= lldb_private::ArchSpec::eMIPSABI_N64;
15410b57cec5SDimitry Andric             else if (header.e_flags & llvm::ELF::EF_MIPS_ABI2)
15420b57cec5SDimitry Andric               arch_flags |= lldb_private::ArchSpec::eMIPSABI_N32;
15430b57cec5SDimitry Andric             break;
15440b57cec5SDimitry Andric           }
15450b57cec5SDimitry Andric           arch_spec.SetFlags(arch_flags);
15460b57cec5SDimitry Andric         }
15470b57cec5SDimitry Andric 
15480b57cec5SDimitry Andric         if (arch_spec.GetMachine() == llvm::Triple::arm ||
15490b57cec5SDimitry Andric             arch_spec.GetMachine() == llvm::Triple::thumb) {
15500b57cec5SDimitry Andric           DataExtractor data;
15510b57cec5SDimitry Andric 
15520b57cec5SDimitry Andric           if (sheader.sh_type == SHT_ARM_ATTRIBUTES && section_size != 0 &&
15530b57cec5SDimitry Andric               data.SetData(object_data, sheader.sh_offset, section_size) == section_size)
15540b57cec5SDimitry Andric             ParseARMAttributes(data, section_size, arch_spec);
15550b57cec5SDimitry Andric         }
15560b57cec5SDimitry Andric 
15570b57cec5SDimitry Andric         if (name == g_sect_name_gnu_debuglink) {
15580b57cec5SDimitry Andric           DataExtractor data;
15590b57cec5SDimitry Andric           if (section_size && (data.SetData(object_data, sheader.sh_offset,
15600b57cec5SDimitry Andric                                             section_size) == section_size)) {
15610b57cec5SDimitry Andric             lldb::offset_t gnu_debuglink_offset = 0;
15620b57cec5SDimitry Andric             gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);
15630b57cec5SDimitry Andric             gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
15640b57cec5SDimitry Andric             data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
15650b57cec5SDimitry Andric           }
15660b57cec5SDimitry Andric         }
15670b57cec5SDimitry Andric 
15680b57cec5SDimitry Andric         // Process ELF note section entries.
15690b57cec5SDimitry Andric         bool is_note_header = (sheader.sh_type == SHT_NOTE);
15700b57cec5SDimitry Andric 
15710b57cec5SDimitry Andric         // The section header ".note.android.ident" is stored as a
15720b57cec5SDimitry Andric         // PROGBITS type header but it is actually a note header.
15730b57cec5SDimitry Andric         static ConstString g_sect_name_android_ident(".note.android.ident");
15740b57cec5SDimitry Andric         if (!is_note_header && name == g_sect_name_android_ident)
15750b57cec5SDimitry Andric           is_note_header = true;
15760b57cec5SDimitry Andric 
15770b57cec5SDimitry Andric         if (is_note_header) {
15780b57cec5SDimitry Andric           // Allow notes to refine module info.
15790b57cec5SDimitry Andric           DataExtractor data;
15800b57cec5SDimitry Andric           if (section_size && (data.SetData(object_data, sheader.sh_offset,
15810b57cec5SDimitry Andric                                             section_size) == section_size)) {
15820b57cec5SDimitry Andric             Status error = RefineModuleDetailsFromNote(data, arch_spec, uuid);
15830b57cec5SDimitry Andric             if (error.Fail()) {
15849dba64beSDimitry Andric               LLDB_LOGF(log, "ObjectFileELF::%s ELF note processing failed: %s",
15850b57cec5SDimitry Andric                         __FUNCTION__, error.AsCString());
15860b57cec5SDimitry Andric             }
15870b57cec5SDimitry Andric           }
15880b57cec5SDimitry Andric         }
15890b57cec5SDimitry Andric       }
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric       // Make any unknown triple components to be unspecified unknowns.
15920b57cec5SDimitry Andric       if (arch_spec.GetTriple().getVendor() == llvm::Triple::UnknownVendor)
15930b57cec5SDimitry Andric         arch_spec.GetTriple().setVendorName(llvm::StringRef());
15940b57cec5SDimitry Andric       if (arch_spec.GetTriple().getOS() == llvm::Triple::UnknownOS)
15950b57cec5SDimitry Andric         arch_spec.GetTriple().setOSName(llvm::StringRef());
15960b57cec5SDimitry Andric 
15970b57cec5SDimitry Andric       return section_headers.size();
15980b57cec5SDimitry Andric     }
15990b57cec5SDimitry Andric   }
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric   section_headers.clear();
16020b57cec5SDimitry Andric   return 0;
16030b57cec5SDimitry Andric }
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric llvm::StringRef
16060b57cec5SDimitry Andric ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const {
16070b57cec5SDimitry Andric   size_t pos = symbol_name.find('@');
16080b57cec5SDimitry Andric   return symbol_name.substr(0, pos);
16090b57cec5SDimitry Andric }
16100b57cec5SDimitry Andric 
16110b57cec5SDimitry Andric // ParseSectionHeaders
16120b57cec5SDimitry Andric size_t ObjectFileELF::ParseSectionHeaders() {
16130b57cec5SDimitry Andric   return GetSectionHeaderInfo(m_section_headers, m_data, m_header, m_uuid,
16140b57cec5SDimitry Andric                               m_gnu_debuglink_file, m_gnu_debuglink_crc,
16150b57cec5SDimitry Andric                               m_arch_spec);
16160b57cec5SDimitry Andric }
16170b57cec5SDimitry Andric 
16180b57cec5SDimitry Andric const ObjectFileELF::ELFSectionHeaderInfo *
16190b57cec5SDimitry Andric ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id) {
16200b57cec5SDimitry Andric   if (!ParseSectionHeaders())
16210b57cec5SDimitry Andric     return nullptr;
16220b57cec5SDimitry Andric 
16230b57cec5SDimitry Andric   if (id < m_section_headers.size())
16240b57cec5SDimitry Andric     return &m_section_headers[id];
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric   return nullptr;
16270b57cec5SDimitry Andric }
16280b57cec5SDimitry Andric 
16290b57cec5SDimitry Andric lldb::user_id_t ObjectFileELF::GetSectionIndexByName(const char *name) {
16300b57cec5SDimitry Andric   if (!name || !name[0] || !ParseSectionHeaders())
16310b57cec5SDimitry Andric     return 0;
16320b57cec5SDimitry Andric   for (size_t i = 1; i < m_section_headers.size(); ++i)
16330b57cec5SDimitry Andric     if (m_section_headers[i].section_name == ConstString(name))
16340b57cec5SDimitry Andric       return i;
16350b57cec5SDimitry Andric   return 0;
16360b57cec5SDimitry Andric }
16370b57cec5SDimitry Andric 
16380b57cec5SDimitry Andric static SectionType GetSectionTypeFromName(llvm::StringRef Name) {
1639fcaf7f86SDimitry Andric   if (Name.consume_front(".debug_")) {
16400b57cec5SDimitry Andric     return llvm::StringSwitch<SectionType>(Name)
16410b57cec5SDimitry Andric         .Case("abbrev", eSectionTypeDWARFDebugAbbrev)
16420b57cec5SDimitry Andric         .Case("abbrev.dwo", eSectionTypeDWARFDebugAbbrevDwo)
16430b57cec5SDimitry Andric         .Case("addr", eSectionTypeDWARFDebugAddr)
16440b57cec5SDimitry Andric         .Case("aranges", eSectionTypeDWARFDebugAranges)
16450b57cec5SDimitry Andric         .Case("cu_index", eSectionTypeDWARFDebugCuIndex)
16460b57cec5SDimitry Andric         .Case("frame", eSectionTypeDWARFDebugFrame)
16470b57cec5SDimitry Andric         .Case("info", eSectionTypeDWARFDebugInfo)
16480b57cec5SDimitry Andric         .Case("info.dwo", eSectionTypeDWARFDebugInfoDwo)
16490b57cec5SDimitry Andric         .Cases("line", "line.dwo", eSectionTypeDWARFDebugLine)
16500b57cec5SDimitry Andric         .Cases("line_str", "line_str.dwo", eSectionTypeDWARFDebugLineStr)
1651480093f4SDimitry Andric         .Case("loc", eSectionTypeDWARFDebugLoc)
1652480093f4SDimitry Andric         .Case("loc.dwo", eSectionTypeDWARFDebugLocDwo)
1653480093f4SDimitry Andric         .Case("loclists", eSectionTypeDWARFDebugLocLists)
1654480093f4SDimitry Andric         .Case("loclists.dwo", eSectionTypeDWARFDebugLocListsDwo)
16550b57cec5SDimitry Andric         .Case("macinfo", eSectionTypeDWARFDebugMacInfo)
16560b57cec5SDimitry Andric         .Cases("macro", "macro.dwo", eSectionTypeDWARFDebugMacro)
16570b57cec5SDimitry Andric         .Case("names", eSectionTypeDWARFDebugNames)
16580b57cec5SDimitry Andric         .Case("pubnames", eSectionTypeDWARFDebugPubNames)
16590b57cec5SDimitry Andric         .Case("pubtypes", eSectionTypeDWARFDebugPubTypes)
16600b57cec5SDimitry Andric         .Case("ranges", eSectionTypeDWARFDebugRanges)
16610b57cec5SDimitry Andric         .Case("rnglists", eSectionTypeDWARFDebugRngLists)
1662480093f4SDimitry Andric         .Case("rnglists.dwo", eSectionTypeDWARFDebugRngListsDwo)
16630b57cec5SDimitry Andric         .Case("str", eSectionTypeDWARFDebugStr)
16640b57cec5SDimitry Andric         .Case("str.dwo", eSectionTypeDWARFDebugStrDwo)
16650b57cec5SDimitry Andric         .Case("str_offsets", eSectionTypeDWARFDebugStrOffsets)
16660b57cec5SDimitry Andric         .Case("str_offsets.dwo", eSectionTypeDWARFDebugStrOffsetsDwo)
16675ffd83dbSDimitry Andric         .Case("tu_index", eSectionTypeDWARFDebugTuIndex)
16680b57cec5SDimitry Andric         .Case("types", eSectionTypeDWARFDebugTypes)
16690b57cec5SDimitry Andric         .Case("types.dwo", eSectionTypeDWARFDebugTypesDwo)
16700b57cec5SDimitry Andric         .Default(eSectionTypeOther);
16710b57cec5SDimitry Andric   }
16720b57cec5SDimitry Andric   return llvm::StringSwitch<SectionType>(Name)
16730b57cec5SDimitry Andric       .Case(".ARM.exidx", eSectionTypeARMexidx)
16740b57cec5SDimitry Andric       .Case(".ARM.extab", eSectionTypeARMextab)
16750b57cec5SDimitry Andric       .Cases(".bss", ".tbss", eSectionTypeZeroFill)
1676*fe013be4SDimitry Andric       .Case(".ctf", eSectionTypeDebug)
16770b57cec5SDimitry Andric       .Cases(".data", ".tdata", eSectionTypeData)
16780b57cec5SDimitry Andric       .Case(".eh_frame", eSectionTypeEHFrame)
16790b57cec5SDimitry Andric       .Case(".gnu_debugaltlink", eSectionTypeDWARFGNUDebugAltLink)
16800b57cec5SDimitry Andric       .Case(".gosymtab", eSectionTypeGoSymtab)
16810b57cec5SDimitry Andric       .Case(".text", eSectionTypeCode)
16820b57cec5SDimitry Andric       .Default(eSectionTypeOther);
16830b57cec5SDimitry Andric }
16840b57cec5SDimitry Andric 
16850b57cec5SDimitry Andric SectionType ObjectFileELF::GetSectionType(const ELFSectionHeaderInfo &H) const {
16860b57cec5SDimitry Andric   switch (H.sh_type) {
16870b57cec5SDimitry Andric   case SHT_PROGBITS:
16880b57cec5SDimitry Andric     if (H.sh_flags & SHF_EXECINSTR)
16890b57cec5SDimitry Andric       return eSectionTypeCode;
16900b57cec5SDimitry Andric     break;
16910b57cec5SDimitry Andric   case SHT_SYMTAB:
16920b57cec5SDimitry Andric     return eSectionTypeELFSymbolTable;
16930b57cec5SDimitry Andric   case SHT_DYNSYM:
16940b57cec5SDimitry Andric     return eSectionTypeELFDynamicSymbols;
16950b57cec5SDimitry Andric   case SHT_RELA:
16960b57cec5SDimitry Andric   case SHT_REL:
16970b57cec5SDimitry Andric     return eSectionTypeELFRelocationEntries;
16980b57cec5SDimitry Andric   case SHT_DYNAMIC:
16990b57cec5SDimitry Andric     return eSectionTypeELFDynamicLinkInfo;
17000b57cec5SDimitry Andric   }
17010b57cec5SDimitry Andric   return GetSectionTypeFromName(H.section_name.GetStringRef());
17020b57cec5SDimitry Andric }
17030b57cec5SDimitry Andric 
17040b57cec5SDimitry Andric static uint32_t GetTargetByteSize(SectionType Type, const ArchSpec &arch) {
17050b57cec5SDimitry Andric   switch (Type) {
17060b57cec5SDimitry Andric   case eSectionTypeData:
17070b57cec5SDimitry Andric   case eSectionTypeZeroFill:
17080b57cec5SDimitry Andric     return arch.GetDataByteSize();
17090b57cec5SDimitry Andric   case eSectionTypeCode:
17100b57cec5SDimitry Andric     return arch.GetCodeByteSize();
17110b57cec5SDimitry Andric   default:
17120b57cec5SDimitry Andric     return 1;
17130b57cec5SDimitry Andric   }
17140b57cec5SDimitry Andric }
17150b57cec5SDimitry Andric 
17160b57cec5SDimitry Andric static Permissions GetPermissions(const ELFSectionHeader &H) {
17170b57cec5SDimitry Andric   Permissions Perm = Permissions(0);
17180b57cec5SDimitry Andric   if (H.sh_flags & SHF_ALLOC)
17190b57cec5SDimitry Andric     Perm |= ePermissionsReadable;
17200b57cec5SDimitry Andric   if (H.sh_flags & SHF_WRITE)
17210b57cec5SDimitry Andric     Perm |= ePermissionsWritable;
17220b57cec5SDimitry Andric   if (H.sh_flags & SHF_EXECINSTR)
17230b57cec5SDimitry Andric     Perm |= ePermissionsExecutable;
17240b57cec5SDimitry Andric   return Perm;
17250b57cec5SDimitry Andric }
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric static Permissions GetPermissions(const ELFProgramHeader &H) {
17280b57cec5SDimitry Andric   Permissions Perm = Permissions(0);
17290b57cec5SDimitry Andric   if (H.p_flags & PF_R)
17300b57cec5SDimitry Andric     Perm |= ePermissionsReadable;
17310b57cec5SDimitry Andric   if (H.p_flags & PF_W)
17320b57cec5SDimitry Andric     Perm |= ePermissionsWritable;
17330b57cec5SDimitry Andric   if (H.p_flags & PF_X)
17340b57cec5SDimitry Andric     Perm |= ePermissionsExecutable;
17350b57cec5SDimitry Andric   return Perm;
17360b57cec5SDimitry Andric }
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric namespace {
17390b57cec5SDimitry Andric 
17400b57cec5SDimitry Andric using VMRange = lldb_private::Range<addr_t, addr_t>;
17410b57cec5SDimitry Andric 
17420b57cec5SDimitry Andric struct SectionAddressInfo {
17430b57cec5SDimitry Andric   SectionSP Segment;
17440b57cec5SDimitry Andric   VMRange Range;
17450b57cec5SDimitry Andric };
17460b57cec5SDimitry Andric 
17470b57cec5SDimitry Andric // (Unlinked) ELF object files usually have 0 for every section address, meaning
17480b57cec5SDimitry Andric // we need to compute synthetic addresses in order for "file addresses" from
17490b57cec5SDimitry Andric // different sections to not overlap. This class handles that logic.
17500b57cec5SDimitry Andric class VMAddressProvider {
17510b57cec5SDimitry Andric   using VMMap = llvm::IntervalMap<addr_t, SectionSP, 4,
17520b57cec5SDimitry Andric                                        llvm::IntervalMapHalfOpenInfo<addr_t>>;
17530b57cec5SDimitry Andric 
17540b57cec5SDimitry Andric   ObjectFile::Type ObjectType;
17550b57cec5SDimitry Andric   addr_t NextVMAddress = 0;
17560b57cec5SDimitry Andric   VMMap::Allocator Alloc;
175781ad6265SDimitry Andric   VMMap Segments{Alloc};
175881ad6265SDimitry Andric   VMMap Sections{Alloc};
175981ad6265SDimitry Andric   lldb_private::Log *Log = GetLog(LLDBLog::Modules);
17609dba64beSDimitry Andric   size_t SegmentCount = 0;
17619dba64beSDimitry Andric   std::string SegmentName;
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric   VMRange GetVMRange(const ELFSectionHeader &H) {
17640b57cec5SDimitry Andric     addr_t Address = H.sh_addr;
17650b57cec5SDimitry Andric     addr_t Size = H.sh_flags & SHF_ALLOC ? H.sh_size : 0;
17660b57cec5SDimitry Andric     if (ObjectType == ObjectFile::Type::eTypeObjectFile && Segments.empty() && (H.sh_flags & SHF_ALLOC)) {
17670b57cec5SDimitry Andric       NextVMAddress =
17680b57cec5SDimitry Andric           llvm::alignTo(NextVMAddress, std::max<addr_t>(H.sh_addralign, 1));
17690b57cec5SDimitry Andric       Address = NextVMAddress;
17700b57cec5SDimitry Andric       NextVMAddress += Size;
17710b57cec5SDimitry Andric     }
17720b57cec5SDimitry Andric     return VMRange(Address, Size);
17730b57cec5SDimitry Andric   }
17740b57cec5SDimitry Andric 
17750b57cec5SDimitry Andric public:
17769dba64beSDimitry Andric   VMAddressProvider(ObjectFile::Type Type, llvm::StringRef SegmentName)
17775ffd83dbSDimitry Andric       : ObjectType(Type), SegmentName(std::string(SegmentName)) {}
17789dba64beSDimitry Andric 
17799dba64beSDimitry Andric   std::string GetNextSegmentName() const {
17809dba64beSDimitry Andric     return llvm::formatv("{0}[{1}]", SegmentName, SegmentCount).str();
17819dba64beSDimitry Andric   }
17820b57cec5SDimitry Andric 
1783bdd1243dSDimitry Andric   std::optional<VMRange> GetAddressInfo(const ELFProgramHeader &H) {
17840b57cec5SDimitry Andric     if (H.p_memsz == 0) {
17859dba64beSDimitry Andric       LLDB_LOG(Log, "Ignoring zero-sized {0} segment. Corrupt object file?",
17869dba64beSDimitry Andric                SegmentName);
1787bdd1243dSDimitry Andric       return std::nullopt;
17880b57cec5SDimitry Andric     }
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric     if (Segments.overlaps(H.p_vaddr, H.p_vaddr + H.p_memsz)) {
17919dba64beSDimitry Andric       LLDB_LOG(Log, "Ignoring overlapping {0} segment. Corrupt object file?",
17929dba64beSDimitry Andric                SegmentName);
1793bdd1243dSDimitry Andric       return std::nullopt;
17940b57cec5SDimitry Andric     }
17950b57cec5SDimitry Andric     return VMRange(H.p_vaddr, H.p_memsz);
17960b57cec5SDimitry Andric   }
17970b57cec5SDimitry Andric 
1798bdd1243dSDimitry Andric   std::optional<SectionAddressInfo> GetAddressInfo(const ELFSectionHeader &H) {
17990b57cec5SDimitry Andric     VMRange Range = GetVMRange(H);
18000b57cec5SDimitry Andric     SectionSP Segment;
18010b57cec5SDimitry Andric     auto It = Segments.find(Range.GetRangeBase());
18020b57cec5SDimitry Andric     if ((H.sh_flags & SHF_ALLOC) && It.valid()) {
18030b57cec5SDimitry Andric       addr_t MaxSize;
18040b57cec5SDimitry Andric       if (It.start() <= Range.GetRangeBase()) {
18050b57cec5SDimitry Andric         MaxSize = It.stop() - Range.GetRangeBase();
18060b57cec5SDimitry Andric         Segment = *It;
18070b57cec5SDimitry Andric       } else
18080b57cec5SDimitry Andric         MaxSize = It.start() - Range.GetRangeBase();
18090b57cec5SDimitry Andric       if (Range.GetByteSize() > MaxSize) {
18100b57cec5SDimitry Andric         LLDB_LOG(Log, "Shortening section crossing segment boundaries. "
18110b57cec5SDimitry Andric                       "Corrupt object file?");
18120b57cec5SDimitry Andric         Range.SetByteSize(MaxSize);
18130b57cec5SDimitry Andric       }
18140b57cec5SDimitry Andric     }
18150b57cec5SDimitry Andric     if (Range.GetByteSize() > 0 &&
18160b57cec5SDimitry Andric         Sections.overlaps(Range.GetRangeBase(), Range.GetRangeEnd())) {
18170b57cec5SDimitry Andric       LLDB_LOG(Log, "Ignoring overlapping section. Corrupt object file?");
1818bdd1243dSDimitry Andric       return std::nullopt;
18190b57cec5SDimitry Andric     }
18200b57cec5SDimitry Andric     if (Segment)
18210b57cec5SDimitry Andric       Range.Slide(-Segment->GetFileAddress());
18220b57cec5SDimitry Andric     return SectionAddressInfo{Segment, Range};
18230b57cec5SDimitry Andric   }
18240b57cec5SDimitry Andric 
18250b57cec5SDimitry Andric   void AddSegment(const VMRange &Range, SectionSP Seg) {
18260b57cec5SDimitry Andric     Segments.insert(Range.GetRangeBase(), Range.GetRangeEnd(), std::move(Seg));
18279dba64beSDimitry Andric     ++SegmentCount;
18280b57cec5SDimitry Andric   }
18290b57cec5SDimitry Andric 
18300b57cec5SDimitry Andric   void AddSection(SectionAddressInfo Info, SectionSP Sect) {
18310b57cec5SDimitry Andric     if (Info.Range.GetByteSize() == 0)
18320b57cec5SDimitry Andric       return;
18330b57cec5SDimitry Andric     if (Info.Segment)
18340b57cec5SDimitry Andric       Info.Range.Slide(Info.Segment->GetFileAddress());
18350b57cec5SDimitry Andric     Sections.insert(Info.Range.GetRangeBase(), Info.Range.GetRangeEnd(),
18360b57cec5SDimitry Andric                     std::move(Sect));
18370b57cec5SDimitry Andric   }
18380b57cec5SDimitry Andric };
18390b57cec5SDimitry Andric }
18400b57cec5SDimitry Andric 
18410b57cec5SDimitry Andric void ObjectFileELF::CreateSections(SectionList &unified_section_list) {
18420b57cec5SDimitry Andric   if (m_sections_up)
18430b57cec5SDimitry Andric     return;
18440b57cec5SDimitry Andric 
18459dba64beSDimitry Andric   m_sections_up = std::make_unique<SectionList>();
18469dba64beSDimitry Andric   VMAddressProvider regular_provider(GetType(), "PT_LOAD");
18479dba64beSDimitry Andric   VMAddressProvider tls_provider(GetType(), "PT_TLS");
18480b57cec5SDimitry Andric 
18490b57cec5SDimitry Andric   for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {
18500b57cec5SDimitry Andric     const ELFProgramHeader &PHdr = EnumPHdr.value();
18519dba64beSDimitry Andric     if (PHdr.p_type != PT_LOAD && PHdr.p_type != PT_TLS)
18520b57cec5SDimitry Andric       continue;
18530b57cec5SDimitry Andric 
18549dba64beSDimitry Andric     VMAddressProvider &provider =
18559dba64beSDimitry Andric         PHdr.p_type == PT_TLS ? tls_provider : regular_provider;
18569dba64beSDimitry Andric     auto InfoOr = provider.GetAddressInfo(PHdr);
18570b57cec5SDimitry Andric     if (!InfoOr)
18580b57cec5SDimitry Andric       continue;
18590b57cec5SDimitry Andric 
18600b57cec5SDimitry Andric     uint32_t Log2Align = llvm::Log2_64(std::max<elf_xword>(PHdr.p_align, 1));
18610b57cec5SDimitry Andric     SectionSP Segment = std::make_shared<Section>(
18629dba64beSDimitry Andric         GetModule(), this, SegmentID(EnumPHdr.index()),
18639dba64beSDimitry Andric         ConstString(provider.GetNextSegmentName()), eSectionTypeContainer,
18649dba64beSDimitry Andric         InfoOr->GetRangeBase(), InfoOr->GetByteSize(), PHdr.p_offset,
18659dba64beSDimitry Andric         PHdr.p_filesz, Log2Align, /*flags*/ 0);
18660b57cec5SDimitry Andric     Segment->SetPermissions(GetPermissions(PHdr));
18679dba64beSDimitry Andric     Segment->SetIsThreadSpecific(PHdr.p_type == PT_TLS);
18680b57cec5SDimitry Andric     m_sections_up->AddSection(Segment);
18690b57cec5SDimitry Andric 
18709dba64beSDimitry Andric     provider.AddSegment(*InfoOr, std::move(Segment));
18710b57cec5SDimitry Andric   }
18720b57cec5SDimitry Andric 
18730b57cec5SDimitry Andric   ParseSectionHeaders();
18740b57cec5SDimitry Andric   if (m_section_headers.empty())
18750b57cec5SDimitry Andric     return;
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric   for (SectionHeaderCollIter I = std::next(m_section_headers.begin());
18780b57cec5SDimitry Andric        I != m_section_headers.end(); ++I) {
18790b57cec5SDimitry Andric     const ELFSectionHeaderInfo &header = *I;
18800b57cec5SDimitry Andric 
18810b57cec5SDimitry Andric     ConstString &name = I->section_name;
18820b57cec5SDimitry Andric     const uint64_t file_size =
18830b57cec5SDimitry Andric         header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
18840b57cec5SDimitry Andric 
18859dba64beSDimitry Andric     VMAddressProvider &provider =
18869dba64beSDimitry Andric         header.sh_flags & SHF_TLS ? tls_provider : regular_provider;
18879dba64beSDimitry Andric     auto InfoOr = provider.GetAddressInfo(header);
18880b57cec5SDimitry Andric     if (!InfoOr)
18890b57cec5SDimitry Andric       continue;
18900b57cec5SDimitry Andric 
18910b57cec5SDimitry Andric     SectionType sect_type = GetSectionType(header);
18920b57cec5SDimitry Andric 
18930b57cec5SDimitry Andric     const uint32_t target_bytes_size =
18940b57cec5SDimitry Andric         GetTargetByteSize(sect_type, m_arch_spec);
18950b57cec5SDimitry Andric 
18960b57cec5SDimitry Andric     elf::elf_xword log2align =
18970b57cec5SDimitry Andric         (header.sh_addralign == 0) ? 0 : llvm::Log2_64(header.sh_addralign);
18980b57cec5SDimitry Andric 
18990b57cec5SDimitry Andric     SectionSP section_sp(new Section(
19000b57cec5SDimitry Andric         InfoOr->Segment, GetModule(), // Module to which this section belongs.
19010b57cec5SDimitry Andric         this,            // ObjectFile to which this section belongs and should
19020b57cec5SDimitry Andric                          // read section data from.
19030b57cec5SDimitry Andric         SectionIndex(I), // Section ID.
19040b57cec5SDimitry Andric         name,            // Section name.
19050b57cec5SDimitry Andric         sect_type,       // Section type.
19060b57cec5SDimitry Andric         InfoOr->Range.GetRangeBase(), // VM address.
19070b57cec5SDimitry Andric         InfoOr->Range.GetByteSize(),  // VM size in bytes of this section.
19080b57cec5SDimitry Andric         header.sh_offset,             // Offset of this section in the file.
19090b57cec5SDimitry Andric         file_size,           // Size of the section as found in the file.
19100b57cec5SDimitry Andric         log2align,           // Alignment of the section
19110b57cec5SDimitry Andric         header.sh_flags,     // Flags for this section.
19120b57cec5SDimitry Andric         target_bytes_size)); // Number of host bytes per target byte
19130b57cec5SDimitry Andric 
19140b57cec5SDimitry Andric     section_sp->SetPermissions(GetPermissions(header));
19150b57cec5SDimitry Andric     section_sp->SetIsThreadSpecific(header.sh_flags & SHF_TLS);
19160b57cec5SDimitry Andric     (InfoOr->Segment ? InfoOr->Segment->GetChildren() : *m_sections_up)
19170b57cec5SDimitry Andric         .AddSection(section_sp);
19189dba64beSDimitry Andric     provider.AddSection(std::move(*InfoOr), std::move(section_sp));
19190b57cec5SDimitry Andric   }
19200b57cec5SDimitry Andric 
19210b57cec5SDimitry Andric   // For eTypeDebugInfo files, the Symbol Vendor will take care of updating the
19220b57cec5SDimitry Andric   // unified section list.
19230b57cec5SDimitry Andric   if (GetType() != eTypeDebugInfo)
19240b57cec5SDimitry Andric     unified_section_list = *m_sections_up;
19259dba64beSDimitry Andric 
19269dba64beSDimitry Andric   // If there's a .gnu_debugdata section, we'll try to read the .symtab that's
19279dba64beSDimitry Andric   // embedded in there and replace the one in the original object file (if any).
19289dba64beSDimitry Andric   // If there's none in the orignal object file, we add it to it.
19299dba64beSDimitry Andric   if (auto gdd_obj_file = GetGnuDebugDataObjectFile()) {
19309dba64beSDimitry Andric     if (auto gdd_objfile_section_list = gdd_obj_file->GetSectionList()) {
19319dba64beSDimitry Andric       if (SectionSP symtab_section_sp =
19329dba64beSDimitry Andric               gdd_objfile_section_list->FindSectionByType(
19339dba64beSDimitry Andric                   eSectionTypeELFSymbolTable, true)) {
19349dba64beSDimitry Andric         SectionSP module_section_sp = unified_section_list.FindSectionByType(
19359dba64beSDimitry Andric             eSectionTypeELFSymbolTable, true);
19369dba64beSDimitry Andric         if (module_section_sp)
19379dba64beSDimitry Andric           unified_section_list.ReplaceSection(module_section_sp->GetID(),
19389dba64beSDimitry Andric                                               symtab_section_sp);
19399dba64beSDimitry Andric         else
19409dba64beSDimitry Andric           unified_section_list.AddSection(symtab_section_sp);
19419dba64beSDimitry Andric       }
19429dba64beSDimitry Andric     }
19439dba64beSDimitry Andric   }
19449dba64beSDimitry Andric }
19459dba64beSDimitry Andric 
19469dba64beSDimitry Andric std::shared_ptr<ObjectFileELF> ObjectFileELF::GetGnuDebugDataObjectFile() {
19479dba64beSDimitry Andric   if (m_gnu_debug_data_object_file != nullptr)
19489dba64beSDimitry Andric     return m_gnu_debug_data_object_file;
19499dba64beSDimitry Andric 
19509dba64beSDimitry Andric   SectionSP section =
19519dba64beSDimitry Andric       GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata"));
19529dba64beSDimitry Andric   if (!section)
19539dba64beSDimitry Andric     return nullptr;
19549dba64beSDimitry Andric 
19559dba64beSDimitry Andric   if (!lldb_private::lzma::isAvailable()) {
19569dba64beSDimitry Andric     GetModule()->ReportWarning(
19579dba64beSDimitry Andric         "No LZMA support found for reading .gnu_debugdata section");
19589dba64beSDimitry Andric     return nullptr;
19599dba64beSDimitry Andric   }
19609dba64beSDimitry Andric 
19619dba64beSDimitry Andric   // Uncompress the data
19629dba64beSDimitry Andric   DataExtractor data;
19639dba64beSDimitry Andric   section->GetSectionData(data);
19649dba64beSDimitry Andric   llvm::SmallVector<uint8_t, 0> uncompressedData;
19659dba64beSDimitry Andric   auto err = lldb_private::lzma::uncompress(data.GetData(), uncompressedData);
19669dba64beSDimitry Andric   if (err) {
19679dba64beSDimitry Andric     GetModule()->ReportWarning(
1968bdd1243dSDimitry Andric         "An error occurred while decompression the section {0}: {1}",
19699dba64beSDimitry Andric         section->GetName().AsCString(), llvm::toString(std::move(err)).c_str());
19709dba64beSDimitry Andric     return nullptr;
19719dba64beSDimitry Andric   }
19729dba64beSDimitry Andric 
19739dba64beSDimitry Andric   // Construct ObjectFileELF object from decompressed buffer
19749dba64beSDimitry Andric   DataBufferSP gdd_data_buf(
19759dba64beSDimitry Andric       new DataBufferHeap(uncompressedData.data(), uncompressedData.size()));
19769dba64beSDimitry Andric   auto fspec = GetFileSpec().CopyByAppendingPathComponent(
19779dba64beSDimitry Andric       llvm::StringRef("gnu_debugdata"));
19789dba64beSDimitry Andric   m_gnu_debug_data_object_file.reset(new ObjectFileELF(
19799dba64beSDimitry Andric       GetModule(), gdd_data_buf, 0, &fspec, 0, gdd_data_buf->GetByteSize()));
19809dba64beSDimitry Andric 
19819dba64beSDimitry Andric   // This line is essential; otherwise a breakpoint can be set but not hit.
19829dba64beSDimitry Andric   m_gnu_debug_data_object_file->SetType(ObjectFile::eTypeDebugInfo);
19839dba64beSDimitry Andric 
19849dba64beSDimitry Andric   ArchSpec spec = m_gnu_debug_data_object_file->GetArchitecture();
19859dba64beSDimitry Andric   if (spec && m_gnu_debug_data_object_file->SetModulesArchitecture(spec))
19869dba64beSDimitry Andric     return m_gnu_debug_data_object_file;
19879dba64beSDimitry Andric 
19889dba64beSDimitry Andric   return nullptr;
19890b57cec5SDimitry Andric }
19900b57cec5SDimitry Andric 
19910b57cec5SDimitry Andric // Find the arm/aarch64 mapping symbol character in the given symbol name.
19920b57cec5SDimitry Andric // Mapping symbols have the form of "$<char>[.<any>]*". Additionally we
19930b57cec5SDimitry Andric // recognize cases when the mapping symbol prefixed by an arbitrary string
19940b57cec5SDimitry Andric // because if a symbol prefix added to each symbol in the object file with
19950b57cec5SDimitry Andric // objcopy then the mapping symbols are also prefixed.
19960b57cec5SDimitry Andric static char FindArmAarch64MappingSymbol(const char *symbol_name) {
19970b57cec5SDimitry Andric   if (!symbol_name)
19980b57cec5SDimitry Andric     return '\0';
19990b57cec5SDimitry Andric 
20000b57cec5SDimitry Andric   const char *dollar_pos = ::strchr(symbol_name, '$');
20010b57cec5SDimitry Andric   if (!dollar_pos || dollar_pos[1] == '\0')
20020b57cec5SDimitry Andric     return '\0';
20030b57cec5SDimitry Andric 
20040b57cec5SDimitry Andric   if (dollar_pos[2] == '\0' || dollar_pos[2] == '.')
20050b57cec5SDimitry Andric     return dollar_pos[1];
20060b57cec5SDimitry Andric   return '\0';
20070b57cec5SDimitry Andric }
20080b57cec5SDimitry Andric 
20090b57cec5SDimitry Andric #define STO_MIPS_ISA (3 << 6)
20100b57cec5SDimitry Andric #define STO_MICROMIPS (2 << 6)
20110b57cec5SDimitry Andric #define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS)
20120b57cec5SDimitry Andric 
20130b57cec5SDimitry Andric // private
20140b57cec5SDimitry Andric unsigned ObjectFileELF::ParseSymbols(Symtab *symtab, user_id_t start_id,
20150b57cec5SDimitry Andric                                      SectionList *section_list,
20160b57cec5SDimitry Andric                                      const size_t num_symbols,
20170b57cec5SDimitry Andric                                      const DataExtractor &symtab_data,
20180b57cec5SDimitry Andric                                      const DataExtractor &strtab_data) {
20190b57cec5SDimitry Andric   ELFSymbol symbol;
20200b57cec5SDimitry Andric   lldb::offset_t offset = 0;
20210b57cec5SDimitry Andric 
20220b57cec5SDimitry Andric   static ConstString text_section_name(".text");
20230b57cec5SDimitry Andric   static ConstString init_section_name(".init");
20240b57cec5SDimitry Andric   static ConstString fini_section_name(".fini");
20250b57cec5SDimitry Andric   static ConstString ctors_section_name(".ctors");
20260b57cec5SDimitry Andric   static ConstString dtors_section_name(".dtors");
20270b57cec5SDimitry Andric 
20280b57cec5SDimitry Andric   static ConstString data_section_name(".data");
20290b57cec5SDimitry Andric   static ConstString rodata_section_name(".rodata");
20300b57cec5SDimitry Andric   static ConstString rodata1_section_name(".rodata1");
20310b57cec5SDimitry Andric   static ConstString data2_section_name(".data1");
20320b57cec5SDimitry Andric   static ConstString bss_section_name(".bss");
20330b57cec5SDimitry Andric   static ConstString opd_section_name(".opd"); // For ppc64
20340b57cec5SDimitry Andric 
20350b57cec5SDimitry Andric   // On Android the oatdata and the oatexec symbols in the oat and odex files
20360b57cec5SDimitry Andric   // covers the full .text section what causes issues with displaying unusable
20370b57cec5SDimitry Andric   // symbol name to the user and very slow unwinding speed because the
20380b57cec5SDimitry Andric   // instruction emulation based unwind plans try to emulate all instructions
20390b57cec5SDimitry Andric   // in these symbols. Don't add these symbols to the symbol list as they have
20400b57cec5SDimitry Andric   // no use for the debugger and they are causing a lot of trouble. Filtering
20410b57cec5SDimitry Andric   // can't be restricted to Android because this special object file don't
20420b57cec5SDimitry Andric   // contain the note section specifying the environment to Android but the
20430b57cec5SDimitry Andric   // custom extension and file name makes it highly unlikely that this will
20440b57cec5SDimitry Andric   // collide with anything else.
2045*fe013be4SDimitry Andric   llvm::StringRef file_extension = m_file.GetFileNameExtension();
20460b57cec5SDimitry Andric   bool skip_oatdata_oatexec =
20470b57cec5SDimitry Andric       file_extension == ".oat" || file_extension == ".odex";
20480b57cec5SDimitry Andric 
20490b57cec5SDimitry Andric   ArchSpec arch = GetArchitecture();
20500b57cec5SDimitry Andric   ModuleSP module_sp(GetModule());
20510b57cec5SDimitry Andric   SectionList *module_section_list =
20520b57cec5SDimitry Andric       module_sp ? module_sp->GetSectionList() : nullptr;
20530b57cec5SDimitry Andric 
20540b57cec5SDimitry Andric   // Local cache to avoid doing a FindSectionByName for each symbol. The "const
20550b57cec5SDimitry Andric   // char*" key must came from a ConstString object so they can be compared by
20560b57cec5SDimitry Andric   // pointer
20570b57cec5SDimitry Andric   std::unordered_map<const char *, lldb::SectionSP> section_name_to_section;
20580b57cec5SDimitry Andric 
20590b57cec5SDimitry Andric   unsigned i;
20600b57cec5SDimitry Andric   for (i = 0; i < num_symbols; ++i) {
20610b57cec5SDimitry Andric     if (!symbol.Parse(symtab_data, &offset))
20620b57cec5SDimitry Andric       break;
20630b57cec5SDimitry Andric 
20640b57cec5SDimitry Andric     const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
20650b57cec5SDimitry Andric     if (!symbol_name)
20660b57cec5SDimitry Andric       symbol_name = "";
20670b57cec5SDimitry Andric 
20680b57cec5SDimitry Andric     // No need to add non-section symbols that have no names
20690b57cec5SDimitry Andric     if (symbol.getType() != STT_SECTION &&
20700b57cec5SDimitry Andric         (symbol_name == nullptr || symbol_name[0] == '\0'))
20710b57cec5SDimitry Andric       continue;
20720b57cec5SDimitry Andric 
20730b57cec5SDimitry Andric     // Skipping oatdata and oatexec sections if it is requested. See details
20740b57cec5SDimitry Andric     // above the definition of skip_oatdata_oatexec for the reasons.
20750b57cec5SDimitry Andric     if (skip_oatdata_oatexec && (::strcmp(symbol_name, "oatdata") == 0 ||
20760b57cec5SDimitry Andric                                  ::strcmp(symbol_name, "oatexec") == 0))
20770b57cec5SDimitry Andric       continue;
20780b57cec5SDimitry Andric 
20790b57cec5SDimitry Andric     SectionSP symbol_section_sp;
20800b57cec5SDimitry Andric     SymbolType symbol_type = eSymbolTypeInvalid;
20810b57cec5SDimitry Andric     Elf64_Half shndx = symbol.st_shndx;
20820b57cec5SDimitry Andric 
20830b57cec5SDimitry Andric     switch (shndx) {
20840b57cec5SDimitry Andric     case SHN_ABS:
20850b57cec5SDimitry Andric       symbol_type = eSymbolTypeAbsolute;
20860b57cec5SDimitry Andric       break;
20870b57cec5SDimitry Andric     case SHN_UNDEF:
20880b57cec5SDimitry Andric       symbol_type = eSymbolTypeUndefined;
20890b57cec5SDimitry Andric       break;
20900b57cec5SDimitry Andric     default:
20910b57cec5SDimitry Andric       symbol_section_sp = section_list->FindSectionByID(shndx);
20920b57cec5SDimitry Andric       break;
20930b57cec5SDimitry Andric     }
20940b57cec5SDimitry Andric 
20950b57cec5SDimitry Andric     // If a symbol is undefined do not process it further even if it has a STT
20960b57cec5SDimitry Andric     // type
20970b57cec5SDimitry Andric     if (symbol_type != eSymbolTypeUndefined) {
20980b57cec5SDimitry Andric       switch (symbol.getType()) {
20990b57cec5SDimitry Andric       default:
21000b57cec5SDimitry Andric       case STT_NOTYPE:
21010b57cec5SDimitry Andric         // The symbol's type is not specified.
21020b57cec5SDimitry Andric         break;
21030b57cec5SDimitry Andric 
21040b57cec5SDimitry Andric       case STT_OBJECT:
21050b57cec5SDimitry Andric         // The symbol is associated with a data object, such as a variable, an
21060b57cec5SDimitry Andric         // array, etc.
21070b57cec5SDimitry Andric         symbol_type = eSymbolTypeData;
21080b57cec5SDimitry Andric         break;
21090b57cec5SDimitry Andric 
21100b57cec5SDimitry Andric       case STT_FUNC:
21110b57cec5SDimitry Andric         // The symbol is associated with a function or other executable code.
21120b57cec5SDimitry Andric         symbol_type = eSymbolTypeCode;
21130b57cec5SDimitry Andric         break;
21140b57cec5SDimitry Andric 
21150b57cec5SDimitry Andric       case STT_SECTION:
21160b57cec5SDimitry Andric         // The symbol is associated with a section. Symbol table entries of
21170b57cec5SDimitry Andric         // this type exist primarily for relocation and normally have STB_LOCAL
21180b57cec5SDimitry Andric         // binding.
21190b57cec5SDimitry Andric         break;
21200b57cec5SDimitry Andric 
21210b57cec5SDimitry Andric       case STT_FILE:
21220b57cec5SDimitry Andric         // Conventionally, the symbol's name gives the name of the source file
21230b57cec5SDimitry Andric         // associated with the object file. A file symbol has STB_LOCAL
21240b57cec5SDimitry Andric         // binding, its section index is SHN_ABS, and it precedes the other
21250b57cec5SDimitry Andric         // STB_LOCAL symbols for the file, if it is present.
21260b57cec5SDimitry Andric         symbol_type = eSymbolTypeSourceFile;
21270b57cec5SDimitry Andric         break;
21280b57cec5SDimitry Andric 
21290b57cec5SDimitry Andric       case STT_GNU_IFUNC:
21300b57cec5SDimitry Andric         // The symbol is associated with an indirect function. The actual
21310b57cec5SDimitry Andric         // function will be resolved if it is referenced.
21320b57cec5SDimitry Andric         symbol_type = eSymbolTypeResolver;
21330b57cec5SDimitry Andric         break;
21340b57cec5SDimitry Andric       }
21350b57cec5SDimitry Andric     }
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric     if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) {
21380b57cec5SDimitry Andric       if (symbol_section_sp) {
21390b57cec5SDimitry Andric         ConstString sect_name = symbol_section_sp->GetName();
21400b57cec5SDimitry Andric         if (sect_name == text_section_name || sect_name == init_section_name ||
21410b57cec5SDimitry Andric             sect_name == fini_section_name || sect_name == ctors_section_name ||
21420b57cec5SDimitry Andric             sect_name == dtors_section_name) {
21430b57cec5SDimitry Andric           symbol_type = eSymbolTypeCode;
21440b57cec5SDimitry Andric         } else if (sect_name == data_section_name ||
21450b57cec5SDimitry Andric                    sect_name == data2_section_name ||
21460b57cec5SDimitry Andric                    sect_name == rodata_section_name ||
21470b57cec5SDimitry Andric                    sect_name == rodata1_section_name ||
21480b57cec5SDimitry Andric                    sect_name == bss_section_name) {
21490b57cec5SDimitry Andric           symbol_type = eSymbolTypeData;
21500b57cec5SDimitry Andric         }
21510b57cec5SDimitry Andric       }
21520b57cec5SDimitry Andric     }
21530b57cec5SDimitry Andric 
21540b57cec5SDimitry Andric     int64_t symbol_value_offset = 0;
21550b57cec5SDimitry Andric     uint32_t additional_flags = 0;
21560b57cec5SDimitry Andric 
21570b57cec5SDimitry Andric     if (arch.IsValid()) {
21580b57cec5SDimitry Andric       if (arch.GetMachine() == llvm::Triple::arm) {
21590b57cec5SDimitry Andric         if (symbol.getBinding() == STB_LOCAL) {
21600b57cec5SDimitry Andric           char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
21610b57cec5SDimitry Andric           if (symbol_type == eSymbolTypeCode) {
21620b57cec5SDimitry Andric             switch (mapping_symbol) {
21630b57cec5SDimitry Andric             case 'a':
21640b57cec5SDimitry Andric               // $a[.<any>]* - marks an ARM instruction sequence
21650b57cec5SDimitry Andric               m_address_class_map[symbol.st_value] = AddressClass::eCode;
21660b57cec5SDimitry Andric               break;
21670b57cec5SDimitry Andric             case 'b':
21680b57cec5SDimitry Andric             case 't':
21690b57cec5SDimitry Andric               // $b[.<any>]* - marks a THUMB BL instruction sequence
21700b57cec5SDimitry Andric               // $t[.<any>]* - marks a THUMB instruction sequence
21710b57cec5SDimitry Andric               m_address_class_map[symbol.st_value] =
21720b57cec5SDimitry Andric                   AddressClass::eCodeAlternateISA;
21730b57cec5SDimitry Andric               break;
21740b57cec5SDimitry Andric             case 'd':
21750b57cec5SDimitry Andric               // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
21760b57cec5SDimitry Andric               m_address_class_map[symbol.st_value] = AddressClass::eData;
21770b57cec5SDimitry Andric               break;
21780b57cec5SDimitry Andric             }
21790b57cec5SDimitry Andric           }
21800b57cec5SDimitry Andric           if (mapping_symbol)
21810b57cec5SDimitry Andric             continue;
21820b57cec5SDimitry Andric         }
21830b57cec5SDimitry Andric       } else if (arch.GetMachine() == llvm::Triple::aarch64) {
21840b57cec5SDimitry Andric         if (symbol.getBinding() == STB_LOCAL) {
21850b57cec5SDimitry Andric           char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
21860b57cec5SDimitry Andric           if (symbol_type == eSymbolTypeCode) {
21870b57cec5SDimitry Andric             switch (mapping_symbol) {
21880b57cec5SDimitry Andric             case 'x':
21890b57cec5SDimitry Andric               // $x[.<any>]* - marks an A64 instruction sequence
21900b57cec5SDimitry Andric               m_address_class_map[symbol.st_value] = AddressClass::eCode;
21910b57cec5SDimitry Andric               break;
21920b57cec5SDimitry Andric             case 'd':
21930b57cec5SDimitry Andric               // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
21940b57cec5SDimitry Andric               m_address_class_map[symbol.st_value] = AddressClass::eData;
21950b57cec5SDimitry Andric               break;
21960b57cec5SDimitry Andric             }
21970b57cec5SDimitry Andric           }
21980b57cec5SDimitry Andric           if (mapping_symbol)
21990b57cec5SDimitry Andric             continue;
22000b57cec5SDimitry Andric         }
22010b57cec5SDimitry Andric       }
22020b57cec5SDimitry Andric 
22030b57cec5SDimitry Andric       if (arch.GetMachine() == llvm::Triple::arm) {
22040b57cec5SDimitry Andric         if (symbol_type == eSymbolTypeCode) {
22050b57cec5SDimitry Andric           if (symbol.st_value & 1) {
22060b57cec5SDimitry Andric             // Subtracting 1 from the address effectively unsets the low order
22070b57cec5SDimitry Andric             // bit, which results in the address actually pointing to the
22080b57cec5SDimitry Andric             // beginning of the symbol. This delta will be used below in
22090b57cec5SDimitry Andric             // conjunction with symbol.st_value to produce the final
22100b57cec5SDimitry Andric             // symbol_value that we store in the symtab.
22110b57cec5SDimitry Andric             symbol_value_offset = -1;
22120b57cec5SDimitry Andric             m_address_class_map[symbol.st_value ^ 1] =
22130b57cec5SDimitry Andric                 AddressClass::eCodeAlternateISA;
22140b57cec5SDimitry Andric           } else {
22150b57cec5SDimitry Andric             // This address is ARM
22160b57cec5SDimitry Andric             m_address_class_map[symbol.st_value] = AddressClass::eCode;
22170b57cec5SDimitry Andric           }
22180b57cec5SDimitry Andric         }
22190b57cec5SDimitry Andric       }
22200b57cec5SDimitry Andric 
22210b57cec5SDimitry Andric       /*
22220b57cec5SDimitry Andric        * MIPS:
22230b57cec5SDimitry Andric        * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for
22240b57cec5SDimitry Andric        * MIPS).
22250b57cec5SDimitry Andric        * This allows processor to switch between microMIPS and MIPS without any
22260b57cec5SDimitry Andric        * need
22270b57cec5SDimitry Andric        * for special mode-control register. However, apart from .debug_line,
22280b57cec5SDimitry Andric        * none of
22290b57cec5SDimitry Andric        * the ELF/DWARF sections set the ISA bit (for symbol or section). Use
22300b57cec5SDimitry Andric        * st_other
22310b57cec5SDimitry Andric        * flag to check whether the symbol is microMIPS and then set the address
22320b57cec5SDimitry Andric        * class
22330b57cec5SDimitry Andric        * accordingly.
22340b57cec5SDimitry Andric       */
22350b57cec5SDimitry Andric       if (arch.IsMIPS()) {
22360b57cec5SDimitry Andric         if (IS_MICROMIPS(symbol.st_other))
22370b57cec5SDimitry Andric           m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
22380b57cec5SDimitry Andric         else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) {
22390b57cec5SDimitry Andric           symbol.st_value = symbol.st_value & (~1ull);
22400b57cec5SDimitry Andric           m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
22410b57cec5SDimitry Andric         } else {
22420b57cec5SDimitry Andric           if (symbol_type == eSymbolTypeCode)
22430b57cec5SDimitry Andric             m_address_class_map[symbol.st_value] = AddressClass::eCode;
22440b57cec5SDimitry Andric           else if (symbol_type == eSymbolTypeData)
22450b57cec5SDimitry Andric             m_address_class_map[symbol.st_value] = AddressClass::eData;
22460b57cec5SDimitry Andric           else
22470b57cec5SDimitry Andric             m_address_class_map[symbol.st_value] = AddressClass::eUnknown;
22480b57cec5SDimitry Andric         }
22490b57cec5SDimitry Andric       }
22500b57cec5SDimitry Andric     }
22510b57cec5SDimitry Andric 
22520b57cec5SDimitry Andric     // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB
22530b57cec5SDimitry Andric     // symbols. See above for more details.
22540b57cec5SDimitry Andric     uint64_t symbol_value = symbol.st_value + symbol_value_offset;
22550b57cec5SDimitry Andric 
22560b57cec5SDimitry Andric     if (symbol_section_sp &&
22570b57cec5SDimitry Andric         CalculateType() != ObjectFile::Type::eTypeObjectFile)
22580b57cec5SDimitry Andric       symbol_value -= symbol_section_sp->GetFileAddress();
22590b57cec5SDimitry Andric 
22600b57cec5SDimitry Andric     if (symbol_section_sp && module_section_list &&
22610b57cec5SDimitry Andric         module_section_list != section_list) {
22620b57cec5SDimitry Andric       ConstString sect_name = symbol_section_sp->GetName();
22630b57cec5SDimitry Andric       auto section_it = section_name_to_section.find(sect_name.GetCString());
22640b57cec5SDimitry Andric       if (section_it == section_name_to_section.end())
22650b57cec5SDimitry Andric         section_it =
22660b57cec5SDimitry Andric             section_name_to_section
22670b57cec5SDimitry Andric                 .emplace(sect_name.GetCString(),
22680b57cec5SDimitry Andric                          module_section_list->FindSectionByName(sect_name))
22690b57cec5SDimitry Andric                 .first;
22700b57cec5SDimitry Andric       if (section_it->second)
22710b57cec5SDimitry Andric         symbol_section_sp = section_it->second;
22720b57cec5SDimitry Andric     }
22730b57cec5SDimitry Andric 
22740b57cec5SDimitry Andric     bool is_global = symbol.getBinding() == STB_GLOBAL;
22750b57cec5SDimitry Andric     uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags;
22760b57cec5SDimitry Andric     llvm::StringRef symbol_ref(symbol_name);
22770b57cec5SDimitry Andric 
22780b57cec5SDimitry Andric     // Symbol names may contain @VERSION suffixes. Find those and strip them
22790b57cec5SDimitry Andric     // temporarily.
22800b57cec5SDimitry Andric     size_t version_pos = symbol_ref.find('@');
22810b57cec5SDimitry Andric     bool has_suffix = version_pos != llvm::StringRef::npos;
22820b57cec5SDimitry Andric     llvm::StringRef symbol_bare = symbol_ref.substr(0, version_pos);
22839dba64beSDimitry Andric     Mangled mangled(symbol_bare);
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric     // Now append the suffix back to mangled and unmangled names. Only do it if
22860b57cec5SDimitry Andric     // the demangling was successful (string is not empty).
22870b57cec5SDimitry Andric     if (has_suffix) {
22880b57cec5SDimitry Andric       llvm::StringRef suffix = symbol_ref.substr(version_pos);
22890b57cec5SDimitry Andric 
22900b57cec5SDimitry Andric       llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef();
22910b57cec5SDimitry Andric       if (!mangled_name.empty())
22920b57cec5SDimitry Andric         mangled.SetMangledName(ConstString((mangled_name + suffix).str()));
22930b57cec5SDimitry Andric 
22945ffd83dbSDimitry Andric       ConstString demangled = mangled.GetDemangledName();
22950b57cec5SDimitry Andric       llvm::StringRef demangled_name = demangled.GetStringRef();
22960b57cec5SDimitry Andric       if (!demangled_name.empty())
22970b57cec5SDimitry Andric         mangled.SetDemangledName(ConstString((demangled_name + suffix).str()));
22980b57cec5SDimitry Andric     }
22990b57cec5SDimitry Andric 
23000b57cec5SDimitry Andric     // In ELF all symbol should have a valid size but it is not true for some
23010b57cec5SDimitry Andric     // function symbols coming from hand written assembly. As none of the
23020b57cec5SDimitry Andric     // function symbol should have 0 size we try to calculate the size for
23030b57cec5SDimitry Andric     // these symbols in the symtab with saying that their original size is not
23040b57cec5SDimitry Andric     // valid.
23050b57cec5SDimitry Andric     bool symbol_size_valid =
23060b57cec5SDimitry Andric         symbol.st_size != 0 || symbol.getType() != STT_FUNC;
23070b57cec5SDimitry Andric 
23080b57cec5SDimitry Andric     Symbol dc_symbol(
23090b57cec5SDimitry Andric         i + start_id, // ID is the original symbol table index.
23100b57cec5SDimitry Andric         mangled,
23110b57cec5SDimitry Andric         symbol_type,                    // Type of this symbol
23120b57cec5SDimitry Andric         is_global,                      // Is this globally visible?
23130b57cec5SDimitry Andric         false,                          // Is this symbol debug info?
23140b57cec5SDimitry Andric         false,                          // Is this symbol a trampoline?
23150b57cec5SDimitry Andric         false,                          // Is this symbol artificial?
23160b57cec5SDimitry Andric         AddressRange(symbol_section_sp, // Section in which this symbol is
23170b57cec5SDimitry Andric                                         // defined or null.
23180b57cec5SDimitry Andric                      symbol_value,      // Offset in section or symbol value.
23190b57cec5SDimitry Andric                      symbol.st_size),   // Size in bytes of this symbol.
23200b57cec5SDimitry Andric         symbol_size_valid,              // Symbol size is valid
23210b57cec5SDimitry Andric         has_suffix,                     // Contains linker annotations?
23220b57cec5SDimitry Andric         flags);                         // Symbol flags.
2323480093f4SDimitry Andric     if (symbol.getBinding() == STB_WEAK)
2324480093f4SDimitry Andric       dc_symbol.SetIsWeak(true);
23250b57cec5SDimitry Andric     symtab->AddSymbol(dc_symbol);
23260b57cec5SDimitry Andric   }
23270b57cec5SDimitry Andric   return i;
23280b57cec5SDimitry Andric }
23290b57cec5SDimitry Andric 
23300b57cec5SDimitry Andric unsigned ObjectFileELF::ParseSymbolTable(Symtab *symbol_table,
23310b57cec5SDimitry Andric                                          user_id_t start_id,
23320b57cec5SDimitry Andric                                          lldb_private::Section *symtab) {
23330b57cec5SDimitry Andric   if (symtab->GetObjectFile() != this) {
23340b57cec5SDimitry Andric     // If the symbol table section is owned by a different object file, have it
23350b57cec5SDimitry Andric     // do the parsing.
23360b57cec5SDimitry Andric     ObjectFileELF *obj_file_elf =
23370b57cec5SDimitry Andric         static_cast<ObjectFileELF *>(symtab->GetObjectFile());
23380b57cec5SDimitry Andric     return obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab);
23390b57cec5SDimitry Andric   }
23400b57cec5SDimitry Andric 
23410b57cec5SDimitry Andric   // Get section list for this object file.
23420b57cec5SDimitry Andric   SectionList *section_list = m_sections_up.get();
23430b57cec5SDimitry Andric   if (!section_list)
23440b57cec5SDimitry Andric     return 0;
23450b57cec5SDimitry Andric 
23460b57cec5SDimitry Andric   user_id_t symtab_id = symtab->GetID();
23470b57cec5SDimitry Andric   const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
23480b57cec5SDimitry Andric   assert(symtab_hdr->sh_type == SHT_SYMTAB ||
23490b57cec5SDimitry Andric          symtab_hdr->sh_type == SHT_DYNSYM);
23500b57cec5SDimitry Andric 
23510b57cec5SDimitry Andric   // sh_link: section header index of associated string table.
23520b57cec5SDimitry Andric   user_id_t strtab_id = symtab_hdr->sh_link;
23530b57cec5SDimitry Andric   Section *strtab = section_list->FindSectionByID(strtab_id).get();
23540b57cec5SDimitry Andric 
23550b57cec5SDimitry Andric   if (symtab && strtab) {
23560b57cec5SDimitry Andric     assert(symtab->GetObjectFile() == this);
23570b57cec5SDimitry Andric     assert(strtab->GetObjectFile() == this);
23580b57cec5SDimitry Andric 
23590b57cec5SDimitry Andric     DataExtractor symtab_data;
23600b57cec5SDimitry Andric     DataExtractor strtab_data;
23610b57cec5SDimitry Andric     if (ReadSectionData(symtab, symtab_data) &&
23620b57cec5SDimitry Andric         ReadSectionData(strtab, strtab_data)) {
23630b57cec5SDimitry Andric       size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
23640b57cec5SDimitry Andric 
23650b57cec5SDimitry Andric       return ParseSymbols(symbol_table, start_id, section_list, num_symbols,
23660b57cec5SDimitry Andric                           symtab_data, strtab_data);
23670b57cec5SDimitry Andric     }
23680b57cec5SDimitry Andric   }
23690b57cec5SDimitry Andric 
23700b57cec5SDimitry Andric   return 0;
23710b57cec5SDimitry Andric }
23720b57cec5SDimitry Andric 
23730b57cec5SDimitry Andric size_t ObjectFileELF::ParseDynamicSymbols() {
23740b57cec5SDimitry Andric   if (m_dynamic_symbols.size())
23750b57cec5SDimitry Andric     return m_dynamic_symbols.size();
23760b57cec5SDimitry Andric 
23770b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
23780b57cec5SDimitry Andric   if (!section_list)
23790b57cec5SDimitry Andric     return 0;
23800b57cec5SDimitry Andric 
23810b57cec5SDimitry Andric   // Find the SHT_DYNAMIC section.
23820b57cec5SDimitry Andric   Section *dynsym =
23830b57cec5SDimitry Andric       section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
23840b57cec5SDimitry Andric           .get();
23850b57cec5SDimitry Andric   if (!dynsym)
23860b57cec5SDimitry Andric     return 0;
23870b57cec5SDimitry Andric   assert(dynsym->GetObjectFile() == this);
23880b57cec5SDimitry Andric 
23890b57cec5SDimitry Andric   ELFDynamic symbol;
23900b57cec5SDimitry Andric   DataExtractor dynsym_data;
23910b57cec5SDimitry Andric   if (ReadSectionData(dynsym, dynsym_data)) {
23920b57cec5SDimitry Andric     const lldb::offset_t section_size = dynsym_data.GetByteSize();
23930b57cec5SDimitry Andric     lldb::offset_t cursor = 0;
23940b57cec5SDimitry Andric 
23950b57cec5SDimitry Andric     while (cursor < section_size) {
23960b57cec5SDimitry Andric       if (!symbol.Parse(dynsym_data, &cursor))
23970b57cec5SDimitry Andric         break;
23980b57cec5SDimitry Andric 
23990b57cec5SDimitry Andric       m_dynamic_symbols.push_back(symbol);
24000b57cec5SDimitry Andric     }
24010b57cec5SDimitry Andric   }
24020b57cec5SDimitry Andric 
24030b57cec5SDimitry Andric   return m_dynamic_symbols.size();
24040b57cec5SDimitry Andric }
24050b57cec5SDimitry Andric 
24060b57cec5SDimitry Andric const ELFDynamic *ObjectFileELF::FindDynamicSymbol(unsigned tag) {
24070b57cec5SDimitry Andric   if (!ParseDynamicSymbols())
24080b57cec5SDimitry Andric     return nullptr;
24090b57cec5SDimitry Andric 
24100b57cec5SDimitry Andric   DynamicSymbolCollIter I = m_dynamic_symbols.begin();
24110b57cec5SDimitry Andric   DynamicSymbolCollIter E = m_dynamic_symbols.end();
24120b57cec5SDimitry Andric   for (; I != E; ++I) {
24130b57cec5SDimitry Andric     ELFDynamic *symbol = &*I;
24140b57cec5SDimitry Andric 
24150b57cec5SDimitry Andric     if (symbol->d_tag == tag)
24160b57cec5SDimitry Andric       return symbol;
24170b57cec5SDimitry Andric   }
24180b57cec5SDimitry Andric 
24190b57cec5SDimitry Andric   return nullptr;
24200b57cec5SDimitry Andric }
24210b57cec5SDimitry Andric 
24220b57cec5SDimitry Andric unsigned ObjectFileELF::PLTRelocationType() {
24230b57cec5SDimitry Andric   // DT_PLTREL
24240b57cec5SDimitry Andric   //  This member specifies the type of relocation entry to which the
24250b57cec5SDimitry Andric   //  procedure linkage table refers. The d_val member holds DT_REL or
24260b57cec5SDimitry Andric   //  DT_RELA, as appropriate. All relocations in a procedure linkage table
24270b57cec5SDimitry Andric   //  must use the same relocation.
24280b57cec5SDimitry Andric   const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
24290b57cec5SDimitry Andric 
24300b57cec5SDimitry Andric   if (symbol)
24310b57cec5SDimitry Andric     return symbol->d_val;
24320b57cec5SDimitry Andric 
24330b57cec5SDimitry Andric   return 0;
24340b57cec5SDimitry Andric }
24350b57cec5SDimitry Andric 
24360b57cec5SDimitry Andric // Returns the size of the normal plt entries and the offset of the first
24370b57cec5SDimitry Andric // normal plt entry. The 0th entry in the plt table is usually a resolution
24380b57cec5SDimitry Andric // entry which have different size in some architectures then the rest of the
24390b57cec5SDimitry Andric // plt entries.
24400b57cec5SDimitry Andric static std::pair<uint64_t, uint64_t>
24410b57cec5SDimitry Andric GetPltEntrySizeAndOffset(const ELFSectionHeader *rel_hdr,
24420b57cec5SDimitry Andric                          const ELFSectionHeader *plt_hdr) {
24430b57cec5SDimitry Andric   const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
24440b57cec5SDimitry Andric 
24450b57cec5SDimitry Andric   // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are
24460b57cec5SDimitry Andric   // 16 bytes. So round the entsize up by the alignment if addralign is set.
24470b57cec5SDimitry Andric   elf_xword plt_entsize =
24480b57cec5SDimitry Andric       plt_hdr->sh_addralign
24490b57cec5SDimitry Andric           ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign)
24500b57cec5SDimitry Andric           : plt_hdr->sh_entsize;
24510b57cec5SDimitry Andric 
24520b57cec5SDimitry Andric   // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly.
24530b57cec5SDimitry Andric   // PLT entries relocation code in general requires multiple instruction and
24540b57cec5SDimitry Andric   // should be greater than 4 bytes in most cases. Try to guess correct size
24550b57cec5SDimitry Andric   // just in case.
24560b57cec5SDimitry Andric   if (plt_entsize <= 4) {
24570b57cec5SDimitry Andric     // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the
24580b57cec5SDimitry Andric     // size of the plt entries based on the number of entries and the size of
24590b57cec5SDimitry Andric     // the plt section with the assumption that the size of the 0th entry is at
24600b57cec5SDimitry Andric     // least as big as the size of the normal entries and it isn't much bigger
24610b57cec5SDimitry Andric     // then that.
24620b57cec5SDimitry Andric     if (plt_hdr->sh_addralign)
24630b57cec5SDimitry Andric       plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign /
24640b57cec5SDimitry Andric                     (num_relocations + 1) * plt_hdr->sh_addralign;
24650b57cec5SDimitry Andric     else
24660b57cec5SDimitry Andric       plt_entsize = plt_hdr->sh_size / (num_relocations + 1);
24670b57cec5SDimitry Andric   }
24680b57cec5SDimitry Andric 
24690b57cec5SDimitry Andric   elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize;
24700b57cec5SDimitry Andric 
24710b57cec5SDimitry Andric   return std::make_pair(plt_entsize, plt_offset);
24720b57cec5SDimitry Andric }
24730b57cec5SDimitry Andric 
24740b57cec5SDimitry Andric static unsigned ParsePLTRelocations(
24750b57cec5SDimitry Andric     Symtab *symbol_table, user_id_t start_id, unsigned rel_type,
24760b57cec5SDimitry Andric     const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
24770b57cec5SDimitry Andric     const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr,
24780b57cec5SDimitry Andric     const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data,
24790b57cec5SDimitry Andric     DataExtractor &symtab_data, DataExtractor &strtab_data) {
24800b57cec5SDimitry Andric   ELFRelocation rel(rel_type);
24810b57cec5SDimitry Andric   ELFSymbol symbol;
24820b57cec5SDimitry Andric   lldb::offset_t offset = 0;
24830b57cec5SDimitry Andric 
24840b57cec5SDimitry Andric   uint64_t plt_offset, plt_entsize;
24850b57cec5SDimitry Andric   std::tie(plt_entsize, plt_offset) =
24860b57cec5SDimitry Andric       GetPltEntrySizeAndOffset(rel_hdr, plt_hdr);
24870b57cec5SDimitry Andric   const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
24880b57cec5SDimitry Andric 
24890b57cec5SDimitry Andric   typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
24900b57cec5SDimitry Andric   reloc_info_fn reloc_type;
24910b57cec5SDimitry Andric   reloc_info_fn reloc_symbol;
24920b57cec5SDimitry Andric 
24930b57cec5SDimitry Andric   if (hdr->Is32Bit()) {
24940b57cec5SDimitry Andric     reloc_type = ELFRelocation::RelocType32;
24950b57cec5SDimitry Andric     reloc_symbol = ELFRelocation::RelocSymbol32;
24960b57cec5SDimitry Andric   } else {
24970b57cec5SDimitry Andric     reloc_type = ELFRelocation::RelocType64;
24980b57cec5SDimitry Andric     reloc_symbol = ELFRelocation::RelocSymbol64;
24990b57cec5SDimitry Andric   }
25000b57cec5SDimitry Andric 
25010b57cec5SDimitry Andric   unsigned slot_type = hdr->GetRelocationJumpSlotType();
25020b57cec5SDimitry Andric   unsigned i;
25030b57cec5SDimitry Andric   for (i = 0; i < num_relocations; ++i) {
25040b57cec5SDimitry Andric     if (!rel.Parse(rel_data, &offset))
25050b57cec5SDimitry Andric       break;
25060b57cec5SDimitry Andric 
25070b57cec5SDimitry Andric     if (reloc_type(rel) != slot_type)
25080b57cec5SDimitry Andric       continue;
25090b57cec5SDimitry Andric 
25100b57cec5SDimitry Andric     lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
25110b57cec5SDimitry Andric     if (!symbol.Parse(symtab_data, &symbol_offset))
25120b57cec5SDimitry Andric       break;
25130b57cec5SDimitry Andric 
25140b57cec5SDimitry Andric     const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
25150b57cec5SDimitry Andric     uint64_t plt_index = plt_offset + i * plt_entsize;
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric     Symbol jump_symbol(
25180b57cec5SDimitry Andric         i + start_id,          // Symbol table index
25190b57cec5SDimitry Andric         symbol_name,           // symbol name.
25200b57cec5SDimitry Andric         eSymbolTypeTrampoline, // Type of this symbol
25210b57cec5SDimitry Andric         false,                 // Is this globally visible?
25220b57cec5SDimitry Andric         false,                 // Is this symbol debug info?
25230b57cec5SDimitry Andric         true,                  // Is this symbol a trampoline?
25240b57cec5SDimitry Andric         true,                  // Is this symbol artificial?
25250b57cec5SDimitry Andric         plt_section_sp, // Section in which this symbol is defined or null.
25260b57cec5SDimitry Andric         plt_index,      // Offset in section or symbol value.
25270b57cec5SDimitry Andric         plt_entsize,    // Size in bytes of this symbol.
25280b57cec5SDimitry Andric         true,           // Size is valid
25290b57cec5SDimitry Andric         false,          // Contains linker annotations?
25300b57cec5SDimitry Andric         0);             // Symbol flags.
25310b57cec5SDimitry Andric 
25320b57cec5SDimitry Andric     symbol_table->AddSymbol(jump_symbol);
25330b57cec5SDimitry Andric   }
25340b57cec5SDimitry Andric 
25350b57cec5SDimitry Andric   return i;
25360b57cec5SDimitry Andric }
25370b57cec5SDimitry Andric 
25380b57cec5SDimitry Andric unsigned
25390b57cec5SDimitry Andric ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table, user_id_t start_id,
25400b57cec5SDimitry Andric                                       const ELFSectionHeaderInfo *rel_hdr,
25410b57cec5SDimitry Andric                                       user_id_t rel_id) {
25420b57cec5SDimitry Andric   assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
25430b57cec5SDimitry Andric 
25440b57cec5SDimitry Andric   // The link field points to the associated symbol table.
25450b57cec5SDimitry Andric   user_id_t symtab_id = rel_hdr->sh_link;
25460b57cec5SDimitry Andric 
25470b57cec5SDimitry Andric   // If the link field doesn't point to the appropriate symbol name table then
25480b57cec5SDimitry Andric   // try to find it by name as some compiler don't fill in the link fields.
25490b57cec5SDimitry Andric   if (!symtab_id)
25500b57cec5SDimitry Andric     symtab_id = GetSectionIndexByName(".dynsym");
25510b57cec5SDimitry Andric 
25520b57cec5SDimitry Andric   // Get PLT section.  We cannot use rel_hdr->sh_info, since current linkers
25530b57cec5SDimitry Andric   // point that to the .got.plt or .got section instead of .plt.
25540b57cec5SDimitry Andric   user_id_t plt_id = GetSectionIndexByName(".plt");
25550b57cec5SDimitry Andric 
25560b57cec5SDimitry Andric   if (!symtab_id || !plt_id)
25570b57cec5SDimitry Andric     return 0;
25580b57cec5SDimitry Andric 
25590b57cec5SDimitry Andric   const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
25600b57cec5SDimitry Andric   if (!plt_hdr)
25610b57cec5SDimitry Andric     return 0;
25620b57cec5SDimitry Andric 
25630b57cec5SDimitry Andric   const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
25640b57cec5SDimitry Andric   if (!sym_hdr)
25650b57cec5SDimitry Andric     return 0;
25660b57cec5SDimitry Andric 
25670b57cec5SDimitry Andric   SectionList *section_list = m_sections_up.get();
25680b57cec5SDimitry Andric   if (!section_list)
25690b57cec5SDimitry Andric     return 0;
25700b57cec5SDimitry Andric 
25710b57cec5SDimitry Andric   Section *rel_section = section_list->FindSectionByID(rel_id).get();
25720b57cec5SDimitry Andric   if (!rel_section)
25730b57cec5SDimitry Andric     return 0;
25740b57cec5SDimitry Andric 
25750b57cec5SDimitry Andric   SectionSP plt_section_sp(section_list->FindSectionByID(plt_id));
25760b57cec5SDimitry Andric   if (!plt_section_sp)
25770b57cec5SDimitry Andric     return 0;
25780b57cec5SDimitry Andric 
25790b57cec5SDimitry Andric   Section *symtab = section_list->FindSectionByID(symtab_id).get();
25800b57cec5SDimitry Andric   if (!symtab)
25810b57cec5SDimitry Andric     return 0;
25820b57cec5SDimitry Andric 
25830b57cec5SDimitry Andric   // sh_link points to associated string table.
25840b57cec5SDimitry Andric   Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link).get();
25850b57cec5SDimitry Andric   if (!strtab)
25860b57cec5SDimitry Andric     return 0;
25870b57cec5SDimitry Andric 
25880b57cec5SDimitry Andric   DataExtractor rel_data;
25890b57cec5SDimitry Andric   if (!ReadSectionData(rel_section, rel_data))
25900b57cec5SDimitry Andric     return 0;
25910b57cec5SDimitry Andric 
25920b57cec5SDimitry Andric   DataExtractor symtab_data;
25930b57cec5SDimitry Andric   if (!ReadSectionData(symtab, symtab_data))
25940b57cec5SDimitry Andric     return 0;
25950b57cec5SDimitry Andric 
25960b57cec5SDimitry Andric   DataExtractor strtab_data;
25970b57cec5SDimitry Andric   if (!ReadSectionData(strtab, strtab_data))
25980b57cec5SDimitry Andric     return 0;
25990b57cec5SDimitry Andric 
26000b57cec5SDimitry Andric   unsigned rel_type = PLTRelocationType();
26010b57cec5SDimitry Andric   if (!rel_type)
26020b57cec5SDimitry Andric     return 0;
26030b57cec5SDimitry Andric 
26040b57cec5SDimitry Andric   return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header,
26050b57cec5SDimitry Andric                              rel_hdr, plt_hdr, sym_hdr, plt_section_sp,
26060b57cec5SDimitry Andric                              rel_data, symtab_data, strtab_data);
26070b57cec5SDimitry Andric }
26080b57cec5SDimitry Andric 
26091ac55f4cSDimitry Andric static void ApplyELF64ABS64Relocation(Symtab *symtab, ELFRelocation &rel,
26101ac55f4cSDimitry Andric                                       DataExtractor &debug_data,
26111ac55f4cSDimitry Andric                                       Section *rel_section) {
26121ac55f4cSDimitry Andric   Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol64(rel));
26131ac55f4cSDimitry Andric   if (symbol) {
26141ac55f4cSDimitry Andric     addr_t value = symbol->GetAddressRef().GetFileAddress();
26151ac55f4cSDimitry Andric     DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
26161ac55f4cSDimitry Andric     // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
26171ac55f4cSDimitry Andric     WritableDataBuffer *data_buffer =
26181ac55f4cSDimitry Andric         llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
26191ac55f4cSDimitry Andric     uint64_t *dst = reinterpret_cast<uint64_t *>(
26201ac55f4cSDimitry Andric         data_buffer->GetBytes() + rel_section->GetFileOffset() +
26211ac55f4cSDimitry Andric         ELFRelocation::RelocOffset64(rel));
26221ac55f4cSDimitry Andric     uint64_t val_offset = value + ELFRelocation::RelocAddend64(rel);
26231ac55f4cSDimitry Andric     memcpy(dst, &val_offset, sizeof(uint64_t));
26241ac55f4cSDimitry Andric   }
26251ac55f4cSDimitry Andric }
26261ac55f4cSDimitry Andric 
26271ac55f4cSDimitry Andric static void ApplyELF64ABS32Relocation(Symtab *symtab, ELFRelocation &rel,
26281ac55f4cSDimitry Andric                                       DataExtractor &debug_data,
26291ac55f4cSDimitry Andric                                       Section *rel_section, bool is_signed) {
26301ac55f4cSDimitry Andric   Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol64(rel));
26311ac55f4cSDimitry Andric   if (symbol) {
26321ac55f4cSDimitry Andric     addr_t value = symbol->GetAddressRef().GetFileAddress();
26331ac55f4cSDimitry Andric     value += ELFRelocation::RelocAddend32(rel);
26341ac55f4cSDimitry Andric     if ((!is_signed && (value > UINT32_MAX)) ||
26351ac55f4cSDimitry Andric         (is_signed &&
26361ac55f4cSDimitry Andric          ((int64_t)value > INT32_MAX || (int64_t)value < INT32_MIN))) {
26371ac55f4cSDimitry Andric       Log *log = GetLog(LLDBLog::Modules);
26381ac55f4cSDimitry Andric       LLDB_LOGF(log, "Failed to apply debug info relocations");
26391ac55f4cSDimitry Andric       return;
26401ac55f4cSDimitry Andric     }
26411ac55f4cSDimitry Andric     uint32_t truncated_addr = (value & 0xFFFFFFFF);
26421ac55f4cSDimitry Andric     DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
26431ac55f4cSDimitry Andric     // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
26441ac55f4cSDimitry Andric     WritableDataBuffer *data_buffer =
26451ac55f4cSDimitry Andric         llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
26461ac55f4cSDimitry Andric     uint32_t *dst = reinterpret_cast<uint32_t *>(
26471ac55f4cSDimitry Andric         data_buffer->GetBytes() + rel_section->GetFileOffset() +
26481ac55f4cSDimitry Andric         ELFRelocation::RelocOffset32(rel));
26491ac55f4cSDimitry Andric     memcpy(dst, &truncated_addr, sizeof(uint32_t));
26501ac55f4cSDimitry Andric   }
26511ac55f4cSDimitry Andric }
26521ac55f4cSDimitry Andric 
2653*fe013be4SDimitry Andric static void ApplyELF32ABS32RelRelocation(Symtab *symtab, ELFRelocation &rel,
2654*fe013be4SDimitry Andric                                          DataExtractor &debug_data,
2655*fe013be4SDimitry Andric                                          Section *rel_section) {
2656*fe013be4SDimitry Andric   Log *log = GetLog(LLDBLog::Modules);
2657*fe013be4SDimitry Andric   Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol32(rel));
2658*fe013be4SDimitry Andric   if (symbol) {
2659*fe013be4SDimitry Andric     addr_t value = symbol->GetAddressRef().GetFileAddress();
2660*fe013be4SDimitry Andric     if (value == LLDB_INVALID_ADDRESS) {
2661*fe013be4SDimitry Andric       const char *name = symbol->GetName().GetCString();
2662*fe013be4SDimitry Andric       LLDB_LOGF(log, "Debug info symbol invalid: %s", name);
2663*fe013be4SDimitry Andric       return;
2664*fe013be4SDimitry Andric     }
2665*fe013be4SDimitry Andric     assert(llvm::isUInt<32>(value) && "Valid addresses are 32-bit");
2666*fe013be4SDimitry Andric     DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2667*fe013be4SDimitry Andric     // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
2668*fe013be4SDimitry Andric     WritableDataBuffer *data_buffer =
2669*fe013be4SDimitry Andric         llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
2670*fe013be4SDimitry Andric     uint8_t *dst = data_buffer->GetBytes() + rel_section->GetFileOffset() +
2671*fe013be4SDimitry Andric                    ELFRelocation::RelocOffset32(rel);
2672*fe013be4SDimitry Andric     // Implicit addend is stored inline as a signed value.
2673*fe013be4SDimitry Andric     int32_t addend;
2674*fe013be4SDimitry Andric     memcpy(&addend, dst, sizeof(int32_t));
2675*fe013be4SDimitry Andric     // The sum must be positive. This extra check prevents UB from overflow in
2676*fe013be4SDimitry Andric     // the actual range check below.
2677*fe013be4SDimitry Andric     if (addend < 0 && static_cast<uint32_t>(-addend) > value) {
2678*fe013be4SDimitry Andric       LLDB_LOGF(log, "Debug info relocation overflow: 0x%" PRIx64,
2679*fe013be4SDimitry Andric                 static_cast<int64_t>(value) + addend);
2680*fe013be4SDimitry Andric       return;
2681*fe013be4SDimitry Andric     }
2682*fe013be4SDimitry Andric     if (!llvm::isUInt<32>(value + addend)) {
2683*fe013be4SDimitry Andric       LLDB_LOGF(log, "Debug info relocation out of range: 0x%" PRIx64, value);
2684*fe013be4SDimitry Andric       return;
2685*fe013be4SDimitry Andric     }
2686*fe013be4SDimitry Andric     uint32_t addr = value + addend;
2687*fe013be4SDimitry Andric     memcpy(dst, &addr, sizeof(uint32_t));
2688*fe013be4SDimitry Andric   }
2689*fe013be4SDimitry Andric }
2690*fe013be4SDimitry Andric 
26910b57cec5SDimitry Andric unsigned ObjectFileELF::ApplyRelocations(
26920b57cec5SDimitry Andric     Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
26930b57cec5SDimitry Andric     const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr,
26940b57cec5SDimitry Andric     DataExtractor &rel_data, DataExtractor &symtab_data,
26950b57cec5SDimitry Andric     DataExtractor &debug_data, Section *rel_section) {
26960b57cec5SDimitry Andric   ELFRelocation rel(rel_hdr->sh_type);
26970b57cec5SDimitry Andric   lldb::addr_t offset = 0;
26980b57cec5SDimitry Andric   const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
26990b57cec5SDimitry Andric   typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
27000b57cec5SDimitry Andric   reloc_info_fn reloc_type;
27010b57cec5SDimitry Andric   reloc_info_fn reloc_symbol;
27020b57cec5SDimitry Andric 
27030b57cec5SDimitry Andric   if (hdr->Is32Bit()) {
27040b57cec5SDimitry Andric     reloc_type = ELFRelocation::RelocType32;
27050b57cec5SDimitry Andric     reloc_symbol = ELFRelocation::RelocSymbol32;
27060b57cec5SDimitry Andric   } else {
27070b57cec5SDimitry Andric     reloc_type = ELFRelocation::RelocType64;
27080b57cec5SDimitry Andric     reloc_symbol = ELFRelocation::RelocSymbol64;
27090b57cec5SDimitry Andric   }
27100b57cec5SDimitry Andric 
27110b57cec5SDimitry Andric   for (unsigned i = 0; i < num_relocations; ++i) {
2712bdd1243dSDimitry Andric     if (!rel.Parse(rel_data, &offset)) {
2713bdd1243dSDimitry Andric       GetModule()->ReportError(".rel{0}[{1:d}] failed to parse relocation",
2714bdd1243dSDimitry Andric                                rel_section->GetName().AsCString(), i);
27150b57cec5SDimitry Andric       break;
2716bdd1243dSDimitry Andric     }
27170b57cec5SDimitry Andric     Symbol *symbol = nullptr;
27180b57cec5SDimitry Andric 
27190b57cec5SDimitry Andric     if (hdr->Is32Bit()) {
2720*fe013be4SDimitry Andric       switch (hdr->e_machine) {
2721*fe013be4SDimitry Andric       case llvm::ELF::EM_ARM:
2722*fe013be4SDimitry Andric         switch (reloc_type(rel)) {
2723*fe013be4SDimitry Andric         case R_ARM_ABS32:
2724*fe013be4SDimitry Andric           ApplyELF32ABS32RelRelocation(symtab, rel, debug_data, rel_section);
2725*fe013be4SDimitry Andric           break;
2726*fe013be4SDimitry Andric         case R_ARM_REL32:
2727*fe013be4SDimitry Andric           GetModule()->ReportError("unsupported AArch32 relocation:"
2728*fe013be4SDimitry Andric                                    " .rel{0}[{1}], type {2}",
2729*fe013be4SDimitry Andric                                    rel_section->GetName().AsCString(), i,
2730*fe013be4SDimitry Andric                                    reloc_type(rel));
2731*fe013be4SDimitry Andric           break;
2732*fe013be4SDimitry Andric         default:
2733*fe013be4SDimitry Andric           assert(false && "unexpected relocation type");
2734*fe013be4SDimitry Andric         }
2735*fe013be4SDimitry Andric         break;
2736*fe013be4SDimitry Andric       case llvm::ELF::EM_386:
27370b57cec5SDimitry Andric         switch (reloc_type(rel)) {
27380b57cec5SDimitry Andric         case R_386_32:
2739bdd1243dSDimitry Andric           symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2740bdd1243dSDimitry Andric           if (symbol) {
2741bdd1243dSDimitry Andric             addr_t f_offset =
2742bdd1243dSDimitry Andric                 rel_section->GetFileOffset() + ELFRelocation::RelocOffset32(rel);
2743bdd1243dSDimitry Andric             DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2744bdd1243dSDimitry Andric             // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
2745bdd1243dSDimitry Andric             WritableDataBuffer *data_buffer =
2746bdd1243dSDimitry Andric                 llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
2747bdd1243dSDimitry Andric             uint32_t *dst = reinterpret_cast<uint32_t *>(
2748bdd1243dSDimitry Andric                 data_buffer->GetBytes() + f_offset);
2749bdd1243dSDimitry Andric 
2750bdd1243dSDimitry Andric             addr_t value = symbol->GetAddressRef().GetFileAddress();
2751bdd1243dSDimitry Andric             if (rel.IsRela()) {
2752bdd1243dSDimitry Andric               value += ELFRelocation::RelocAddend32(rel);
2753bdd1243dSDimitry Andric             } else {
2754bdd1243dSDimitry Andric               value += *dst;
2755bdd1243dSDimitry Andric             }
2756bdd1243dSDimitry Andric             *dst = value;
2757bdd1243dSDimitry Andric           } else {
2758bdd1243dSDimitry Andric             GetModule()->ReportError(".rel{0}[{1}] unknown symbol id: {2:d}",
2759bdd1243dSDimitry Andric                                     rel_section->GetName().AsCString(), i,
2760bdd1243dSDimitry Andric                                     reloc_symbol(rel));
2761bdd1243dSDimitry Andric           }
2762bdd1243dSDimitry Andric           break;
2763*fe013be4SDimitry Andric         case R_386_NONE:
27640b57cec5SDimitry Andric         case R_386_PC32:
2765*fe013be4SDimitry Andric           GetModule()->ReportError("unsupported i386 relocation:"
2766bdd1243dSDimitry Andric                                    " .rel{0}[{1}], type {2}",
2767bdd1243dSDimitry Andric                                    rel_section->GetName().AsCString(), i,
2768bdd1243dSDimitry Andric                                    reloc_type(rel));
2769*fe013be4SDimitry Andric           break;
2770*fe013be4SDimitry Andric         default:
2771*fe013be4SDimitry Andric           assert(false && "unexpected relocation type");
2772*fe013be4SDimitry Andric           break;
2773*fe013be4SDimitry Andric         }
2774*fe013be4SDimitry Andric         break;
2775*fe013be4SDimitry Andric       default:
2776*fe013be4SDimitry Andric         GetModule()->ReportError("unsupported 32-bit ELF machine arch: {0}", hdr->e_machine);
2777*fe013be4SDimitry Andric         break;
27780b57cec5SDimitry Andric       }
27790b57cec5SDimitry Andric     } else {
27801ac55f4cSDimitry Andric       switch (hdr->e_machine) {
27811ac55f4cSDimitry Andric       case llvm::ELF::EM_AARCH64:
27820b57cec5SDimitry Andric         switch (reloc_type(rel)) {
27830b57cec5SDimitry Andric         case R_AARCH64_ABS64:
27841ac55f4cSDimitry Andric           ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
27851ac55f4cSDimitry Andric           break;
27861ac55f4cSDimitry Andric         case R_AARCH64_ABS32:
27871ac55f4cSDimitry Andric           ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
27881ac55f4cSDimitry Andric           break;
27891ac55f4cSDimitry Andric         default:
27901ac55f4cSDimitry Andric           assert(false && "unexpected relocation type");
27910b57cec5SDimitry Andric         }
27920b57cec5SDimitry Andric         break;
27931ac55f4cSDimitry Andric       case llvm::ELF::EM_LOONGARCH:
27941ac55f4cSDimitry Andric         switch (reloc_type(rel)) {
27951ac55f4cSDimitry Andric         case R_LARCH_64:
27961ac55f4cSDimitry Andric           ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
27971ac55f4cSDimitry Andric           break;
27981ac55f4cSDimitry Andric         case R_LARCH_32:
27991ac55f4cSDimitry Andric           ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
28001ac55f4cSDimitry Andric           break;
28011ac55f4cSDimitry Andric         default:
28021ac55f4cSDimitry Andric           assert(false && "unexpected relocation type");
28030b57cec5SDimitry Andric         }
28041ac55f4cSDimitry Andric         break;
28051ac55f4cSDimitry Andric       case llvm::ELF::EM_X86_64:
28061ac55f4cSDimitry Andric         switch (reloc_type(rel)) {
28071ac55f4cSDimitry Andric         case R_X86_64_64:
28081ac55f4cSDimitry Andric           ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
28091ac55f4cSDimitry Andric           break;
28100b57cec5SDimitry Andric         case R_X86_64_32:
28111ac55f4cSDimitry Andric           ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section,
28121ac55f4cSDimitry Andric                                     false);
28131ac55f4cSDimitry Andric           break;
28140b57cec5SDimitry Andric         case R_X86_64_32S:
28151ac55f4cSDimitry Andric           ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
28160b57cec5SDimitry Andric           break;
28170b57cec5SDimitry Andric         case R_X86_64_PC32:
28180b57cec5SDimitry Andric         default:
28190b57cec5SDimitry Andric           assert(false && "unexpected relocation type");
28200b57cec5SDimitry Andric         }
28211ac55f4cSDimitry Andric         break;
28221ac55f4cSDimitry Andric       default:
2823*fe013be4SDimitry Andric         GetModule()->ReportError("unsupported 64-bit ELF machine arch: {0}", hdr->e_machine);
2824*fe013be4SDimitry Andric         break;
28251ac55f4cSDimitry Andric       }
28260b57cec5SDimitry Andric     }
28270b57cec5SDimitry Andric   }
28280b57cec5SDimitry Andric 
28290b57cec5SDimitry Andric   return 0;
28300b57cec5SDimitry Andric }
28310b57cec5SDimitry Andric 
28320b57cec5SDimitry Andric unsigned ObjectFileELF::RelocateDebugSections(const ELFSectionHeader *rel_hdr,
28330b57cec5SDimitry Andric                                               user_id_t rel_id,
28340b57cec5SDimitry Andric                                               lldb_private::Symtab *thetab) {
28350b57cec5SDimitry Andric   assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
28360b57cec5SDimitry Andric 
28370b57cec5SDimitry Andric   // Parse in the section list if needed.
28380b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
28390b57cec5SDimitry Andric   if (!section_list)
28400b57cec5SDimitry Andric     return 0;
28410b57cec5SDimitry Andric 
28420b57cec5SDimitry Andric   user_id_t symtab_id = rel_hdr->sh_link;
28430b57cec5SDimitry Andric   user_id_t debug_id = rel_hdr->sh_info;
28440b57cec5SDimitry Andric 
28450b57cec5SDimitry Andric   const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
28460b57cec5SDimitry Andric   if (!symtab_hdr)
28470b57cec5SDimitry Andric     return 0;
28480b57cec5SDimitry Andric 
28490b57cec5SDimitry Andric   const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id);
28500b57cec5SDimitry Andric   if (!debug_hdr)
28510b57cec5SDimitry Andric     return 0;
28520b57cec5SDimitry Andric 
28530b57cec5SDimitry Andric   Section *rel = section_list->FindSectionByID(rel_id).get();
28540b57cec5SDimitry Andric   if (!rel)
28550b57cec5SDimitry Andric     return 0;
28560b57cec5SDimitry Andric 
28570b57cec5SDimitry Andric   Section *symtab = section_list->FindSectionByID(symtab_id).get();
28580b57cec5SDimitry Andric   if (!symtab)
28590b57cec5SDimitry Andric     return 0;
28600b57cec5SDimitry Andric 
28610b57cec5SDimitry Andric   Section *debug = section_list->FindSectionByID(debug_id).get();
28620b57cec5SDimitry Andric   if (!debug)
28630b57cec5SDimitry Andric     return 0;
28640b57cec5SDimitry Andric 
28650b57cec5SDimitry Andric   DataExtractor rel_data;
28660b57cec5SDimitry Andric   DataExtractor symtab_data;
28670b57cec5SDimitry Andric   DataExtractor debug_data;
28680b57cec5SDimitry Andric 
28690b57cec5SDimitry Andric   if (GetData(rel->GetFileOffset(), rel->GetFileSize(), rel_data) &&
28700b57cec5SDimitry Andric       GetData(symtab->GetFileOffset(), symtab->GetFileSize(), symtab_data) &&
28710b57cec5SDimitry Andric       GetData(debug->GetFileOffset(), debug->GetFileSize(), debug_data)) {
28720b57cec5SDimitry Andric     ApplyRelocations(thetab, &m_header, rel_hdr, symtab_hdr, debug_hdr,
28730b57cec5SDimitry Andric                      rel_data, symtab_data, debug_data, debug);
28740b57cec5SDimitry Andric   }
28750b57cec5SDimitry Andric 
28760b57cec5SDimitry Andric   return 0;
28770b57cec5SDimitry Andric }
28780b57cec5SDimitry Andric 
28794824e7fdSDimitry Andric void ObjectFileELF::ParseSymtab(Symtab &lldb_symtab) {
28800b57cec5SDimitry Andric   ModuleSP module_sp(GetModule());
28810b57cec5SDimitry Andric   if (!module_sp)
28824824e7fdSDimitry Andric     return;
28834824e7fdSDimitry Andric 
28844824e7fdSDimitry Andric   Progress progress(
28854824e7fdSDimitry Andric       llvm::formatv("Parsing symbol table for {0}",
28864824e7fdSDimitry Andric                     m_file.GetFilename().AsCString("<Unknown>")));
28874824e7fdSDimitry Andric   ElapsedTime elapsed(module_sp->GetSymtabParseTime());
28880b57cec5SDimitry Andric 
28890b57cec5SDimitry Andric   // We always want to use the main object file so we (hopefully) only have one
28900b57cec5SDimitry Andric   // cached copy of our symtab, dynamic sections, etc.
28910b57cec5SDimitry Andric   ObjectFile *module_obj_file = module_sp->GetObjectFile();
28920b57cec5SDimitry Andric   if (module_obj_file && module_obj_file != this)
28934824e7fdSDimitry Andric     return module_obj_file->ParseSymtab(lldb_symtab);
28940b57cec5SDimitry Andric 
28950b57cec5SDimitry Andric   SectionList *section_list = module_sp->GetSectionList();
28960b57cec5SDimitry Andric   if (!section_list)
28974824e7fdSDimitry Andric     return;
28980b57cec5SDimitry Andric 
28990b57cec5SDimitry Andric   uint64_t symbol_id = 0;
29000b57cec5SDimitry Andric 
29010b57cec5SDimitry Andric   // Sharable objects and dynamic executables usually have 2 distinct symbol
29020b57cec5SDimitry Andric   // tables, one named ".symtab", and the other ".dynsym". The dynsym is a
29030b57cec5SDimitry Andric   // smaller version of the symtab that only contains global symbols. The
29040b57cec5SDimitry Andric   // information found in the dynsym is therefore also found in the symtab,
29050b57cec5SDimitry Andric   // while the reverse is not necessarily true.
29060b57cec5SDimitry Andric   Section *symtab =
29070b57cec5SDimitry Andric       section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get();
29084824e7fdSDimitry Andric   if (symtab)
29094824e7fdSDimitry Andric     symbol_id += ParseSymbolTable(&lldb_symtab, symbol_id, symtab);
29100b57cec5SDimitry Andric 
29119dba64beSDimitry Andric   // The symtab section is non-allocable and can be stripped, while the
29129dba64beSDimitry Andric   // .dynsym section which should always be always be there. To support the
29139dba64beSDimitry Andric   // minidebuginfo case we parse .dynsym when there's a .gnu_debuginfo
29149dba64beSDimitry Andric   // section, nomatter if .symtab was already parsed or not. This is because
29159dba64beSDimitry Andric   // minidebuginfo normally removes the .symtab symbols which have their
29169dba64beSDimitry Andric   // matching .dynsym counterparts.
29179dba64beSDimitry Andric   if (!symtab ||
29189dba64beSDimitry Andric       GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata"))) {
29199dba64beSDimitry Andric     Section *dynsym =
29209dba64beSDimitry Andric         section_list->FindSectionByType(eSectionTypeELFDynamicSymbols, true)
29219dba64beSDimitry Andric             .get();
29224824e7fdSDimitry Andric     if (dynsym)
29234824e7fdSDimitry Andric       symbol_id += ParseSymbolTable(&lldb_symtab, symbol_id, dynsym);
29249dba64beSDimitry Andric   }
29259dba64beSDimitry Andric 
29260b57cec5SDimitry Andric   // DT_JMPREL
29270b57cec5SDimitry Andric   //      If present, this entry's d_ptr member holds the address of
29280b57cec5SDimitry Andric   //      relocation
29290b57cec5SDimitry Andric   //      entries associated solely with the procedure linkage table.
29300b57cec5SDimitry Andric   //      Separating
29310b57cec5SDimitry Andric   //      these relocation entries lets the dynamic linker ignore them during
29320b57cec5SDimitry Andric   //      process initialization, if lazy binding is enabled. If this entry is
29330b57cec5SDimitry Andric   //      present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
29340b57cec5SDimitry Andric   //      also be present.
29350b57cec5SDimitry Andric   const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
29360b57cec5SDimitry Andric   if (symbol) {
29370b57cec5SDimitry Andric     // Synthesize trampoline symbols to help navigate the PLT.
29380b57cec5SDimitry Andric     addr_t addr = symbol->d_ptr;
29390b57cec5SDimitry Andric     Section *reloc_section =
29400b57cec5SDimitry Andric         section_list->FindSectionContainingFileAddress(addr).get();
29410b57cec5SDimitry Andric     if (reloc_section) {
29420b57cec5SDimitry Andric       user_id_t reloc_id = reloc_section->GetID();
29430b57cec5SDimitry Andric       const ELFSectionHeaderInfo *reloc_header =
29440b57cec5SDimitry Andric           GetSectionHeaderByIndex(reloc_id);
29454824e7fdSDimitry Andric       if (reloc_header)
29464824e7fdSDimitry Andric         ParseTrampolineSymbols(&lldb_symtab, symbol_id, reloc_header, reloc_id);
29470b57cec5SDimitry Andric     }
2948fe6060f1SDimitry Andric   }
29490b57cec5SDimitry Andric 
29500b57cec5SDimitry Andric   if (DWARFCallFrameInfo *eh_frame =
29510b57cec5SDimitry Andric           GetModule()->GetUnwindTable().GetEHFrameInfo()) {
29524824e7fdSDimitry Andric     ParseUnwindSymbols(&lldb_symtab, eh_frame);
29530b57cec5SDimitry Andric   }
29540b57cec5SDimitry Andric 
29559dba64beSDimitry Andric   // In the event that there's no symbol entry for the entry point we'll
29565ffd83dbSDimitry Andric   // artificially create one. We delegate to the symtab object the figuring
29579dba64beSDimitry Andric   // out of the proper size, this will usually make it span til the next
29589dba64beSDimitry Andric   // symbol it finds in the section. This means that if there are missing
29599dba64beSDimitry Andric   // symbols the entry point might span beyond its function definition.
29609dba64beSDimitry Andric   // We're fine with this as it doesn't make it worse than not having a
29619dba64beSDimitry Andric   // symbol entry at all.
29629dba64beSDimitry Andric   if (CalculateType() == eTypeExecutable) {
29639dba64beSDimitry Andric     ArchSpec arch = GetArchitecture();
29649dba64beSDimitry Andric     auto entry_point_addr = GetEntryPointAddress();
29659dba64beSDimitry Andric     bool is_valid_entry_point =
29669dba64beSDimitry Andric         entry_point_addr.IsValid() && entry_point_addr.IsSectionOffset();
29679dba64beSDimitry Andric     addr_t entry_point_file_addr = entry_point_addr.GetFileAddress();
29684824e7fdSDimitry Andric     if (is_valid_entry_point && !lldb_symtab.FindSymbolContainingFileAddress(
29699dba64beSDimitry Andric                                     entry_point_file_addr)) {
29704824e7fdSDimitry Andric       uint64_t symbol_id = lldb_symtab.GetNumSymbols();
2971fe6060f1SDimitry Andric       // Don't set the name for any synthetic symbols, the Symbol
2972fe6060f1SDimitry Andric       // object will generate one if needed when the name is accessed
2973fe6060f1SDimitry Andric       // via accessors.
2974fe6060f1SDimitry Andric       SectionSP section_sp = entry_point_addr.GetSection();
2975fe6060f1SDimitry Andric       Symbol symbol(
2976fe6060f1SDimitry Andric           /*symID=*/symbol_id,
2977fe6060f1SDimitry Andric           /*name=*/llvm::StringRef(), // Name will be auto generated.
2978fe6060f1SDimitry Andric           /*type=*/eSymbolTypeCode,
2979fe6060f1SDimitry Andric           /*external=*/true,
2980fe6060f1SDimitry Andric           /*is_debug=*/false,
2981fe6060f1SDimitry Andric           /*is_trampoline=*/false,
2982fe6060f1SDimitry Andric           /*is_artificial=*/true,
2983fe6060f1SDimitry Andric           /*section_sp=*/section_sp,
2984fe6060f1SDimitry Andric           /*offset=*/0,
2985fe6060f1SDimitry Andric           /*size=*/0, // FDE can span multiple symbols so don't use its size.
2986fe6060f1SDimitry Andric           /*size_is_valid=*/false,
2987fe6060f1SDimitry Andric           /*contains_linker_annotations=*/false,
2988fe6060f1SDimitry Andric           /*flags=*/0);
29899dba64beSDimitry Andric       // When the entry point is arm thumb we need to explicitly set its
29909dba64beSDimitry Andric       // class address to reflect that. This is important because expression
29919dba64beSDimitry Andric       // evaluation relies on correctly setting a breakpoint at this
29929dba64beSDimitry Andric       // address.
29939dba64beSDimitry Andric       if (arch.GetMachine() == llvm::Triple::arm &&
2994fe6060f1SDimitry Andric           (entry_point_file_addr & 1)) {
2995fe6060f1SDimitry Andric         symbol.GetAddressRef().SetOffset(entry_point_addr.GetOffset() ^ 1);
29969dba64beSDimitry Andric         m_address_class_map[entry_point_file_addr ^ 1] =
29979dba64beSDimitry Andric             AddressClass::eCodeAlternateISA;
2998fe6060f1SDimitry Andric       } else {
29999dba64beSDimitry Andric         m_address_class_map[entry_point_file_addr] = AddressClass::eCode;
30009dba64beSDimitry Andric       }
30014824e7fdSDimitry Andric       lldb_symtab.AddSymbol(symbol);
3002fe6060f1SDimitry Andric     }
30039dba64beSDimitry Andric   }
30040b57cec5SDimitry Andric }
30050b57cec5SDimitry Andric 
30060b57cec5SDimitry Andric void ObjectFileELF::RelocateSection(lldb_private::Section *section)
30070b57cec5SDimitry Andric {
30080b57cec5SDimitry Andric   static const char *debug_prefix = ".debug";
30090b57cec5SDimitry Andric 
30100b57cec5SDimitry Andric   // Set relocated bit so we stop getting called, regardless of whether we
30110b57cec5SDimitry Andric   // actually relocate.
30120b57cec5SDimitry Andric   section->SetIsRelocated(true);
30130b57cec5SDimitry Andric 
30140b57cec5SDimitry Andric   // We only relocate in ELF relocatable files
30150b57cec5SDimitry Andric   if (CalculateType() != eTypeObjectFile)
30160b57cec5SDimitry Andric     return;
30170b57cec5SDimitry Andric 
30180b57cec5SDimitry Andric   const char *section_name = section->GetName().GetCString();
30190b57cec5SDimitry Andric   // Can't relocate that which can't be named
30200b57cec5SDimitry Andric   if (section_name == nullptr)
30210b57cec5SDimitry Andric     return;
30220b57cec5SDimitry Andric 
30230b57cec5SDimitry Andric   // We don't relocate non-debug sections at the moment
30240b57cec5SDimitry Andric   if (strncmp(section_name, debug_prefix, strlen(debug_prefix)))
30250b57cec5SDimitry Andric     return;
30260b57cec5SDimitry Andric 
30270b57cec5SDimitry Andric   // Relocation section names to look for
30280b57cec5SDimitry Andric   std::string needle = std::string(".rel") + section_name;
30290b57cec5SDimitry Andric   std::string needlea = std::string(".rela") + section_name;
30300b57cec5SDimitry Andric 
30310b57cec5SDimitry Andric   for (SectionHeaderCollIter I = m_section_headers.begin();
30320b57cec5SDimitry Andric        I != m_section_headers.end(); ++I) {
30330b57cec5SDimitry Andric     if (I->sh_type == SHT_RELA || I->sh_type == SHT_REL) {
30340b57cec5SDimitry Andric       const char *hay_name = I->section_name.GetCString();
30350b57cec5SDimitry Andric       if (hay_name == nullptr)
30360b57cec5SDimitry Andric         continue;
30370b57cec5SDimitry Andric       if (needle == hay_name || needlea == hay_name) {
30380b57cec5SDimitry Andric         const ELFSectionHeader &reloc_header = *I;
30390b57cec5SDimitry Andric         user_id_t reloc_id = SectionIndex(I);
30400b57cec5SDimitry Andric         RelocateDebugSections(&reloc_header, reloc_id, GetSymtab());
30410b57cec5SDimitry Andric         break;
30420b57cec5SDimitry Andric       }
30430b57cec5SDimitry Andric     }
30440b57cec5SDimitry Andric   }
30450b57cec5SDimitry Andric }
30460b57cec5SDimitry Andric 
30470b57cec5SDimitry Andric void ObjectFileELF::ParseUnwindSymbols(Symtab *symbol_table,
30480b57cec5SDimitry Andric                                        DWARFCallFrameInfo *eh_frame) {
30490b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
30500b57cec5SDimitry Andric   if (!section_list)
30510b57cec5SDimitry Andric     return;
30520b57cec5SDimitry Andric 
30530b57cec5SDimitry Andric   // First we save the new symbols into a separate list and add them to the
30545ffd83dbSDimitry Andric   // symbol table after we collected all symbols we want to add. This is
30550b57cec5SDimitry Andric   // neccessary because adding a new symbol invalidates the internal index of
30560b57cec5SDimitry Andric   // the symtab what causing the next lookup to be slow because it have to
30570b57cec5SDimitry Andric   // recalculate the index first.
30580b57cec5SDimitry Andric   std::vector<Symbol> new_symbols;
30590b57cec5SDimitry Andric 
3060fe6060f1SDimitry Andric   size_t num_symbols = symbol_table->GetNumSymbols();
3061fe6060f1SDimitry Andric   uint64_t last_symbol_id =
3062fe6060f1SDimitry Andric       num_symbols ? symbol_table->SymbolAtIndex(num_symbols - 1)->GetID() : 0;
3063fe6060f1SDimitry Andric   eh_frame->ForEachFDEEntries([&](lldb::addr_t file_addr, uint32_t size,
3064fe6060f1SDimitry Andric                                   dw_offset_t) {
30650b57cec5SDimitry Andric     Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr);
30660b57cec5SDimitry Andric     if (symbol) {
30670b57cec5SDimitry Andric       if (!symbol->GetByteSizeIsValid()) {
30680b57cec5SDimitry Andric         symbol->SetByteSize(size);
30690b57cec5SDimitry Andric         symbol->SetSizeIsSynthesized(true);
30700b57cec5SDimitry Andric       }
30710b57cec5SDimitry Andric     } else {
30720b57cec5SDimitry Andric       SectionSP section_sp =
30730b57cec5SDimitry Andric           section_list->FindSectionContainingFileAddress(file_addr);
30740b57cec5SDimitry Andric       if (section_sp) {
30750b57cec5SDimitry Andric         addr_t offset = file_addr - section_sp->GetFileAddress();
3076fe6060f1SDimitry Andric         uint64_t symbol_id = ++last_symbol_id;
3077fe6060f1SDimitry Andric         // Don't set the name for any synthetic symbols, the Symbol
3078fe6060f1SDimitry Andric         // object will generate one if needed when the name is accessed
3079fe6060f1SDimitry Andric         // via accessors.
30800b57cec5SDimitry Andric         Symbol eh_symbol(
3081fe6060f1SDimitry Andric             /*symID=*/symbol_id,
3082fe6060f1SDimitry Andric             /*name=*/llvm::StringRef(), // Name will be auto generated.
3083fe6060f1SDimitry Andric             /*type=*/eSymbolTypeCode,
3084fe6060f1SDimitry Andric             /*external=*/true,
3085fe6060f1SDimitry Andric             /*is_debug=*/false,
3086fe6060f1SDimitry Andric             /*is_trampoline=*/false,
3087fe6060f1SDimitry Andric             /*is_artificial=*/true,
3088fe6060f1SDimitry Andric             /*section_sp=*/section_sp,
3089fe6060f1SDimitry Andric             /*offset=*/offset,
3090fe6060f1SDimitry Andric             /*size=*/0, // FDE can span multiple symbols so don't use its size.
3091fe6060f1SDimitry Andric             /*size_is_valid=*/false,
3092fe6060f1SDimitry Andric             /*contains_linker_annotations=*/false,
3093fe6060f1SDimitry Andric             /*flags=*/0);
30940b57cec5SDimitry Andric         new_symbols.push_back(eh_symbol);
30950b57cec5SDimitry Andric       }
30960b57cec5SDimitry Andric     }
30970b57cec5SDimitry Andric     return true;
30980b57cec5SDimitry Andric   });
30990b57cec5SDimitry Andric 
31000b57cec5SDimitry Andric   for (const Symbol &s : new_symbols)
31010b57cec5SDimitry Andric     symbol_table->AddSymbol(s);
31020b57cec5SDimitry Andric }
31030b57cec5SDimitry Andric 
31040b57cec5SDimitry Andric bool ObjectFileELF::IsStripped() {
31050b57cec5SDimitry Andric   // TODO: determine this for ELF
31060b57cec5SDimitry Andric   return false;
31070b57cec5SDimitry Andric }
31080b57cec5SDimitry Andric 
31090b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
31100b57cec5SDimitry Andric // Dump
31110b57cec5SDimitry Andric //
31120b57cec5SDimitry Andric // Dump the specifics of the runtime file container (such as any headers
31130b57cec5SDimitry Andric // segments, sections, etc).
31140b57cec5SDimitry Andric void ObjectFileELF::Dump(Stream *s) {
31150b57cec5SDimitry Andric   ModuleSP module_sp(GetModule());
31160b57cec5SDimitry Andric   if (!module_sp) {
31170b57cec5SDimitry Andric     return;
31180b57cec5SDimitry Andric   }
31190b57cec5SDimitry Andric 
31200b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
31210b57cec5SDimitry Andric   s->Printf("%p: ", static_cast<void *>(this));
31220b57cec5SDimitry Andric   s->Indent();
31230b57cec5SDimitry Andric   s->PutCString("ObjectFileELF");
31240b57cec5SDimitry Andric 
31250b57cec5SDimitry Andric   ArchSpec header_arch = GetArchitecture();
31260b57cec5SDimitry Andric 
31270b57cec5SDimitry Andric   *s << ", file = '" << m_file
31280b57cec5SDimitry Andric      << "', arch = " << header_arch.GetArchitectureName() << "\n";
31290b57cec5SDimitry Andric 
31300b57cec5SDimitry Andric   DumpELFHeader(s, m_header);
31310b57cec5SDimitry Andric   s->EOL();
31320b57cec5SDimitry Andric   DumpELFProgramHeaders(s);
31330b57cec5SDimitry Andric   s->EOL();
31340b57cec5SDimitry Andric   DumpELFSectionHeaders(s);
31350b57cec5SDimitry Andric   s->EOL();
31360b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
31370b57cec5SDimitry Andric   if (section_list)
31385ffd83dbSDimitry Andric     section_list->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
31395ffd83dbSDimitry Andric                        UINT32_MAX);
31400b57cec5SDimitry Andric   Symtab *symtab = GetSymtab();
31410b57cec5SDimitry Andric   if (symtab)
31420b57cec5SDimitry Andric     symtab->Dump(s, nullptr, eSortOrderNone);
31430b57cec5SDimitry Andric   s->EOL();
31440b57cec5SDimitry Andric   DumpDependentModules(s);
31450b57cec5SDimitry Andric   s->EOL();
31460b57cec5SDimitry Andric }
31470b57cec5SDimitry Andric 
31480b57cec5SDimitry Andric // DumpELFHeader
31490b57cec5SDimitry Andric //
31500b57cec5SDimitry Andric // Dump the ELF header to the specified output stream
31510b57cec5SDimitry Andric void ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header) {
31520b57cec5SDimitry Andric   s->PutCString("ELF Header\n");
31530b57cec5SDimitry Andric   s->Printf("e_ident[EI_MAG0   ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
31540b57cec5SDimitry Andric   s->Printf("e_ident[EI_MAG1   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG1],
31550b57cec5SDimitry Andric             header.e_ident[EI_MAG1]);
31560b57cec5SDimitry Andric   s->Printf("e_ident[EI_MAG2   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG2],
31570b57cec5SDimitry Andric             header.e_ident[EI_MAG2]);
31580b57cec5SDimitry Andric   s->Printf("e_ident[EI_MAG3   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG3],
31590b57cec5SDimitry Andric             header.e_ident[EI_MAG3]);
31600b57cec5SDimitry Andric 
31610b57cec5SDimitry Andric   s->Printf("e_ident[EI_CLASS  ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
31620b57cec5SDimitry Andric   s->Printf("e_ident[EI_DATA   ] = 0x%2.2x ", header.e_ident[EI_DATA]);
31630b57cec5SDimitry Andric   DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
31640b57cec5SDimitry Andric   s->Printf("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
31650b57cec5SDimitry Andric   s->Printf("e_ident[EI_PAD    ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
31660b57cec5SDimitry Andric 
31670b57cec5SDimitry Andric   s->Printf("e_type      = 0x%4.4x ", header.e_type);
31680b57cec5SDimitry Andric   DumpELFHeader_e_type(s, header.e_type);
31690b57cec5SDimitry Andric   s->Printf("\ne_machine   = 0x%4.4x\n", header.e_machine);
31700b57cec5SDimitry Andric   s->Printf("e_version   = 0x%8.8x\n", header.e_version);
31710b57cec5SDimitry Andric   s->Printf("e_entry     = 0x%8.8" PRIx64 "\n", header.e_entry);
31720b57cec5SDimitry Andric   s->Printf("e_phoff     = 0x%8.8" PRIx64 "\n", header.e_phoff);
31730b57cec5SDimitry Andric   s->Printf("e_shoff     = 0x%8.8" PRIx64 "\n", header.e_shoff);
31740b57cec5SDimitry Andric   s->Printf("e_flags     = 0x%8.8x\n", header.e_flags);
31750b57cec5SDimitry Andric   s->Printf("e_ehsize    = 0x%4.4x\n", header.e_ehsize);
31760b57cec5SDimitry Andric   s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
31770b57cec5SDimitry Andric   s->Printf("e_phnum     = 0x%8.8x\n", header.e_phnum);
31780b57cec5SDimitry Andric   s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
31790b57cec5SDimitry Andric   s->Printf("e_shnum     = 0x%8.8x\n", header.e_shnum);
31800b57cec5SDimitry Andric   s->Printf("e_shstrndx  = 0x%8.8x\n", header.e_shstrndx);
31810b57cec5SDimitry Andric }
31820b57cec5SDimitry Andric 
31830b57cec5SDimitry Andric // DumpELFHeader_e_type
31840b57cec5SDimitry Andric //
31850b57cec5SDimitry Andric // Dump an token value for the ELF header member e_type
31860b57cec5SDimitry Andric void ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type) {
31870b57cec5SDimitry Andric   switch (e_type) {
31880b57cec5SDimitry Andric   case ET_NONE:
31890b57cec5SDimitry Andric     *s << "ET_NONE";
31900b57cec5SDimitry Andric     break;
31910b57cec5SDimitry Andric   case ET_REL:
31920b57cec5SDimitry Andric     *s << "ET_REL";
31930b57cec5SDimitry Andric     break;
31940b57cec5SDimitry Andric   case ET_EXEC:
31950b57cec5SDimitry Andric     *s << "ET_EXEC";
31960b57cec5SDimitry Andric     break;
31970b57cec5SDimitry Andric   case ET_DYN:
31980b57cec5SDimitry Andric     *s << "ET_DYN";
31990b57cec5SDimitry Andric     break;
32000b57cec5SDimitry Andric   case ET_CORE:
32010b57cec5SDimitry Andric     *s << "ET_CORE";
32020b57cec5SDimitry Andric     break;
32030b57cec5SDimitry Andric   default:
32040b57cec5SDimitry Andric     break;
32050b57cec5SDimitry Andric   }
32060b57cec5SDimitry Andric }
32070b57cec5SDimitry Andric 
32080b57cec5SDimitry Andric // DumpELFHeader_e_ident_EI_DATA
32090b57cec5SDimitry Andric //
32100b57cec5SDimitry Andric // Dump an token value for the ELF header member e_ident[EI_DATA]
32110b57cec5SDimitry Andric void ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s,
32120b57cec5SDimitry Andric                                                   unsigned char ei_data) {
32130b57cec5SDimitry Andric   switch (ei_data) {
32140b57cec5SDimitry Andric   case ELFDATANONE:
32150b57cec5SDimitry Andric     *s << "ELFDATANONE";
32160b57cec5SDimitry Andric     break;
32170b57cec5SDimitry Andric   case ELFDATA2LSB:
32180b57cec5SDimitry Andric     *s << "ELFDATA2LSB - Little Endian";
32190b57cec5SDimitry Andric     break;
32200b57cec5SDimitry Andric   case ELFDATA2MSB:
32210b57cec5SDimitry Andric     *s << "ELFDATA2MSB - Big Endian";
32220b57cec5SDimitry Andric     break;
32230b57cec5SDimitry Andric   default:
32240b57cec5SDimitry Andric     break;
32250b57cec5SDimitry Andric   }
32260b57cec5SDimitry Andric }
32270b57cec5SDimitry Andric 
32280b57cec5SDimitry Andric // DumpELFProgramHeader
32290b57cec5SDimitry Andric //
32300b57cec5SDimitry Andric // Dump a single ELF program header to the specified output stream
32310b57cec5SDimitry Andric void ObjectFileELF::DumpELFProgramHeader(Stream *s,
32320b57cec5SDimitry Andric                                          const ELFProgramHeader &ph) {
32330b57cec5SDimitry Andric   DumpELFProgramHeader_p_type(s, ph.p_type);
32340b57cec5SDimitry Andric   s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset,
32350b57cec5SDimitry Andric             ph.p_vaddr, ph.p_paddr);
32360b57cec5SDimitry Andric   s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz,
32370b57cec5SDimitry Andric             ph.p_flags);
32380b57cec5SDimitry Andric 
32390b57cec5SDimitry Andric   DumpELFProgramHeader_p_flags(s, ph.p_flags);
32400b57cec5SDimitry Andric   s->Printf(") %8.8" PRIx64, ph.p_align);
32410b57cec5SDimitry Andric }
32420b57cec5SDimitry Andric 
32430b57cec5SDimitry Andric // DumpELFProgramHeader_p_type
32440b57cec5SDimitry Andric //
32450b57cec5SDimitry Andric // Dump an token value for the ELF program header member p_type which describes
32460b57cec5SDimitry Andric // the type of the program header
32470b57cec5SDimitry Andric void ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type) {
32480b57cec5SDimitry Andric   const int kStrWidth = 15;
32490b57cec5SDimitry Andric   switch (p_type) {
32500b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_NULL, kStrWidth);
32510b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_LOAD, kStrWidth);
32520b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_DYNAMIC, kStrWidth);
32530b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_INTERP, kStrWidth);
32540b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_NOTE, kStrWidth);
32550b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_SHLIB, kStrWidth);
32560b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_PHDR, kStrWidth);
32570b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_TLS, kStrWidth);
32580b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
32590b57cec5SDimitry Andric   default:
32600b57cec5SDimitry Andric     s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
32610b57cec5SDimitry Andric     break;
32620b57cec5SDimitry Andric   }
32630b57cec5SDimitry Andric }
32640b57cec5SDimitry Andric 
32650b57cec5SDimitry Andric // DumpELFProgramHeader_p_flags
32660b57cec5SDimitry Andric //
32670b57cec5SDimitry Andric // Dump an token value for the ELF program header member p_flags
32680b57cec5SDimitry Andric void ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags) {
32690b57cec5SDimitry Andric   *s << ((p_flags & PF_X) ? "PF_X" : "    ")
32700b57cec5SDimitry Andric      << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
32710b57cec5SDimitry Andric      << ((p_flags & PF_W) ? "PF_W" : "    ")
32720b57cec5SDimitry Andric      << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
32730b57cec5SDimitry Andric      << ((p_flags & PF_R) ? "PF_R" : "    ");
32740b57cec5SDimitry Andric }
32750b57cec5SDimitry Andric 
32760b57cec5SDimitry Andric // DumpELFProgramHeaders
32770b57cec5SDimitry Andric //
32780b57cec5SDimitry Andric // Dump all of the ELF program header to the specified output stream
32790b57cec5SDimitry Andric void ObjectFileELF::DumpELFProgramHeaders(Stream *s) {
32800b57cec5SDimitry Andric   if (!ParseProgramHeaders())
32810b57cec5SDimitry Andric     return;
32820b57cec5SDimitry Andric 
32830b57cec5SDimitry Andric   s->PutCString("Program Headers\n");
32840b57cec5SDimitry Andric   s->PutCString("IDX  p_type          p_offset p_vaddr  p_paddr  "
32850b57cec5SDimitry Andric                 "p_filesz p_memsz  p_flags                   p_align\n");
32860b57cec5SDimitry Andric   s->PutCString("==== --------------- -------- -------- -------- "
32870b57cec5SDimitry Andric                 "-------- -------- ------------------------- --------\n");
32880b57cec5SDimitry Andric 
32890b57cec5SDimitry Andric   for (const auto &H : llvm::enumerate(m_program_headers)) {
32900b57cec5SDimitry Andric     s->Format("[{0,2}] ", H.index());
32910b57cec5SDimitry Andric     ObjectFileELF::DumpELFProgramHeader(s, H.value());
32920b57cec5SDimitry Andric     s->EOL();
32930b57cec5SDimitry Andric   }
32940b57cec5SDimitry Andric }
32950b57cec5SDimitry Andric 
32960b57cec5SDimitry Andric // DumpELFSectionHeader
32970b57cec5SDimitry Andric //
32980b57cec5SDimitry Andric // Dump a single ELF section header to the specified output stream
32990b57cec5SDimitry Andric void ObjectFileELF::DumpELFSectionHeader(Stream *s,
33000b57cec5SDimitry Andric                                          const ELFSectionHeaderInfo &sh) {
33010b57cec5SDimitry Andric   s->Printf("%8.8x ", sh.sh_name);
33020b57cec5SDimitry Andric   DumpELFSectionHeader_sh_type(s, sh.sh_type);
33030b57cec5SDimitry Andric   s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
33040b57cec5SDimitry Andric   DumpELFSectionHeader_sh_flags(s, sh.sh_flags);
33050b57cec5SDimitry Andric   s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr,
33060b57cec5SDimitry Andric             sh.sh_offset, sh.sh_size);
33070b57cec5SDimitry Andric   s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
33080b57cec5SDimitry Andric   s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
33090b57cec5SDimitry Andric }
33100b57cec5SDimitry Andric 
33110b57cec5SDimitry Andric // DumpELFSectionHeader_sh_type
33120b57cec5SDimitry Andric //
33130b57cec5SDimitry Andric // Dump an token value for the ELF section header member sh_type which
33140b57cec5SDimitry Andric // describes the type of the section
33150b57cec5SDimitry Andric void ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type) {
33160b57cec5SDimitry Andric   const int kStrWidth = 12;
33170b57cec5SDimitry Andric   switch (sh_type) {
33180b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_NULL, kStrWidth);
33190b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_PROGBITS, kStrWidth);
33200b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_SYMTAB, kStrWidth);
33210b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_STRTAB, kStrWidth);
33220b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_RELA, kStrWidth);
33230b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_HASH, kStrWidth);
33240b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_DYNAMIC, kStrWidth);
33250b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_NOTE, kStrWidth);
33260b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_NOBITS, kStrWidth);
33270b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_REL, kStrWidth);
33280b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth);
33290b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_DYNSYM, kStrWidth);
33300b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth);
33310b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth);
33320b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth);
33330b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth);
33340b57cec5SDimitry Andric   default:
33350b57cec5SDimitry Andric     s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
33360b57cec5SDimitry Andric     break;
33370b57cec5SDimitry Andric   }
33380b57cec5SDimitry Andric }
33390b57cec5SDimitry Andric 
33400b57cec5SDimitry Andric // DumpELFSectionHeader_sh_flags
33410b57cec5SDimitry Andric //
33420b57cec5SDimitry Andric // Dump an token value for the ELF section header member sh_flags
33430b57cec5SDimitry Andric void ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s,
33440b57cec5SDimitry Andric                                                   elf_xword sh_flags) {
33450b57cec5SDimitry Andric   *s << ((sh_flags & SHF_WRITE) ? "WRITE" : "     ")
33460b57cec5SDimitry Andric      << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
33470b57cec5SDimitry Andric      << ((sh_flags & SHF_ALLOC) ? "ALLOC" : "     ")
33480b57cec5SDimitry Andric      << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
33490b57cec5SDimitry Andric      << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : "         ");
33500b57cec5SDimitry Andric }
33510b57cec5SDimitry Andric 
33520b57cec5SDimitry Andric // DumpELFSectionHeaders
33530b57cec5SDimitry Andric //
33540b57cec5SDimitry Andric // Dump all of the ELF section header to the specified output stream
33550b57cec5SDimitry Andric void ObjectFileELF::DumpELFSectionHeaders(Stream *s) {
33560b57cec5SDimitry Andric   if (!ParseSectionHeaders())
33570b57cec5SDimitry Andric     return;
33580b57cec5SDimitry Andric 
33590b57cec5SDimitry Andric   s->PutCString("Section Headers\n");
33600b57cec5SDimitry Andric   s->PutCString("IDX  name     type         flags                            "
33610b57cec5SDimitry Andric                 "addr     offset   size     link     info     addralgn "
33620b57cec5SDimitry Andric                 "entsize  Name\n");
33630b57cec5SDimitry Andric   s->PutCString("==== -------- ------------ -------------------------------- "
33640b57cec5SDimitry Andric                 "-------- -------- -------- -------- -------- -------- "
33650b57cec5SDimitry Andric                 "-------- ====================\n");
33660b57cec5SDimitry Andric 
33670b57cec5SDimitry Andric   uint32_t idx = 0;
33680b57cec5SDimitry Andric   for (SectionHeaderCollConstIter I = m_section_headers.begin();
33690b57cec5SDimitry Andric        I != m_section_headers.end(); ++I, ++idx) {
33700b57cec5SDimitry Andric     s->Printf("[%2u] ", idx);
33710b57cec5SDimitry Andric     ObjectFileELF::DumpELFSectionHeader(s, *I);
33720b57cec5SDimitry Andric     const char *section_name = I->section_name.AsCString("");
33730b57cec5SDimitry Andric     if (section_name)
33740b57cec5SDimitry Andric       *s << ' ' << section_name << "\n";
33750b57cec5SDimitry Andric   }
33760b57cec5SDimitry Andric }
33770b57cec5SDimitry Andric 
33780b57cec5SDimitry Andric void ObjectFileELF::DumpDependentModules(lldb_private::Stream *s) {
33790b57cec5SDimitry Andric   size_t num_modules = ParseDependentModules();
33800b57cec5SDimitry Andric 
33810b57cec5SDimitry Andric   if (num_modules > 0) {
33820b57cec5SDimitry Andric     s->PutCString("Dependent Modules:\n");
33830b57cec5SDimitry Andric     for (unsigned i = 0; i < num_modules; ++i) {
33840b57cec5SDimitry Andric       const FileSpec &spec = m_filespec_up->GetFileSpecAtIndex(i);
33850b57cec5SDimitry Andric       s->Printf("   %s\n", spec.GetFilename().GetCString());
33860b57cec5SDimitry Andric     }
33870b57cec5SDimitry Andric   }
33880b57cec5SDimitry Andric }
33890b57cec5SDimitry Andric 
33900b57cec5SDimitry Andric ArchSpec ObjectFileELF::GetArchitecture() {
33910b57cec5SDimitry Andric   if (!ParseHeader())
33920b57cec5SDimitry Andric     return ArchSpec();
33930b57cec5SDimitry Andric 
33940b57cec5SDimitry Andric   if (m_section_headers.empty()) {
33950b57cec5SDimitry Andric     // Allow elf notes to be parsed which may affect the detected architecture.
33960b57cec5SDimitry Andric     ParseSectionHeaders();
33970b57cec5SDimitry Andric   }
33980b57cec5SDimitry Andric 
33990b57cec5SDimitry Andric   if (CalculateType() == eTypeCoreFile &&
34000b57cec5SDimitry Andric       !m_arch_spec.TripleOSWasSpecified()) {
34010b57cec5SDimitry Andric     // Core files don't have section headers yet they have PT_NOTE program
34020b57cec5SDimitry Andric     // headers that might shed more light on the architecture
34030b57cec5SDimitry Andric     for (const elf::ELFProgramHeader &H : ProgramHeaders()) {
34040b57cec5SDimitry Andric       if (H.p_type != PT_NOTE || H.p_offset == 0 || H.p_filesz == 0)
34050b57cec5SDimitry Andric         continue;
34060b57cec5SDimitry Andric       DataExtractor data;
34070b57cec5SDimitry Andric       if (data.SetData(m_data, H.p_offset, H.p_filesz) == H.p_filesz) {
34080b57cec5SDimitry Andric         UUID uuid;
34090b57cec5SDimitry Andric         RefineModuleDetailsFromNote(data, m_arch_spec, uuid);
34100b57cec5SDimitry Andric       }
34110b57cec5SDimitry Andric     }
34120b57cec5SDimitry Andric   }
34130b57cec5SDimitry Andric   return m_arch_spec;
34140b57cec5SDimitry Andric }
34150b57cec5SDimitry Andric 
34160b57cec5SDimitry Andric ObjectFile::Type ObjectFileELF::CalculateType() {
34170b57cec5SDimitry Andric   switch (m_header.e_type) {
34180b57cec5SDimitry Andric   case llvm::ELF::ET_NONE:
34190b57cec5SDimitry Andric     // 0 - No file type
34200b57cec5SDimitry Andric     return eTypeUnknown;
34210b57cec5SDimitry Andric 
34220b57cec5SDimitry Andric   case llvm::ELF::ET_REL:
34230b57cec5SDimitry Andric     // 1 - Relocatable file
34240b57cec5SDimitry Andric     return eTypeObjectFile;
34250b57cec5SDimitry Andric 
34260b57cec5SDimitry Andric   case llvm::ELF::ET_EXEC:
34270b57cec5SDimitry Andric     // 2 - Executable file
34280b57cec5SDimitry Andric     return eTypeExecutable;
34290b57cec5SDimitry Andric 
34300b57cec5SDimitry Andric   case llvm::ELF::ET_DYN:
34310b57cec5SDimitry Andric     // 3 - Shared object file
34320b57cec5SDimitry Andric     return eTypeSharedLibrary;
34330b57cec5SDimitry Andric 
34340b57cec5SDimitry Andric   case ET_CORE:
34350b57cec5SDimitry Andric     // 4 - Core file
34360b57cec5SDimitry Andric     return eTypeCoreFile;
34370b57cec5SDimitry Andric 
34380b57cec5SDimitry Andric   default:
34390b57cec5SDimitry Andric     break;
34400b57cec5SDimitry Andric   }
34410b57cec5SDimitry Andric   return eTypeUnknown;
34420b57cec5SDimitry Andric }
34430b57cec5SDimitry Andric 
34440b57cec5SDimitry Andric ObjectFile::Strata ObjectFileELF::CalculateStrata() {
34450b57cec5SDimitry Andric   switch (m_header.e_type) {
34460b57cec5SDimitry Andric   case llvm::ELF::ET_NONE:
34470b57cec5SDimitry Andric     // 0 - No file type
34480b57cec5SDimitry Andric     return eStrataUnknown;
34490b57cec5SDimitry Andric 
34500b57cec5SDimitry Andric   case llvm::ELF::ET_REL:
34510b57cec5SDimitry Andric     // 1 - Relocatable file
34520b57cec5SDimitry Andric     return eStrataUnknown;
34530b57cec5SDimitry Andric 
34540b57cec5SDimitry Andric   case llvm::ELF::ET_EXEC:
34550b57cec5SDimitry Andric     // 2 - Executable file
34560b57cec5SDimitry Andric     // TODO: is there any way to detect that an executable is a kernel
34570b57cec5SDimitry Andric     // related executable by inspecting the program headers, section headers,
34580b57cec5SDimitry Andric     // symbols, or any other flag bits???
34590b57cec5SDimitry Andric     return eStrataUser;
34600b57cec5SDimitry Andric 
34610b57cec5SDimitry Andric   case llvm::ELF::ET_DYN:
34620b57cec5SDimitry Andric     // 3 - Shared object file
34630b57cec5SDimitry Andric     // TODO: is there any way to detect that an shared library is a kernel
34640b57cec5SDimitry Andric     // related executable by inspecting the program headers, section headers,
34650b57cec5SDimitry Andric     // symbols, or any other flag bits???
34660b57cec5SDimitry Andric     return eStrataUnknown;
34670b57cec5SDimitry Andric 
34680b57cec5SDimitry Andric   case ET_CORE:
34690b57cec5SDimitry Andric     // 4 - Core file
34700b57cec5SDimitry Andric     // TODO: is there any way to detect that an core file is a kernel
34710b57cec5SDimitry Andric     // related executable by inspecting the program headers, section headers,
34720b57cec5SDimitry Andric     // symbols, or any other flag bits???
34730b57cec5SDimitry Andric     return eStrataUnknown;
34740b57cec5SDimitry Andric 
34750b57cec5SDimitry Andric   default:
34760b57cec5SDimitry Andric     break;
34770b57cec5SDimitry Andric   }
34780b57cec5SDimitry Andric   return eStrataUnknown;
34790b57cec5SDimitry Andric }
34800b57cec5SDimitry Andric 
34810b57cec5SDimitry Andric size_t ObjectFileELF::ReadSectionData(Section *section,
34820b57cec5SDimitry Andric                        lldb::offset_t section_offset, void *dst,
34830b57cec5SDimitry Andric                        size_t dst_len) {
34840b57cec5SDimitry Andric   // If some other objectfile owns this data, pass this to them.
34850b57cec5SDimitry Andric   if (section->GetObjectFile() != this)
34860b57cec5SDimitry Andric     return section->GetObjectFile()->ReadSectionData(section, section_offset,
34870b57cec5SDimitry Andric                                                      dst, dst_len);
34880b57cec5SDimitry Andric 
34890b57cec5SDimitry Andric   if (!section->Test(SHF_COMPRESSED))
34900b57cec5SDimitry Andric     return ObjectFile::ReadSectionData(section, section_offset, dst, dst_len);
34910b57cec5SDimitry Andric 
34920b57cec5SDimitry Andric   // For compressed sections we need to read to full data to be able to
34930b57cec5SDimitry Andric   // decompress.
34940b57cec5SDimitry Andric   DataExtractor data;
34950b57cec5SDimitry Andric   ReadSectionData(section, data);
34960b57cec5SDimitry Andric   return data.CopyData(section_offset, dst_len, dst);
34970b57cec5SDimitry Andric }
34980b57cec5SDimitry Andric 
34990b57cec5SDimitry Andric size_t ObjectFileELF::ReadSectionData(Section *section,
35000b57cec5SDimitry Andric                                       DataExtractor &section_data) {
35010b57cec5SDimitry Andric   // If some other objectfile owns this data, pass this to them.
35020b57cec5SDimitry Andric   if (section->GetObjectFile() != this)
35030b57cec5SDimitry Andric     return section->GetObjectFile()->ReadSectionData(section, section_data);
35040b57cec5SDimitry Andric 
35050b57cec5SDimitry Andric   size_t result = ObjectFile::ReadSectionData(section, section_data);
3506fcaf7f86SDimitry Andric   if (result == 0 || !(section->Get() & llvm::ELF::SHF_COMPRESSED))
35070b57cec5SDimitry Andric     return result;
35080b57cec5SDimitry Andric 
35090b57cec5SDimitry Andric   auto Decompressor = llvm::object::Decompressor::create(
35100b57cec5SDimitry Andric       section->GetName().GetStringRef(),
35110b57cec5SDimitry Andric       {reinterpret_cast<const char *>(section_data.GetDataStart()),
35120b57cec5SDimitry Andric        size_t(section_data.GetByteSize())},
35130b57cec5SDimitry Andric       GetByteOrder() == eByteOrderLittle, GetAddressByteSize() == 8);
35140b57cec5SDimitry Andric   if (!Decompressor) {
35150b57cec5SDimitry Andric     GetModule()->ReportWarning(
3516bdd1243dSDimitry Andric         "Unable to initialize decompressor for section '{0}': {1}",
35170b57cec5SDimitry Andric         section->GetName().GetCString(),
35180b57cec5SDimitry Andric         llvm::toString(Decompressor.takeError()).c_str());
35190b57cec5SDimitry Andric     section_data.Clear();
35200b57cec5SDimitry Andric     return 0;
35210b57cec5SDimitry Andric   }
35220b57cec5SDimitry Andric 
35230b57cec5SDimitry Andric   auto buffer_sp =
35240b57cec5SDimitry Andric       std::make_shared<DataBufferHeap>(Decompressor->getDecompressedSize(), 0);
35250b57cec5SDimitry Andric   if (auto error = Decompressor->decompress(
3526753f127fSDimitry Andric           {buffer_sp->GetBytes(), size_t(buffer_sp->GetByteSize())})) {
3527bdd1243dSDimitry Andric     GetModule()->ReportWarning("Decompression of section '{0}' failed: {1}",
35280b57cec5SDimitry Andric                                section->GetName().GetCString(),
35290b57cec5SDimitry Andric                                llvm::toString(std::move(error)).c_str());
35300b57cec5SDimitry Andric     section_data.Clear();
35310b57cec5SDimitry Andric     return 0;
35320b57cec5SDimitry Andric   }
35330b57cec5SDimitry Andric 
35340b57cec5SDimitry Andric   section_data.SetData(buffer_sp);
35350b57cec5SDimitry Andric   return buffer_sp->GetByteSize();
35360b57cec5SDimitry Andric }
35370b57cec5SDimitry Andric 
35380b57cec5SDimitry Andric llvm::ArrayRef<ELFProgramHeader> ObjectFileELF::ProgramHeaders() {
35390b57cec5SDimitry Andric   ParseProgramHeaders();
35400b57cec5SDimitry Andric   return m_program_headers;
35410b57cec5SDimitry Andric }
35420b57cec5SDimitry Andric 
35430b57cec5SDimitry Andric DataExtractor ObjectFileELF::GetSegmentData(const ELFProgramHeader &H) {
35440b57cec5SDimitry Andric   return DataExtractor(m_data, H.p_offset, H.p_filesz);
35450b57cec5SDimitry Andric }
35460b57cec5SDimitry Andric 
35470b57cec5SDimitry Andric bool ObjectFileELF::AnySegmentHasPhysicalAddress() {
35480b57cec5SDimitry Andric   for (const ELFProgramHeader &H : ProgramHeaders()) {
35490b57cec5SDimitry Andric     if (H.p_paddr != 0)
35500b57cec5SDimitry Andric       return true;
35510b57cec5SDimitry Andric   }
35520b57cec5SDimitry Andric   return false;
35530b57cec5SDimitry Andric }
35540b57cec5SDimitry Andric 
35550b57cec5SDimitry Andric std::vector<ObjectFile::LoadableData>
35560b57cec5SDimitry Andric ObjectFileELF::GetLoadableData(Target &target) {
35570b57cec5SDimitry Andric   // Create a list of loadable data from loadable segments, using physical
35580b57cec5SDimitry Andric   // addresses if they aren't all null
35590b57cec5SDimitry Andric   std::vector<LoadableData> loadables;
35600b57cec5SDimitry Andric   bool should_use_paddr = AnySegmentHasPhysicalAddress();
35610b57cec5SDimitry Andric   for (const ELFProgramHeader &H : ProgramHeaders()) {
35620b57cec5SDimitry Andric     LoadableData loadable;
35630b57cec5SDimitry Andric     if (H.p_type != llvm::ELF::PT_LOAD)
35640b57cec5SDimitry Andric       continue;
35650b57cec5SDimitry Andric     loadable.Dest = should_use_paddr ? H.p_paddr : H.p_vaddr;
35660b57cec5SDimitry Andric     if (loadable.Dest == LLDB_INVALID_ADDRESS)
35670b57cec5SDimitry Andric       continue;
35680b57cec5SDimitry Andric     if (H.p_filesz == 0)
35690b57cec5SDimitry Andric       continue;
35700b57cec5SDimitry Andric     auto segment_data = GetSegmentData(H);
35710b57cec5SDimitry Andric     loadable.Contents = llvm::ArrayRef<uint8_t>(segment_data.GetDataStart(),
35720b57cec5SDimitry Andric                                                 segment_data.GetByteSize());
35730b57cec5SDimitry Andric     loadables.push_back(loadable);
35740b57cec5SDimitry Andric   }
35750b57cec5SDimitry Andric   return loadables;
35760b57cec5SDimitry Andric }
357781ad6265SDimitry Andric 
357881ad6265SDimitry Andric lldb::WritableDataBufferSP
357981ad6265SDimitry Andric ObjectFileELF::MapFileDataWritable(const FileSpec &file, uint64_t Size,
358081ad6265SDimitry Andric                                    uint64_t Offset) {
358181ad6265SDimitry Andric   return FileSystem::Instance().CreateWritableDataBuffer(file.GetPath(), Size,
358281ad6265SDimitry Andric                                                          Offset);
358381ad6265SDimitry Andric }
3584