xref: /freebsd-src/contrib/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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"
2906c3fb27SDimitry 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);
55806c3fb27SDimitry Andric         // In Android API level 23 and above, bionic dynamic linker is able to
55906c3fb27SDimitry Andric         // load .so file directly from zip file. In that case, .so file is
56006c3fb27SDimitry Andric         // page aligned and uncompressed, and this module spec should retain the
56106c3fb27SDimitry Andric         // .so file offset and file size to pass through the information from
56206c3fb27SDimitry Andric         // lldb-server to LLDB. For normal file, file_offset should be 0,
56306c3fb27SDimitry Andric         // length should be the size of the file.
56406c3fb27SDimitry Andric         spec.SetObjectOffset(file_offset);
56506c3fb27SDimitry 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 
59706c3fb27SDimitry Andric           // When ELF file does not contain GNU build ID, the later code will
59806c3fb27SDimitry Andric           // calculate CRC32 with this data_sp file_offset and length. It is
59906c3fb27SDimitry Andric           // important for Android zip .so file, which is a slice of a file,
60006c3fb27SDimitry Andric           // to not access the outside of the file slice range.
6015ffd83dbSDimitry Andric           if (data_sp->GetByteSize() < length)
60206c3fb27SDimitry 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",
63806c3fb27SDimitry 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));
720*0fca6ea1SDimitry Andric 
721*0fca6ea1SDimitry Andric         // PT_TLS segments can have the same p_vaddr and p_paddr as other
722*0fca6ea1SDimitry Andric         // PT_LOAD segments so we shouldn't load them. If we do load them, then
723*0fca6ea1SDimitry Andric         // the SectionLoadList will incorrectly fill in the instance variable
724*0fca6ea1SDimitry Andric         // SectionLoadList::m_addr_to_sect with the same address as a PT_LOAD
725*0fca6ea1SDimitry Andric         // segment and we won't be able to resolve addresses in the PT_LOAD
726*0fca6ea1SDimitry Andric         // segment whose p_vaddr entry matches that of the PT_TLS. Any variables
727*0fca6ea1SDimitry Andric         // that appear in the PT_TLS segments get resolved by the DWARF
728*0fca6ea1SDimitry Andric         // expressions. If this ever changes we will need to fix all object
729*0fca6ea1SDimitry Andric         // file plug-ins, but until then, we don't want PT_TLS segments to
730*0fca6ea1SDimitry Andric         // remove the entry from SectionLoadList::m_addr_to_sect when we call
731*0fca6ea1SDimitry Andric         // SetSectionLoadAddress() below.
732*0fca6ea1SDimitry Andric         if (section_sp->IsThreadSpecific())
733*0fca6ea1SDimitry Andric           continue;
7340b57cec5SDimitry Andric         if (section_sp->Test(SHF_ALLOC) ||
7350b57cec5SDimitry Andric             section_sp->GetType() == eSectionTypeContainer) {
7360b57cec5SDimitry Andric           lldb::addr_t load_addr = section_sp->GetFileAddress();
7370b57cec5SDimitry Andric           // We don't want to update the load address of a section with type
7380b57cec5SDimitry Andric           // eSectionTypeAbsoluteAddress as they already have the absolute load
7390b57cec5SDimitry Andric           // address already specified
7400b57cec5SDimitry Andric           if (section_sp->GetType() != eSectionTypeAbsoluteAddress)
7410b57cec5SDimitry Andric             load_addr += value;
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric           // On 32-bit systems the load address have to fit into 4 bytes. The
7440b57cec5SDimitry Andric           // rest of the bytes are the overflow from the addition.
7450b57cec5SDimitry Andric           if (GetAddressByteSize() == 4)
7460b57cec5SDimitry Andric             load_addr &= 0xFFFFFFFF;
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric           if (target.GetSectionLoadList().SetSectionLoadAddress(section_sp,
7490b57cec5SDimitry Andric                                                                 load_addr))
7500b57cec5SDimitry Andric             ++num_loaded_sections;
7510b57cec5SDimitry Andric         }
7520b57cec5SDimitry Andric       }
7530b57cec5SDimitry Andric       return num_loaded_sections > 0;
7540b57cec5SDimitry Andric     }
7550b57cec5SDimitry Andric   }
7560b57cec5SDimitry Andric   return false;
7570b57cec5SDimitry Andric }
7580b57cec5SDimitry Andric 
7590b57cec5SDimitry Andric ByteOrder ObjectFileELF::GetByteOrder() const {
7600b57cec5SDimitry Andric   if (m_header.e_ident[EI_DATA] == ELFDATA2MSB)
7610b57cec5SDimitry Andric     return eByteOrderBig;
7620b57cec5SDimitry Andric   if (m_header.e_ident[EI_DATA] == ELFDATA2LSB)
7630b57cec5SDimitry Andric     return eByteOrderLittle;
7640b57cec5SDimitry Andric   return eByteOrderInvalid;
7650b57cec5SDimitry Andric }
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric uint32_t ObjectFileELF::GetAddressByteSize() const {
7680b57cec5SDimitry Andric   return m_data.GetAddressByteSize();
7690b57cec5SDimitry Andric }
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric AddressClass ObjectFileELF::GetAddressClass(addr_t file_addr) {
7720b57cec5SDimitry Andric   Symtab *symtab = GetSymtab();
7730b57cec5SDimitry Andric   if (!symtab)
7740b57cec5SDimitry Andric     return AddressClass::eUnknown;
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric   // The address class is determined based on the symtab. Ask it from the
7770b57cec5SDimitry Andric   // object file what contains the symtab information.
7780b57cec5SDimitry Andric   ObjectFile *symtab_objfile = symtab->GetObjectFile();
7790b57cec5SDimitry Andric   if (symtab_objfile != nullptr && symtab_objfile != this)
7800b57cec5SDimitry Andric     return symtab_objfile->GetAddressClass(file_addr);
7810b57cec5SDimitry Andric 
7820b57cec5SDimitry Andric   auto res = ObjectFile::GetAddressClass(file_addr);
7830b57cec5SDimitry Andric   if (res != AddressClass::eCode)
7840b57cec5SDimitry Andric     return res;
7850b57cec5SDimitry Andric 
7860b57cec5SDimitry Andric   auto ub = m_address_class_map.upper_bound(file_addr);
7870b57cec5SDimitry Andric   if (ub == m_address_class_map.begin()) {
7880b57cec5SDimitry Andric     // No entry in the address class map before the address. Return default
7890b57cec5SDimitry Andric     // address class for an address in a code section.
7900b57cec5SDimitry Andric     return AddressClass::eCode;
7910b57cec5SDimitry Andric   }
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric   // Move iterator to the address class entry preceding address
7940b57cec5SDimitry Andric   --ub;
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric   return ub->second;
7970b57cec5SDimitry Andric }
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric size_t ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I) {
8000b57cec5SDimitry Andric   return std::distance(m_section_headers.begin(), I);
8010b57cec5SDimitry Andric }
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric size_t ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const {
8040b57cec5SDimitry Andric   return std::distance(m_section_headers.begin(), I);
8050b57cec5SDimitry Andric }
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric bool ObjectFileELF::ParseHeader() {
8080b57cec5SDimitry Andric   lldb::offset_t offset = 0;
8090b57cec5SDimitry Andric   return m_header.Parse(m_data, &offset);
8100b57cec5SDimitry Andric }
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric UUID ObjectFileELF::GetUUID() {
8130b57cec5SDimitry Andric   // Need to parse the section list to get the UUIDs, so make sure that's been
8140b57cec5SDimitry Andric   // done.
8150b57cec5SDimitry Andric   if (!ParseSectionHeaders() && GetType() != ObjectFile::eTypeCoreFile)
8160b57cec5SDimitry Andric     return UUID();
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   if (!m_uuid) {
8190b57cec5SDimitry Andric     using u32le = llvm::support::ulittle32_t;
8200b57cec5SDimitry Andric     if (GetType() == ObjectFile::eTypeCoreFile) {
8210b57cec5SDimitry Andric       uint32_t core_notes_crc = 0;
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric       if (!ParseProgramHeaders())
8240b57cec5SDimitry Andric         return UUID();
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric       core_notes_crc =
8270b57cec5SDimitry Andric           CalculateELFNotesSegmentsCRC32(m_program_headers, m_data);
8280b57cec5SDimitry Andric 
8290b57cec5SDimitry Andric       if (core_notes_crc) {
8300b57cec5SDimitry Andric         // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it
8310b57cec5SDimitry Andric         // look different form .gnu_debuglink crc - followed by 4 bytes of note
8320b57cec5SDimitry Andric         // segments crc.
8330b57cec5SDimitry Andric         u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)};
834bdd1243dSDimitry Andric         m_uuid = UUID(data, sizeof(data));
8350b57cec5SDimitry Andric       }
8360b57cec5SDimitry Andric     } else {
8370b57cec5SDimitry Andric       if (!m_gnu_debuglink_crc)
8389dba64beSDimitry Andric         m_gnu_debuglink_crc = calc_crc32(0, m_data);
8390b57cec5SDimitry Andric       if (m_gnu_debuglink_crc) {
8400b57cec5SDimitry Andric         // Use 4 bytes of crc from the .gnu_debuglink section.
8410b57cec5SDimitry Andric         u32le data(m_gnu_debuglink_crc);
842bdd1243dSDimitry Andric         m_uuid = UUID(&data, sizeof(data));
8430b57cec5SDimitry Andric       }
8440b57cec5SDimitry Andric     }
8450b57cec5SDimitry Andric   }
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric   return m_uuid;
8480b57cec5SDimitry Andric }
8490b57cec5SDimitry Andric 
850bdd1243dSDimitry Andric std::optional<FileSpec> ObjectFileELF::GetDebugLink() {
8519dba64beSDimitry Andric   if (m_gnu_debuglink_file.empty())
852bdd1243dSDimitry Andric     return std::nullopt;
8539dba64beSDimitry Andric   return FileSpec(m_gnu_debuglink_file);
8540b57cec5SDimitry Andric }
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric uint32_t ObjectFileELF::GetDependentModules(FileSpecList &files) {
8570b57cec5SDimitry Andric   size_t num_modules = ParseDependentModules();
8580b57cec5SDimitry Andric   uint32_t num_specs = 0;
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric   for (unsigned i = 0; i < num_modules; ++i) {
8610b57cec5SDimitry Andric     if (files.AppendIfUnique(m_filespec_up->GetFileSpecAtIndex(i)))
8620b57cec5SDimitry Andric       num_specs++;
8630b57cec5SDimitry Andric   }
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric   return num_specs;
8660b57cec5SDimitry Andric }
8670b57cec5SDimitry Andric 
8680b57cec5SDimitry Andric Address ObjectFileELF::GetImageInfoAddress(Target *target) {
8690b57cec5SDimitry Andric   if (!ParseDynamicSymbols())
8700b57cec5SDimitry Andric     return Address();
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
8730b57cec5SDimitry Andric   if (!section_list)
8740b57cec5SDimitry Andric     return Address();
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric   // Find the SHT_DYNAMIC (.dynamic) section.
8770b57cec5SDimitry Andric   SectionSP dynsym_section_sp(
8780b57cec5SDimitry Andric       section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true));
8790b57cec5SDimitry Andric   if (!dynsym_section_sp)
8800b57cec5SDimitry Andric     return Address();
8810b57cec5SDimitry Andric   assert(dynsym_section_sp->GetObjectFile() == this);
8820b57cec5SDimitry Andric 
8830b57cec5SDimitry Andric   user_id_t dynsym_id = dynsym_section_sp->GetID();
8840b57cec5SDimitry Andric   const ELFSectionHeaderInfo *dynsym_hdr = GetSectionHeaderByIndex(dynsym_id);
8850b57cec5SDimitry Andric   if (!dynsym_hdr)
8860b57cec5SDimitry Andric     return Address();
8870b57cec5SDimitry Andric 
8880b57cec5SDimitry Andric   for (size_t i = 0; i < m_dynamic_symbols.size(); ++i) {
8890b57cec5SDimitry Andric     ELFDynamic &symbol = m_dynamic_symbols[i];
8900b57cec5SDimitry Andric 
8910b57cec5SDimitry Andric     if (symbol.d_tag == DT_DEBUG) {
8920b57cec5SDimitry Andric       // Compute the offset as the number of previous entries plus the size of
8930b57cec5SDimitry Andric       // d_tag.
8940b57cec5SDimitry Andric       addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
8950b57cec5SDimitry Andric       return Address(dynsym_section_sp, offset);
8960b57cec5SDimitry Andric     }
8970b57cec5SDimitry Andric     // MIPS executables uses DT_MIPS_RLD_MAP_REL to support PIE. DT_MIPS_RLD_MAP
8980b57cec5SDimitry Andric     // exists in non-PIE.
8990b57cec5SDimitry Andric     else if ((symbol.d_tag == DT_MIPS_RLD_MAP ||
9000b57cec5SDimitry Andric               symbol.d_tag == DT_MIPS_RLD_MAP_REL) &&
9010b57cec5SDimitry Andric              target) {
9020b57cec5SDimitry Andric       addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
9030b57cec5SDimitry Andric       addr_t dyn_base = dynsym_section_sp->GetLoadBaseAddress(target);
9040b57cec5SDimitry Andric       if (dyn_base == LLDB_INVALID_ADDRESS)
9050b57cec5SDimitry Andric         return Address();
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric       Status error;
9080b57cec5SDimitry Andric       if (symbol.d_tag == DT_MIPS_RLD_MAP) {
9090b57cec5SDimitry Andric         // DT_MIPS_RLD_MAP tag stores an absolute address of the debug pointer.
9100b57cec5SDimitry Andric         Address addr;
911fe6060f1SDimitry Andric         if (target->ReadPointerFromMemory(dyn_base + offset, error, addr, true))
9120b57cec5SDimitry Andric           return addr;
9130b57cec5SDimitry Andric       }
9140b57cec5SDimitry Andric       if (symbol.d_tag == DT_MIPS_RLD_MAP_REL) {
9150b57cec5SDimitry Andric         // DT_MIPS_RLD_MAP_REL tag stores the offset to the debug pointer,
9160b57cec5SDimitry Andric         // relative to the address of the tag.
9170b57cec5SDimitry Andric         uint64_t rel_offset;
9180b57cec5SDimitry Andric         rel_offset = target->ReadUnsignedIntegerFromMemory(
919fe6060f1SDimitry Andric             dyn_base + offset, GetAddressByteSize(), UINT64_MAX, error, true);
9200b57cec5SDimitry Andric         if (error.Success() && rel_offset != UINT64_MAX) {
9210b57cec5SDimitry Andric           Address addr;
9220b57cec5SDimitry Andric           addr_t debug_ptr_address =
9230b57cec5SDimitry Andric               dyn_base + (offset - GetAddressByteSize()) + rel_offset;
9240b57cec5SDimitry Andric           addr.SetOffset(debug_ptr_address);
9250b57cec5SDimitry Andric           return addr;
9260b57cec5SDimitry Andric         }
9270b57cec5SDimitry Andric       }
9280b57cec5SDimitry Andric     }
9290b57cec5SDimitry Andric   }
9300b57cec5SDimitry Andric 
9310b57cec5SDimitry Andric   return Address();
9320b57cec5SDimitry Andric }
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric lldb_private::Address ObjectFileELF::GetEntryPointAddress() {
9350b57cec5SDimitry Andric   if (m_entry_point_address.IsValid())
9360b57cec5SDimitry Andric     return m_entry_point_address;
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric   if (!ParseHeader() || !IsExecutable())
9390b57cec5SDimitry Andric     return m_entry_point_address;
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
9420b57cec5SDimitry Andric   addr_t offset = m_header.e_entry;
9430b57cec5SDimitry Andric 
9440b57cec5SDimitry Andric   if (!section_list)
9450b57cec5SDimitry Andric     m_entry_point_address.SetOffset(offset);
9460b57cec5SDimitry Andric   else
9470b57cec5SDimitry Andric     m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list);
9480b57cec5SDimitry Andric   return m_entry_point_address;
9490b57cec5SDimitry Andric }
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric Address ObjectFileELF::GetBaseAddress() {
9525f757f3fSDimitry Andric   if (GetType() == ObjectFile::eTypeObjectFile) {
9535f757f3fSDimitry Andric     for (SectionHeaderCollIter I = std::next(m_section_headers.begin());
9545f757f3fSDimitry Andric          I != m_section_headers.end(); ++I) {
9555f757f3fSDimitry Andric       const ELFSectionHeaderInfo &header = *I;
9565f757f3fSDimitry Andric       if (header.sh_flags & SHF_ALLOC)
9575f757f3fSDimitry Andric         return Address(GetSectionList()->FindSectionByID(SectionIndex(I)), 0);
9585f757f3fSDimitry Andric     }
9595f757f3fSDimitry Andric     return LLDB_INVALID_ADDRESS;
9605f757f3fSDimitry Andric   }
9615f757f3fSDimitry Andric 
9620b57cec5SDimitry Andric   for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {
9630b57cec5SDimitry Andric     const ELFProgramHeader &H = EnumPHdr.value();
9640b57cec5SDimitry Andric     if (H.p_type != PT_LOAD)
9650b57cec5SDimitry Andric       continue;
9660b57cec5SDimitry Andric 
9670b57cec5SDimitry Andric     return Address(
9680b57cec5SDimitry Andric         GetSectionList()->FindSectionByID(SegmentID(EnumPHdr.index())), 0);
9690b57cec5SDimitry Andric   }
9700b57cec5SDimitry Andric   return LLDB_INVALID_ADDRESS;
9710b57cec5SDimitry Andric }
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric // ParseDependentModules
9740b57cec5SDimitry Andric size_t ObjectFileELF::ParseDependentModules() {
9750b57cec5SDimitry Andric   if (m_filespec_up)
9760b57cec5SDimitry Andric     return m_filespec_up->GetSize();
9770b57cec5SDimitry Andric 
9785ffd83dbSDimitry Andric   m_filespec_up = std::make_unique<FileSpecList>();
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric   if (!ParseSectionHeaders())
9810b57cec5SDimitry Andric     return 0;
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
9840b57cec5SDimitry Andric   if (!section_list)
9850b57cec5SDimitry Andric     return 0;
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric   // Find the SHT_DYNAMIC section.
9880b57cec5SDimitry Andric   Section *dynsym =
9890b57cec5SDimitry Andric       section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
9900b57cec5SDimitry Andric           .get();
9910b57cec5SDimitry Andric   if (!dynsym)
9920b57cec5SDimitry Andric     return 0;
9930b57cec5SDimitry Andric   assert(dynsym->GetObjectFile() == this);
9940b57cec5SDimitry Andric 
9950b57cec5SDimitry Andric   const ELFSectionHeaderInfo *header = GetSectionHeaderByIndex(dynsym->GetID());
9960b57cec5SDimitry Andric   if (!header)
9970b57cec5SDimitry Andric     return 0;
9980b57cec5SDimitry Andric   // sh_link: section header index of string table used by entries in the
9990b57cec5SDimitry Andric   // section.
10000b57cec5SDimitry Andric   Section *dynstr = section_list->FindSectionByID(header->sh_link).get();
10010b57cec5SDimitry Andric   if (!dynstr)
10020b57cec5SDimitry Andric     return 0;
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric   DataExtractor dynsym_data;
10050b57cec5SDimitry Andric   DataExtractor dynstr_data;
10060b57cec5SDimitry Andric   if (ReadSectionData(dynsym, dynsym_data) &&
10070b57cec5SDimitry Andric       ReadSectionData(dynstr, dynstr_data)) {
10080b57cec5SDimitry Andric     ELFDynamic symbol;
10090b57cec5SDimitry Andric     const lldb::offset_t section_size = dynsym_data.GetByteSize();
10100b57cec5SDimitry Andric     lldb::offset_t offset = 0;
10110b57cec5SDimitry Andric 
10120b57cec5SDimitry Andric     // The only type of entries we are concerned with are tagged DT_NEEDED,
10130b57cec5SDimitry Andric     // yielding the name of a required library.
10140b57cec5SDimitry Andric     while (offset < section_size) {
10150b57cec5SDimitry Andric       if (!symbol.Parse(dynsym_data, &offset))
10160b57cec5SDimitry Andric         break;
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric       if (symbol.d_tag != DT_NEEDED)
10190b57cec5SDimitry Andric         continue;
10200b57cec5SDimitry Andric 
10210b57cec5SDimitry Andric       uint32_t str_index = static_cast<uint32_t>(symbol.d_val);
10220b57cec5SDimitry Andric       const char *lib_name = dynstr_data.PeekCStr(str_index);
10230b57cec5SDimitry Andric       FileSpec file_spec(lib_name);
10240b57cec5SDimitry Andric       FileSystem::Instance().Resolve(file_spec);
10250b57cec5SDimitry Andric       m_filespec_up->Append(file_spec);
10260b57cec5SDimitry Andric     }
10270b57cec5SDimitry Andric   }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   return m_filespec_up->GetSize();
10300b57cec5SDimitry Andric }
10310b57cec5SDimitry Andric 
10320b57cec5SDimitry Andric // GetProgramHeaderInfo
10330b57cec5SDimitry Andric size_t ObjectFileELF::GetProgramHeaderInfo(ProgramHeaderColl &program_headers,
10340b57cec5SDimitry Andric                                            DataExtractor &object_data,
10350b57cec5SDimitry Andric                                            const ELFHeader &header) {
10360b57cec5SDimitry Andric   // We have already parsed the program headers
10370b57cec5SDimitry Andric   if (!program_headers.empty())
10380b57cec5SDimitry Andric     return program_headers.size();
10390b57cec5SDimitry Andric 
10400b57cec5SDimitry Andric   // If there are no program headers to read we are done.
10410b57cec5SDimitry Andric   if (header.e_phnum == 0)
10420b57cec5SDimitry Andric     return 0;
10430b57cec5SDimitry Andric 
10440b57cec5SDimitry Andric   program_headers.resize(header.e_phnum);
10450b57cec5SDimitry Andric   if (program_headers.size() != header.e_phnum)
10460b57cec5SDimitry Andric     return 0;
10470b57cec5SDimitry Andric 
10480b57cec5SDimitry Andric   const size_t ph_size = header.e_phnum * header.e_phentsize;
10490b57cec5SDimitry Andric   const elf_off ph_offset = header.e_phoff;
10500b57cec5SDimitry Andric   DataExtractor data;
10510b57cec5SDimitry Andric   if (data.SetData(object_data, ph_offset, ph_size) != ph_size)
10520b57cec5SDimitry Andric     return 0;
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric   uint32_t idx;
10550b57cec5SDimitry Andric   lldb::offset_t offset;
10560b57cec5SDimitry Andric   for (idx = 0, offset = 0; idx < header.e_phnum; ++idx) {
10570b57cec5SDimitry Andric     if (!program_headers[idx].Parse(data, &offset))
10580b57cec5SDimitry Andric       break;
10590b57cec5SDimitry Andric   }
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric   if (idx < program_headers.size())
10620b57cec5SDimitry Andric     program_headers.resize(idx);
10630b57cec5SDimitry Andric 
10640b57cec5SDimitry Andric   return program_headers.size();
10650b57cec5SDimitry Andric }
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric // ParseProgramHeaders
10680b57cec5SDimitry Andric bool ObjectFileELF::ParseProgramHeaders() {
10690b57cec5SDimitry Andric   return GetProgramHeaderInfo(m_program_headers, m_data, m_header) != 0;
10700b57cec5SDimitry Andric }
10710b57cec5SDimitry Andric 
10720b57cec5SDimitry Andric lldb_private::Status
10730b57cec5SDimitry Andric ObjectFileELF::RefineModuleDetailsFromNote(lldb_private::DataExtractor &data,
10740b57cec5SDimitry Andric                                            lldb_private::ArchSpec &arch_spec,
10750b57cec5SDimitry Andric                                            lldb_private::UUID &uuid) {
107681ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Modules);
10770b57cec5SDimitry Andric   Status error;
10780b57cec5SDimitry Andric 
10790b57cec5SDimitry Andric   lldb::offset_t offset = 0;
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric   while (true) {
10820b57cec5SDimitry Andric     // Parse the note header.  If this fails, bail out.
10830b57cec5SDimitry Andric     const lldb::offset_t note_offset = offset;
10840b57cec5SDimitry Andric     ELFNote note = ELFNote();
10850b57cec5SDimitry Andric     if (!note.Parse(data, &offset)) {
10860b57cec5SDimitry Andric       // We're done.
10870b57cec5SDimitry Andric       return error;
10880b57cec5SDimitry Andric     }
10890b57cec5SDimitry Andric 
10909dba64beSDimitry Andric     LLDB_LOGF(log, "ObjectFileELF::%s parsing note name='%s', type=%" PRIu32,
10910b57cec5SDimitry Andric               __FUNCTION__, note.n_name.c_str(), note.n_type);
10920b57cec5SDimitry Andric 
10930b57cec5SDimitry Andric     // Process FreeBSD ELF notes.
10940b57cec5SDimitry Andric     if ((note.n_name == LLDB_NT_OWNER_FREEBSD) &&
10950b57cec5SDimitry Andric         (note.n_type == LLDB_NT_FREEBSD_ABI_TAG) &&
10960b57cec5SDimitry Andric         (note.n_descsz == LLDB_NT_FREEBSD_ABI_SIZE)) {
10970b57cec5SDimitry Andric       // Pull out the min version info.
10980b57cec5SDimitry Andric       uint32_t version_info;
10990b57cec5SDimitry Andric       if (data.GetU32(&offset, &version_info, 1) == nullptr) {
11000b57cec5SDimitry Andric         error.SetErrorString("failed to read FreeBSD ABI note payload");
11010b57cec5SDimitry Andric         return error;
11020b57cec5SDimitry Andric       }
11030b57cec5SDimitry Andric 
11040b57cec5SDimitry Andric       // Convert the version info into a major/minor number.
11050b57cec5SDimitry Andric       const uint32_t version_major = version_info / 100000;
11060b57cec5SDimitry Andric       const uint32_t version_minor = (version_info / 1000) % 100;
11070b57cec5SDimitry Andric 
11080b57cec5SDimitry Andric       char os_name[32];
11090b57cec5SDimitry Andric       snprintf(os_name, sizeof(os_name), "freebsd%" PRIu32 ".%" PRIu32,
11100b57cec5SDimitry Andric                version_major, version_minor);
11110b57cec5SDimitry Andric 
11120b57cec5SDimitry Andric       // Set the elf OS version to FreeBSD.  Also clear the vendor.
11130b57cec5SDimitry Andric       arch_spec.GetTriple().setOSName(os_name);
11140b57cec5SDimitry Andric       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
11150b57cec5SDimitry Andric 
11169dba64beSDimitry Andric       LLDB_LOGF(log,
11179dba64beSDimitry Andric                 "ObjectFileELF::%s detected FreeBSD %" PRIu32 ".%" PRIu32
11180b57cec5SDimitry Andric                 ".%" PRIu32,
11190b57cec5SDimitry Andric                 __FUNCTION__, version_major, version_minor,
11200b57cec5SDimitry Andric                 static_cast<uint32_t>(version_info % 1000));
11210b57cec5SDimitry Andric     }
11220b57cec5SDimitry Andric     // Process GNU ELF notes.
11230b57cec5SDimitry Andric     else if (note.n_name == LLDB_NT_OWNER_GNU) {
11240b57cec5SDimitry Andric       switch (note.n_type) {
11250b57cec5SDimitry Andric       case LLDB_NT_GNU_ABI_TAG:
11260b57cec5SDimitry Andric         if (note.n_descsz == LLDB_NT_GNU_ABI_SIZE) {
11270b57cec5SDimitry Andric           // Pull out the min OS version supporting the ABI.
11280b57cec5SDimitry Andric           uint32_t version_info[4];
11290b57cec5SDimitry Andric           if (data.GetU32(&offset, &version_info[0], note.n_descsz / 4) ==
11300b57cec5SDimitry Andric               nullptr) {
11310b57cec5SDimitry Andric             error.SetErrorString("failed to read GNU ABI note payload");
11320b57cec5SDimitry Andric             return error;
11330b57cec5SDimitry Andric           }
11340b57cec5SDimitry Andric 
11350b57cec5SDimitry Andric           // Set the OS per the OS field.
11360b57cec5SDimitry Andric           switch (version_info[0]) {
11370b57cec5SDimitry Andric           case LLDB_NT_GNU_ABI_OS_LINUX:
11380b57cec5SDimitry Andric             arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
11390b57cec5SDimitry Andric             arch_spec.GetTriple().setVendor(
11400b57cec5SDimitry Andric                 llvm::Triple::VendorType::UnknownVendor);
11419dba64beSDimitry Andric             LLDB_LOGF(log,
11420b57cec5SDimitry Andric                       "ObjectFileELF::%s detected Linux, min version %" PRIu32
11430b57cec5SDimitry Andric                       ".%" PRIu32 ".%" PRIu32,
11440b57cec5SDimitry Andric                       __FUNCTION__, version_info[1], version_info[2],
11450b57cec5SDimitry Andric                       version_info[3]);
11460b57cec5SDimitry Andric             // FIXME we have the minimal version number, we could be propagating
11470b57cec5SDimitry Andric             // that.  version_info[1] = OS Major, version_info[2] = OS Minor,
11480b57cec5SDimitry Andric             // version_info[3] = Revision.
11490b57cec5SDimitry Andric             break;
11500b57cec5SDimitry Andric           case LLDB_NT_GNU_ABI_OS_HURD:
11510b57cec5SDimitry Andric             arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
11520b57cec5SDimitry Andric             arch_spec.GetTriple().setVendor(
11530b57cec5SDimitry Andric                 llvm::Triple::VendorType::UnknownVendor);
11549dba64beSDimitry Andric             LLDB_LOGF(log,
11559dba64beSDimitry Andric                       "ObjectFileELF::%s detected Hurd (unsupported), min "
11560b57cec5SDimitry Andric                       "version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
11570b57cec5SDimitry Andric                       __FUNCTION__, version_info[1], version_info[2],
11580b57cec5SDimitry Andric                       version_info[3]);
11590b57cec5SDimitry Andric             break;
11600b57cec5SDimitry Andric           case LLDB_NT_GNU_ABI_OS_SOLARIS:
11610b57cec5SDimitry Andric             arch_spec.GetTriple().setOS(llvm::Triple::OSType::Solaris);
11620b57cec5SDimitry Andric             arch_spec.GetTriple().setVendor(
11630b57cec5SDimitry Andric                 llvm::Triple::VendorType::UnknownVendor);
11649dba64beSDimitry Andric             LLDB_LOGF(log,
11650b57cec5SDimitry Andric                       "ObjectFileELF::%s detected Solaris, min version %" PRIu32
11660b57cec5SDimitry Andric                       ".%" PRIu32 ".%" PRIu32,
11670b57cec5SDimitry Andric                       __FUNCTION__, version_info[1], version_info[2],
11680b57cec5SDimitry Andric                       version_info[3]);
11690b57cec5SDimitry Andric             break;
11700b57cec5SDimitry Andric           default:
11719dba64beSDimitry Andric             LLDB_LOGF(log,
11720b57cec5SDimitry Andric                       "ObjectFileELF::%s unrecognized OS in note, id %" PRIu32
11730b57cec5SDimitry Andric                       ", min version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
11740b57cec5SDimitry Andric                       __FUNCTION__, version_info[0], version_info[1],
11750b57cec5SDimitry Andric                       version_info[2], version_info[3]);
11760b57cec5SDimitry Andric             break;
11770b57cec5SDimitry Andric           }
11780b57cec5SDimitry Andric         }
11790b57cec5SDimitry Andric         break;
11800b57cec5SDimitry Andric 
11810b57cec5SDimitry Andric       case LLDB_NT_GNU_BUILD_ID_TAG:
11820b57cec5SDimitry Andric         // Only bother processing this if we don't already have the uuid set.
11830b57cec5SDimitry Andric         if (!uuid.IsValid()) {
11840b57cec5SDimitry Andric           // 16 bytes is UUID|MD5, 20 bytes is SHA1. Other linkers may produce a
11850b57cec5SDimitry Andric           // build-id of a different length. Accept it as long as it's at least
11860b57cec5SDimitry Andric           // 4 bytes as it will be better than our own crc32.
11870b57cec5SDimitry Andric           if (note.n_descsz >= 4) {
11880b57cec5SDimitry Andric             if (const uint8_t *buf = data.PeekData(offset, note.n_descsz)) {
11890b57cec5SDimitry Andric               // Save the build id as the UUID for the module.
1190bdd1243dSDimitry Andric               uuid = UUID(buf, note.n_descsz);
11910b57cec5SDimitry Andric             } else {
11920b57cec5SDimitry Andric               error.SetErrorString("failed to read GNU_BUILD_ID note payload");
11930b57cec5SDimitry Andric               return error;
11940b57cec5SDimitry Andric             }
11950b57cec5SDimitry Andric           }
11960b57cec5SDimitry Andric         }
11970b57cec5SDimitry Andric         break;
11980b57cec5SDimitry Andric       }
11990b57cec5SDimitry Andric       if (arch_spec.IsMIPS() &&
12000b57cec5SDimitry Andric           arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)
12010b57cec5SDimitry Andric         // The note.n_name == LLDB_NT_OWNER_GNU is valid for Linux platform
12020b57cec5SDimitry Andric         arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
12030b57cec5SDimitry Andric     }
12040b57cec5SDimitry Andric     // Process NetBSD ELF executables and shared libraries
12050b57cec5SDimitry Andric     else if ((note.n_name == LLDB_NT_OWNER_NETBSD) &&
12060b57cec5SDimitry Andric              (note.n_type == LLDB_NT_NETBSD_IDENT_TAG) &&
12070b57cec5SDimitry Andric              (note.n_descsz == LLDB_NT_NETBSD_IDENT_DESCSZ) &&
12080b57cec5SDimitry Andric              (note.n_namesz == LLDB_NT_NETBSD_IDENT_NAMESZ)) {
12090b57cec5SDimitry Andric       // Pull out the version info.
12100b57cec5SDimitry Andric       uint32_t version_info;
12110b57cec5SDimitry Andric       if (data.GetU32(&offset, &version_info, 1) == nullptr) {
12120b57cec5SDimitry Andric         error.SetErrorString("failed to read NetBSD ABI note payload");
12130b57cec5SDimitry Andric         return error;
12140b57cec5SDimitry Andric       }
12150b57cec5SDimitry Andric       // Convert the version info into a major/minor/patch number.
12160b57cec5SDimitry Andric       //     #define __NetBSD_Version__ MMmmrrpp00
12170b57cec5SDimitry Andric       //
12180b57cec5SDimitry Andric       //     M = major version
12190b57cec5SDimitry Andric       //     m = minor version; a minor number of 99 indicates current.
12200b57cec5SDimitry Andric       //     r = 0 (since NetBSD 3.0 not used)
12210b57cec5SDimitry Andric       //     p = patchlevel
12220b57cec5SDimitry Andric       const uint32_t version_major = version_info / 100000000;
12230b57cec5SDimitry Andric       const uint32_t version_minor = (version_info % 100000000) / 1000000;
12240b57cec5SDimitry Andric       const uint32_t version_patch = (version_info % 10000) / 100;
12250b57cec5SDimitry Andric       // Set the elf OS version to NetBSD.  Also clear the vendor.
12260b57cec5SDimitry Andric       arch_spec.GetTriple().setOSName(
12270b57cec5SDimitry Andric           llvm::formatv("netbsd{0}.{1}.{2}", version_major, version_minor,
12280b57cec5SDimitry Andric                         version_patch).str());
12290b57cec5SDimitry Andric       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
12300b57cec5SDimitry Andric     }
12310b57cec5SDimitry Andric     // Process NetBSD ELF core(5) notes
12320b57cec5SDimitry Andric     else if ((note.n_name == LLDB_NT_OWNER_NETBSDCORE) &&
12330b57cec5SDimitry Andric              (note.n_type == LLDB_NT_NETBSD_PROCINFO)) {
12340b57cec5SDimitry Andric       // Set the elf OS version to NetBSD.  Also clear the vendor.
12350b57cec5SDimitry Andric       arch_spec.GetTriple().setOS(llvm::Triple::OSType::NetBSD);
12360b57cec5SDimitry Andric       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
12370b57cec5SDimitry Andric     }
12380b57cec5SDimitry Andric     // Process OpenBSD ELF notes.
12390b57cec5SDimitry Andric     else if (note.n_name == LLDB_NT_OWNER_OPENBSD) {
12400b57cec5SDimitry Andric       // Set the elf OS version to OpenBSD.  Also clear the vendor.
12410b57cec5SDimitry Andric       arch_spec.GetTriple().setOS(llvm::Triple::OSType::OpenBSD);
12420b57cec5SDimitry Andric       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
12430b57cec5SDimitry Andric     } else if (note.n_name == LLDB_NT_OWNER_ANDROID) {
12440b57cec5SDimitry Andric       arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
12450b57cec5SDimitry Andric       arch_spec.GetTriple().setEnvironment(
12460b57cec5SDimitry Andric           llvm::Triple::EnvironmentType::Android);
12470b57cec5SDimitry Andric     } else if (note.n_name == LLDB_NT_OWNER_LINUX) {
12480b57cec5SDimitry Andric       // This is sometimes found in core files and usually contains extended
12490b57cec5SDimitry Andric       // register info
12500b57cec5SDimitry Andric       arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
12510b57cec5SDimitry Andric     } else if (note.n_name == LLDB_NT_OWNER_CORE) {
125281ad6265SDimitry Andric       // Parse the NT_FILE to look for stuff in paths to shared libraries
125381ad6265SDimitry Andric       // The contents look like this in a 64 bit ELF core file:
125481ad6265SDimitry Andric       //
125581ad6265SDimitry Andric       // count     = 0x000000000000000a (10)
125681ad6265SDimitry Andric       // page_size = 0x0000000000001000 (4096)
125781ad6265SDimitry Andric       // Index start              end                file_ofs           path
125881ad6265SDimitry Andric       // ===== ------------------ ------------------ ------------------ -------------------------------------
125981ad6265SDimitry Andric       // [  0] 0x0000000000401000 0x0000000000000000                    /tmp/a.out
126081ad6265SDimitry Andric       // [  1] 0x0000000000600000 0x0000000000601000 0x0000000000000000 /tmp/a.out
126181ad6265SDimitry Andric       // [  2] 0x0000000000601000 0x0000000000602000 0x0000000000000001 /tmp/a.out
126281ad6265SDimitry Andric       // [  3] 0x00007fa79c9ed000 0x00007fa79cba8000 0x0000000000000000 /lib/x86_64-linux-gnu/libc-2.19.so
126381ad6265SDimitry Andric       // [  4] 0x00007fa79cba8000 0x00007fa79cda7000 0x00000000000001bb /lib/x86_64-linux-gnu/libc-2.19.so
126481ad6265SDimitry Andric       // [  5] 0x00007fa79cda7000 0x00007fa79cdab000 0x00000000000001ba /lib/x86_64-linux-gnu/libc-2.19.so
126581ad6265SDimitry Andric       // [  6] 0x00007fa79cdab000 0x00007fa79cdad000 0x00000000000001be /lib/x86_64-linux-gnu/libc-2.19.so
126681ad6265SDimitry Andric       // [  7] 0x00007fa79cdb2000 0x00007fa79cdd5000 0x0000000000000000 /lib/x86_64-linux-gnu/ld-2.19.so
126781ad6265SDimitry Andric       // [  8] 0x00007fa79cfd4000 0x00007fa79cfd5000 0x0000000000000022 /lib/x86_64-linux-gnu/ld-2.19.so
126881ad6265SDimitry Andric       // [  9] 0x00007fa79cfd5000 0x00007fa79cfd6000 0x0000000000000023 /lib/x86_64-linux-gnu/ld-2.19.so
126981ad6265SDimitry Andric       //
127081ad6265SDimitry Andric       // In the 32 bit ELFs the count, page_size, start, end, file_ofs are
127181ad6265SDimitry Andric       // uint32_t.
127281ad6265SDimitry Andric       //
127381ad6265SDimitry Andric       // For reference: see readelf source code (in binutils).
12740b57cec5SDimitry Andric       if (note.n_type == NT_FILE) {
12750b57cec5SDimitry Andric         uint64_t count = data.GetAddress(&offset);
12760b57cec5SDimitry Andric         const char *cstr;
12770b57cec5SDimitry Andric         data.GetAddress(&offset); // Skip page size
12780b57cec5SDimitry Andric         offset += count * 3 *
12790b57cec5SDimitry Andric                   data.GetAddressByteSize(); // Skip all start/end/file_ofs
12800b57cec5SDimitry Andric         for (size_t i = 0; i < count; ++i) {
12810b57cec5SDimitry Andric           cstr = data.GetCStr(&offset);
12820b57cec5SDimitry Andric           if (cstr == nullptr) {
12830b57cec5SDimitry Andric             error.SetErrorStringWithFormat("ObjectFileELF::%s trying to read "
12840b57cec5SDimitry Andric                                            "at an offset after the end "
12850b57cec5SDimitry Andric                                            "(GetCStr returned nullptr)",
12860b57cec5SDimitry Andric                                            __FUNCTION__);
12870b57cec5SDimitry Andric             return error;
12880b57cec5SDimitry Andric           }
12890b57cec5SDimitry Andric           llvm::StringRef path(cstr);
12900b57cec5SDimitry Andric           if (path.contains("/lib/x86_64-linux-gnu") || path.contains("/lib/i386-linux-gnu")) {
12910b57cec5SDimitry Andric             arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
12920b57cec5SDimitry Andric             break;
12930b57cec5SDimitry Andric           }
12940b57cec5SDimitry Andric         }
12950b57cec5SDimitry Andric         if (arch_spec.IsMIPS() &&
12960b57cec5SDimitry Andric             arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)
12970b57cec5SDimitry Andric           // In case of MIPSR6, the LLDB_NT_OWNER_GNU note is missing for some
12980b57cec5SDimitry Andric           // cases (e.g. compile with -nostdlib) Hence set OS to Linux
12990b57cec5SDimitry Andric           arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
13000b57cec5SDimitry Andric       }
13010b57cec5SDimitry Andric     }
13020b57cec5SDimitry Andric 
13030b57cec5SDimitry Andric     // Calculate the offset of the next note just in case "offset" has been
13040b57cec5SDimitry Andric     // used to poke at the contents of the note data
13050b57cec5SDimitry Andric     offset = note_offset + note.GetByteSize();
13060b57cec5SDimitry Andric   }
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric   return error;
13090b57cec5SDimitry Andric }
13100b57cec5SDimitry Andric 
13110b57cec5SDimitry Andric void ObjectFileELF::ParseARMAttributes(DataExtractor &data, uint64_t length,
13120b57cec5SDimitry Andric                                        ArchSpec &arch_spec) {
13130b57cec5SDimitry Andric   lldb::offset_t Offset = 0;
13140b57cec5SDimitry Andric 
13150b57cec5SDimitry Andric   uint8_t FormatVersion = data.GetU8(&Offset);
13165ffd83dbSDimitry Andric   if (FormatVersion != llvm::ELFAttrs::Format_Version)
13170b57cec5SDimitry Andric     return;
13180b57cec5SDimitry Andric 
13190b57cec5SDimitry Andric   Offset = Offset + sizeof(uint32_t); // Section Length
13200b57cec5SDimitry Andric   llvm::StringRef VendorName = data.GetCStr(&Offset);
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric   if (VendorName != "aeabi")
13230b57cec5SDimitry Andric     return;
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric   if (arch_spec.GetTriple().getEnvironment() ==
13260b57cec5SDimitry Andric       llvm::Triple::UnknownEnvironment)
13270b57cec5SDimitry Andric     arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
13280b57cec5SDimitry Andric 
13290b57cec5SDimitry Andric   while (Offset < length) {
13300b57cec5SDimitry Andric     uint8_t Tag = data.GetU8(&Offset);
13310b57cec5SDimitry Andric     uint32_t Size = data.GetU32(&Offset);
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric     if (Tag != llvm::ARMBuildAttrs::File || Size == 0)
13340b57cec5SDimitry Andric       continue;
13350b57cec5SDimitry Andric 
13360b57cec5SDimitry Andric     while (Offset < length) {
13370b57cec5SDimitry Andric       uint64_t Tag = data.GetULEB128(&Offset);
13380b57cec5SDimitry Andric       switch (Tag) {
13390b57cec5SDimitry Andric       default:
13400b57cec5SDimitry Andric         if (Tag < 32)
13410b57cec5SDimitry Andric           data.GetULEB128(&Offset);
13420b57cec5SDimitry Andric         else if (Tag % 2 == 0)
13430b57cec5SDimitry Andric           data.GetULEB128(&Offset);
13440b57cec5SDimitry Andric         else
13450b57cec5SDimitry Andric           data.GetCStr(&Offset);
13460b57cec5SDimitry Andric 
13470b57cec5SDimitry Andric         break;
13480b57cec5SDimitry Andric 
13490b57cec5SDimitry Andric       case llvm::ARMBuildAttrs::CPU_raw_name:
13500b57cec5SDimitry Andric       case llvm::ARMBuildAttrs::CPU_name:
13510b57cec5SDimitry Andric         data.GetCStr(&Offset);
13520b57cec5SDimitry Andric 
13530b57cec5SDimitry Andric         break;
13540b57cec5SDimitry Andric 
13550b57cec5SDimitry Andric       case llvm::ARMBuildAttrs::ABI_VFP_args: {
13560b57cec5SDimitry Andric         uint64_t VFPArgs = data.GetULEB128(&Offset);
13570b57cec5SDimitry Andric 
13580b57cec5SDimitry Andric         if (VFPArgs == llvm::ARMBuildAttrs::BaseAAPCS) {
13590b57cec5SDimitry Andric           if (arch_spec.GetTriple().getEnvironment() ==
13600b57cec5SDimitry Andric                   llvm::Triple::UnknownEnvironment ||
13610b57cec5SDimitry Andric               arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABIHF)
13620b57cec5SDimitry Andric             arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
13630b57cec5SDimitry Andric 
13640b57cec5SDimitry Andric           arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
13650b57cec5SDimitry Andric         } else if (VFPArgs == llvm::ARMBuildAttrs::HardFPAAPCS) {
13660b57cec5SDimitry Andric           if (arch_spec.GetTriple().getEnvironment() ==
13670b57cec5SDimitry Andric                   llvm::Triple::UnknownEnvironment ||
13680b57cec5SDimitry Andric               arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABI)
13690b57cec5SDimitry Andric             arch_spec.GetTriple().setEnvironment(llvm::Triple::EABIHF);
13700b57cec5SDimitry Andric 
13710b57cec5SDimitry Andric           arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
13720b57cec5SDimitry Andric         }
13730b57cec5SDimitry Andric 
13740b57cec5SDimitry Andric         break;
13750b57cec5SDimitry Andric       }
13760b57cec5SDimitry Andric       }
13770b57cec5SDimitry Andric     }
13780b57cec5SDimitry Andric   }
13790b57cec5SDimitry Andric }
13800b57cec5SDimitry Andric 
13810b57cec5SDimitry Andric // GetSectionHeaderInfo
13820b57cec5SDimitry Andric size_t ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl &section_headers,
13830b57cec5SDimitry Andric                                            DataExtractor &object_data,
13840b57cec5SDimitry Andric                                            const elf::ELFHeader &header,
13850b57cec5SDimitry Andric                                            lldb_private::UUID &uuid,
13860b57cec5SDimitry Andric                                            std::string &gnu_debuglink_file,
13870b57cec5SDimitry Andric                                            uint32_t &gnu_debuglink_crc,
13880b57cec5SDimitry Andric                                            ArchSpec &arch_spec) {
13890b57cec5SDimitry Andric   // Don't reparse the section headers if we already did that.
13900b57cec5SDimitry Andric   if (!section_headers.empty())
13910b57cec5SDimitry Andric     return section_headers.size();
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric   // Only initialize the arch_spec to okay defaults if they're not already set.
13940b57cec5SDimitry Andric   // We'll refine this with note data as we parse the notes.
13950b57cec5SDimitry Andric   if (arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) {
13960b57cec5SDimitry Andric     llvm::Triple::OSType ostype;
13970b57cec5SDimitry Andric     llvm::Triple::OSType spec_ostype;
13980b57cec5SDimitry Andric     const uint32_t sub_type = subTypeFromElfHeader(header);
13990b57cec5SDimitry Andric     arch_spec.SetArchitecture(eArchTypeELF, header.e_machine, sub_type,
14000b57cec5SDimitry Andric                               header.e_ident[EI_OSABI]);
14010b57cec5SDimitry Andric 
14020b57cec5SDimitry Andric     // Validate if it is ok to remove GetOsFromOSABI. Note, that now the OS is
14030b57cec5SDimitry Andric     // determined based on EI_OSABI flag and the info extracted from ELF notes
14040b57cec5SDimitry Andric     // (see RefineModuleDetailsFromNote). However in some cases that still
14050b57cec5SDimitry Andric     // might be not enough: for example a shared library might not have any
14060b57cec5SDimitry Andric     // notes at all and have EI_OSABI flag set to System V, as result the OS
14070b57cec5SDimitry Andric     // will be set to UnknownOS.
14080b57cec5SDimitry Andric     GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
14090b57cec5SDimitry Andric     spec_ostype = arch_spec.GetTriple().getOS();
14100b57cec5SDimitry Andric     assert(spec_ostype == ostype);
14110b57cec5SDimitry Andric     UNUSED_IF_ASSERT_DISABLED(spec_ostype);
14120b57cec5SDimitry Andric   }
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric   if (arch_spec.GetMachine() == llvm::Triple::mips ||
14150b57cec5SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::mipsel ||
14160b57cec5SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::mips64 ||
14170b57cec5SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::mips64el) {
14180b57cec5SDimitry Andric     switch (header.e_flags & llvm::ELF::EF_MIPS_ARCH_ASE) {
14190b57cec5SDimitry Andric     case llvm::ELF::EF_MIPS_MICROMIPS:
14200b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eMIPSAse_micromips);
14210b57cec5SDimitry Andric       break;
14220b57cec5SDimitry Andric     case llvm::ELF::EF_MIPS_ARCH_ASE_M16:
14230b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eMIPSAse_mips16);
14240b57cec5SDimitry Andric       break;
14250b57cec5SDimitry Andric     case llvm::ELF::EF_MIPS_ARCH_ASE_MDMX:
14260b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eMIPSAse_mdmx);
14270b57cec5SDimitry Andric       break;
14280b57cec5SDimitry Andric     default:
14290b57cec5SDimitry Andric       break;
14300b57cec5SDimitry Andric     }
14310b57cec5SDimitry Andric   }
14320b57cec5SDimitry Andric 
14330b57cec5SDimitry Andric   if (arch_spec.GetMachine() == llvm::Triple::arm ||
14340b57cec5SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::thumb) {
14350b57cec5SDimitry Andric     if (header.e_flags & llvm::ELF::EF_ARM_SOFT_FLOAT)
14360b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
14370b57cec5SDimitry Andric     else if (header.e_flags & llvm::ELF::EF_ARM_VFP_FLOAT)
14380b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
14390b57cec5SDimitry Andric   }
14400b57cec5SDimitry Andric 
144181ad6265SDimitry Andric   if (arch_spec.GetMachine() == llvm::Triple::riscv32 ||
144281ad6265SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::riscv64) {
144381ad6265SDimitry Andric     uint32_t flags = arch_spec.GetFlags();
144481ad6265SDimitry Andric 
144581ad6265SDimitry Andric     if (header.e_flags & llvm::ELF::EF_RISCV_RVC)
144681ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_rvc;
144781ad6265SDimitry Andric     if (header.e_flags & llvm::ELF::EF_RISCV_RVE)
144881ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_rve;
144981ad6265SDimitry Andric 
145081ad6265SDimitry Andric     if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_SINGLE) ==
145181ad6265SDimitry Andric         llvm::ELF::EF_RISCV_FLOAT_ABI_SINGLE)
145281ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_float_abi_single;
145381ad6265SDimitry Andric     else if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_DOUBLE) ==
145481ad6265SDimitry Andric              llvm::ELF::EF_RISCV_FLOAT_ABI_DOUBLE)
145581ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_float_abi_double;
145681ad6265SDimitry Andric     else if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_QUAD) ==
145781ad6265SDimitry Andric              llvm::ELF::EF_RISCV_FLOAT_ABI_QUAD)
145881ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_float_abi_quad;
145981ad6265SDimitry Andric 
146081ad6265SDimitry Andric     arch_spec.SetFlags(flags);
146181ad6265SDimitry Andric   }
146281ad6265SDimitry Andric 
14630b57cec5SDimitry Andric   // If there are no section headers we are done.
14640b57cec5SDimitry Andric   if (header.e_shnum == 0)
14650b57cec5SDimitry Andric     return 0;
14660b57cec5SDimitry Andric 
146781ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Modules);
14680b57cec5SDimitry Andric 
14690b57cec5SDimitry Andric   section_headers.resize(header.e_shnum);
14700b57cec5SDimitry Andric   if (section_headers.size() != header.e_shnum)
14710b57cec5SDimitry Andric     return 0;
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric   const size_t sh_size = header.e_shnum * header.e_shentsize;
14740b57cec5SDimitry Andric   const elf_off sh_offset = header.e_shoff;
14750b57cec5SDimitry Andric   DataExtractor sh_data;
14760b57cec5SDimitry Andric   if (sh_data.SetData(object_data, sh_offset, sh_size) != sh_size)
14770b57cec5SDimitry Andric     return 0;
14780b57cec5SDimitry Andric 
14790b57cec5SDimitry Andric   uint32_t idx;
14800b57cec5SDimitry Andric   lldb::offset_t offset;
14810b57cec5SDimitry Andric   for (idx = 0, offset = 0; idx < header.e_shnum; ++idx) {
14820b57cec5SDimitry Andric     if (!section_headers[idx].Parse(sh_data, &offset))
14830b57cec5SDimitry Andric       break;
14840b57cec5SDimitry Andric   }
14850b57cec5SDimitry Andric   if (idx < section_headers.size())
14860b57cec5SDimitry Andric     section_headers.resize(idx);
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric   const unsigned strtab_idx = header.e_shstrndx;
14890b57cec5SDimitry Andric   if (strtab_idx && strtab_idx < section_headers.size()) {
14900b57cec5SDimitry Andric     const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];
14910b57cec5SDimitry Andric     const size_t byte_size = sheader.sh_size;
14920b57cec5SDimitry Andric     const Elf64_Off offset = sheader.sh_offset;
14930b57cec5SDimitry Andric     lldb_private::DataExtractor shstr_data;
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric     if (shstr_data.SetData(object_data, offset, byte_size) == byte_size) {
14960b57cec5SDimitry Andric       for (SectionHeaderCollIter I = section_headers.begin();
14970b57cec5SDimitry Andric            I != section_headers.end(); ++I) {
14980b57cec5SDimitry Andric         static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");
14990b57cec5SDimitry Andric         const ELFSectionHeaderInfo &sheader = *I;
15000b57cec5SDimitry Andric         const uint64_t section_size =
15010b57cec5SDimitry Andric             sheader.sh_type == SHT_NOBITS ? 0 : sheader.sh_size;
15020b57cec5SDimitry Andric         ConstString name(shstr_data.PeekCStr(I->sh_name));
15030b57cec5SDimitry Andric 
15040b57cec5SDimitry Andric         I->section_name = name;
15050b57cec5SDimitry Andric 
15060b57cec5SDimitry Andric         if (arch_spec.IsMIPS()) {
15070b57cec5SDimitry Andric           uint32_t arch_flags = arch_spec.GetFlags();
15080b57cec5SDimitry Andric           DataExtractor data;
15090b57cec5SDimitry Andric           if (sheader.sh_type == SHT_MIPS_ABIFLAGS) {
15100b57cec5SDimitry Andric 
15110b57cec5SDimitry Andric             if (section_size && (data.SetData(object_data, sheader.sh_offset,
15120b57cec5SDimitry Andric                                               section_size) == section_size)) {
15130b57cec5SDimitry Andric               // MIPS ASE Mask is at offset 12 in MIPS.abiflags section
15140b57cec5SDimitry Andric               lldb::offset_t offset = 12; // MIPS ABI Flags Version: 0
15150b57cec5SDimitry Andric               arch_flags |= data.GetU32(&offset);
15160b57cec5SDimitry Andric 
15170b57cec5SDimitry Andric               // The floating point ABI is at offset 7
15180b57cec5SDimitry Andric               offset = 7;
15190b57cec5SDimitry Andric               switch (data.GetU8(&offset)) {
15200b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_ANY:
15210b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_ANY;
15220b57cec5SDimitry Andric                 break;
15230b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_DOUBLE:
15240b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_DOUBLE;
15250b57cec5SDimitry Andric                 break;
15260b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_SINGLE:
15270b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SINGLE;
15280b57cec5SDimitry Andric                 break;
15290b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_SOFT:
15300b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SOFT;
15310b57cec5SDimitry Andric                 break;
15320b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_OLD_64:
15330b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_OLD_64;
15340b57cec5SDimitry Andric                 break;
15350b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_XX:
15360b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_XX;
15370b57cec5SDimitry Andric                 break;
15380b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_64:
15390b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64;
15400b57cec5SDimitry Andric                 break;
15410b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_64A:
15420b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64A;
15430b57cec5SDimitry Andric                 break;
15440b57cec5SDimitry Andric               }
15450b57cec5SDimitry Andric             }
15460b57cec5SDimitry Andric           }
15470b57cec5SDimitry Andric           // Settings appropriate ArchSpec ABI Flags
15480b57cec5SDimitry Andric           switch (header.e_flags & llvm::ELF::EF_MIPS_ABI) {
15490b57cec5SDimitry Andric           case llvm::ELF::EF_MIPS_ABI_O32:
15500b57cec5SDimitry Andric             arch_flags |= lldb_private::ArchSpec::eMIPSABI_O32;
15510b57cec5SDimitry Andric             break;
15520b57cec5SDimitry Andric           case EF_MIPS_ABI_O64:
15530b57cec5SDimitry Andric             arch_flags |= lldb_private::ArchSpec::eMIPSABI_O64;
15540b57cec5SDimitry Andric             break;
15550b57cec5SDimitry Andric           case EF_MIPS_ABI_EABI32:
15560b57cec5SDimitry Andric             arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI32;
15570b57cec5SDimitry Andric             break;
15580b57cec5SDimitry Andric           case EF_MIPS_ABI_EABI64:
15590b57cec5SDimitry Andric             arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI64;
15600b57cec5SDimitry Andric             break;
15610b57cec5SDimitry Andric           default:
15620b57cec5SDimitry Andric             // ABI Mask doesn't cover N32 and N64 ABI.
15630b57cec5SDimitry Andric             if (header.e_ident[EI_CLASS] == llvm::ELF::ELFCLASS64)
15640b57cec5SDimitry Andric               arch_flags |= lldb_private::ArchSpec::eMIPSABI_N64;
15650b57cec5SDimitry Andric             else if (header.e_flags & llvm::ELF::EF_MIPS_ABI2)
15660b57cec5SDimitry Andric               arch_flags |= lldb_private::ArchSpec::eMIPSABI_N32;
15670b57cec5SDimitry Andric             break;
15680b57cec5SDimitry Andric           }
15690b57cec5SDimitry Andric           arch_spec.SetFlags(arch_flags);
15700b57cec5SDimitry Andric         }
15710b57cec5SDimitry Andric 
15720b57cec5SDimitry Andric         if (arch_spec.GetMachine() == llvm::Triple::arm ||
15730b57cec5SDimitry Andric             arch_spec.GetMachine() == llvm::Triple::thumb) {
15740b57cec5SDimitry Andric           DataExtractor data;
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric           if (sheader.sh_type == SHT_ARM_ATTRIBUTES && section_size != 0 &&
15770b57cec5SDimitry Andric               data.SetData(object_data, sheader.sh_offset, section_size) == section_size)
15780b57cec5SDimitry Andric             ParseARMAttributes(data, section_size, arch_spec);
15790b57cec5SDimitry Andric         }
15800b57cec5SDimitry Andric 
15810b57cec5SDimitry Andric         if (name == g_sect_name_gnu_debuglink) {
15820b57cec5SDimitry Andric           DataExtractor data;
15830b57cec5SDimitry Andric           if (section_size && (data.SetData(object_data, sheader.sh_offset,
15840b57cec5SDimitry Andric                                             section_size) == section_size)) {
15850b57cec5SDimitry Andric             lldb::offset_t gnu_debuglink_offset = 0;
15860b57cec5SDimitry Andric             gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);
15870b57cec5SDimitry Andric             gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
15880b57cec5SDimitry Andric             data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
15890b57cec5SDimitry Andric           }
15900b57cec5SDimitry Andric         }
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric         // Process ELF note section entries.
15930b57cec5SDimitry Andric         bool is_note_header = (sheader.sh_type == SHT_NOTE);
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric         // The section header ".note.android.ident" is stored as a
15960b57cec5SDimitry Andric         // PROGBITS type header but it is actually a note header.
15970b57cec5SDimitry Andric         static ConstString g_sect_name_android_ident(".note.android.ident");
15980b57cec5SDimitry Andric         if (!is_note_header && name == g_sect_name_android_ident)
15990b57cec5SDimitry Andric           is_note_header = true;
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric         if (is_note_header) {
16020b57cec5SDimitry Andric           // Allow notes to refine module info.
16030b57cec5SDimitry Andric           DataExtractor data;
16040b57cec5SDimitry Andric           if (section_size && (data.SetData(object_data, sheader.sh_offset,
16050b57cec5SDimitry Andric                                             section_size) == section_size)) {
16060b57cec5SDimitry Andric             Status error = RefineModuleDetailsFromNote(data, arch_spec, uuid);
16070b57cec5SDimitry Andric             if (error.Fail()) {
16089dba64beSDimitry Andric               LLDB_LOGF(log, "ObjectFileELF::%s ELF note processing failed: %s",
16090b57cec5SDimitry Andric                         __FUNCTION__, error.AsCString());
16100b57cec5SDimitry Andric             }
16110b57cec5SDimitry Andric           }
16120b57cec5SDimitry Andric         }
16130b57cec5SDimitry Andric       }
16140b57cec5SDimitry Andric 
16150b57cec5SDimitry Andric       // Make any unknown triple components to be unspecified unknowns.
16160b57cec5SDimitry Andric       if (arch_spec.GetTriple().getVendor() == llvm::Triple::UnknownVendor)
16170b57cec5SDimitry Andric         arch_spec.GetTriple().setVendorName(llvm::StringRef());
16180b57cec5SDimitry Andric       if (arch_spec.GetTriple().getOS() == llvm::Triple::UnknownOS)
16190b57cec5SDimitry Andric         arch_spec.GetTriple().setOSName(llvm::StringRef());
16200b57cec5SDimitry Andric 
16210b57cec5SDimitry Andric       return section_headers.size();
16220b57cec5SDimitry Andric     }
16230b57cec5SDimitry Andric   }
16240b57cec5SDimitry Andric 
16250b57cec5SDimitry Andric   section_headers.clear();
16260b57cec5SDimitry Andric   return 0;
16270b57cec5SDimitry Andric }
16280b57cec5SDimitry Andric 
16290b57cec5SDimitry Andric llvm::StringRef
16300b57cec5SDimitry Andric ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const {
16310b57cec5SDimitry Andric   size_t pos = symbol_name.find('@');
16320b57cec5SDimitry Andric   return symbol_name.substr(0, pos);
16330b57cec5SDimitry Andric }
16340b57cec5SDimitry Andric 
16350b57cec5SDimitry Andric // ParseSectionHeaders
16360b57cec5SDimitry Andric size_t ObjectFileELF::ParseSectionHeaders() {
16370b57cec5SDimitry Andric   return GetSectionHeaderInfo(m_section_headers, m_data, m_header, m_uuid,
16380b57cec5SDimitry Andric                               m_gnu_debuglink_file, m_gnu_debuglink_crc,
16390b57cec5SDimitry Andric                               m_arch_spec);
16400b57cec5SDimitry Andric }
16410b57cec5SDimitry Andric 
16420b57cec5SDimitry Andric const ObjectFileELF::ELFSectionHeaderInfo *
16430b57cec5SDimitry Andric ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id) {
16440b57cec5SDimitry Andric   if (!ParseSectionHeaders())
16450b57cec5SDimitry Andric     return nullptr;
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric   if (id < m_section_headers.size())
16480b57cec5SDimitry Andric     return &m_section_headers[id];
16490b57cec5SDimitry Andric 
16500b57cec5SDimitry Andric   return nullptr;
16510b57cec5SDimitry Andric }
16520b57cec5SDimitry Andric 
16530b57cec5SDimitry Andric lldb::user_id_t ObjectFileELF::GetSectionIndexByName(const char *name) {
16540b57cec5SDimitry Andric   if (!name || !name[0] || !ParseSectionHeaders())
16550b57cec5SDimitry Andric     return 0;
16560b57cec5SDimitry Andric   for (size_t i = 1; i < m_section_headers.size(); ++i)
16570b57cec5SDimitry Andric     if (m_section_headers[i].section_name == ConstString(name))
16580b57cec5SDimitry Andric       return i;
16590b57cec5SDimitry Andric   return 0;
16600b57cec5SDimitry Andric }
16610b57cec5SDimitry Andric 
16620b57cec5SDimitry Andric static SectionType GetSectionTypeFromName(llvm::StringRef Name) {
1663fcaf7f86SDimitry Andric   if (Name.consume_front(".debug_")) {
16640b57cec5SDimitry Andric     return llvm::StringSwitch<SectionType>(Name)
16650b57cec5SDimitry Andric         .Case("abbrev", eSectionTypeDWARFDebugAbbrev)
16660b57cec5SDimitry Andric         .Case("abbrev.dwo", eSectionTypeDWARFDebugAbbrevDwo)
16670b57cec5SDimitry Andric         .Case("addr", eSectionTypeDWARFDebugAddr)
16680b57cec5SDimitry Andric         .Case("aranges", eSectionTypeDWARFDebugAranges)
16690b57cec5SDimitry Andric         .Case("cu_index", eSectionTypeDWARFDebugCuIndex)
16700b57cec5SDimitry Andric         .Case("frame", eSectionTypeDWARFDebugFrame)
16710b57cec5SDimitry Andric         .Case("info", eSectionTypeDWARFDebugInfo)
16720b57cec5SDimitry Andric         .Case("info.dwo", eSectionTypeDWARFDebugInfoDwo)
16730b57cec5SDimitry Andric         .Cases("line", "line.dwo", eSectionTypeDWARFDebugLine)
16740b57cec5SDimitry Andric         .Cases("line_str", "line_str.dwo", eSectionTypeDWARFDebugLineStr)
1675480093f4SDimitry Andric         .Case("loc", eSectionTypeDWARFDebugLoc)
1676480093f4SDimitry Andric         .Case("loc.dwo", eSectionTypeDWARFDebugLocDwo)
1677480093f4SDimitry Andric         .Case("loclists", eSectionTypeDWARFDebugLocLists)
1678480093f4SDimitry Andric         .Case("loclists.dwo", eSectionTypeDWARFDebugLocListsDwo)
16790b57cec5SDimitry Andric         .Case("macinfo", eSectionTypeDWARFDebugMacInfo)
16800b57cec5SDimitry Andric         .Cases("macro", "macro.dwo", eSectionTypeDWARFDebugMacro)
16810b57cec5SDimitry Andric         .Case("names", eSectionTypeDWARFDebugNames)
16820b57cec5SDimitry Andric         .Case("pubnames", eSectionTypeDWARFDebugPubNames)
16830b57cec5SDimitry Andric         .Case("pubtypes", eSectionTypeDWARFDebugPubTypes)
16840b57cec5SDimitry Andric         .Case("ranges", eSectionTypeDWARFDebugRanges)
16850b57cec5SDimitry Andric         .Case("rnglists", eSectionTypeDWARFDebugRngLists)
1686480093f4SDimitry Andric         .Case("rnglists.dwo", eSectionTypeDWARFDebugRngListsDwo)
16870b57cec5SDimitry Andric         .Case("str", eSectionTypeDWARFDebugStr)
16880b57cec5SDimitry Andric         .Case("str.dwo", eSectionTypeDWARFDebugStrDwo)
16890b57cec5SDimitry Andric         .Case("str_offsets", eSectionTypeDWARFDebugStrOffsets)
16900b57cec5SDimitry Andric         .Case("str_offsets.dwo", eSectionTypeDWARFDebugStrOffsetsDwo)
16915ffd83dbSDimitry Andric         .Case("tu_index", eSectionTypeDWARFDebugTuIndex)
16920b57cec5SDimitry Andric         .Case("types", eSectionTypeDWARFDebugTypes)
16930b57cec5SDimitry Andric         .Case("types.dwo", eSectionTypeDWARFDebugTypesDwo)
16940b57cec5SDimitry Andric         .Default(eSectionTypeOther);
16950b57cec5SDimitry Andric   }
16960b57cec5SDimitry Andric   return llvm::StringSwitch<SectionType>(Name)
16970b57cec5SDimitry Andric       .Case(".ARM.exidx", eSectionTypeARMexidx)
16980b57cec5SDimitry Andric       .Case(".ARM.extab", eSectionTypeARMextab)
169906c3fb27SDimitry Andric       .Case(".ctf", eSectionTypeDebug)
17000b57cec5SDimitry Andric       .Cases(".data", ".tdata", eSectionTypeData)
17010b57cec5SDimitry Andric       .Case(".eh_frame", eSectionTypeEHFrame)
17020b57cec5SDimitry Andric       .Case(".gnu_debugaltlink", eSectionTypeDWARFGNUDebugAltLink)
17030b57cec5SDimitry Andric       .Case(".gosymtab", eSectionTypeGoSymtab)
17040b57cec5SDimitry Andric       .Case(".text", eSectionTypeCode)
17055f757f3fSDimitry Andric       .Case(".swift_ast", eSectionTypeSwiftModules)
17060b57cec5SDimitry Andric       .Default(eSectionTypeOther);
17070b57cec5SDimitry Andric }
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric SectionType ObjectFileELF::GetSectionType(const ELFSectionHeaderInfo &H) const {
17100b57cec5SDimitry Andric   switch (H.sh_type) {
17110b57cec5SDimitry Andric   case SHT_PROGBITS:
17120b57cec5SDimitry Andric     if (H.sh_flags & SHF_EXECINSTR)
17130b57cec5SDimitry Andric       return eSectionTypeCode;
17140b57cec5SDimitry Andric     break;
1715*0fca6ea1SDimitry Andric   case SHT_NOBITS:
1716*0fca6ea1SDimitry Andric     if (H.sh_flags & SHF_ALLOC)
1717*0fca6ea1SDimitry Andric       return eSectionTypeZeroFill;
1718*0fca6ea1SDimitry Andric     break;
17190b57cec5SDimitry Andric   case SHT_SYMTAB:
17200b57cec5SDimitry Andric     return eSectionTypeELFSymbolTable;
17210b57cec5SDimitry Andric   case SHT_DYNSYM:
17220b57cec5SDimitry Andric     return eSectionTypeELFDynamicSymbols;
17230b57cec5SDimitry Andric   case SHT_RELA:
17240b57cec5SDimitry Andric   case SHT_REL:
17250b57cec5SDimitry Andric     return eSectionTypeELFRelocationEntries;
17260b57cec5SDimitry Andric   case SHT_DYNAMIC:
17270b57cec5SDimitry Andric     return eSectionTypeELFDynamicLinkInfo;
17280b57cec5SDimitry Andric   }
17290b57cec5SDimitry Andric   return GetSectionTypeFromName(H.section_name.GetStringRef());
17300b57cec5SDimitry Andric }
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric static uint32_t GetTargetByteSize(SectionType Type, const ArchSpec &arch) {
17330b57cec5SDimitry Andric   switch (Type) {
17340b57cec5SDimitry Andric   case eSectionTypeData:
17350b57cec5SDimitry Andric   case eSectionTypeZeroFill:
17360b57cec5SDimitry Andric     return arch.GetDataByteSize();
17370b57cec5SDimitry Andric   case eSectionTypeCode:
17380b57cec5SDimitry Andric     return arch.GetCodeByteSize();
17390b57cec5SDimitry Andric   default:
17400b57cec5SDimitry Andric     return 1;
17410b57cec5SDimitry Andric   }
17420b57cec5SDimitry Andric }
17430b57cec5SDimitry Andric 
17440b57cec5SDimitry Andric static Permissions GetPermissions(const ELFSectionHeader &H) {
17450b57cec5SDimitry Andric   Permissions Perm = Permissions(0);
17460b57cec5SDimitry Andric   if (H.sh_flags & SHF_ALLOC)
17470b57cec5SDimitry Andric     Perm |= ePermissionsReadable;
17480b57cec5SDimitry Andric   if (H.sh_flags & SHF_WRITE)
17490b57cec5SDimitry Andric     Perm |= ePermissionsWritable;
17500b57cec5SDimitry Andric   if (H.sh_flags & SHF_EXECINSTR)
17510b57cec5SDimitry Andric     Perm |= ePermissionsExecutable;
17520b57cec5SDimitry Andric   return Perm;
17530b57cec5SDimitry Andric }
17540b57cec5SDimitry Andric 
17550b57cec5SDimitry Andric static Permissions GetPermissions(const ELFProgramHeader &H) {
17560b57cec5SDimitry Andric   Permissions Perm = Permissions(0);
17570b57cec5SDimitry Andric   if (H.p_flags & PF_R)
17580b57cec5SDimitry Andric     Perm |= ePermissionsReadable;
17590b57cec5SDimitry Andric   if (H.p_flags & PF_W)
17600b57cec5SDimitry Andric     Perm |= ePermissionsWritable;
17610b57cec5SDimitry Andric   if (H.p_flags & PF_X)
17620b57cec5SDimitry Andric     Perm |= ePermissionsExecutable;
17630b57cec5SDimitry Andric   return Perm;
17640b57cec5SDimitry Andric }
17650b57cec5SDimitry Andric 
17660b57cec5SDimitry Andric namespace {
17670b57cec5SDimitry Andric 
17680b57cec5SDimitry Andric using VMRange = lldb_private::Range<addr_t, addr_t>;
17690b57cec5SDimitry Andric 
17700b57cec5SDimitry Andric struct SectionAddressInfo {
17710b57cec5SDimitry Andric   SectionSP Segment;
17720b57cec5SDimitry Andric   VMRange Range;
17730b57cec5SDimitry Andric };
17740b57cec5SDimitry Andric 
17750b57cec5SDimitry Andric // (Unlinked) ELF object files usually have 0 for every section address, meaning
17760b57cec5SDimitry Andric // we need to compute synthetic addresses in order for "file addresses" from
17770b57cec5SDimitry Andric // different sections to not overlap. This class handles that logic.
17780b57cec5SDimitry Andric class VMAddressProvider {
17790b57cec5SDimitry Andric   using VMMap = llvm::IntervalMap<addr_t, SectionSP, 4,
17800b57cec5SDimitry Andric                                        llvm::IntervalMapHalfOpenInfo<addr_t>>;
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric   ObjectFile::Type ObjectType;
17830b57cec5SDimitry Andric   addr_t NextVMAddress = 0;
17840b57cec5SDimitry Andric   VMMap::Allocator Alloc;
178581ad6265SDimitry Andric   VMMap Segments{Alloc};
178681ad6265SDimitry Andric   VMMap Sections{Alloc};
178781ad6265SDimitry Andric   lldb_private::Log *Log = GetLog(LLDBLog::Modules);
17889dba64beSDimitry Andric   size_t SegmentCount = 0;
17899dba64beSDimitry Andric   std::string SegmentName;
17900b57cec5SDimitry Andric 
17910b57cec5SDimitry Andric   VMRange GetVMRange(const ELFSectionHeader &H) {
17920b57cec5SDimitry Andric     addr_t Address = H.sh_addr;
17930b57cec5SDimitry Andric     addr_t Size = H.sh_flags & SHF_ALLOC ? H.sh_size : 0;
17945f757f3fSDimitry Andric 
17955f757f3fSDimitry Andric     // When this is a debug file for relocatable file, the address is all zero
17965f757f3fSDimitry Andric     // and thus needs to use accumulate method
17975f757f3fSDimitry Andric     if ((ObjectType == ObjectFile::Type::eTypeObjectFile ||
17985f757f3fSDimitry Andric          (ObjectType == ObjectFile::Type::eTypeDebugInfo && H.sh_addr == 0)) &&
17995f757f3fSDimitry Andric         Segments.empty() && (H.sh_flags & SHF_ALLOC)) {
18000b57cec5SDimitry Andric       NextVMAddress =
18010b57cec5SDimitry Andric           llvm::alignTo(NextVMAddress, std::max<addr_t>(H.sh_addralign, 1));
18020b57cec5SDimitry Andric       Address = NextVMAddress;
18030b57cec5SDimitry Andric       NextVMAddress += Size;
18040b57cec5SDimitry Andric     }
18050b57cec5SDimitry Andric     return VMRange(Address, Size);
18060b57cec5SDimitry Andric   }
18070b57cec5SDimitry Andric 
18080b57cec5SDimitry Andric public:
18099dba64beSDimitry Andric   VMAddressProvider(ObjectFile::Type Type, llvm::StringRef SegmentName)
18105ffd83dbSDimitry Andric       : ObjectType(Type), SegmentName(std::string(SegmentName)) {}
18119dba64beSDimitry Andric 
18129dba64beSDimitry Andric   std::string GetNextSegmentName() const {
18139dba64beSDimitry Andric     return llvm::formatv("{0}[{1}]", SegmentName, SegmentCount).str();
18149dba64beSDimitry Andric   }
18150b57cec5SDimitry Andric 
1816bdd1243dSDimitry Andric   std::optional<VMRange> GetAddressInfo(const ELFProgramHeader &H) {
18170b57cec5SDimitry Andric     if (H.p_memsz == 0) {
18189dba64beSDimitry Andric       LLDB_LOG(Log, "Ignoring zero-sized {0} segment. Corrupt object file?",
18199dba64beSDimitry Andric                SegmentName);
1820bdd1243dSDimitry Andric       return std::nullopt;
18210b57cec5SDimitry Andric     }
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric     if (Segments.overlaps(H.p_vaddr, H.p_vaddr + H.p_memsz)) {
18249dba64beSDimitry Andric       LLDB_LOG(Log, "Ignoring overlapping {0} segment. Corrupt object file?",
18259dba64beSDimitry Andric                SegmentName);
1826bdd1243dSDimitry Andric       return std::nullopt;
18270b57cec5SDimitry Andric     }
18280b57cec5SDimitry Andric     return VMRange(H.p_vaddr, H.p_memsz);
18290b57cec5SDimitry Andric   }
18300b57cec5SDimitry Andric 
1831bdd1243dSDimitry Andric   std::optional<SectionAddressInfo> GetAddressInfo(const ELFSectionHeader &H) {
18320b57cec5SDimitry Andric     VMRange Range = GetVMRange(H);
18330b57cec5SDimitry Andric     SectionSP Segment;
18340b57cec5SDimitry Andric     auto It = Segments.find(Range.GetRangeBase());
18350b57cec5SDimitry Andric     if ((H.sh_flags & SHF_ALLOC) && It.valid()) {
18360b57cec5SDimitry Andric       addr_t MaxSize;
18370b57cec5SDimitry Andric       if (It.start() <= Range.GetRangeBase()) {
18380b57cec5SDimitry Andric         MaxSize = It.stop() - Range.GetRangeBase();
18390b57cec5SDimitry Andric         Segment = *It;
18400b57cec5SDimitry Andric       } else
18410b57cec5SDimitry Andric         MaxSize = It.start() - Range.GetRangeBase();
18420b57cec5SDimitry Andric       if (Range.GetByteSize() > MaxSize) {
18430b57cec5SDimitry Andric         LLDB_LOG(Log, "Shortening section crossing segment boundaries. "
18440b57cec5SDimitry Andric                       "Corrupt object file?");
18450b57cec5SDimitry Andric         Range.SetByteSize(MaxSize);
18460b57cec5SDimitry Andric       }
18470b57cec5SDimitry Andric     }
18480b57cec5SDimitry Andric     if (Range.GetByteSize() > 0 &&
18490b57cec5SDimitry Andric         Sections.overlaps(Range.GetRangeBase(), Range.GetRangeEnd())) {
18500b57cec5SDimitry Andric       LLDB_LOG(Log, "Ignoring overlapping section. Corrupt object file?");
1851bdd1243dSDimitry Andric       return std::nullopt;
18520b57cec5SDimitry Andric     }
18530b57cec5SDimitry Andric     if (Segment)
18540b57cec5SDimitry Andric       Range.Slide(-Segment->GetFileAddress());
18550b57cec5SDimitry Andric     return SectionAddressInfo{Segment, Range};
18560b57cec5SDimitry Andric   }
18570b57cec5SDimitry Andric 
18580b57cec5SDimitry Andric   void AddSegment(const VMRange &Range, SectionSP Seg) {
18590b57cec5SDimitry Andric     Segments.insert(Range.GetRangeBase(), Range.GetRangeEnd(), std::move(Seg));
18609dba64beSDimitry Andric     ++SegmentCount;
18610b57cec5SDimitry Andric   }
18620b57cec5SDimitry Andric 
18630b57cec5SDimitry Andric   void AddSection(SectionAddressInfo Info, SectionSP Sect) {
18640b57cec5SDimitry Andric     if (Info.Range.GetByteSize() == 0)
18650b57cec5SDimitry Andric       return;
18660b57cec5SDimitry Andric     if (Info.Segment)
18670b57cec5SDimitry Andric       Info.Range.Slide(Info.Segment->GetFileAddress());
18680b57cec5SDimitry Andric     Sections.insert(Info.Range.GetRangeBase(), Info.Range.GetRangeEnd(),
18690b57cec5SDimitry Andric                     std::move(Sect));
18700b57cec5SDimitry Andric   }
18710b57cec5SDimitry Andric };
18720b57cec5SDimitry Andric }
18730b57cec5SDimitry Andric 
1874*0fca6ea1SDimitry Andric // We have to do this because ELF doesn't have section IDs, and also
1875*0fca6ea1SDimitry Andric // doesn't require section names to be unique.  (We use the section index
1876*0fca6ea1SDimitry Andric // for section IDs, but that isn't guaranteed to be the same in separate
1877*0fca6ea1SDimitry Andric // debug images.)
1878*0fca6ea1SDimitry Andric static SectionSP FindMatchingSection(const SectionList &section_list,
1879*0fca6ea1SDimitry Andric                                      SectionSP section) {
1880*0fca6ea1SDimitry Andric   SectionSP sect_sp;
1881*0fca6ea1SDimitry Andric 
1882*0fca6ea1SDimitry Andric   addr_t vm_addr = section->GetFileAddress();
1883*0fca6ea1SDimitry Andric   ConstString name = section->GetName();
1884*0fca6ea1SDimitry Andric   offset_t byte_size = section->GetByteSize();
1885*0fca6ea1SDimitry Andric   bool thread_specific = section->IsThreadSpecific();
1886*0fca6ea1SDimitry Andric   uint32_t permissions = section->GetPermissions();
1887*0fca6ea1SDimitry Andric   uint32_t alignment = section->GetLog2Align();
1888*0fca6ea1SDimitry Andric 
1889*0fca6ea1SDimitry Andric   for (auto sect : section_list) {
1890*0fca6ea1SDimitry Andric     if (sect->GetName() == name &&
1891*0fca6ea1SDimitry Andric         sect->IsThreadSpecific() == thread_specific &&
1892*0fca6ea1SDimitry Andric         sect->GetPermissions() == permissions &&
1893*0fca6ea1SDimitry Andric         sect->GetByteSize() == byte_size && sect->GetFileAddress() == vm_addr &&
1894*0fca6ea1SDimitry Andric         sect->GetLog2Align() == alignment) {
1895*0fca6ea1SDimitry Andric       sect_sp = sect;
1896*0fca6ea1SDimitry Andric       break;
1897*0fca6ea1SDimitry Andric     } else {
1898*0fca6ea1SDimitry Andric       sect_sp = FindMatchingSection(sect->GetChildren(), section);
1899*0fca6ea1SDimitry Andric       if (sect_sp)
1900*0fca6ea1SDimitry Andric         break;
1901*0fca6ea1SDimitry Andric     }
1902*0fca6ea1SDimitry Andric   }
1903*0fca6ea1SDimitry Andric 
1904*0fca6ea1SDimitry Andric   return sect_sp;
1905*0fca6ea1SDimitry Andric }
1906*0fca6ea1SDimitry Andric 
19070b57cec5SDimitry Andric void ObjectFileELF::CreateSections(SectionList &unified_section_list) {
19080b57cec5SDimitry Andric   if (m_sections_up)
19090b57cec5SDimitry Andric     return;
19100b57cec5SDimitry Andric 
19119dba64beSDimitry Andric   m_sections_up = std::make_unique<SectionList>();
19129dba64beSDimitry Andric   VMAddressProvider regular_provider(GetType(), "PT_LOAD");
19139dba64beSDimitry Andric   VMAddressProvider tls_provider(GetType(), "PT_TLS");
19140b57cec5SDimitry Andric 
19150b57cec5SDimitry Andric   for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {
19160b57cec5SDimitry Andric     const ELFProgramHeader &PHdr = EnumPHdr.value();
19179dba64beSDimitry Andric     if (PHdr.p_type != PT_LOAD && PHdr.p_type != PT_TLS)
19180b57cec5SDimitry Andric       continue;
19190b57cec5SDimitry Andric 
19209dba64beSDimitry Andric     VMAddressProvider &provider =
19219dba64beSDimitry Andric         PHdr.p_type == PT_TLS ? tls_provider : regular_provider;
19229dba64beSDimitry Andric     auto InfoOr = provider.GetAddressInfo(PHdr);
19230b57cec5SDimitry Andric     if (!InfoOr)
19240b57cec5SDimitry Andric       continue;
19250b57cec5SDimitry Andric 
19260b57cec5SDimitry Andric     uint32_t Log2Align = llvm::Log2_64(std::max<elf_xword>(PHdr.p_align, 1));
19270b57cec5SDimitry Andric     SectionSP Segment = std::make_shared<Section>(
19289dba64beSDimitry Andric         GetModule(), this, SegmentID(EnumPHdr.index()),
19299dba64beSDimitry Andric         ConstString(provider.GetNextSegmentName()), eSectionTypeContainer,
19309dba64beSDimitry Andric         InfoOr->GetRangeBase(), InfoOr->GetByteSize(), PHdr.p_offset,
19319dba64beSDimitry Andric         PHdr.p_filesz, Log2Align, /*flags*/ 0);
19320b57cec5SDimitry Andric     Segment->SetPermissions(GetPermissions(PHdr));
19339dba64beSDimitry Andric     Segment->SetIsThreadSpecific(PHdr.p_type == PT_TLS);
19340b57cec5SDimitry Andric     m_sections_up->AddSection(Segment);
19350b57cec5SDimitry Andric 
19369dba64beSDimitry Andric     provider.AddSegment(*InfoOr, std::move(Segment));
19370b57cec5SDimitry Andric   }
19380b57cec5SDimitry Andric 
19390b57cec5SDimitry Andric   ParseSectionHeaders();
19400b57cec5SDimitry Andric   if (m_section_headers.empty())
19410b57cec5SDimitry Andric     return;
19420b57cec5SDimitry Andric 
19430b57cec5SDimitry Andric   for (SectionHeaderCollIter I = std::next(m_section_headers.begin());
19440b57cec5SDimitry Andric        I != m_section_headers.end(); ++I) {
19450b57cec5SDimitry Andric     const ELFSectionHeaderInfo &header = *I;
19460b57cec5SDimitry Andric 
19470b57cec5SDimitry Andric     ConstString &name = I->section_name;
19480b57cec5SDimitry Andric     const uint64_t file_size =
19490b57cec5SDimitry Andric         header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
19500b57cec5SDimitry Andric 
19519dba64beSDimitry Andric     VMAddressProvider &provider =
19529dba64beSDimitry Andric         header.sh_flags & SHF_TLS ? tls_provider : regular_provider;
19539dba64beSDimitry Andric     auto InfoOr = provider.GetAddressInfo(header);
19540b57cec5SDimitry Andric     if (!InfoOr)
19550b57cec5SDimitry Andric       continue;
19560b57cec5SDimitry Andric 
19570b57cec5SDimitry Andric     SectionType sect_type = GetSectionType(header);
19580b57cec5SDimitry Andric 
19590b57cec5SDimitry Andric     const uint32_t target_bytes_size =
19600b57cec5SDimitry Andric         GetTargetByteSize(sect_type, m_arch_spec);
19610b57cec5SDimitry Andric 
19620b57cec5SDimitry Andric     elf::elf_xword log2align =
19630b57cec5SDimitry Andric         (header.sh_addralign == 0) ? 0 : llvm::Log2_64(header.sh_addralign);
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric     SectionSP section_sp(new Section(
19660b57cec5SDimitry Andric         InfoOr->Segment, GetModule(), // Module to which this section belongs.
19670b57cec5SDimitry Andric         this,            // ObjectFile to which this section belongs and should
19680b57cec5SDimitry Andric                          // read section data from.
19690b57cec5SDimitry Andric         SectionIndex(I), // Section ID.
19700b57cec5SDimitry Andric         name,            // Section name.
19710b57cec5SDimitry Andric         sect_type,       // Section type.
19720b57cec5SDimitry Andric         InfoOr->Range.GetRangeBase(), // VM address.
19730b57cec5SDimitry Andric         InfoOr->Range.GetByteSize(),  // VM size in bytes of this section.
19740b57cec5SDimitry Andric         header.sh_offset,             // Offset of this section in the file.
19750b57cec5SDimitry Andric         file_size,           // Size of the section as found in the file.
19760b57cec5SDimitry Andric         log2align,           // Alignment of the section
19770b57cec5SDimitry Andric         header.sh_flags,     // Flags for this section.
19780b57cec5SDimitry Andric         target_bytes_size)); // Number of host bytes per target byte
19790b57cec5SDimitry Andric 
19800b57cec5SDimitry Andric     section_sp->SetPermissions(GetPermissions(header));
19810b57cec5SDimitry Andric     section_sp->SetIsThreadSpecific(header.sh_flags & SHF_TLS);
19820b57cec5SDimitry Andric     (InfoOr->Segment ? InfoOr->Segment->GetChildren() : *m_sections_up)
19830b57cec5SDimitry Andric         .AddSection(section_sp);
19849dba64beSDimitry Andric     provider.AddSection(std::move(*InfoOr), std::move(section_sp));
19850b57cec5SDimitry Andric   }
19860b57cec5SDimitry Andric 
19870b57cec5SDimitry Andric   // For eTypeDebugInfo files, the Symbol Vendor will take care of updating the
19880b57cec5SDimitry Andric   // unified section list.
19890b57cec5SDimitry Andric   if (GetType() != eTypeDebugInfo)
19900b57cec5SDimitry Andric     unified_section_list = *m_sections_up;
19919dba64beSDimitry Andric 
19929dba64beSDimitry Andric   // If there's a .gnu_debugdata section, we'll try to read the .symtab that's
19939dba64beSDimitry Andric   // embedded in there and replace the one in the original object file (if any).
19949dba64beSDimitry Andric   // If there's none in the orignal object file, we add it to it.
19959dba64beSDimitry Andric   if (auto gdd_obj_file = GetGnuDebugDataObjectFile()) {
19969dba64beSDimitry Andric     if (auto gdd_objfile_section_list = gdd_obj_file->GetSectionList()) {
19979dba64beSDimitry Andric       if (SectionSP symtab_section_sp =
19989dba64beSDimitry Andric               gdd_objfile_section_list->FindSectionByType(
19999dba64beSDimitry Andric                   eSectionTypeELFSymbolTable, true)) {
20009dba64beSDimitry Andric         SectionSP module_section_sp = unified_section_list.FindSectionByType(
20019dba64beSDimitry Andric             eSectionTypeELFSymbolTable, true);
20029dba64beSDimitry Andric         if (module_section_sp)
20039dba64beSDimitry Andric           unified_section_list.ReplaceSection(module_section_sp->GetID(),
20049dba64beSDimitry Andric                                               symtab_section_sp);
20059dba64beSDimitry Andric         else
20069dba64beSDimitry Andric           unified_section_list.AddSection(symtab_section_sp);
20079dba64beSDimitry Andric       }
20089dba64beSDimitry Andric     }
20099dba64beSDimitry Andric   }
20109dba64beSDimitry Andric }
20119dba64beSDimitry Andric 
20129dba64beSDimitry Andric std::shared_ptr<ObjectFileELF> ObjectFileELF::GetGnuDebugDataObjectFile() {
20139dba64beSDimitry Andric   if (m_gnu_debug_data_object_file != nullptr)
20149dba64beSDimitry Andric     return m_gnu_debug_data_object_file;
20159dba64beSDimitry Andric 
20169dba64beSDimitry Andric   SectionSP section =
20179dba64beSDimitry Andric       GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata"));
20189dba64beSDimitry Andric   if (!section)
20199dba64beSDimitry Andric     return nullptr;
20209dba64beSDimitry Andric 
20219dba64beSDimitry Andric   if (!lldb_private::lzma::isAvailable()) {
20229dba64beSDimitry Andric     GetModule()->ReportWarning(
20239dba64beSDimitry Andric         "No LZMA support found for reading .gnu_debugdata section");
20249dba64beSDimitry Andric     return nullptr;
20259dba64beSDimitry Andric   }
20269dba64beSDimitry Andric 
20279dba64beSDimitry Andric   // Uncompress the data
20289dba64beSDimitry Andric   DataExtractor data;
20299dba64beSDimitry Andric   section->GetSectionData(data);
20309dba64beSDimitry Andric   llvm::SmallVector<uint8_t, 0> uncompressedData;
20319dba64beSDimitry Andric   auto err = lldb_private::lzma::uncompress(data.GetData(), uncompressedData);
20329dba64beSDimitry Andric   if (err) {
20339dba64beSDimitry Andric     GetModule()->ReportWarning(
2034bdd1243dSDimitry Andric         "An error occurred while decompression the section {0}: {1}",
20359dba64beSDimitry Andric         section->GetName().AsCString(), llvm::toString(std::move(err)).c_str());
20369dba64beSDimitry Andric     return nullptr;
20379dba64beSDimitry Andric   }
20389dba64beSDimitry Andric 
20399dba64beSDimitry Andric   // Construct ObjectFileELF object from decompressed buffer
20409dba64beSDimitry Andric   DataBufferSP gdd_data_buf(
20419dba64beSDimitry Andric       new DataBufferHeap(uncompressedData.data(), uncompressedData.size()));
20429dba64beSDimitry Andric   auto fspec = GetFileSpec().CopyByAppendingPathComponent(
20439dba64beSDimitry Andric       llvm::StringRef("gnu_debugdata"));
20449dba64beSDimitry Andric   m_gnu_debug_data_object_file.reset(new ObjectFileELF(
20459dba64beSDimitry Andric       GetModule(), gdd_data_buf, 0, &fspec, 0, gdd_data_buf->GetByteSize()));
20469dba64beSDimitry Andric 
20479dba64beSDimitry Andric   // This line is essential; otherwise a breakpoint can be set but not hit.
20489dba64beSDimitry Andric   m_gnu_debug_data_object_file->SetType(ObjectFile::eTypeDebugInfo);
20499dba64beSDimitry Andric 
20509dba64beSDimitry Andric   ArchSpec spec = m_gnu_debug_data_object_file->GetArchitecture();
20519dba64beSDimitry Andric   if (spec && m_gnu_debug_data_object_file->SetModulesArchitecture(spec))
20529dba64beSDimitry Andric     return m_gnu_debug_data_object_file;
20539dba64beSDimitry Andric 
20549dba64beSDimitry Andric   return nullptr;
20550b57cec5SDimitry Andric }
20560b57cec5SDimitry Andric 
20570b57cec5SDimitry Andric // Find the arm/aarch64 mapping symbol character in the given symbol name.
20580b57cec5SDimitry Andric // Mapping symbols have the form of "$<char>[.<any>]*". Additionally we
20590b57cec5SDimitry Andric // recognize cases when the mapping symbol prefixed by an arbitrary string
20600b57cec5SDimitry Andric // because if a symbol prefix added to each symbol in the object file with
20610b57cec5SDimitry Andric // objcopy then the mapping symbols are also prefixed.
20620b57cec5SDimitry Andric static char FindArmAarch64MappingSymbol(const char *symbol_name) {
20630b57cec5SDimitry Andric   if (!symbol_name)
20640b57cec5SDimitry Andric     return '\0';
20650b57cec5SDimitry Andric 
20660b57cec5SDimitry Andric   const char *dollar_pos = ::strchr(symbol_name, '$');
20670b57cec5SDimitry Andric   if (!dollar_pos || dollar_pos[1] == '\0')
20680b57cec5SDimitry Andric     return '\0';
20690b57cec5SDimitry Andric 
20700b57cec5SDimitry Andric   if (dollar_pos[2] == '\0' || dollar_pos[2] == '.')
20710b57cec5SDimitry Andric     return dollar_pos[1];
20720b57cec5SDimitry Andric   return '\0';
20730b57cec5SDimitry Andric }
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric #define STO_MIPS_ISA (3 << 6)
20760b57cec5SDimitry Andric #define STO_MICROMIPS (2 << 6)
20770b57cec5SDimitry Andric #define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS)
20780b57cec5SDimitry Andric 
20790b57cec5SDimitry Andric // private
2080*0fca6ea1SDimitry Andric std::pair<unsigned, ObjectFileELF::FileAddressToAddressClassMap>
2081*0fca6ea1SDimitry Andric ObjectFileELF::ParseSymbols(Symtab *symtab, user_id_t start_id,
2082*0fca6ea1SDimitry Andric                             SectionList *section_list, const size_t num_symbols,
20830b57cec5SDimitry Andric                             const DataExtractor &symtab_data,
20840b57cec5SDimitry Andric                             const DataExtractor &strtab_data) {
20850b57cec5SDimitry Andric   ELFSymbol symbol;
20860b57cec5SDimitry Andric   lldb::offset_t offset = 0;
2087*0fca6ea1SDimitry Andric   // The changes these symbols would make to the class map. We will also update
2088*0fca6ea1SDimitry Andric   // m_address_class_map but need to tell the caller what changed because the
2089*0fca6ea1SDimitry Andric   // caller may be another object file.
2090*0fca6ea1SDimitry Andric   FileAddressToAddressClassMap address_class_map;
20910b57cec5SDimitry Andric 
20920b57cec5SDimitry Andric   static ConstString text_section_name(".text");
20930b57cec5SDimitry Andric   static ConstString init_section_name(".init");
20940b57cec5SDimitry Andric   static ConstString fini_section_name(".fini");
20950b57cec5SDimitry Andric   static ConstString ctors_section_name(".ctors");
20960b57cec5SDimitry Andric   static ConstString dtors_section_name(".dtors");
20970b57cec5SDimitry Andric 
20980b57cec5SDimitry Andric   static ConstString data_section_name(".data");
20990b57cec5SDimitry Andric   static ConstString rodata_section_name(".rodata");
21000b57cec5SDimitry Andric   static ConstString rodata1_section_name(".rodata1");
21010b57cec5SDimitry Andric   static ConstString data2_section_name(".data1");
21020b57cec5SDimitry Andric   static ConstString bss_section_name(".bss");
21030b57cec5SDimitry Andric   static ConstString opd_section_name(".opd"); // For ppc64
21040b57cec5SDimitry Andric 
21050b57cec5SDimitry Andric   // On Android the oatdata and the oatexec symbols in the oat and odex files
21060b57cec5SDimitry Andric   // covers the full .text section what causes issues with displaying unusable
21070b57cec5SDimitry Andric   // symbol name to the user and very slow unwinding speed because the
21080b57cec5SDimitry Andric   // instruction emulation based unwind plans try to emulate all instructions
21090b57cec5SDimitry Andric   // in these symbols. Don't add these symbols to the symbol list as they have
21100b57cec5SDimitry Andric   // no use for the debugger and they are causing a lot of trouble. Filtering
21110b57cec5SDimitry Andric   // can't be restricted to Android because this special object file don't
21120b57cec5SDimitry Andric   // contain the note section specifying the environment to Android but the
21130b57cec5SDimitry Andric   // custom extension and file name makes it highly unlikely that this will
21140b57cec5SDimitry Andric   // collide with anything else.
211506c3fb27SDimitry Andric   llvm::StringRef file_extension = m_file.GetFileNameExtension();
21160b57cec5SDimitry Andric   bool skip_oatdata_oatexec =
21170b57cec5SDimitry Andric       file_extension == ".oat" || file_extension == ".odex";
21180b57cec5SDimitry Andric 
21190b57cec5SDimitry Andric   ArchSpec arch = GetArchitecture();
21200b57cec5SDimitry Andric   ModuleSP module_sp(GetModule());
21210b57cec5SDimitry Andric   SectionList *module_section_list =
21220b57cec5SDimitry Andric       module_sp ? module_sp->GetSectionList() : nullptr;
21230b57cec5SDimitry Andric 
2124*0fca6ea1SDimitry Andric   // We might have debug information in a separate object, in which case
2125*0fca6ea1SDimitry Andric   // we need to map the sections from that object to the sections in the
2126*0fca6ea1SDimitry Andric   // main object during symbol lookup.  If we had to compare the sections
2127*0fca6ea1SDimitry Andric   // for every single symbol, that would be expensive, so this map is
2128*0fca6ea1SDimitry Andric   // used to accelerate the process.
2129*0fca6ea1SDimitry Andric   std::unordered_map<lldb::SectionSP, lldb::SectionSP> section_map;
21300b57cec5SDimitry Andric 
21310b57cec5SDimitry Andric   unsigned i;
21320b57cec5SDimitry Andric   for (i = 0; i < num_symbols; ++i) {
21330b57cec5SDimitry Andric     if (!symbol.Parse(symtab_data, &offset))
21340b57cec5SDimitry Andric       break;
21350b57cec5SDimitry Andric 
21360b57cec5SDimitry Andric     const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
21370b57cec5SDimitry Andric     if (!symbol_name)
21380b57cec5SDimitry Andric       symbol_name = "";
21390b57cec5SDimitry Andric 
21400b57cec5SDimitry Andric     // No need to add non-section symbols that have no names
21410b57cec5SDimitry Andric     if (symbol.getType() != STT_SECTION &&
21420b57cec5SDimitry Andric         (symbol_name == nullptr || symbol_name[0] == '\0'))
21430b57cec5SDimitry Andric       continue;
21440b57cec5SDimitry Andric 
21450b57cec5SDimitry Andric     // Skipping oatdata and oatexec sections if it is requested. See details
21460b57cec5SDimitry Andric     // above the definition of skip_oatdata_oatexec for the reasons.
21470b57cec5SDimitry Andric     if (skip_oatdata_oatexec && (::strcmp(symbol_name, "oatdata") == 0 ||
21480b57cec5SDimitry Andric                                  ::strcmp(symbol_name, "oatexec") == 0))
21490b57cec5SDimitry Andric       continue;
21500b57cec5SDimitry Andric 
21510b57cec5SDimitry Andric     SectionSP symbol_section_sp;
21520b57cec5SDimitry Andric     SymbolType symbol_type = eSymbolTypeInvalid;
21530b57cec5SDimitry Andric     Elf64_Half shndx = symbol.st_shndx;
21540b57cec5SDimitry Andric 
21550b57cec5SDimitry Andric     switch (shndx) {
21560b57cec5SDimitry Andric     case SHN_ABS:
21570b57cec5SDimitry Andric       symbol_type = eSymbolTypeAbsolute;
21580b57cec5SDimitry Andric       break;
21590b57cec5SDimitry Andric     case SHN_UNDEF:
21600b57cec5SDimitry Andric       symbol_type = eSymbolTypeUndefined;
21610b57cec5SDimitry Andric       break;
21620b57cec5SDimitry Andric     default:
21630b57cec5SDimitry Andric       symbol_section_sp = section_list->FindSectionByID(shndx);
21640b57cec5SDimitry Andric       break;
21650b57cec5SDimitry Andric     }
21660b57cec5SDimitry Andric 
21670b57cec5SDimitry Andric     // If a symbol is undefined do not process it further even if it has a STT
21680b57cec5SDimitry Andric     // type
21690b57cec5SDimitry Andric     if (symbol_type != eSymbolTypeUndefined) {
21700b57cec5SDimitry Andric       switch (symbol.getType()) {
21710b57cec5SDimitry Andric       default:
21720b57cec5SDimitry Andric       case STT_NOTYPE:
21730b57cec5SDimitry Andric         // The symbol's type is not specified.
21740b57cec5SDimitry Andric         break;
21750b57cec5SDimitry Andric 
21760b57cec5SDimitry Andric       case STT_OBJECT:
21770b57cec5SDimitry Andric         // The symbol is associated with a data object, such as a variable, an
21780b57cec5SDimitry Andric         // array, etc.
21790b57cec5SDimitry Andric         symbol_type = eSymbolTypeData;
21800b57cec5SDimitry Andric         break;
21810b57cec5SDimitry Andric 
21820b57cec5SDimitry Andric       case STT_FUNC:
21830b57cec5SDimitry Andric         // The symbol is associated with a function or other executable code.
21840b57cec5SDimitry Andric         symbol_type = eSymbolTypeCode;
21850b57cec5SDimitry Andric         break;
21860b57cec5SDimitry Andric 
21870b57cec5SDimitry Andric       case STT_SECTION:
21880b57cec5SDimitry Andric         // The symbol is associated with a section. Symbol table entries of
21890b57cec5SDimitry Andric         // this type exist primarily for relocation and normally have STB_LOCAL
21900b57cec5SDimitry Andric         // binding.
21910b57cec5SDimitry Andric         break;
21920b57cec5SDimitry Andric 
21930b57cec5SDimitry Andric       case STT_FILE:
21940b57cec5SDimitry Andric         // Conventionally, the symbol's name gives the name of the source file
21950b57cec5SDimitry Andric         // associated with the object file. A file symbol has STB_LOCAL
21960b57cec5SDimitry Andric         // binding, its section index is SHN_ABS, and it precedes the other
21970b57cec5SDimitry Andric         // STB_LOCAL symbols for the file, if it is present.
21980b57cec5SDimitry Andric         symbol_type = eSymbolTypeSourceFile;
21990b57cec5SDimitry Andric         break;
22000b57cec5SDimitry Andric 
22010b57cec5SDimitry Andric       case STT_GNU_IFUNC:
22020b57cec5SDimitry Andric         // The symbol is associated with an indirect function. The actual
22030b57cec5SDimitry Andric         // function will be resolved if it is referenced.
22040b57cec5SDimitry Andric         symbol_type = eSymbolTypeResolver;
22050b57cec5SDimitry Andric         break;
22060b57cec5SDimitry Andric       }
22070b57cec5SDimitry Andric     }
22080b57cec5SDimitry Andric 
22090b57cec5SDimitry Andric     if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) {
22100b57cec5SDimitry Andric       if (symbol_section_sp) {
22110b57cec5SDimitry Andric         ConstString sect_name = symbol_section_sp->GetName();
22120b57cec5SDimitry Andric         if (sect_name == text_section_name || sect_name == init_section_name ||
22130b57cec5SDimitry Andric             sect_name == fini_section_name || sect_name == ctors_section_name ||
22140b57cec5SDimitry Andric             sect_name == dtors_section_name) {
22150b57cec5SDimitry Andric           symbol_type = eSymbolTypeCode;
22160b57cec5SDimitry Andric         } else if (sect_name == data_section_name ||
22170b57cec5SDimitry Andric                    sect_name == data2_section_name ||
22180b57cec5SDimitry Andric                    sect_name == rodata_section_name ||
22190b57cec5SDimitry Andric                    sect_name == rodata1_section_name ||
22200b57cec5SDimitry Andric                    sect_name == bss_section_name) {
22210b57cec5SDimitry Andric           symbol_type = eSymbolTypeData;
22220b57cec5SDimitry Andric         }
22230b57cec5SDimitry Andric       }
22240b57cec5SDimitry Andric     }
22250b57cec5SDimitry Andric 
22260b57cec5SDimitry Andric     int64_t symbol_value_offset = 0;
22270b57cec5SDimitry Andric     uint32_t additional_flags = 0;
22280b57cec5SDimitry Andric 
22290b57cec5SDimitry Andric     if (arch.IsValid()) {
22300b57cec5SDimitry Andric       if (arch.GetMachine() == llvm::Triple::arm) {
22310b57cec5SDimitry Andric         if (symbol.getBinding() == STB_LOCAL) {
22320b57cec5SDimitry Andric           char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
22330b57cec5SDimitry Andric           if (symbol_type == eSymbolTypeCode) {
22340b57cec5SDimitry Andric             switch (mapping_symbol) {
22350b57cec5SDimitry Andric             case 'a':
22360b57cec5SDimitry Andric               // $a[.<any>]* - marks an ARM instruction sequence
2237*0fca6ea1SDimitry Andric               address_class_map[symbol.st_value] = AddressClass::eCode;
22380b57cec5SDimitry Andric               break;
22390b57cec5SDimitry Andric             case 'b':
22400b57cec5SDimitry Andric             case 't':
22410b57cec5SDimitry Andric               // $b[.<any>]* - marks a THUMB BL instruction sequence
22420b57cec5SDimitry Andric               // $t[.<any>]* - marks a THUMB instruction sequence
2243*0fca6ea1SDimitry Andric               address_class_map[symbol.st_value] =
22440b57cec5SDimitry Andric                   AddressClass::eCodeAlternateISA;
22450b57cec5SDimitry Andric               break;
22460b57cec5SDimitry Andric             case 'd':
22470b57cec5SDimitry Andric               // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2248*0fca6ea1SDimitry Andric               address_class_map[symbol.st_value] = AddressClass::eData;
22490b57cec5SDimitry Andric               break;
22500b57cec5SDimitry Andric             }
22510b57cec5SDimitry Andric           }
22520b57cec5SDimitry Andric           if (mapping_symbol)
22530b57cec5SDimitry Andric             continue;
22540b57cec5SDimitry Andric         }
22550b57cec5SDimitry Andric       } else if (arch.GetMachine() == llvm::Triple::aarch64) {
22560b57cec5SDimitry Andric         if (symbol.getBinding() == STB_LOCAL) {
22570b57cec5SDimitry Andric           char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
22580b57cec5SDimitry Andric           if (symbol_type == eSymbolTypeCode) {
22590b57cec5SDimitry Andric             switch (mapping_symbol) {
22600b57cec5SDimitry Andric             case 'x':
22610b57cec5SDimitry Andric               // $x[.<any>]* - marks an A64 instruction sequence
2262*0fca6ea1SDimitry Andric               address_class_map[symbol.st_value] = AddressClass::eCode;
22630b57cec5SDimitry Andric               break;
22640b57cec5SDimitry Andric             case 'd':
22650b57cec5SDimitry Andric               // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2266*0fca6ea1SDimitry Andric               address_class_map[symbol.st_value] = AddressClass::eData;
22670b57cec5SDimitry Andric               break;
22680b57cec5SDimitry Andric             }
22690b57cec5SDimitry Andric           }
22700b57cec5SDimitry Andric           if (mapping_symbol)
22710b57cec5SDimitry Andric             continue;
22720b57cec5SDimitry Andric         }
22730b57cec5SDimitry Andric       }
22740b57cec5SDimitry Andric 
22750b57cec5SDimitry Andric       if (arch.GetMachine() == llvm::Triple::arm) {
22760b57cec5SDimitry Andric         if (symbol_type == eSymbolTypeCode) {
22770b57cec5SDimitry Andric           if (symbol.st_value & 1) {
22780b57cec5SDimitry Andric             // Subtracting 1 from the address effectively unsets the low order
22790b57cec5SDimitry Andric             // bit, which results in the address actually pointing to the
22800b57cec5SDimitry Andric             // beginning of the symbol. This delta will be used below in
22810b57cec5SDimitry Andric             // conjunction with symbol.st_value to produce the final
22820b57cec5SDimitry Andric             // symbol_value that we store in the symtab.
22830b57cec5SDimitry Andric             symbol_value_offset = -1;
2284*0fca6ea1SDimitry Andric             address_class_map[symbol.st_value ^ 1] =
22850b57cec5SDimitry Andric                 AddressClass::eCodeAlternateISA;
22860b57cec5SDimitry Andric           } else {
22870b57cec5SDimitry Andric             // This address is ARM
2288*0fca6ea1SDimitry Andric             address_class_map[symbol.st_value] = AddressClass::eCode;
22890b57cec5SDimitry Andric           }
22900b57cec5SDimitry Andric         }
22910b57cec5SDimitry Andric       }
22920b57cec5SDimitry Andric 
22930b57cec5SDimitry Andric       /*
22940b57cec5SDimitry Andric        * MIPS:
22950b57cec5SDimitry Andric        * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for
22960b57cec5SDimitry Andric        * MIPS).
22970b57cec5SDimitry Andric        * This allows processor to switch between microMIPS and MIPS without any
22980b57cec5SDimitry Andric        * need
22990b57cec5SDimitry Andric        * for special mode-control register. However, apart from .debug_line,
23000b57cec5SDimitry Andric        * none of
23010b57cec5SDimitry Andric        * the ELF/DWARF sections set the ISA bit (for symbol or section). Use
23020b57cec5SDimitry Andric        * st_other
23030b57cec5SDimitry Andric        * flag to check whether the symbol is microMIPS and then set the address
23040b57cec5SDimitry Andric        * class
23050b57cec5SDimitry Andric        * accordingly.
23060b57cec5SDimitry Andric       */
23070b57cec5SDimitry Andric       if (arch.IsMIPS()) {
23080b57cec5SDimitry Andric         if (IS_MICROMIPS(symbol.st_other))
2309*0fca6ea1SDimitry Andric           address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
23100b57cec5SDimitry Andric         else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) {
23110b57cec5SDimitry Andric           symbol.st_value = symbol.st_value & (~1ull);
2312*0fca6ea1SDimitry Andric           address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
23130b57cec5SDimitry Andric         } else {
23140b57cec5SDimitry Andric           if (symbol_type == eSymbolTypeCode)
2315*0fca6ea1SDimitry Andric             address_class_map[symbol.st_value] = AddressClass::eCode;
23160b57cec5SDimitry Andric           else if (symbol_type == eSymbolTypeData)
2317*0fca6ea1SDimitry Andric             address_class_map[symbol.st_value] = AddressClass::eData;
23180b57cec5SDimitry Andric           else
2319*0fca6ea1SDimitry Andric             address_class_map[symbol.st_value] = AddressClass::eUnknown;
23200b57cec5SDimitry Andric         }
23210b57cec5SDimitry Andric       }
23220b57cec5SDimitry Andric     }
23230b57cec5SDimitry Andric 
23240b57cec5SDimitry Andric     // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB
23250b57cec5SDimitry Andric     // symbols. See above for more details.
23260b57cec5SDimitry Andric     uint64_t symbol_value = symbol.st_value + symbol_value_offset;
23270b57cec5SDimitry Andric 
23280b57cec5SDimitry Andric     if (symbol_section_sp &&
23290b57cec5SDimitry Andric         CalculateType() != ObjectFile::Type::eTypeObjectFile)
23300b57cec5SDimitry Andric       symbol_value -= symbol_section_sp->GetFileAddress();
23310b57cec5SDimitry Andric 
23320b57cec5SDimitry Andric     if (symbol_section_sp && module_section_list &&
23330b57cec5SDimitry Andric         module_section_list != section_list) {
2334*0fca6ea1SDimitry Andric       auto section_it = section_map.find(symbol_section_sp);
2335*0fca6ea1SDimitry Andric       if (section_it == section_map.end()) {
2336*0fca6ea1SDimitry Andric         section_it = section_map
2337*0fca6ea1SDimitry Andric                          .emplace(symbol_section_sp,
2338*0fca6ea1SDimitry Andric                                   FindMatchingSection(*module_section_list,
2339*0fca6ea1SDimitry Andric                                                       symbol_section_sp))
23400b57cec5SDimitry Andric                          .first;
2341*0fca6ea1SDimitry Andric       }
23420b57cec5SDimitry Andric       if (section_it->second)
23430b57cec5SDimitry Andric         symbol_section_sp = section_it->second;
23440b57cec5SDimitry Andric     }
23450b57cec5SDimitry Andric 
23460b57cec5SDimitry Andric     bool is_global = symbol.getBinding() == STB_GLOBAL;
23470b57cec5SDimitry Andric     uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags;
23480b57cec5SDimitry Andric     llvm::StringRef symbol_ref(symbol_name);
23490b57cec5SDimitry Andric 
23500b57cec5SDimitry Andric     // Symbol names may contain @VERSION suffixes. Find those and strip them
23510b57cec5SDimitry Andric     // temporarily.
23520b57cec5SDimitry Andric     size_t version_pos = symbol_ref.find('@');
23530b57cec5SDimitry Andric     bool has_suffix = version_pos != llvm::StringRef::npos;
23540b57cec5SDimitry Andric     llvm::StringRef symbol_bare = symbol_ref.substr(0, version_pos);
23559dba64beSDimitry Andric     Mangled mangled(symbol_bare);
23560b57cec5SDimitry Andric 
23570b57cec5SDimitry Andric     // Now append the suffix back to mangled and unmangled names. Only do it if
23580b57cec5SDimitry Andric     // the demangling was successful (string is not empty).
23590b57cec5SDimitry Andric     if (has_suffix) {
23600b57cec5SDimitry Andric       llvm::StringRef suffix = symbol_ref.substr(version_pos);
23610b57cec5SDimitry Andric 
23620b57cec5SDimitry Andric       llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef();
23630b57cec5SDimitry Andric       if (!mangled_name.empty())
23640b57cec5SDimitry Andric         mangled.SetMangledName(ConstString((mangled_name + suffix).str()));
23650b57cec5SDimitry Andric 
23665ffd83dbSDimitry Andric       ConstString demangled = mangled.GetDemangledName();
23670b57cec5SDimitry Andric       llvm::StringRef demangled_name = demangled.GetStringRef();
23680b57cec5SDimitry Andric       if (!demangled_name.empty())
23690b57cec5SDimitry Andric         mangled.SetDemangledName(ConstString((demangled_name + suffix).str()));
23700b57cec5SDimitry Andric     }
23710b57cec5SDimitry Andric 
23720b57cec5SDimitry Andric     // In ELF all symbol should have a valid size but it is not true for some
23730b57cec5SDimitry Andric     // function symbols coming from hand written assembly. As none of the
23740b57cec5SDimitry Andric     // function symbol should have 0 size we try to calculate the size for
23750b57cec5SDimitry Andric     // these symbols in the symtab with saying that their original size is not
23760b57cec5SDimitry Andric     // valid.
23770b57cec5SDimitry Andric     bool symbol_size_valid =
23780b57cec5SDimitry Andric         symbol.st_size != 0 || symbol.getType() != STT_FUNC;
23790b57cec5SDimitry Andric 
2380*0fca6ea1SDimitry Andric     bool is_trampoline = false;
2381*0fca6ea1SDimitry Andric     if (arch.IsValid() && (arch.GetMachine() == llvm::Triple::aarch64)) {
2382*0fca6ea1SDimitry Andric       // On AArch64, trampolines are registered as code.
2383*0fca6ea1SDimitry Andric       // If we detect a trampoline (which starts with __AArch64ADRPThunk_ or
2384*0fca6ea1SDimitry Andric       // __AArch64AbsLongThunk_) we register the symbol as a trampoline. This
2385*0fca6ea1SDimitry Andric       // way we will be able to detect the trampoline when we step in a function
2386*0fca6ea1SDimitry Andric       // and step through the trampoline.
2387*0fca6ea1SDimitry Andric       if (symbol_type == eSymbolTypeCode) {
2388*0fca6ea1SDimitry Andric         llvm::StringRef trampoline_name = mangled.GetName().GetStringRef();
2389*0fca6ea1SDimitry Andric         if (trampoline_name.starts_with("__AArch64ADRPThunk_") ||
2390*0fca6ea1SDimitry Andric             trampoline_name.starts_with("__AArch64AbsLongThunk_")) {
2391*0fca6ea1SDimitry Andric           symbol_type = eSymbolTypeTrampoline;
2392*0fca6ea1SDimitry Andric           is_trampoline = true;
2393*0fca6ea1SDimitry Andric         }
2394*0fca6ea1SDimitry Andric       }
2395*0fca6ea1SDimitry Andric     }
2396*0fca6ea1SDimitry Andric 
23970b57cec5SDimitry Andric     Symbol dc_symbol(
23980b57cec5SDimitry Andric         i + start_id, // ID is the original symbol table index.
23990b57cec5SDimitry Andric         mangled,
24000b57cec5SDimitry Andric         symbol_type,                    // Type of this symbol
24010b57cec5SDimitry Andric         is_global,                      // Is this globally visible?
24020b57cec5SDimitry Andric         false,                          // Is this symbol debug info?
2403*0fca6ea1SDimitry Andric         is_trampoline,                  // Is this symbol a trampoline?
24040b57cec5SDimitry Andric         false,                          // Is this symbol artificial?
24050b57cec5SDimitry Andric         AddressRange(symbol_section_sp, // Section in which this symbol is
24060b57cec5SDimitry Andric                                         // defined or null.
24070b57cec5SDimitry Andric                      symbol_value,      // Offset in section or symbol value.
24080b57cec5SDimitry Andric                      symbol.st_size),   // Size in bytes of this symbol.
24090b57cec5SDimitry Andric         symbol_size_valid,              // Symbol size is valid
24100b57cec5SDimitry Andric         has_suffix,                     // Contains linker annotations?
24110b57cec5SDimitry Andric         flags);                         // Symbol flags.
2412480093f4SDimitry Andric     if (symbol.getBinding() == STB_WEAK)
2413480093f4SDimitry Andric       dc_symbol.SetIsWeak(true);
24140b57cec5SDimitry Andric     symtab->AddSymbol(dc_symbol);
24150b57cec5SDimitry Andric   }
2416*0fca6ea1SDimitry Andric 
2417*0fca6ea1SDimitry Andric   m_address_class_map.merge(address_class_map);
2418*0fca6ea1SDimitry Andric   return {i, address_class_map};
24190b57cec5SDimitry Andric }
24200b57cec5SDimitry Andric 
2421*0fca6ea1SDimitry Andric std::pair<unsigned, ObjectFileELF::FileAddressToAddressClassMap>
2422*0fca6ea1SDimitry Andric ObjectFileELF::ParseSymbolTable(Symtab *symbol_table, user_id_t start_id,
24230b57cec5SDimitry Andric                                 lldb_private::Section *symtab) {
24240b57cec5SDimitry Andric   if (symtab->GetObjectFile() != this) {
24250b57cec5SDimitry Andric     // If the symbol table section is owned by a different object file, have it
24260b57cec5SDimitry Andric     // do the parsing.
24270b57cec5SDimitry Andric     ObjectFileELF *obj_file_elf =
24280b57cec5SDimitry Andric         static_cast<ObjectFileELF *>(symtab->GetObjectFile());
2429*0fca6ea1SDimitry Andric     auto [num_symbols, address_class_map] =
2430*0fca6ea1SDimitry Andric         obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab);
2431*0fca6ea1SDimitry Andric 
2432*0fca6ea1SDimitry Andric     // The other object file returned the changes it made to its address
2433*0fca6ea1SDimitry Andric     // class map, make the same changes to ours.
2434*0fca6ea1SDimitry Andric     m_address_class_map.merge(address_class_map);
2435*0fca6ea1SDimitry Andric 
2436*0fca6ea1SDimitry Andric     return {num_symbols, address_class_map};
24370b57cec5SDimitry Andric   }
24380b57cec5SDimitry Andric 
24390b57cec5SDimitry Andric   // Get section list for this object file.
24400b57cec5SDimitry Andric   SectionList *section_list = m_sections_up.get();
24410b57cec5SDimitry Andric   if (!section_list)
2442*0fca6ea1SDimitry Andric     return {};
24430b57cec5SDimitry Andric 
24440b57cec5SDimitry Andric   user_id_t symtab_id = symtab->GetID();
24450b57cec5SDimitry Andric   const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
24460b57cec5SDimitry Andric   assert(symtab_hdr->sh_type == SHT_SYMTAB ||
24470b57cec5SDimitry Andric          symtab_hdr->sh_type == SHT_DYNSYM);
24480b57cec5SDimitry Andric 
24490b57cec5SDimitry Andric   // sh_link: section header index of associated string table.
24500b57cec5SDimitry Andric   user_id_t strtab_id = symtab_hdr->sh_link;
24510b57cec5SDimitry Andric   Section *strtab = section_list->FindSectionByID(strtab_id).get();
24520b57cec5SDimitry Andric 
24530b57cec5SDimitry Andric   if (symtab && strtab) {
24540b57cec5SDimitry Andric     assert(symtab->GetObjectFile() == this);
24550b57cec5SDimitry Andric     assert(strtab->GetObjectFile() == this);
24560b57cec5SDimitry Andric 
24570b57cec5SDimitry Andric     DataExtractor symtab_data;
24580b57cec5SDimitry Andric     DataExtractor strtab_data;
24590b57cec5SDimitry Andric     if (ReadSectionData(symtab, symtab_data) &&
24600b57cec5SDimitry Andric         ReadSectionData(strtab, strtab_data)) {
24610b57cec5SDimitry Andric       size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
24620b57cec5SDimitry Andric 
24630b57cec5SDimitry Andric       return ParseSymbols(symbol_table, start_id, section_list, num_symbols,
24640b57cec5SDimitry Andric                           symtab_data, strtab_data);
24650b57cec5SDimitry Andric     }
24660b57cec5SDimitry Andric   }
24670b57cec5SDimitry Andric 
2468*0fca6ea1SDimitry Andric   return {0, {}};
24690b57cec5SDimitry Andric }
24700b57cec5SDimitry Andric 
24710b57cec5SDimitry Andric size_t ObjectFileELF::ParseDynamicSymbols() {
24720b57cec5SDimitry Andric   if (m_dynamic_symbols.size())
24730b57cec5SDimitry Andric     return m_dynamic_symbols.size();
24740b57cec5SDimitry Andric 
24750b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
24760b57cec5SDimitry Andric   if (!section_list)
24770b57cec5SDimitry Andric     return 0;
24780b57cec5SDimitry Andric 
24790b57cec5SDimitry Andric   // Find the SHT_DYNAMIC section.
24800b57cec5SDimitry Andric   Section *dynsym =
24810b57cec5SDimitry Andric       section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
24820b57cec5SDimitry Andric           .get();
24830b57cec5SDimitry Andric   if (!dynsym)
24840b57cec5SDimitry Andric     return 0;
24850b57cec5SDimitry Andric   assert(dynsym->GetObjectFile() == this);
24860b57cec5SDimitry Andric 
24870b57cec5SDimitry Andric   ELFDynamic symbol;
24880b57cec5SDimitry Andric   DataExtractor dynsym_data;
24890b57cec5SDimitry Andric   if (ReadSectionData(dynsym, dynsym_data)) {
24900b57cec5SDimitry Andric     const lldb::offset_t section_size = dynsym_data.GetByteSize();
24910b57cec5SDimitry Andric     lldb::offset_t cursor = 0;
24920b57cec5SDimitry Andric 
24930b57cec5SDimitry Andric     while (cursor < section_size) {
24940b57cec5SDimitry Andric       if (!symbol.Parse(dynsym_data, &cursor))
24950b57cec5SDimitry Andric         break;
24960b57cec5SDimitry Andric 
24970b57cec5SDimitry Andric       m_dynamic_symbols.push_back(symbol);
24980b57cec5SDimitry Andric     }
24990b57cec5SDimitry Andric   }
25000b57cec5SDimitry Andric 
25010b57cec5SDimitry Andric   return m_dynamic_symbols.size();
25020b57cec5SDimitry Andric }
25030b57cec5SDimitry Andric 
25040b57cec5SDimitry Andric const ELFDynamic *ObjectFileELF::FindDynamicSymbol(unsigned tag) {
25050b57cec5SDimitry Andric   if (!ParseDynamicSymbols())
25060b57cec5SDimitry Andric     return nullptr;
25070b57cec5SDimitry Andric 
25080b57cec5SDimitry Andric   DynamicSymbolCollIter I = m_dynamic_symbols.begin();
25090b57cec5SDimitry Andric   DynamicSymbolCollIter E = m_dynamic_symbols.end();
25100b57cec5SDimitry Andric   for (; I != E; ++I) {
25110b57cec5SDimitry Andric     ELFDynamic *symbol = &*I;
25120b57cec5SDimitry Andric 
25130b57cec5SDimitry Andric     if (symbol->d_tag == tag)
25140b57cec5SDimitry Andric       return symbol;
25150b57cec5SDimitry Andric   }
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric   return nullptr;
25180b57cec5SDimitry Andric }
25190b57cec5SDimitry Andric 
25200b57cec5SDimitry Andric unsigned ObjectFileELF::PLTRelocationType() {
25210b57cec5SDimitry Andric   // DT_PLTREL
25220b57cec5SDimitry Andric   //  This member specifies the type of relocation entry to which the
25230b57cec5SDimitry Andric   //  procedure linkage table refers. The d_val member holds DT_REL or
25240b57cec5SDimitry Andric   //  DT_RELA, as appropriate. All relocations in a procedure linkage table
25250b57cec5SDimitry Andric   //  must use the same relocation.
25260b57cec5SDimitry Andric   const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
25270b57cec5SDimitry Andric 
25280b57cec5SDimitry Andric   if (symbol)
25290b57cec5SDimitry Andric     return symbol->d_val;
25300b57cec5SDimitry Andric 
25310b57cec5SDimitry Andric   return 0;
25320b57cec5SDimitry Andric }
25330b57cec5SDimitry Andric 
25340b57cec5SDimitry Andric // Returns the size of the normal plt entries and the offset of the first
25350b57cec5SDimitry Andric // normal plt entry. The 0th entry in the plt table is usually a resolution
25360b57cec5SDimitry Andric // entry which have different size in some architectures then the rest of the
25370b57cec5SDimitry Andric // plt entries.
25380b57cec5SDimitry Andric static std::pair<uint64_t, uint64_t>
25390b57cec5SDimitry Andric GetPltEntrySizeAndOffset(const ELFSectionHeader *rel_hdr,
25400b57cec5SDimitry Andric                          const ELFSectionHeader *plt_hdr) {
25410b57cec5SDimitry Andric   const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
25420b57cec5SDimitry Andric 
25430b57cec5SDimitry Andric   // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are
25440b57cec5SDimitry Andric   // 16 bytes. So round the entsize up by the alignment if addralign is set.
25450b57cec5SDimitry Andric   elf_xword plt_entsize =
25460b57cec5SDimitry Andric       plt_hdr->sh_addralign
25470b57cec5SDimitry Andric           ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign)
25480b57cec5SDimitry Andric           : plt_hdr->sh_entsize;
25490b57cec5SDimitry Andric 
25500b57cec5SDimitry Andric   // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly.
25510b57cec5SDimitry Andric   // PLT entries relocation code in general requires multiple instruction and
25520b57cec5SDimitry Andric   // should be greater than 4 bytes in most cases. Try to guess correct size
25530b57cec5SDimitry Andric   // just in case.
25540b57cec5SDimitry Andric   if (plt_entsize <= 4) {
25550b57cec5SDimitry Andric     // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the
25560b57cec5SDimitry Andric     // size of the plt entries based on the number of entries and the size of
25570b57cec5SDimitry Andric     // the plt section with the assumption that the size of the 0th entry is at
25580b57cec5SDimitry Andric     // least as big as the size of the normal entries and it isn't much bigger
25590b57cec5SDimitry Andric     // then that.
25600b57cec5SDimitry Andric     if (plt_hdr->sh_addralign)
25610b57cec5SDimitry Andric       plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign /
25620b57cec5SDimitry Andric                     (num_relocations + 1) * plt_hdr->sh_addralign;
25630b57cec5SDimitry Andric     else
25640b57cec5SDimitry Andric       plt_entsize = plt_hdr->sh_size / (num_relocations + 1);
25650b57cec5SDimitry Andric   }
25660b57cec5SDimitry Andric 
25670b57cec5SDimitry Andric   elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize;
25680b57cec5SDimitry Andric 
25690b57cec5SDimitry Andric   return std::make_pair(plt_entsize, plt_offset);
25700b57cec5SDimitry Andric }
25710b57cec5SDimitry Andric 
25720b57cec5SDimitry Andric static unsigned ParsePLTRelocations(
25730b57cec5SDimitry Andric     Symtab *symbol_table, user_id_t start_id, unsigned rel_type,
25740b57cec5SDimitry Andric     const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
25750b57cec5SDimitry Andric     const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr,
25760b57cec5SDimitry Andric     const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data,
25770b57cec5SDimitry Andric     DataExtractor &symtab_data, DataExtractor &strtab_data) {
25780b57cec5SDimitry Andric   ELFRelocation rel(rel_type);
25790b57cec5SDimitry Andric   ELFSymbol symbol;
25800b57cec5SDimitry Andric   lldb::offset_t offset = 0;
25810b57cec5SDimitry Andric 
25820b57cec5SDimitry Andric   uint64_t plt_offset, plt_entsize;
25830b57cec5SDimitry Andric   std::tie(plt_entsize, plt_offset) =
25840b57cec5SDimitry Andric       GetPltEntrySizeAndOffset(rel_hdr, plt_hdr);
25850b57cec5SDimitry Andric   const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
25860b57cec5SDimitry Andric 
25870b57cec5SDimitry Andric   typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
25880b57cec5SDimitry Andric   reloc_info_fn reloc_type;
25890b57cec5SDimitry Andric   reloc_info_fn reloc_symbol;
25900b57cec5SDimitry Andric 
25910b57cec5SDimitry Andric   if (hdr->Is32Bit()) {
25920b57cec5SDimitry Andric     reloc_type = ELFRelocation::RelocType32;
25930b57cec5SDimitry Andric     reloc_symbol = ELFRelocation::RelocSymbol32;
25940b57cec5SDimitry Andric   } else {
25950b57cec5SDimitry Andric     reloc_type = ELFRelocation::RelocType64;
25960b57cec5SDimitry Andric     reloc_symbol = ELFRelocation::RelocSymbol64;
25970b57cec5SDimitry Andric   }
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric   unsigned slot_type = hdr->GetRelocationJumpSlotType();
26000b57cec5SDimitry Andric   unsigned i;
26010b57cec5SDimitry Andric   for (i = 0; i < num_relocations; ++i) {
26020b57cec5SDimitry Andric     if (!rel.Parse(rel_data, &offset))
26030b57cec5SDimitry Andric       break;
26040b57cec5SDimitry Andric 
26050b57cec5SDimitry Andric     if (reloc_type(rel) != slot_type)
26060b57cec5SDimitry Andric       continue;
26070b57cec5SDimitry Andric 
26080b57cec5SDimitry Andric     lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
26090b57cec5SDimitry Andric     if (!symbol.Parse(symtab_data, &symbol_offset))
26100b57cec5SDimitry Andric       break;
26110b57cec5SDimitry Andric 
26120b57cec5SDimitry Andric     const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
26130b57cec5SDimitry Andric     uint64_t plt_index = plt_offset + i * plt_entsize;
26140b57cec5SDimitry Andric 
26150b57cec5SDimitry Andric     Symbol jump_symbol(
26160b57cec5SDimitry Andric         i + start_id,          // Symbol table index
26170b57cec5SDimitry Andric         symbol_name,           // symbol name.
26180b57cec5SDimitry Andric         eSymbolTypeTrampoline, // Type of this symbol
26190b57cec5SDimitry Andric         false,                 // Is this globally visible?
26200b57cec5SDimitry Andric         false,                 // Is this symbol debug info?
26210b57cec5SDimitry Andric         true,                  // Is this symbol a trampoline?
26220b57cec5SDimitry Andric         true,                  // Is this symbol artificial?
26230b57cec5SDimitry Andric         plt_section_sp, // Section in which this symbol is defined or null.
26240b57cec5SDimitry Andric         plt_index,      // Offset in section or symbol value.
26250b57cec5SDimitry Andric         plt_entsize,    // Size in bytes of this symbol.
26260b57cec5SDimitry Andric         true,           // Size is valid
26270b57cec5SDimitry Andric         false,          // Contains linker annotations?
26280b57cec5SDimitry Andric         0);             // Symbol flags.
26290b57cec5SDimitry Andric 
26300b57cec5SDimitry Andric     symbol_table->AddSymbol(jump_symbol);
26310b57cec5SDimitry Andric   }
26320b57cec5SDimitry Andric 
26330b57cec5SDimitry Andric   return i;
26340b57cec5SDimitry Andric }
26350b57cec5SDimitry Andric 
26360b57cec5SDimitry Andric unsigned
26370b57cec5SDimitry Andric ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table, user_id_t start_id,
26380b57cec5SDimitry Andric                                       const ELFSectionHeaderInfo *rel_hdr,
26390b57cec5SDimitry Andric                                       user_id_t rel_id) {
26400b57cec5SDimitry Andric   assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
26410b57cec5SDimitry Andric 
26420b57cec5SDimitry Andric   // The link field points to the associated symbol table.
26430b57cec5SDimitry Andric   user_id_t symtab_id = rel_hdr->sh_link;
26440b57cec5SDimitry Andric 
26450b57cec5SDimitry Andric   // If the link field doesn't point to the appropriate symbol name table then
26460b57cec5SDimitry Andric   // try to find it by name as some compiler don't fill in the link fields.
26470b57cec5SDimitry Andric   if (!symtab_id)
26480b57cec5SDimitry Andric     symtab_id = GetSectionIndexByName(".dynsym");
26490b57cec5SDimitry Andric 
26500b57cec5SDimitry Andric   // Get PLT section.  We cannot use rel_hdr->sh_info, since current linkers
26510b57cec5SDimitry Andric   // point that to the .got.plt or .got section instead of .plt.
26520b57cec5SDimitry Andric   user_id_t plt_id = GetSectionIndexByName(".plt");
26530b57cec5SDimitry Andric 
26540b57cec5SDimitry Andric   if (!symtab_id || !plt_id)
26550b57cec5SDimitry Andric     return 0;
26560b57cec5SDimitry Andric 
26570b57cec5SDimitry Andric   const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
26580b57cec5SDimitry Andric   if (!plt_hdr)
26590b57cec5SDimitry Andric     return 0;
26600b57cec5SDimitry Andric 
26610b57cec5SDimitry Andric   const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
26620b57cec5SDimitry Andric   if (!sym_hdr)
26630b57cec5SDimitry Andric     return 0;
26640b57cec5SDimitry Andric 
26650b57cec5SDimitry Andric   SectionList *section_list = m_sections_up.get();
26660b57cec5SDimitry Andric   if (!section_list)
26670b57cec5SDimitry Andric     return 0;
26680b57cec5SDimitry Andric 
26690b57cec5SDimitry Andric   Section *rel_section = section_list->FindSectionByID(rel_id).get();
26700b57cec5SDimitry Andric   if (!rel_section)
26710b57cec5SDimitry Andric     return 0;
26720b57cec5SDimitry Andric 
26730b57cec5SDimitry Andric   SectionSP plt_section_sp(section_list->FindSectionByID(plt_id));
26740b57cec5SDimitry Andric   if (!plt_section_sp)
26750b57cec5SDimitry Andric     return 0;
26760b57cec5SDimitry Andric 
26770b57cec5SDimitry Andric   Section *symtab = section_list->FindSectionByID(symtab_id).get();
26780b57cec5SDimitry Andric   if (!symtab)
26790b57cec5SDimitry Andric     return 0;
26800b57cec5SDimitry Andric 
26810b57cec5SDimitry Andric   // sh_link points to associated string table.
26820b57cec5SDimitry Andric   Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link).get();
26830b57cec5SDimitry Andric   if (!strtab)
26840b57cec5SDimitry Andric     return 0;
26850b57cec5SDimitry Andric 
26860b57cec5SDimitry Andric   DataExtractor rel_data;
26870b57cec5SDimitry Andric   if (!ReadSectionData(rel_section, rel_data))
26880b57cec5SDimitry Andric     return 0;
26890b57cec5SDimitry Andric 
26900b57cec5SDimitry Andric   DataExtractor symtab_data;
26910b57cec5SDimitry Andric   if (!ReadSectionData(symtab, symtab_data))
26920b57cec5SDimitry Andric     return 0;
26930b57cec5SDimitry Andric 
26940b57cec5SDimitry Andric   DataExtractor strtab_data;
26950b57cec5SDimitry Andric   if (!ReadSectionData(strtab, strtab_data))
26960b57cec5SDimitry Andric     return 0;
26970b57cec5SDimitry Andric 
26980b57cec5SDimitry Andric   unsigned rel_type = PLTRelocationType();
26990b57cec5SDimitry Andric   if (!rel_type)
27000b57cec5SDimitry Andric     return 0;
27010b57cec5SDimitry Andric 
27020b57cec5SDimitry Andric   return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header,
27030b57cec5SDimitry Andric                              rel_hdr, plt_hdr, sym_hdr, plt_section_sp,
27040b57cec5SDimitry Andric                              rel_data, symtab_data, strtab_data);
27050b57cec5SDimitry Andric }
27060b57cec5SDimitry Andric 
27071ac55f4cSDimitry Andric static void ApplyELF64ABS64Relocation(Symtab *symtab, ELFRelocation &rel,
27081ac55f4cSDimitry Andric                                       DataExtractor &debug_data,
27091ac55f4cSDimitry Andric                                       Section *rel_section) {
27101ac55f4cSDimitry Andric   Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol64(rel));
27111ac55f4cSDimitry Andric   if (symbol) {
27121ac55f4cSDimitry Andric     addr_t value = symbol->GetAddressRef().GetFileAddress();
27131ac55f4cSDimitry Andric     DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
27141ac55f4cSDimitry Andric     // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
27151ac55f4cSDimitry Andric     WritableDataBuffer *data_buffer =
27161ac55f4cSDimitry Andric         llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
27171ac55f4cSDimitry Andric     uint64_t *dst = reinterpret_cast<uint64_t *>(
27181ac55f4cSDimitry Andric         data_buffer->GetBytes() + rel_section->GetFileOffset() +
27191ac55f4cSDimitry Andric         ELFRelocation::RelocOffset64(rel));
27201ac55f4cSDimitry Andric     uint64_t val_offset = value + ELFRelocation::RelocAddend64(rel);
27211ac55f4cSDimitry Andric     memcpy(dst, &val_offset, sizeof(uint64_t));
27221ac55f4cSDimitry Andric   }
27231ac55f4cSDimitry Andric }
27241ac55f4cSDimitry Andric 
27251ac55f4cSDimitry Andric static void ApplyELF64ABS32Relocation(Symtab *symtab, ELFRelocation &rel,
27261ac55f4cSDimitry Andric                                       DataExtractor &debug_data,
27271ac55f4cSDimitry Andric                                       Section *rel_section, bool is_signed) {
27281ac55f4cSDimitry Andric   Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol64(rel));
27291ac55f4cSDimitry Andric   if (symbol) {
27301ac55f4cSDimitry Andric     addr_t value = symbol->GetAddressRef().GetFileAddress();
27311ac55f4cSDimitry Andric     value += ELFRelocation::RelocAddend32(rel);
27321ac55f4cSDimitry Andric     if ((!is_signed && (value > UINT32_MAX)) ||
27331ac55f4cSDimitry Andric         (is_signed &&
27341ac55f4cSDimitry Andric          ((int64_t)value > INT32_MAX || (int64_t)value < INT32_MIN))) {
27351ac55f4cSDimitry Andric       Log *log = GetLog(LLDBLog::Modules);
27361ac55f4cSDimitry Andric       LLDB_LOGF(log, "Failed to apply debug info relocations");
27371ac55f4cSDimitry Andric       return;
27381ac55f4cSDimitry Andric     }
27391ac55f4cSDimitry Andric     uint32_t truncated_addr = (value & 0xFFFFFFFF);
27401ac55f4cSDimitry Andric     DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
27411ac55f4cSDimitry Andric     // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
27421ac55f4cSDimitry Andric     WritableDataBuffer *data_buffer =
27431ac55f4cSDimitry Andric         llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
27441ac55f4cSDimitry Andric     uint32_t *dst = reinterpret_cast<uint32_t *>(
27451ac55f4cSDimitry Andric         data_buffer->GetBytes() + rel_section->GetFileOffset() +
27461ac55f4cSDimitry Andric         ELFRelocation::RelocOffset32(rel));
27471ac55f4cSDimitry Andric     memcpy(dst, &truncated_addr, sizeof(uint32_t));
27481ac55f4cSDimitry Andric   }
27491ac55f4cSDimitry Andric }
27501ac55f4cSDimitry Andric 
275106c3fb27SDimitry Andric static void ApplyELF32ABS32RelRelocation(Symtab *symtab, ELFRelocation &rel,
275206c3fb27SDimitry Andric                                          DataExtractor &debug_data,
275306c3fb27SDimitry Andric                                          Section *rel_section) {
275406c3fb27SDimitry Andric   Log *log = GetLog(LLDBLog::Modules);
275506c3fb27SDimitry Andric   Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol32(rel));
275606c3fb27SDimitry Andric   if (symbol) {
275706c3fb27SDimitry Andric     addr_t value = symbol->GetAddressRef().GetFileAddress();
275806c3fb27SDimitry Andric     if (value == LLDB_INVALID_ADDRESS) {
275906c3fb27SDimitry Andric       const char *name = symbol->GetName().GetCString();
276006c3fb27SDimitry Andric       LLDB_LOGF(log, "Debug info symbol invalid: %s", name);
276106c3fb27SDimitry Andric       return;
276206c3fb27SDimitry Andric     }
276306c3fb27SDimitry Andric     assert(llvm::isUInt<32>(value) && "Valid addresses are 32-bit");
276406c3fb27SDimitry Andric     DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
276506c3fb27SDimitry Andric     // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
276606c3fb27SDimitry Andric     WritableDataBuffer *data_buffer =
276706c3fb27SDimitry Andric         llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
276806c3fb27SDimitry Andric     uint8_t *dst = data_buffer->GetBytes() + rel_section->GetFileOffset() +
276906c3fb27SDimitry Andric                    ELFRelocation::RelocOffset32(rel);
277006c3fb27SDimitry Andric     // Implicit addend is stored inline as a signed value.
277106c3fb27SDimitry Andric     int32_t addend;
277206c3fb27SDimitry Andric     memcpy(&addend, dst, sizeof(int32_t));
277306c3fb27SDimitry Andric     // The sum must be positive. This extra check prevents UB from overflow in
277406c3fb27SDimitry Andric     // the actual range check below.
277506c3fb27SDimitry Andric     if (addend < 0 && static_cast<uint32_t>(-addend) > value) {
277606c3fb27SDimitry Andric       LLDB_LOGF(log, "Debug info relocation overflow: 0x%" PRIx64,
277706c3fb27SDimitry Andric                 static_cast<int64_t>(value) + addend);
277806c3fb27SDimitry Andric       return;
277906c3fb27SDimitry Andric     }
278006c3fb27SDimitry Andric     if (!llvm::isUInt<32>(value + addend)) {
278106c3fb27SDimitry Andric       LLDB_LOGF(log, "Debug info relocation out of range: 0x%" PRIx64, value);
278206c3fb27SDimitry Andric       return;
278306c3fb27SDimitry Andric     }
278406c3fb27SDimitry Andric     uint32_t addr = value + addend;
278506c3fb27SDimitry Andric     memcpy(dst, &addr, sizeof(uint32_t));
278606c3fb27SDimitry Andric   }
278706c3fb27SDimitry Andric }
278806c3fb27SDimitry Andric 
27890b57cec5SDimitry Andric unsigned ObjectFileELF::ApplyRelocations(
27900b57cec5SDimitry Andric     Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
27910b57cec5SDimitry Andric     const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr,
27920b57cec5SDimitry Andric     DataExtractor &rel_data, DataExtractor &symtab_data,
27930b57cec5SDimitry Andric     DataExtractor &debug_data, Section *rel_section) {
27940b57cec5SDimitry Andric   ELFRelocation rel(rel_hdr->sh_type);
27950b57cec5SDimitry Andric   lldb::addr_t offset = 0;
27960b57cec5SDimitry Andric   const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
27970b57cec5SDimitry Andric   typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
27980b57cec5SDimitry Andric   reloc_info_fn reloc_type;
27990b57cec5SDimitry Andric   reloc_info_fn reloc_symbol;
28000b57cec5SDimitry Andric 
28010b57cec5SDimitry Andric   if (hdr->Is32Bit()) {
28020b57cec5SDimitry Andric     reloc_type = ELFRelocation::RelocType32;
28030b57cec5SDimitry Andric     reloc_symbol = ELFRelocation::RelocSymbol32;
28040b57cec5SDimitry Andric   } else {
28050b57cec5SDimitry Andric     reloc_type = ELFRelocation::RelocType64;
28060b57cec5SDimitry Andric     reloc_symbol = ELFRelocation::RelocSymbol64;
28070b57cec5SDimitry Andric   }
28080b57cec5SDimitry Andric 
28090b57cec5SDimitry Andric   for (unsigned i = 0; i < num_relocations; ++i) {
2810bdd1243dSDimitry Andric     if (!rel.Parse(rel_data, &offset)) {
2811bdd1243dSDimitry Andric       GetModule()->ReportError(".rel{0}[{1:d}] failed to parse relocation",
2812bdd1243dSDimitry Andric                                rel_section->GetName().AsCString(), i);
28130b57cec5SDimitry Andric       break;
2814bdd1243dSDimitry Andric     }
28150b57cec5SDimitry Andric     Symbol *symbol = nullptr;
28160b57cec5SDimitry Andric 
28170b57cec5SDimitry Andric     if (hdr->Is32Bit()) {
281806c3fb27SDimitry Andric       switch (hdr->e_machine) {
281906c3fb27SDimitry Andric       case llvm::ELF::EM_ARM:
282006c3fb27SDimitry Andric         switch (reloc_type(rel)) {
282106c3fb27SDimitry Andric         case R_ARM_ABS32:
282206c3fb27SDimitry Andric           ApplyELF32ABS32RelRelocation(symtab, rel, debug_data, rel_section);
282306c3fb27SDimitry Andric           break;
282406c3fb27SDimitry Andric         case R_ARM_REL32:
282506c3fb27SDimitry Andric           GetModule()->ReportError("unsupported AArch32 relocation:"
282606c3fb27SDimitry Andric                                    " .rel{0}[{1}], type {2}",
282706c3fb27SDimitry Andric                                    rel_section->GetName().AsCString(), i,
282806c3fb27SDimitry Andric                                    reloc_type(rel));
282906c3fb27SDimitry Andric           break;
283006c3fb27SDimitry Andric         default:
283106c3fb27SDimitry Andric           assert(false && "unexpected relocation type");
283206c3fb27SDimitry Andric         }
283306c3fb27SDimitry Andric         break;
283406c3fb27SDimitry Andric       case llvm::ELF::EM_386:
28350b57cec5SDimitry Andric         switch (reloc_type(rel)) {
28360b57cec5SDimitry Andric         case R_386_32:
2837bdd1243dSDimitry Andric           symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2838bdd1243dSDimitry Andric           if (symbol) {
2839bdd1243dSDimitry Andric             addr_t f_offset =
2840bdd1243dSDimitry Andric                 rel_section->GetFileOffset() + ELFRelocation::RelocOffset32(rel);
2841bdd1243dSDimitry Andric             DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2842bdd1243dSDimitry Andric             // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
2843bdd1243dSDimitry Andric             WritableDataBuffer *data_buffer =
2844bdd1243dSDimitry Andric                 llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
2845bdd1243dSDimitry Andric             uint32_t *dst = reinterpret_cast<uint32_t *>(
2846bdd1243dSDimitry Andric                 data_buffer->GetBytes() + f_offset);
2847bdd1243dSDimitry Andric 
2848bdd1243dSDimitry Andric             addr_t value = symbol->GetAddressRef().GetFileAddress();
2849bdd1243dSDimitry Andric             if (rel.IsRela()) {
2850bdd1243dSDimitry Andric               value += ELFRelocation::RelocAddend32(rel);
2851bdd1243dSDimitry Andric             } else {
2852bdd1243dSDimitry Andric               value += *dst;
2853bdd1243dSDimitry Andric             }
2854bdd1243dSDimitry Andric             *dst = value;
2855bdd1243dSDimitry Andric           } else {
2856bdd1243dSDimitry Andric             GetModule()->ReportError(".rel{0}[{1}] unknown symbol id: {2:d}",
2857bdd1243dSDimitry Andric                                     rel_section->GetName().AsCString(), i,
2858bdd1243dSDimitry Andric                                     reloc_symbol(rel));
2859bdd1243dSDimitry Andric           }
2860bdd1243dSDimitry Andric           break;
286106c3fb27SDimitry Andric         case R_386_NONE:
28620b57cec5SDimitry Andric         case R_386_PC32:
286306c3fb27SDimitry Andric           GetModule()->ReportError("unsupported i386 relocation:"
2864bdd1243dSDimitry Andric                                    " .rel{0}[{1}], type {2}",
2865bdd1243dSDimitry Andric                                    rel_section->GetName().AsCString(), i,
2866bdd1243dSDimitry Andric                                    reloc_type(rel));
286706c3fb27SDimitry Andric           break;
286806c3fb27SDimitry Andric         default:
286906c3fb27SDimitry Andric           assert(false && "unexpected relocation type");
287006c3fb27SDimitry Andric           break;
287106c3fb27SDimitry Andric         }
287206c3fb27SDimitry Andric         break;
287306c3fb27SDimitry Andric       default:
287406c3fb27SDimitry Andric         GetModule()->ReportError("unsupported 32-bit ELF machine arch: {0}", hdr->e_machine);
287506c3fb27SDimitry Andric         break;
28760b57cec5SDimitry Andric       }
28770b57cec5SDimitry Andric     } else {
28781ac55f4cSDimitry Andric       switch (hdr->e_machine) {
28791ac55f4cSDimitry Andric       case llvm::ELF::EM_AARCH64:
28800b57cec5SDimitry Andric         switch (reloc_type(rel)) {
28810b57cec5SDimitry Andric         case R_AARCH64_ABS64:
28821ac55f4cSDimitry Andric           ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
28831ac55f4cSDimitry Andric           break;
28841ac55f4cSDimitry Andric         case R_AARCH64_ABS32:
28851ac55f4cSDimitry Andric           ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
28861ac55f4cSDimitry Andric           break;
28871ac55f4cSDimitry Andric         default:
28881ac55f4cSDimitry Andric           assert(false && "unexpected relocation type");
28890b57cec5SDimitry Andric         }
28900b57cec5SDimitry Andric         break;
28911ac55f4cSDimitry Andric       case llvm::ELF::EM_LOONGARCH:
28921ac55f4cSDimitry Andric         switch (reloc_type(rel)) {
28931ac55f4cSDimitry Andric         case R_LARCH_64:
28941ac55f4cSDimitry Andric           ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
28951ac55f4cSDimitry Andric           break;
28961ac55f4cSDimitry Andric         case R_LARCH_32:
28971ac55f4cSDimitry Andric           ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
28981ac55f4cSDimitry Andric           break;
28991ac55f4cSDimitry Andric         default:
29001ac55f4cSDimitry Andric           assert(false && "unexpected relocation type");
29010b57cec5SDimitry Andric         }
29021ac55f4cSDimitry Andric         break;
29031ac55f4cSDimitry Andric       case llvm::ELF::EM_X86_64:
29041ac55f4cSDimitry Andric         switch (reloc_type(rel)) {
29051ac55f4cSDimitry Andric         case R_X86_64_64:
29061ac55f4cSDimitry Andric           ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
29071ac55f4cSDimitry Andric           break;
29080b57cec5SDimitry Andric         case R_X86_64_32:
29091ac55f4cSDimitry Andric           ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section,
29101ac55f4cSDimitry Andric                                     false);
29111ac55f4cSDimitry Andric           break;
29120b57cec5SDimitry Andric         case R_X86_64_32S:
29131ac55f4cSDimitry Andric           ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
29140b57cec5SDimitry Andric           break;
29150b57cec5SDimitry Andric         case R_X86_64_PC32:
29160b57cec5SDimitry Andric         default:
29170b57cec5SDimitry Andric           assert(false && "unexpected relocation type");
29180b57cec5SDimitry Andric         }
29191ac55f4cSDimitry Andric         break;
29201ac55f4cSDimitry Andric       default:
292106c3fb27SDimitry Andric         GetModule()->ReportError("unsupported 64-bit ELF machine arch: {0}", hdr->e_machine);
292206c3fb27SDimitry Andric         break;
29231ac55f4cSDimitry Andric       }
29240b57cec5SDimitry Andric     }
29250b57cec5SDimitry Andric   }
29260b57cec5SDimitry Andric 
29270b57cec5SDimitry Andric   return 0;
29280b57cec5SDimitry Andric }
29290b57cec5SDimitry Andric 
29300b57cec5SDimitry Andric unsigned ObjectFileELF::RelocateDebugSections(const ELFSectionHeader *rel_hdr,
29310b57cec5SDimitry Andric                                               user_id_t rel_id,
29320b57cec5SDimitry Andric                                               lldb_private::Symtab *thetab) {
29330b57cec5SDimitry Andric   assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
29340b57cec5SDimitry Andric 
29350b57cec5SDimitry Andric   // Parse in the section list if needed.
29360b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
29370b57cec5SDimitry Andric   if (!section_list)
29380b57cec5SDimitry Andric     return 0;
29390b57cec5SDimitry Andric 
29400b57cec5SDimitry Andric   user_id_t symtab_id = rel_hdr->sh_link;
29410b57cec5SDimitry Andric   user_id_t debug_id = rel_hdr->sh_info;
29420b57cec5SDimitry Andric 
29430b57cec5SDimitry Andric   const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
29440b57cec5SDimitry Andric   if (!symtab_hdr)
29450b57cec5SDimitry Andric     return 0;
29460b57cec5SDimitry Andric 
29470b57cec5SDimitry Andric   const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id);
29480b57cec5SDimitry Andric   if (!debug_hdr)
29490b57cec5SDimitry Andric     return 0;
29500b57cec5SDimitry Andric 
29510b57cec5SDimitry Andric   Section *rel = section_list->FindSectionByID(rel_id).get();
29520b57cec5SDimitry Andric   if (!rel)
29530b57cec5SDimitry Andric     return 0;
29540b57cec5SDimitry Andric 
29550b57cec5SDimitry Andric   Section *symtab = section_list->FindSectionByID(symtab_id).get();
29560b57cec5SDimitry Andric   if (!symtab)
29570b57cec5SDimitry Andric     return 0;
29580b57cec5SDimitry Andric 
29590b57cec5SDimitry Andric   Section *debug = section_list->FindSectionByID(debug_id).get();
29600b57cec5SDimitry Andric   if (!debug)
29610b57cec5SDimitry Andric     return 0;
29620b57cec5SDimitry Andric 
29630b57cec5SDimitry Andric   DataExtractor rel_data;
29640b57cec5SDimitry Andric   DataExtractor symtab_data;
29650b57cec5SDimitry Andric   DataExtractor debug_data;
29660b57cec5SDimitry Andric 
29670b57cec5SDimitry Andric   if (GetData(rel->GetFileOffset(), rel->GetFileSize(), rel_data) &&
29680b57cec5SDimitry Andric       GetData(symtab->GetFileOffset(), symtab->GetFileSize(), symtab_data) &&
29690b57cec5SDimitry Andric       GetData(debug->GetFileOffset(), debug->GetFileSize(), debug_data)) {
29700b57cec5SDimitry Andric     ApplyRelocations(thetab, &m_header, rel_hdr, symtab_hdr, debug_hdr,
29710b57cec5SDimitry Andric                      rel_data, symtab_data, debug_data, debug);
29720b57cec5SDimitry Andric   }
29730b57cec5SDimitry Andric 
29740b57cec5SDimitry Andric   return 0;
29750b57cec5SDimitry Andric }
29760b57cec5SDimitry Andric 
29774824e7fdSDimitry Andric void ObjectFileELF::ParseSymtab(Symtab &lldb_symtab) {
29780b57cec5SDimitry Andric   ModuleSP module_sp(GetModule());
29790b57cec5SDimitry Andric   if (!module_sp)
29804824e7fdSDimitry Andric     return;
29814824e7fdSDimitry Andric 
29827a6dacacSDimitry Andric   Progress progress("Parsing symbol table",
29837a6dacacSDimitry Andric                     m_file.GetFilename().AsCString("<Unknown>"));
29844824e7fdSDimitry Andric   ElapsedTime elapsed(module_sp->GetSymtabParseTime());
29850b57cec5SDimitry Andric 
29860b57cec5SDimitry Andric   // We always want to use the main object file so we (hopefully) only have one
29870b57cec5SDimitry Andric   // cached copy of our symtab, dynamic sections, etc.
29880b57cec5SDimitry Andric   ObjectFile *module_obj_file = module_sp->GetObjectFile();
29890b57cec5SDimitry Andric   if (module_obj_file && module_obj_file != this)
29904824e7fdSDimitry Andric     return module_obj_file->ParseSymtab(lldb_symtab);
29910b57cec5SDimitry Andric 
29920b57cec5SDimitry Andric   SectionList *section_list = module_sp->GetSectionList();
29930b57cec5SDimitry Andric   if (!section_list)
29944824e7fdSDimitry Andric     return;
29950b57cec5SDimitry Andric 
29960b57cec5SDimitry Andric   uint64_t symbol_id = 0;
29970b57cec5SDimitry Andric 
29980b57cec5SDimitry Andric   // Sharable objects and dynamic executables usually have 2 distinct symbol
29990b57cec5SDimitry Andric   // tables, one named ".symtab", and the other ".dynsym". The dynsym is a
30000b57cec5SDimitry Andric   // smaller version of the symtab that only contains global symbols. The
30010b57cec5SDimitry Andric   // information found in the dynsym is therefore also found in the symtab,
30020b57cec5SDimitry Andric   // while the reverse is not necessarily true.
30030b57cec5SDimitry Andric   Section *symtab =
30040b57cec5SDimitry Andric       section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get();
3005*0fca6ea1SDimitry Andric   if (symtab) {
3006*0fca6ea1SDimitry Andric     auto [num_symbols, address_class_map] =
3007*0fca6ea1SDimitry Andric         ParseSymbolTable(&lldb_symtab, symbol_id, symtab);
3008*0fca6ea1SDimitry Andric     m_address_class_map.merge(address_class_map);
3009*0fca6ea1SDimitry Andric     symbol_id += num_symbols;
3010*0fca6ea1SDimitry Andric   }
30110b57cec5SDimitry Andric 
30129dba64beSDimitry Andric   // The symtab section is non-allocable and can be stripped, while the
30139dba64beSDimitry Andric   // .dynsym section which should always be always be there. To support the
30149dba64beSDimitry Andric   // minidebuginfo case we parse .dynsym when there's a .gnu_debuginfo
30159dba64beSDimitry Andric   // section, nomatter if .symtab was already parsed or not. This is because
30169dba64beSDimitry Andric   // minidebuginfo normally removes the .symtab symbols which have their
30179dba64beSDimitry Andric   // matching .dynsym counterparts.
30189dba64beSDimitry Andric   if (!symtab ||
30199dba64beSDimitry Andric       GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata"))) {
30209dba64beSDimitry Andric     Section *dynsym =
30219dba64beSDimitry Andric         section_list->FindSectionByType(eSectionTypeELFDynamicSymbols, true)
30229dba64beSDimitry Andric             .get();
3023*0fca6ea1SDimitry Andric     if (dynsym) {
3024*0fca6ea1SDimitry Andric       auto [num_symbols, address_class_map] =
3025*0fca6ea1SDimitry Andric           ParseSymbolTable(&lldb_symtab, symbol_id, dynsym);
3026*0fca6ea1SDimitry Andric       symbol_id += num_symbols;
3027*0fca6ea1SDimitry Andric       m_address_class_map.merge(address_class_map);
3028*0fca6ea1SDimitry Andric     }
30299dba64beSDimitry Andric   }
30309dba64beSDimitry Andric 
30310b57cec5SDimitry Andric   // DT_JMPREL
30320b57cec5SDimitry Andric   //      If present, this entry's d_ptr member holds the address of
30330b57cec5SDimitry Andric   //      relocation
30340b57cec5SDimitry Andric   //      entries associated solely with the procedure linkage table.
30350b57cec5SDimitry Andric   //      Separating
30360b57cec5SDimitry Andric   //      these relocation entries lets the dynamic linker ignore them during
30370b57cec5SDimitry Andric   //      process initialization, if lazy binding is enabled. If this entry is
30380b57cec5SDimitry Andric   //      present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
30390b57cec5SDimitry Andric   //      also be present.
30400b57cec5SDimitry Andric   const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
30410b57cec5SDimitry Andric   if (symbol) {
30420b57cec5SDimitry Andric     // Synthesize trampoline symbols to help navigate the PLT.
30430b57cec5SDimitry Andric     addr_t addr = symbol->d_ptr;
30440b57cec5SDimitry Andric     Section *reloc_section =
30450b57cec5SDimitry Andric         section_list->FindSectionContainingFileAddress(addr).get();
30460b57cec5SDimitry Andric     if (reloc_section) {
30470b57cec5SDimitry Andric       user_id_t reloc_id = reloc_section->GetID();
30480b57cec5SDimitry Andric       const ELFSectionHeaderInfo *reloc_header =
30490b57cec5SDimitry Andric           GetSectionHeaderByIndex(reloc_id);
30504824e7fdSDimitry Andric       if (reloc_header)
30514824e7fdSDimitry Andric         ParseTrampolineSymbols(&lldb_symtab, symbol_id, reloc_header, reloc_id);
30520b57cec5SDimitry Andric     }
3053fe6060f1SDimitry Andric   }
30540b57cec5SDimitry Andric 
30550b57cec5SDimitry Andric   if (DWARFCallFrameInfo *eh_frame =
30560b57cec5SDimitry Andric           GetModule()->GetUnwindTable().GetEHFrameInfo()) {
30574824e7fdSDimitry Andric     ParseUnwindSymbols(&lldb_symtab, eh_frame);
30580b57cec5SDimitry Andric   }
30590b57cec5SDimitry Andric 
30609dba64beSDimitry Andric   // In the event that there's no symbol entry for the entry point we'll
30615ffd83dbSDimitry Andric   // artificially create one. We delegate to the symtab object the figuring
30629dba64beSDimitry Andric   // out of the proper size, this will usually make it span til the next
30639dba64beSDimitry Andric   // symbol it finds in the section. This means that if there are missing
30649dba64beSDimitry Andric   // symbols the entry point might span beyond its function definition.
30659dba64beSDimitry Andric   // We're fine with this as it doesn't make it worse than not having a
30669dba64beSDimitry Andric   // symbol entry at all.
30679dba64beSDimitry Andric   if (CalculateType() == eTypeExecutable) {
30689dba64beSDimitry Andric     ArchSpec arch = GetArchitecture();
30699dba64beSDimitry Andric     auto entry_point_addr = GetEntryPointAddress();
30709dba64beSDimitry Andric     bool is_valid_entry_point =
30719dba64beSDimitry Andric         entry_point_addr.IsValid() && entry_point_addr.IsSectionOffset();
30729dba64beSDimitry Andric     addr_t entry_point_file_addr = entry_point_addr.GetFileAddress();
30734824e7fdSDimitry Andric     if (is_valid_entry_point && !lldb_symtab.FindSymbolContainingFileAddress(
30749dba64beSDimitry Andric                                     entry_point_file_addr)) {
30754824e7fdSDimitry Andric       uint64_t symbol_id = lldb_symtab.GetNumSymbols();
3076fe6060f1SDimitry Andric       // Don't set the name for any synthetic symbols, the Symbol
3077fe6060f1SDimitry Andric       // object will generate one if needed when the name is accessed
3078fe6060f1SDimitry Andric       // via accessors.
3079fe6060f1SDimitry Andric       SectionSP section_sp = entry_point_addr.GetSection();
3080fe6060f1SDimitry Andric       Symbol 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=*/0,
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);
30949dba64beSDimitry Andric       // When the entry point is arm thumb we need to explicitly set its
30959dba64beSDimitry Andric       // class address to reflect that. This is important because expression
30969dba64beSDimitry Andric       // evaluation relies on correctly setting a breakpoint at this
30979dba64beSDimitry Andric       // address.
30989dba64beSDimitry Andric       if (arch.GetMachine() == llvm::Triple::arm &&
3099fe6060f1SDimitry Andric           (entry_point_file_addr & 1)) {
3100fe6060f1SDimitry Andric         symbol.GetAddressRef().SetOffset(entry_point_addr.GetOffset() ^ 1);
31019dba64beSDimitry Andric         m_address_class_map[entry_point_file_addr ^ 1] =
31029dba64beSDimitry Andric             AddressClass::eCodeAlternateISA;
3103fe6060f1SDimitry Andric       } else {
31049dba64beSDimitry Andric         m_address_class_map[entry_point_file_addr] = AddressClass::eCode;
31059dba64beSDimitry Andric       }
31064824e7fdSDimitry Andric       lldb_symtab.AddSymbol(symbol);
3107fe6060f1SDimitry Andric     }
31089dba64beSDimitry Andric   }
31090b57cec5SDimitry Andric }
31100b57cec5SDimitry Andric 
31110b57cec5SDimitry Andric void ObjectFileELF::RelocateSection(lldb_private::Section *section)
31120b57cec5SDimitry Andric {
31130b57cec5SDimitry Andric   static const char *debug_prefix = ".debug";
31140b57cec5SDimitry Andric 
31150b57cec5SDimitry Andric   // Set relocated bit so we stop getting called, regardless of whether we
31160b57cec5SDimitry Andric   // actually relocate.
31170b57cec5SDimitry Andric   section->SetIsRelocated(true);
31180b57cec5SDimitry Andric 
31190b57cec5SDimitry Andric   // We only relocate in ELF relocatable files
31200b57cec5SDimitry Andric   if (CalculateType() != eTypeObjectFile)
31210b57cec5SDimitry Andric     return;
31220b57cec5SDimitry Andric 
31230b57cec5SDimitry Andric   const char *section_name = section->GetName().GetCString();
31240b57cec5SDimitry Andric   // Can't relocate that which can't be named
31250b57cec5SDimitry Andric   if (section_name == nullptr)
31260b57cec5SDimitry Andric     return;
31270b57cec5SDimitry Andric 
31280b57cec5SDimitry Andric   // We don't relocate non-debug sections at the moment
31290b57cec5SDimitry Andric   if (strncmp(section_name, debug_prefix, strlen(debug_prefix)))
31300b57cec5SDimitry Andric     return;
31310b57cec5SDimitry Andric 
31320b57cec5SDimitry Andric   // Relocation section names to look for
31330b57cec5SDimitry Andric   std::string needle = std::string(".rel") + section_name;
31340b57cec5SDimitry Andric   std::string needlea = std::string(".rela") + section_name;
31350b57cec5SDimitry Andric 
31360b57cec5SDimitry Andric   for (SectionHeaderCollIter I = m_section_headers.begin();
31370b57cec5SDimitry Andric        I != m_section_headers.end(); ++I) {
31380b57cec5SDimitry Andric     if (I->sh_type == SHT_RELA || I->sh_type == SHT_REL) {
31390b57cec5SDimitry Andric       const char *hay_name = I->section_name.GetCString();
31400b57cec5SDimitry Andric       if (hay_name == nullptr)
31410b57cec5SDimitry Andric         continue;
31420b57cec5SDimitry Andric       if (needle == hay_name || needlea == hay_name) {
31430b57cec5SDimitry Andric         const ELFSectionHeader &reloc_header = *I;
31440b57cec5SDimitry Andric         user_id_t reloc_id = SectionIndex(I);
31450b57cec5SDimitry Andric         RelocateDebugSections(&reloc_header, reloc_id, GetSymtab());
31460b57cec5SDimitry Andric         break;
31470b57cec5SDimitry Andric       }
31480b57cec5SDimitry Andric     }
31490b57cec5SDimitry Andric   }
31500b57cec5SDimitry Andric }
31510b57cec5SDimitry Andric 
31520b57cec5SDimitry Andric void ObjectFileELF::ParseUnwindSymbols(Symtab *symbol_table,
31530b57cec5SDimitry Andric                                        DWARFCallFrameInfo *eh_frame) {
31540b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
31550b57cec5SDimitry Andric   if (!section_list)
31560b57cec5SDimitry Andric     return;
31570b57cec5SDimitry Andric 
31580b57cec5SDimitry Andric   // First we save the new symbols into a separate list and add them to the
31595ffd83dbSDimitry Andric   // symbol table after we collected all symbols we want to add. This is
31600b57cec5SDimitry Andric   // neccessary because adding a new symbol invalidates the internal index of
31610b57cec5SDimitry Andric   // the symtab what causing the next lookup to be slow because it have to
31620b57cec5SDimitry Andric   // recalculate the index first.
31630b57cec5SDimitry Andric   std::vector<Symbol> new_symbols;
31640b57cec5SDimitry Andric 
3165fe6060f1SDimitry Andric   size_t num_symbols = symbol_table->GetNumSymbols();
3166fe6060f1SDimitry Andric   uint64_t last_symbol_id =
3167fe6060f1SDimitry Andric       num_symbols ? symbol_table->SymbolAtIndex(num_symbols - 1)->GetID() : 0;
3168fe6060f1SDimitry Andric   eh_frame->ForEachFDEEntries([&](lldb::addr_t file_addr, uint32_t size,
3169fe6060f1SDimitry Andric                                   dw_offset_t) {
31700b57cec5SDimitry Andric     Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr);
31710b57cec5SDimitry Andric     if (symbol) {
31720b57cec5SDimitry Andric       if (!symbol->GetByteSizeIsValid()) {
31730b57cec5SDimitry Andric         symbol->SetByteSize(size);
31740b57cec5SDimitry Andric         symbol->SetSizeIsSynthesized(true);
31750b57cec5SDimitry Andric       }
31760b57cec5SDimitry Andric     } else {
31770b57cec5SDimitry Andric       SectionSP section_sp =
31780b57cec5SDimitry Andric           section_list->FindSectionContainingFileAddress(file_addr);
31790b57cec5SDimitry Andric       if (section_sp) {
31800b57cec5SDimitry Andric         addr_t offset = file_addr - section_sp->GetFileAddress();
3181fe6060f1SDimitry Andric         uint64_t symbol_id = ++last_symbol_id;
3182fe6060f1SDimitry Andric         // Don't set the name for any synthetic symbols, the Symbol
3183fe6060f1SDimitry Andric         // object will generate one if needed when the name is accessed
3184fe6060f1SDimitry Andric         // via accessors.
31850b57cec5SDimitry Andric         Symbol eh_symbol(
3186fe6060f1SDimitry Andric             /*symID=*/symbol_id,
3187fe6060f1SDimitry Andric             /*name=*/llvm::StringRef(), // Name will be auto generated.
3188fe6060f1SDimitry Andric             /*type=*/eSymbolTypeCode,
3189fe6060f1SDimitry Andric             /*external=*/true,
3190fe6060f1SDimitry Andric             /*is_debug=*/false,
3191fe6060f1SDimitry Andric             /*is_trampoline=*/false,
3192fe6060f1SDimitry Andric             /*is_artificial=*/true,
3193fe6060f1SDimitry Andric             /*section_sp=*/section_sp,
3194fe6060f1SDimitry Andric             /*offset=*/offset,
3195fe6060f1SDimitry Andric             /*size=*/0, // FDE can span multiple symbols so don't use its size.
3196fe6060f1SDimitry Andric             /*size_is_valid=*/false,
3197fe6060f1SDimitry Andric             /*contains_linker_annotations=*/false,
3198fe6060f1SDimitry Andric             /*flags=*/0);
31990b57cec5SDimitry Andric         new_symbols.push_back(eh_symbol);
32000b57cec5SDimitry Andric       }
32010b57cec5SDimitry Andric     }
32020b57cec5SDimitry Andric     return true;
32030b57cec5SDimitry Andric   });
32040b57cec5SDimitry Andric 
32050b57cec5SDimitry Andric   for (const Symbol &s : new_symbols)
32060b57cec5SDimitry Andric     symbol_table->AddSymbol(s);
32070b57cec5SDimitry Andric }
32080b57cec5SDimitry Andric 
32090b57cec5SDimitry Andric bool ObjectFileELF::IsStripped() {
32100b57cec5SDimitry Andric   // TODO: determine this for ELF
32110b57cec5SDimitry Andric   return false;
32120b57cec5SDimitry Andric }
32130b57cec5SDimitry Andric 
32140b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
32150b57cec5SDimitry Andric // Dump
32160b57cec5SDimitry Andric //
32170b57cec5SDimitry Andric // Dump the specifics of the runtime file container (such as any headers
32180b57cec5SDimitry Andric // segments, sections, etc).
32190b57cec5SDimitry Andric void ObjectFileELF::Dump(Stream *s) {
32200b57cec5SDimitry Andric   ModuleSP module_sp(GetModule());
32210b57cec5SDimitry Andric   if (!module_sp) {
32220b57cec5SDimitry Andric     return;
32230b57cec5SDimitry Andric   }
32240b57cec5SDimitry Andric 
32250b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
32260b57cec5SDimitry Andric   s->Printf("%p: ", static_cast<void *>(this));
32270b57cec5SDimitry Andric   s->Indent();
32280b57cec5SDimitry Andric   s->PutCString("ObjectFileELF");
32290b57cec5SDimitry Andric 
32300b57cec5SDimitry Andric   ArchSpec header_arch = GetArchitecture();
32310b57cec5SDimitry Andric 
32320b57cec5SDimitry Andric   *s << ", file = '" << m_file
32330b57cec5SDimitry Andric      << "', arch = " << header_arch.GetArchitectureName() << "\n";
32340b57cec5SDimitry Andric 
32350b57cec5SDimitry Andric   DumpELFHeader(s, m_header);
32360b57cec5SDimitry Andric   s->EOL();
32370b57cec5SDimitry Andric   DumpELFProgramHeaders(s);
32380b57cec5SDimitry Andric   s->EOL();
32390b57cec5SDimitry Andric   DumpELFSectionHeaders(s);
32400b57cec5SDimitry Andric   s->EOL();
32410b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
32420b57cec5SDimitry Andric   if (section_list)
32435ffd83dbSDimitry Andric     section_list->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
32445ffd83dbSDimitry Andric                        UINT32_MAX);
32450b57cec5SDimitry Andric   Symtab *symtab = GetSymtab();
32460b57cec5SDimitry Andric   if (symtab)
32470b57cec5SDimitry Andric     symtab->Dump(s, nullptr, eSortOrderNone);
32480b57cec5SDimitry Andric   s->EOL();
32490b57cec5SDimitry Andric   DumpDependentModules(s);
32500b57cec5SDimitry Andric   s->EOL();
32510b57cec5SDimitry Andric }
32520b57cec5SDimitry Andric 
32530b57cec5SDimitry Andric // DumpELFHeader
32540b57cec5SDimitry Andric //
32550b57cec5SDimitry Andric // Dump the ELF header to the specified output stream
32560b57cec5SDimitry Andric void ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header) {
32570b57cec5SDimitry Andric   s->PutCString("ELF Header\n");
32580b57cec5SDimitry Andric   s->Printf("e_ident[EI_MAG0   ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
32590b57cec5SDimitry Andric   s->Printf("e_ident[EI_MAG1   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG1],
32600b57cec5SDimitry Andric             header.e_ident[EI_MAG1]);
32610b57cec5SDimitry Andric   s->Printf("e_ident[EI_MAG2   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG2],
32620b57cec5SDimitry Andric             header.e_ident[EI_MAG2]);
32630b57cec5SDimitry Andric   s->Printf("e_ident[EI_MAG3   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG3],
32640b57cec5SDimitry Andric             header.e_ident[EI_MAG3]);
32650b57cec5SDimitry Andric 
32660b57cec5SDimitry Andric   s->Printf("e_ident[EI_CLASS  ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
32670b57cec5SDimitry Andric   s->Printf("e_ident[EI_DATA   ] = 0x%2.2x ", header.e_ident[EI_DATA]);
32680b57cec5SDimitry Andric   DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
32690b57cec5SDimitry Andric   s->Printf("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
32700b57cec5SDimitry Andric   s->Printf("e_ident[EI_PAD    ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
32710b57cec5SDimitry Andric 
32720b57cec5SDimitry Andric   s->Printf("e_type      = 0x%4.4x ", header.e_type);
32730b57cec5SDimitry Andric   DumpELFHeader_e_type(s, header.e_type);
32740b57cec5SDimitry Andric   s->Printf("\ne_machine   = 0x%4.4x\n", header.e_machine);
32750b57cec5SDimitry Andric   s->Printf("e_version   = 0x%8.8x\n", header.e_version);
32760b57cec5SDimitry Andric   s->Printf("e_entry     = 0x%8.8" PRIx64 "\n", header.e_entry);
32770b57cec5SDimitry Andric   s->Printf("e_phoff     = 0x%8.8" PRIx64 "\n", header.e_phoff);
32780b57cec5SDimitry Andric   s->Printf("e_shoff     = 0x%8.8" PRIx64 "\n", header.e_shoff);
32790b57cec5SDimitry Andric   s->Printf("e_flags     = 0x%8.8x\n", header.e_flags);
32800b57cec5SDimitry Andric   s->Printf("e_ehsize    = 0x%4.4x\n", header.e_ehsize);
32810b57cec5SDimitry Andric   s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
32820b57cec5SDimitry Andric   s->Printf("e_phnum     = 0x%8.8x\n", header.e_phnum);
32830b57cec5SDimitry Andric   s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
32840b57cec5SDimitry Andric   s->Printf("e_shnum     = 0x%8.8x\n", header.e_shnum);
32850b57cec5SDimitry Andric   s->Printf("e_shstrndx  = 0x%8.8x\n", header.e_shstrndx);
32860b57cec5SDimitry Andric }
32870b57cec5SDimitry Andric 
32880b57cec5SDimitry Andric // DumpELFHeader_e_type
32890b57cec5SDimitry Andric //
32900b57cec5SDimitry Andric // Dump an token value for the ELF header member e_type
32910b57cec5SDimitry Andric void ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type) {
32920b57cec5SDimitry Andric   switch (e_type) {
32930b57cec5SDimitry Andric   case ET_NONE:
32940b57cec5SDimitry Andric     *s << "ET_NONE";
32950b57cec5SDimitry Andric     break;
32960b57cec5SDimitry Andric   case ET_REL:
32970b57cec5SDimitry Andric     *s << "ET_REL";
32980b57cec5SDimitry Andric     break;
32990b57cec5SDimitry Andric   case ET_EXEC:
33000b57cec5SDimitry Andric     *s << "ET_EXEC";
33010b57cec5SDimitry Andric     break;
33020b57cec5SDimitry Andric   case ET_DYN:
33030b57cec5SDimitry Andric     *s << "ET_DYN";
33040b57cec5SDimitry Andric     break;
33050b57cec5SDimitry Andric   case ET_CORE:
33060b57cec5SDimitry Andric     *s << "ET_CORE";
33070b57cec5SDimitry Andric     break;
33080b57cec5SDimitry Andric   default:
33090b57cec5SDimitry Andric     break;
33100b57cec5SDimitry Andric   }
33110b57cec5SDimitry Andric }
33120b57cec5SDimitry Andric 
33130b57cec5SDimitry Andric // DumpELFHeader_e_ident_EI_DATA
33140b57cec5SDimitry Andric //
33150b57cec5SDimitry Andric // Dump an token value for the ELF header member e_ident[EI_DATA]
33160b57cec5SDimitry Andric void ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s,
33170b57cec5SDimitry Andric                                                   unsigned char ei_data) {
33180b57cec5SDimitry Andric   switch (ei_data) {
33190b57cec5SDimitry Andric   case ELFDATANONE:
33200b57cec5SDimitry Andric     *s << "ELFDATANONE";
33210b57cec5SDimitry Andric     break;
33220b57cec5SDimitry Andric   case ELFDATA2LSB:
33230b57cec5SDimitry Andric     *s << "ELFDATA2LSB - Little Endian";
33240b57cec5SDimitry Andric     break;
33250b57cec5SDimitry Andric   case ELFDATA2MSB:
33260b57cec5SDimitry Andric     *s << "ELFDATA2MSB - Big Endian";
33270b57cec5SDimitry Andric     break;
33280b57cec5SDimitry Andric   default:
33290b57cec5SDimitry Andric     break;
33300b57cec5SDimitry Andric   }
33310b57cec5SDimitry Andric }
33320b57cec5SDimitry Andric 
33330b57cec5SDimitry Andric // DumpELFProgramHeader
33340b57cec5SDimitry Andric //
33350b57cec5SDimitry Andric // Dump a single ELF program header to the specified output stream
33360b57cec5SDimitry Andric void ObjectFileELF::DumpELFProgramHeader(Stream *s,
33370b57cec5SDimitry Andric                                          const ELFProgramHeader &ph) {
33380b57cec5SDimitry Andric   DumpELFProgramHeader_p_type(s, ph.p_type);
33390b57cec5SDimitry Andric   s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset,
33400b57cec5SDimitry Andric             ph.p_vaddr, ph.p_paddr);
33410b57cec5SDimitry Andric   s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz,
33420b57cec5SDimitry Andric             ph.p_flags);
33430b57cec5SDimitry Andric 
33440b57cec5SDimitry Andric   DumpELFProgramHeader_p_flags(s, ph.p_flags);
33450b57cec5SDimitry Andric   s->Printf(") %8.8" PRIx64, ph.p_align);
33460b57cec5SDimitry Andric }
33470b57cec5SDimitry Andric 
33480b57cec5SDimitry Andric // DumpELFProgramHeader_p_type
33490b57cec5SDimitry Andric //
33500b57cec5SDimitry Andric // Dump an token value for the ELF program header member p_type which describes
33510b57cec5SDimitry Andric // the type of the program header
33520b57cec5SDimitry Andric void ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type) {
33530b57cec5SDimitry Andric   const int kStrWidth = 15;
33540b57cec5SDimitry Andric   switch (p_type) {
33550b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_NULL, kStrWidth);
33560b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_LOAD, kStrWidth);
33570b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_DYNAMIC, kStrWidth);
33580b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_INTERP, kStrWidth);
33590b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_NOTE, kStrWidth);
33600b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_SHLIB, kStrWidth);
33610b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_PHDR, kStrWidth);
33620b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_TLS, kStrWidth);
33630b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
33640b57cec5SDimitry Andric   default:
33650b57cec5SDimitry Andric     s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
33660b57cec5SDimitry Andric     break;
33670b57cec5SDimitry Andric   }
33680b57cec5SDimitry Andric }
33690b57cec5SDimitry Andric 
33700b57cec5SDimitry Andric // DumpELFProgramHeader_p_flags
33710b57cec5SDimitry Andric //
33720b57cec5SDimitry Andric // Dump an token value for the ELF program header member p_flags
33730b57cec5SDimitry Andric void ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags) {
33740b57cec5SDimitry Andric   *s << ((p_flags & PF_X) ? "PF_X" : "    ")
33750b57cec5SDimitry Andric      << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
33760b57cec5SDimitry Andric      << ((p_flags & PF_W) ? "PF_W" : "    ")
33770b57cec5SDimitry Andric      << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
33780b57cec5SDimitry Andric      << ((p_flags & PF_R) ? "PF_R" : "    ");
33790b57cec5SDimitry Andric }
33800b57cec5SDimitry Andric 
33810b57cec5SDimitry Andric // DumpELFProgramHeaders
33820b57cec5SDimitry Andric //
33830b57cec5SDimitry Andric // Dump all of the ELF program header to the specified output stream
33840b57cec5SDimitry Andric void ObjectFileELF::DumpELFProgramHeaders(Stream *s) {
33850b57cec5SDimitry Andric   if (!ParseProgramHeaders())
33860b57cec5SDimitry Andric     return;
33870b57cec5SDimitry Andric 
33880b57cec5SDimitry Andric   s->PutCString("Program Headers\n");
33890b57cec5SDimitry Andric   s->PutCString("IDX  p_type          p_offset p_vaddr  p_paddr  "
33900b57cec5SDimitry Andric                 "p_filesz p_memsz  p_flags                   p_align\n");
33910b57cec5SDimitry Andric   s->PutCString("==== --------------- -------- -------- -------- "
33920b57cec5SDimitry Andric                 "-------- -------- ------------------------- --------\n");
33930b57cec5SDimitry Andric 
33940b57cec5SDimitry Andric   for (const auto &H : llvm::enumerate(m_program_headers)) {
33950b57cec5SDimitry Andric     s->Format("[{0,2}] ", H.index());
33960b57cec5SDimitry Andric     ObjectFileELF::DumpELFProgramHeader(s, H.value());
33970b57cec5SDimitry Andric     s->EOL();
33980b57cec5SDimitry Andric   }
33990b57cec5SDimitry Andric }
34000b57cec5SDimitry Andric 
34010b57cec5SDimitry Andric // DumpELFSectionHeader
34020b57cec5SDimitry Andric //
34030b57cec5SDimitry Andric // Dump a single ELF section header to the specified output stream
34040b57cec5SDimitry Andric void ObjectFileELF::DumpELFSectionHeader(Stream *s,
34050b57cec5SDimitry Andric                                          const ELFSectionHeaderInfo &sh) {
34060b57cec5SDimitry Andric   s->Printf("%8.8x ", sh.sh_name);
34070b57cec5SDimitry Andric   DumpELFSectionHeader_sh_type(s, sh.sh_type);
34080b57cec5SDimitry Andric   s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
34090b57cec5SDimitry Andric   DumpELFSectionHeader_sh_flags(s, sh.sh_flags);
34100b57cec5SDimitry Andric   s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr,
34110b57cec5SDimitry Andric             sh.sh_offset, sh.sh_size);
34120b57cec5SDimitry Andric   s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
34130b57cec5SDimitry Andric   s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
34140b57cec5SDimitry Andric }
34150b57cec5SDimitry Andric 
34160b57cec5SDimitry Andric // DumpELFSectionHeader_sh_type
34170b57cec5SDimitry Andric //
34180b57cec5SDimitry Andric // Dump an token value for the ELF section header member sh_type which
34190b57cec5SDimitry Andric // describes the type of the section
34200b57cec5SDimitry Andric void ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type) {
34210b57cec5SDimitry Andric   const int kStrWidth = 12;
34220b57cec5SDimitry Andric   switch (sh_type) {
34230b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_NULL, kStrWidth);
34240b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_PROGBITS, kStrWidth);
34250b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_SYMTAB, kStrWidth);
34260b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_STRTAB, kStrWidth);
34270b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_RELA, kStrWidth);
34280b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_HASH, kStrWidth);
34290b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_DYNAMIC, kStrWidth);
34300b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_NOTE, kStrWidth);
34310b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_NOBITS, kStrWidth);
34320b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_REL, kStrWidth);
34330b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth);
34340b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_DYNSYM, kStrWidth);
34350b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth);
34360b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth);
34370b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth);
34380b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth);
34390b57cec5SDimitry Andric   default:
34400b57cec5SDimitry Andric     s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
34410b57cec5SDimitry Andric     break;
34420b57cec5SDimitry Andric   }
34430b57cec5SDimitry Andric }
34440b57cec5SDimitry Andric 
34450b57cec5SDimitry Andric // DumpELFSectionHeader_sh_flags
34460b57cec5SDimitry Andric //
34470b57cec5SDimitry Andric // Dump an token value for the ELF section header member sh_flags
34480b57cec5SDimitry Andric void ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s,
34490b57cec5SDimitry Andric                                                   elf_xword sh_flags) {
34500b57cec5SDimitry Andric   *s << ((sh_flags & SHF_WRITE) ? "WRITE" : "     ")
34510b57cec5SDimitry Andric      << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
34520b57cec5SDimitry Andric      << ((sh_flags & SHF_ALLOC) ? "ALLOC" : "     ")
34530b57cec5SDimitry Andric      << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
34540b57cec5SDimitry Andric      << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : "         ");
34550b57cec5SDimitry Andric }
34560b57cec5SDimitry Andric 
34570b57cec5SDimitry Andric // DumpELFSectionHeaders
34580b57cec5SDimitry Andric //
34590b57cec5SDimitry Andric // Dump all of the ELF section header to the specified output stream
34600b57cec5SDimitry Andric void ObjectFileELF::DumpELFSectionHeaders(Stream *s) {
34610b57cec5SDimitry Andric   if (!ParseSectionHeaders())
34620b57cec5SDimitry Andric     return;
34630b57cec5SDimitry Andric 
34640b57cec5SDimitry Andric   s->PutCString("Section Headers\n");
34650b57cec5SDimitry Andric   s->PutCString("IDX  name     type         flags                            "
34660b57cec5SDimitry Andric                 "addr     offset   size     link     info     addralgn "
34670b57cec5SDimitry Andric                 "entsize  Name\n");
34680b57cec5SDimitry Andric   s->PutCString("==== -------- ------------ -------------------------------- "
34690b57cec5SDimitry Andric                 "-------- -------- -------- -------- -------- -------- "
34700b57cec5SDimitry Andric                 "-------- ====================\n");
34710b57cec5SDimitry Andric 
34720b57cec5SDimitry Andric   uint32_t idx = 0;
34730b57cec5SDimitry Andric   for (SectionHeaderCollConstIter I = m_section_headers.begin();
34740b57cec5SDimitry Andric        I != m_section_headers.end(); ++I, ++idx) {
34750b57cec5SDimitry Andric     s->Printf("[%2u] ", idx);
34760b57cec5SDimitry Andric     ObjectFileELF::DumpELFSectionHeader(s, *I);
34770b57cec5SDimitry Andric     const char *section_name = I->section_name.AsCString("");
34780b57cec5SDimitry Andric     if (section_name)
34790b57cec5SDimitry Andric       *s << ' ' << section_name << "\n";
34800b57cec5SDimitry Andric   }
34810b57cec5SDimitry Andric }
34820b57cec5SDimitry Andric 
34830b57cec5SDimitry Andric void ObjectFileELF::DumpDependentModules(lldb_private::Stream *s) {
34840b57cec5SDimitry Andric   size_t num_modules = ParseDependentModules();
34850b57cec5SDimitry Andric 
34860b57cec5SDimitry Andric   if (num_modules > 0) {
34870b57cec5SDimitry Andric     s->PutCString("Dependent Modules:\n");
34880b57cec5SDimitry Andric     for (unsigned i = 0; i < num_modules; ++i) {
34890b57cec5SDimitry Andric       const FileSpec &spec = m_filespec_up->GetFileSpecAtIndex(i);
34900b57cec5SDimitry Andric       s->Printf("   %s\n", spec.GetFilename().GetCString());
34910b57cec5SDimitry Andric     }
34920b57cec5SDimitry Andric   }
34930b57cec5SDimitry Andric }
34940b57cec5SDimitry Andric 
34950b57cec5SDimitry Andric ArchSpec ObjectFileELF::GetArchitecture() {
34960b57cec5SDimitry Andric   if (!ParseHeader())
34970b57cec5SDimitry Andric     return ArchSpec();
34980b57cec5SDimitry Andric 
34990b57cec5SDimitry Andric   if (m_section_headers.empty()) {
35000b57cec5SDimitry Andric     // Allow elf notes to be parsed which may affect the detected architecture.
35010b57cec5SDimitry Andric     ParseSectionHeaders();
35020b57cec5SDimitry Andric   }
35030b57cec5SDimitry Andric 
35040b57cec5SDimitry Andric   if (CalculateType() == eTypeCoreFile &&
35050b57cec5SDimitry Andric       !m_arch_spec.TripleOSWasSpecified()) {
35060b57cec5SDimitry Andric     // Core files don't have section headers yet they have PT_NOTE program
35070b57cec5SDimitry Andric     // headers that might shed more light on the architecture
35080b57cec5SDimitry Andric     for (const elf::ELFProgramHeader &H : ProgramHeaders()) {
35090b57cec5SDimitry Andric       if (H.p_type != PT_NOTE || H.p_offset == 0 || H.p_filesz == 0)
35100b57cec5SDimitry Andric         continue;
35110b57cec5SDimitry Andric       DataExtractor data;
35120b57cec5SDimitry Andric       if (data.SetData(m_data, H.p_offset, H.p_filesz) == H.p_filesz) {
35130b57cec5SDimitry Andric         UUID uuid;
35140b57cec5SDimitry Andric         RefineModuleDetailsFromNote(data, m_arch_spec, uuid);
35150b57cec5SDimitry Andric       }
35160b57cec5SDimitry Andric     }
35170b57cec5SDimitry Andric   }
35180b57cec5SDimitry Andric   return m_arch_spec;
35190b57cec5SDimitry Andric }
35200b57cec5SDimitry Andric 
35210b57cec5SDimitry Andric ObjectFile::Type ObjectFileELF::CalculateType() {
35220b57cec5SDimitry Andric   switch (m_header.e_type) {
35230b57cec5SDimitry Andric   case llvm::ELF::ET_NONE:
35240b57cec5SDimitry Andric     // 0 - No file type
35250b57cec5SDimitry Andric     return eTypeUnknown;
35260b57cec5SDimitry Andric 
35270b57cec5SDimitry Andric   case llvm::ELF::ET_REL:
35280b57cec5SDimitry Andric     // 1 - Relocatable file
35290b57cec5SDimitry Andric     return eTypeObjectFile;
35300b57cec5SDimitry Andric 
35310b57cec5SDimitry Andric   case llvm::ELF::ET_EXEC:
35320b57cec5SDimitry Andric     // 2 - Executable file
35330b57cec5SDimitry Andric     return eTypeExecutable;
35340b57cec5SDimitry Andric 
35350b57cec5SDimitry Andric   case llvm::ELF::ET_DYN:
35360b57cec5SDimitry Andric     // 3 - Shared object file
35370b57cec5SDimitry Andric     return eTypeSharedLibrary;
35380b57cec5SDimitry Andric 
35390b57cec5SDimitry Andric   case ET_CORE:
35400b57cec5SDimitry Andric     // 4 - Core file
35410b57cec5SDimitry Andric     return eTypeCoreFile;
35420b57cec5SDimitry Andric 
35430b57cec5SDimitry Andric   default:
35440b57cec5SDimitry Andric     break;
35450b57cec5SDimitry Andric   }
35460b57cec5SDimitry Andric   return eTypeUnknown;
35470b57cec5SDimitry Andric }
35480b57cec5SDimitry Andric 
35490b57cec5SDimitry Andric ObjectFile::Strata ObjectFileELF::CalculateStrata() {
35500b57cec5SDimitry Andric   switch (m_header.e_type) {
35510b57cec5SDimitry Andric   case llvm::ELF::ET_NONE:
35520b57cec5SDimitry Andric     // 0 - No file type
35530b57cec5SDimitry Andric     return eStrataUnknown;
35540b57cec5SDimitry Andric 
35550b57cec5SDimitry Andric   case llvm::ELF::ET_REL:
35560b57cec5SDimitry Andric     // 1 - Relocatable file
35570b57cec5SDimitry Andric     return eStrataUnknown;
35580b57cec5SDimitry Andric 
35590b57cec5SDimitry Andric   case llvm::ELF::ET_EXEC:
35600b57cec5SDimitry Andric     // 2 - Executable file
35615f757f3fSDimitry Andric     {
35625f757f3fSDimitry Andric       SectionList *section_list = GetSectionList();
35635f757f3fSDimitry Andric       if (section_list) {
35645f757f3fSDimitry Andric         static ConstString loader_section_name(".interp");
35655f757f3fSDimitry Andric         SectionSP loader_section =
35665f757f3fSDimitry Andric             section_list->FindSectionByName(loader_section_name);
35675f757f3fSDimitry Andric         if (loader_section) {
35685f757f3fSDimitry Andric           char buffer[256];
35695f757f3fSDimitry Andric           size_t read_size =
35705f757f3fSDimitry Andric               ReadSectionData(loader_section.get(), 0, buffer, sizeof(buffer));
35715f757f3fSDimitry Andric 
35725f757f3fSDimitry Andric           // We compare the content of .interp section
35735f757f3fSDimitry Andric           // It will contains \0 when counting read_size, so the size needs to
35745f757f3fSDimitry Andric           // decrease by one
35755f757f3fSDimitry Andric           llvm::StringRef loader_name(buffer, read_size - 1);
35765f757f3fSDimitry Andric           llvm::StringRef freebsd_kernel_loader_name("/red/herring");
3577*0fca6ea1SDimitry Andric           if (loader_name == freebsd_kernel_loader_name)
35785f757f3fSDimitry Andric             return eStrataKernel;
35795f757f3fSDimitry Andric         }
35805f757f3fSDimitry Andric       }
35810b57cec5SDimitry Andric       return eStrataUser;
35825f757f3fSDimitry Andric     }
35830b57cec5SDimitry Andric 
35840b57cec5SDimitry Andric   case llvm::ELF::ET_DYN:
35850b57cec5SDimitry Andric     // 3 - Shared object file
35860b57cec5SDimitry Andric     // TODO: is there any way to detect that an shared library is a kernel
35870b57cec5SDimitry Andric     // related executable by inspecting the program headers, section headers,
35880b57cec5SDimitry Andric     // symbols, or any other flag bits???
35890b57cec5SDimitry Andric     return eStrataUnknown;
35900b57cec5SDimitry Andric 
35910b57cec5SDimitry Andric   case ET_CORE:
35920b57cec5SDimitry Andric     // 4 - Core file
35930b57cec5SDimitry Andric     // TODO: is there any way to detect that an core file is a kernel
35940b57cec5SDimitry Andric     // related executable by inspecting the program headers, section headers,
35950b57cec5SDimitry Andric     // symbols, or any other flag bits???
35960b57cec5SDimitry Andric     return eStrataUnknown;
35970b57cec5SDimitry Andric 
35980b57cec5SDimitry Andric   default:
35990b57cec5SDimitry Andric     break;
36000b57cec5SDimitry Andric   }
36010b57cec5SDimitry Andric   return eStrataUnknown;
36020b57cec5SDimitry Andric }
36030b57cec5SDimitry Andric 
36040b57cec5SDimitry Andric size_t ObjectFileELF::ReadSectionData(Section *section,
36050b57cec5SDimitry Andric                        lldb::offset_t section_offset, void *dst,
36060b57cec5SDimitry Andric                        size_t dst_len) {
36070b57cec5SDimitry Andric   // If some other objectfile owns this data, pass this to them.
36080b57cec5SDimitry Andric   if (section->GetObjectFile() != this)
36090b57cec5SDimitry Andric     return section->GetObjectFile()->ReadSectionData(section, section_offset,
36100b57cec5SDimitry Andric                                                      dst, dst_len);
36110b57cec5SDimitry Andric 
36120b57cec5SDimitry Andric   if (!section->Test(SHF_COMPRESSED))
36130b57cec5SDimitry Andric     return ObjectFile::ReadSectionData(section, section_offset, dst, dst_len);
36140b57cec5SDimitry Andric 
36150b57cec5SDimitry Andric   // For compressed sections we need to read to full data to be able to
36160b57cec5SDimitry Andric   // decompress.
36170b57cec5SDimitry Andric   DataExtractor data;
36180b57cec5SDimitry Andric   ReadSectionData(section, data);
36190b57cec5SDimitry Andric   return data.CopyData(section_offset, dst_len, dst);
36200b57cec5SDimitry Andric }
36210b57cec5SDimitry Andric 
36220b57cec5SDimitry Andric size_t ObjectFileELF::ReadSectionData(Section *section,
36230b57cec5SDimitry Andric                                       DataExtractor &section_data) {
36240b57cec5SDimitry Andric   // If some other objectfile owns this data, pass this to them.
36250b57cec5SDimitry Andric   if (section->GetObjectFile() != this)
36260b57cec5SDimitry Andric     return section->GetObjectFile()->ReadSectionData(section, section_data);
36270b57cec5SDimitry Andric 
36280b57cec5SDimitry Andric   size_t result = ObjectFile::ReadSectionData(section, section_data);
3629fcaf7f86SDimitry Andric   if (result == 0 || !(section->Get() & llvm::ELF::SHF_COMPRESSED))
36300b57cec5SDimitry Andric     return result;
36310b57cec5SDimitry Andric 
36320b57cec5SDimitry Andric   auto Decompressor = llvm::object::Decompressor::create(
36330b57cec5SDimitry Andric       section->GetName().GetStringRef(),
36340b57cec5SDimitry Andric       {reinterpret_cast<const char *>(section_data.GetDataStart()),
36350b57cec5SDimitry Andric        size_t(section_data.GetByteSize())},
36360b57cec5SDimitry Andric       GetByteOrder() == eByteOrderLittle, GetAddressByteSize() == 8);
36370b57cec5SDimitry Andric   if (!Decompressor) {
36380b57cec5SDimitry Andric     GetModule()->ReportWarning(
3639bdd1243dSDimitry Andric         "Unable to initialize decompressor for section '{0}': {1}",
36400b57cec5SDimitry Andric         section->GetName().GetCString(),
36410b57cec5SDimitry Andric         llvm::toString(Decompressor.takeError()).c_str());
36420b57cec5SDimitry Andric     section_data.Clear();
36430b57cec5SDimitry Andric     return 0;
36440b57cec5SDimitry Andric   }
36450b57cec5SDimitry Andric 
36460b57cec5SDimitry Andric   auto buffer_sp =
36470b57cec5SDimitry Andric       std::make_shared<DataBufferHeap>(Decompressor->getDecompressedSize(), 0);
36480b57cec5SDimitry Andric   if (auto error = Decompressor->decompress(
3649753f127fSDimitry Andric           {buffer_sp->GetBytes(), size_t(buffer_sp->GetByteSize())})) {
3650bdd1243dSDimitry Andric     GetModule()->ReportWarning("Decompression of section '{0}' failed: {1}",
36510b57cec5SDimitry Andric                                section->GetName().GetCString(),
36520b57cec5SDimitry Andric                                llvm::toString(std::move(error)).c_str());
36530b57cec5SDimitry Andric     section_data.Clear();
36540b57cec5SDimitry Andric     return 0;
36550b57cec5SDimitry Andric   }
36560b57cec5SDimitry Andric 
36570b57cec5SDimitry Andric   section_data.SetData(buffer_sp);
36580b57cec5SDimitry Andric   return buffer_sp->GetByteSize();
36590b57cec5SDimitry Andric }
36600b57cec5SDimitry Andric 
36610b57cec5SDimitry Andric llvm::ArrayRef<ELFProgramHeader> ObjectFileELF::ProgramHeaders() {
36620b57cec5SDimitry Andric   ParseProgramHeaders();
36630b57cec5SDimitry Andric   return m_program_headers;
36640b57cec5SDimitry Andric }
36650b57cec5SDimitry Andric 
36660b57cec5SDimitry Andric DataExtractor ObjectFileELF::GetSegmentData(const ELFProgramHeader &H) {
36670b57cec5SDimitry Andric   return DataExtractor(m_data, H.p_offset, H.p_filesz);
36680b57cec5SDimitry Andric }
36690b57cec5SDimitry Andric 
36700b57cec5SDimitry Andric bool ObjectFileELF::AnySegmentHasPhysicalAddress() {
36710b57cec5SDimitry Andric   for (const ELFProgramHeader &H : ProgramHeaders()) {
36720b57cec5SDimitry Andric     if (H.p_paddr != 0)
36730b57cec5SDimitry Andric       return true;
36740b57cec5SDimitry Andric   }
36750b57cec5SDimitry Andric   return false;
36760b57cec5SDimitry Andric }
36770b57cec5SDimitry Andric 
36780b57cec5SDimitry Andric std::vector<ObjectFile::LoadableData>
36790b57cec5SDimitry Andric ObjectFileELF::GetLoadableData(Target &target) {
36800b57cec5SDimitry Andric   // Create a list of loadable data from loadable segments, using physical
36810b57cec5SDimitry Andric   // addresses if they aren't all null
36820b57cec5SDimitry Andric   std::vector<LoadableData> loadables;
36830b57cec5SDimitry Andric   bool should_use_paddr = AnySegmentHasPhysicalAddress();
36840b57cec5SDimitry Andric   for (const ELFProgramHeader &H : ProgramHeaders()) {
36850b57cec5SDimitry Andric     LoadableData loadable;
36860b57cec5SDimitry Andric     if (H.p_type != llvm::ELF::PT_LOAD)
36870b57cec5SDimitry Andric       continue;
36880b57cec5SDimitry Andric     loadable.Dest = should_use_paddr ? H.p_paddr : H.p_vaddr;
36890b57cec5SDimitry Andric     if (loadable.Dest == LLDB_INVALID_ADDRESS)
36900b57cec5SDimitry Andric       continue;
36910b57cec5SDimitry Andric     if (H.p_filesz == 0)
36920b57cec5SDimitry Andric       continue;
36930b57cec5SDimitry Andric     auto segment_data = GetSegmentData(H);
36940b57cec5SDimitry Andric     loadable.Contents = llvm::ArrayRef<uint8_t>(segment_data.GetDataStart(),
36950b57cec5SDimitry Andric                                                 segment_data.GetByteSize());
36960b57cec5SDimitry Andric     loadables.push_back(loadable);
36970b57cec5SDimitry Andric   }
36980b57cec5SDimitry Andric   return loadables;
36990b57cec5SDimitry Andric }
370081ad6265SDimitry Andric 
370181ad6265SDimitry Andric lldb::WritableDataBufferSP
370281ad6265SDimitry Andric ObjectFileELF::MapFileDataWritable(const FileSpec &file, uint64_t Size,
370381ad6265SDimitry Andric                                    uint64_t Offset) {
370481ad6265SDimitry Andric   return FileSystem::Instance().CreateWritableDataBuffer(file.GetPath(), Size,
370581ad6265SDimitry Andric                                                          Offset);
370681ad6265SDimitry Andric }
3707