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"
29fe013be4SDimitry 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 
IsRela()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 
ELFRelocation(unsigned type)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 
~ELFRelocation()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 
Parse(const lldb_private::DataExtractor & data,lldb::offset_t * offset)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 
RelocType32(const ELFRelocation & rel)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 
RelocType64(const ELFRelocation & rel)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 
RelocSymbol32(const ELFRelocation & rel)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 
RelocSymbol64(const ELFRelocation & rel)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 
RelocOffset32(const ELFRelocation & rel)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 
RelocOffset64(const ELFRelocation & rel)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 
RelocAddend32(const ELFRelocation & rel)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 
RelocAddend64(const ELFRelocation & rel)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 
SegmentID(size_t PHdrIndex)2165ffd83dbSDimitry Andric static user_id_t SegmentID(size_t PHdrIndex) {
2175ffd83dbSDimitry Andric   return ~user_id_t(PHdrIndex);
2185ffd83dbSDimitry Andric }
2190b57cec5SDimitry Andric 
Parse(const DataExtractor & data,lldb::offset_t * offset)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 
mipsVariantFromElfFlags(const elf::ELFHeader & header)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 
riscvVariantFromElfFlags(const elf::ELFHeader & header)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 
ppc64VariantFromElfFlags(const elf::ELFHeader & header)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 
loongarchVariantFromElfFlags(const elf::ELFHeader & header)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 
subTypeFromElfHeader(const elf::ELFHeader & header)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.
Initialize()3550b57cec5SDimitry Andric void ObjectFileELF::Initialize() {
3560b57cec5SDimitry Andric   PluginManager::RegisterPlugin(GetPluginNameStatic(),
3570b57cec5SDimitry Andric                                 GetPluginDescriptionStatic(), CreateInstance,
3580b57cec5SDimitry Andric                                 CreateMemoryInstance, GetModuleSpecifications);
3590b57cec5SDimitry Andric }
3600b57cec5SDimitry Andric 
Terminate()3610b57cec5SDimitry Andric void ObjectFileELF::Terminate() {
3620b57cec5SDimitry Andric   PluginManager::UnregisterPlugin(CreateInstance);
3630b57cec5SDimitry Andric }
3640b57cec5SDimitry Andric 
CreateInstance(const lldb::ModuleSP & module_sp,DataBufferSP data_sp,lldb::offset_t data_offset,const lldb_private::FileSpec * file,lldb::offset_t file_offset,lldb::offset_t length)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 
CreateMemoryInstance(const lldb::ModuleSP & module_sp,WritableDataBufferSP data_sp,const lldb::ProcessSP & process_sp,lldb::addr_t header_addr)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 
MagicBytesMatch(DataBufferSP & data_sp,lldb::addr_t data_offset,lldb::addr_t data_length)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 
calc_crc32(uint32_t init,const DataExtractor & data)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 
CalculateELFNotesSegmentsCRC32(const ProgramHeaderColl & program_headers,DataExtractor & object_data)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 
OSABIAsCString(unsigned char osabi_byte)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
GetOsFromOSABI(unsigned char osabi_byte,llvm::Triple::OSType & ostype)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 
GetModuleSpecifications(const lldb_private::FileSpec & file,lldb::DataBufferSP & data_sp,lldb::offset_t data_offset,lldb::offset_t file_offset,lldb::offset_t length,lldb_private::ModuleSpecList & specs)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);
558fe013be4SDimitry Andric         // In Android API level 23 and above, bionic dynamic linker is able to
559fe013be4SDimitry Andric         // load .so file directly from zip file. In that case, .so file is
560fe013be4SDimitry Andric         // page aligned and uncompressed, and this module spec should retain the
561fe013be4SDimitry Andric         // .so file offset and file size to pass through the information from
562fe013be4SDimitry Andric         // lldb-server to LLDB. For normal file, file_offset should be 0,
563fe013be4SDimitry Andric         // length should be the size of the file.
564fe013be4SDimitry Andric         spec.SetObjectOffset(file_offset);
565fe013be4SDimitry 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 
597fe013be4SDimitry Andric           // When ELF file does not contain GNU build ID, the later code will
598fe013be4SDimitry Andric           // calculate CRC32 with this data_sp file_offset and length. It is
599fe013be4SDimitry Andric           // important for Android zip .so file, which is a slice of a file,
600fe013be4SDimitry Andric           // to not access the outside of the file slice range.
6015ffd83dbSDimitry Andric           if (data_sp->GetByteSize() < length)
602fe013be4SDimitry 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",
638fe013be4SDimitry 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 
ObjectFileELF(const lldb::ModuleSP & module_sp,DataBufferSP data_sp,lldb::offset_t data_offset,const FileSpec * file,lldb::offset_t file_offset,lldb::offset_t length)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 
ObjectFileELF(const lldb::ModuleSP & module_sp,DataBufferSP header_data_sp,const lldb::ProcessSP & process_sp,addr_t header_addr)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 
IsExecutable() const6950b57cec5SDimitry Andric bool ObjectFileELF::IsExecutable() const {
6960b57cec5SDimitry Andric   return ((m_header.e_type & ET_EXEC) != 0) || (m_header.e_entry != 0);
6970b57cec5SDimitry Andric }
6980b57cec5SDimitry Andric 
SetLoadAddress(Target & target,lldb::addr_t value,bool value_is_offset)6990b57cec5SDimitry Andric bool ObjectFileELF::SetLoadAddress(Target &target, lldb::addr_t value,
7000b57cec5SDimitry Andric                                    bool value_is_offset) {
7010b57cec5SDimitry Andric   ModuleSP module_sp = GetModule();
7020b57cec5SDimitry Andric   if (module_sp) {
7030b57cec5SDimitry Andric     size_t num_loaded_sections = 0;
7040b57cec5SDimitry Andric     SectionList *section_list = GetSectionList();
7050b57cec5SDimitry Andric     if (section_list) {
7060b57cec5SDimitry Andric       if (!value_is_offset) {
7070b57cec5SDimitry Andric         addr_t base = GetBaseAddress().GetFileAddress();
7080b57cec5SDimitry Andric         if (base == LLDB_INVALID_ADDRESS)
7090b57cec5SDimitry Andric           return false;
7100b57cec5SDimitry Andric         value -= base;
7110b57cec5SDimitry Andric       }
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric       const size_t num_sections = section_list->GetSize();
7140b57cec5SDimitry Andric       size_t sect_idx = 0;
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric       for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
7170b57cec5SDimitry Andric         // Iterate through the object file sections to find all of the sections
7180b57cec5SDimitry Andric         // that have SHF_ALLOC in their flag bits.
7190b57cec5SDimitry Andric         SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
7200b57cec5SDimitry Andric         if (section_sp->Test(SHF_ALLOC) ||
7210b57cec5SDimitry Andric             section_sp->GetType() == eSectionTypeContainer) {
7220b57cec5SDimitry Andric           lldb::addr_t load_addr = section_sp->GetFileAddress();
7230b57cec5SDimitry Andric           // We don't want to update the load address of a section with type
7240b57cec5SDimitry Andric           // eSectionTypeAbsoluteAddress as they already have the absolute load
7250b57cec5SDimitry Andric           // address already specified
7260b57cec5SDimitry Andric           if (section_sp->GetType() != eSectionTypeAbsoluteAddress)
7270b57cec5SDimitry Andric             load_addr += value;
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric           // On 32-bit systems the load address have to fit into 4 bytes. The
7300b57cec5SDimitry Andric           // rest of the bytes are the overflow from the addition.
7310b57cec5SDimitry Andric           if (GetAddressByteSize() == 4)
7320b57cec5SDimitry Andric             load_addr &= 0xFFFFFFFF;
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric           if (target.GetSectionLoadList().SetSectionLoadAddress(section_sp,
7350b57cec5SDimitry Andric                                                                 load_addr))
7360b57cec5SDimitry Andric             ++num_loaded_sections;
7370b57cec5SDimitry Andric         }
7380b57cec5SDimitry Andric       }
7390b57cec5SDimitry Andric       return num_loaded_sections > 0;
7400b57cec5SDimitry Andric     }
7410b57cec5SDimitry Andric   }
7420b57cec5SDimitry Andric   return false;
7430b57cec5SDimitry Andric }
7440b57cec5SDimitry Andric 
GetByteOrder() const7450b57cec5SDimitry Andric ByteOrder ObjectFileELF::GetByteOrder() const {
7460b57cec5SDimitry Andric   if (m_header.e_ident[EI_DATA] == ELFDATA2MSB)
7470b57cec5SDimitry Andric     return eByteOrderBig;
7480b57cec5SDimitry Andric   if (m_header.e_ident[EI_DATA] == ELFDATA2LSB)
7490b57cec5SDimitry Andric     return eByteOrderLittle;
7500b57cec5SDimitry Andric   return eByteOrderInvalid;
7510b57cec5SDimitry Andric }
7520b57cec5SDimitry Andric 
GetAddressByteSize() const7530b57cec5SDimitry Andric uint32_t ObjectFileELF::GetAddressByteSize() const {
7540b57cec5SDimitry Andric   return m_data.GetAddressByteSize();
7550b57cec5SDimitry Andric }
7560b57cec5SDimitry Andric 
GetAddressClass(addr_t file_addr)7570b57cec5SDimitry Andric AddressClass ObjectFileELF::GetAddressClass(addr_t file_addr) {
7580b57cec5SDimitry Andric   Symtab *symtab = GetSymtab();
7590b57cec5SDimitry Andric   if (!symtab)
7600b57cec5SDimitry Andric     return AddressClass::eUnknown;
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric   // The address class is determined based on the symtab. Ask it from the
7630b57cec5SDimitry Andric   // object file what contains the symtab information.
7640b57cec5SDimitry Andric   ObjectFile *symtab_objfile = symtab->GetObjectFile();
7650b57cec5SDimitry Andric   if (symtab_objfile != nullptr && symtab_objfile != this)
7660b57cec5SDimitry Andric     return symtab_objfile->GetAddressClass(file_addr);
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric   auto res = ObjectFile::GetAddressClass(file_addr);
7690b57cec5SDimitry Andric   if (res != AddressClass::eCode)
7700b57cec5SDimitry Andric     return res;
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric   auto ub = m_address_class_map.upper_bound(file_addr);
7730b57cec5SDimitry Andric   if (ub == m_address_class_map.begin()) {
7740b57cec5SDimitry Andric     // No entry in the address class map before the address. Return default
7750b57cec5SDimitry Andric     // address class for an address in a code section.
7760b57cec5SDimitry Andric     return AddressClass::eCode;
7770b57cec5SDimitry Andric   }
7780b57cec5SDimitry Andric 
7790b57cec5SDimitry Andric   // Move iterator to the address class entry preceding address
7800b57cec5SDimitry Andric   --ub;
7810b57cec5SDimitry Andric 
7820b57cec5SDimitry Andric   return ub->second;
7830b57cec5SDimitry Andric }
7840b57cec5SDimitry Andric 
SectionIndex(const SectionHeaderCollIter & I)7850b57cec5SDimitry Andric size_t ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I) {
7860b57cec5SDimitry Andric   return std::distance(m_section_headers.begin(), I);
7870b57cec5SDimitry Andric }
7880b57cec5SDimitry Andric 
SectionIndex(const SectionHeaderCollConstIter & I) const7890b57cec5SDimitry Andric size_t ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const {
7900b57cec5SDimitry Andric   return std::distance(m_section_headers.begin(), I);
7910b57cec5SDimitry Andric }
7920b57cec5SDimitry Andric 
ParseHeader()7930b57cec5SDimitry Andric bool ObjectFileELF::ParseHeader() {
7940b57cec5SDimitry Andric   lldb::offset_t offset = 0;
7950b57cec5SDimitry Andric   return m_header.Parse(m_data, &offset);
7960b57cec5SDimitry Andric }
7970b57cec5SDimitry Andric 
GetUUID()7980b57cec5SDimitry Andric UUID ObjectFileELF::GetUUID() {
7990b57cec5SDimitry Andric   // Need to parse the section list to get the UUIDs, so make sure that's been
8000b57cec5SDimitry Andric   // done.
8010b57cec5SDimitry Andric   if (!ParseSectionHeaders() && GetType() != ObjectFile::eTypeCoreFile)
8020b57cec5SDimitry Andric     return UUID();
8030b57cec5SDimitry Andric 
8040b57cec5SDimitry Andric   if (!m_uuid) {
8050b57cec5SDimitry Andric     using u32le = llvm::support::ulittle32_t;
8060b57cec5SDimitry Andric     if (GetType() == ObjectFile::eTypeCoreFile) {
8070b57cec5SDimitry Andric       uint32_t core_notes_crc = 0;
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric       if (!ParseProgramHeaders())
8100b57cec5SDimitry Andric         return UUID();
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric       core_notes_crc =
8130b57cec5SDimitry Andric           CalculateELFNotesSegmentsCRC32(m_program_headers, m_data);
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric       if (core_notes_crc) {
8160b57cec5SDimitry Andric         // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it
8170b57cec5SDimitry Andric         // look different form .gnu_debuglink crc - followed by 4 bytes of note
8180b57cec5SDimitry Andric         // segments crc.
8190b57cec5SDimitry Andric         u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)};
820bdd1243dSDimitry Andric         m_uuid = UUID(data, sizeof(data));
8210b57cec5SDimitry Andric       }
8220b57cec5SDimitry Andric     } else {
8230b57cec5SDimitry Andric       if (!m_gnu_debuglink_crc)
8249dba64beSDimitry Andric         m_gnu_debuglink_crc = calc_crc32(0, m_data);
8250b57cec5SDimitry Andric       if (m_gnu_debuglink_crc) {
8260b57cec5SDimitry Andric         // Use 4 bytes of crc from the .gnu_debuglink section.
8270b57cec5SDimitry Andric         u32le data(m_gnu_debuglink_crc);
828bdd1243dSDimitry Andric         m_uuid = UUID(&data, sizeof(data));
8290b57cec5SDimitry Andric       }
8300b57cec5SDimitry Andric     }
8310b57cec5SDimitry Andric   }
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric   return m_uuid;
8340b57cec5SDimitry Andric }
8350b57cec5SDimitry Andric 
GetDebugLink()836bdd1243dSDimitry Andric std::optional<FileSpec> ObjectFileELF::GetDebugLink() {
8379dba64beSDimitry Andric   if (m_gnu_debuglink_file.empty())
838bdd1243dSDimitry Andric     return std::nullopt;
8399dba64beSDimitry Andric   return FileSpec(m_gnu_debuglink_file);
8400b57cec5SDimitry Andric }
8410b57cec5SDimitry Andric 
GetDependentModules(FileSpecList & files)8420b57cec5SDimitry Andric uint32_t ObjectFileELF::GetDependentModules(FileSpecList &files) {
8430b57cec5SDimitry Andric   size_t num_modules = ParseDependentModules();
8440b57cec5SDimitry Andric   uint32_t num_specs = 0;
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric   for (unsigned i = 0; i < num_modules; ++i) {
8470b57cec5SDimitry Andric     if (files.AppendIfUnique(m_filespec_up->GetFileSpecAtIndex(i)))
8480b57cec5SDimitry Andric       num_specs++;
8490b57cec5SDimitry Andric   }
8500b57cec5SDimitry Andric 
8510b57cec5SDimitry Andric   return num_specs;
8520b57cec5SDimitry Andric }
8530b57cec5SDimitry Andric 
GetImageInfoAddress(Target * target)8540b57cec5SDimitry Andric Address ObjectFileELF::GetImageInfoAddress(Target *target) {
8550b57cec5SDimitry Andric   if (!ParseDynamicSymbols())
8560b57cec5SDimitry Andric     return Address();
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
8590b57cec5SDimitry Andric   if (!section_list)
8600b57cec5SDimitry Andric     return Address();
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric   // Find the SHT_DYNAMIC (.dynamic) section.
8630b57cec5SDimitry Andric   SectionSP dynsym_section_sp(
8640b57cec5SDimitry Andric       section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true));
8650b57cec5SDimitry Andric   if (!dynsym_section_sp)
8660b57cec5SDimitry Andric     return Address();
8670b57cec5SDimitry Andric   assert(dynsym_section_sp->GetObjectFile() == this);
8680b57cec5SDimitry Andric 
8690b57cec5SDimitry Andric   user_id_t dynsym_id = dynsym_section_sp->GetID();
8700b57cec5SDimitry Andric   const ELFSectionHeaderInfo *dynsym_hdr = GetSectionHeaderByIndex(dynsym_id);
8710b57cec5SDimitry Andric   if (!dynsym_hdr)
8720b57cec5SDimitry Andric     return Address();
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric   for (size_t i = 0; i < m_dynamic_symbols.size(); ++i) {
8750b57cec5SDimitry Andric     ELFDynamic &symbol = m_dynamic_symbols[i];
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric     if (symbol.d_tag == DT_DEBUG) {
8780b57cec5SDimitry Andric       // Compute the offset as the number of previous entries plus the size of
8790b57cec5SDimitry Andric       // d_tag.
8800b57cec5SDimitry Andric       addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
8810b57cec5SDimitry Andric       return Address(dynsym_section_sp, offset);
8820b57cec5SDimitry Andric     }
8830b57cec5SDimitry Andric     // MIPS executables uses DT_MIPS_RLD_MAP_REL to support PIE. DT_MIPS_RLD_MAP
8840b57cec5SDimitry Andric     // exists in non-PIE.
8850b57cec5SDimitry Andric     else if ((symbol.d_tag == DT_MIPS_RLD_MAP ||
8860b57cec5SDimitry Andric               symbol.d_tag == DT_MIPS_RLD_MAP_REL) &&
8870b57cec5SDimitry Andric              target) {
8880b57cec5SDimitry Andric       addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
8890b57cec5SDimitry Andric       addr_t dyn_base = dynsym_section_sp->GetLoadBaseAddress(target);
8900b57cec5SDimitry Andric       if (dyn_base == LLDB_INVALID_ADDRESS)
8910b57cec5SDimitry Andric         return Address();
8920b57cec5SDimitry Andric 
8930b57cec5SDimitry Andric       Status error;
8940b57cec5SDimitry Andric       if (symbol.d_tag == DT_MIPS_RLD_MAP) {
8950b57cec5SDimitry Andric         // DT_MIPS_RLD_MAP tag stores an absolute address of the debug pointer.
8960b57cec5SDimitry Andric         Address addr;
897fe6060f1SDimitry Andric         if (target->ReadPointerFromMemory(dyn_base + offset, error, addr, true))
8980b57cec5SDimitry Andric           return addr;
8990b57cec5SDimitry Andric       }
9000b57cec5SDimitry Andric       if (symbol.d_tag == DT_MIPS_RLD_MAP_REL) {
9010b57cec5SDimitry Andric         // DT_MIPS_RLD_MAP_REL tag stores the offset to the debug pointer,
9020b57cec5SDimitry Andric         // relative to the address of the tag.
9030b57cec5SDimitry Andric         uint64_t rel_offset;
9040b57cec5SDimitry Andric         rel_offset = target->ReadUnsignedIntegerFromMemory(
905fe6060f1SDimitry Andric             dyn_base + offset, GetAddressByteSize(), UINT64_MAX, error, true);
9060b57cec5SDimitry Andric         if (error.Success() && rel_offset != UINT64_MAX) {
9070b57cec5SDimitry Andric           Address addr;
9080b57cec5SDimitry Andric           addr_t debug_ptr_address =
9090b57cec5SDimitry Andric               dyn_base + (offset - GetAddressByteSize()) + rel_offset;
9100b57cec5SDimitry Andric           addr.SetOffset(debug_ptr_address);
9110b57cec5SDimitry Andric           return addr;
9120b57cec5SDimitry Andric         }
9130b57cec5SDimitry Andric       }
9140b57cec5SDimitry Andric     }
9150b57cec5SDimitry Andric   }
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric   return Address();
9180b57cec5SDimitry Andric }
9190b57cec5SDimitry Andric 
GetEntryPointAddress()9200b57cec5SDimitry Andric lldb_private::Address ObjectFileELF::GetEntryPointAddress() {
9210b57cec5SDimitry Andric   if (m_entry_point_address.IsValid())
9220b57cec5SDimitry Andric     return m_entry_point_address;
9230b57cec5SDimitry Andric 
9240b57cec5SDimitry Andric   if (!ParseHeader() || !IsExecutable())
9250b57cec5SDimitry Andric     return m_entry_point_address;
9260b57cec5SDimitry Andric 
9270b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
9280b57cec5SDimitry Andric   addr_t offset = m_header.e_entry;
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric   if (!section_list)
9310b57cec5SDimitry Andric     m_entry_point_address.SetOffset(offset);
9320b57cec5SDimitry Andric   else
9330b57cec5SDimitry Andric     m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list);
9340b57cec5SDimitry Andric   return m_entry_point_address;
9350b57cec5SDimitry Andric }
9360b57cec5SDimitry Andric 
GetBaseAddress()9370b57cec5SDimitry Andric Address ObjectFileELF::GetBaseAddress() {
938c9157d92SDimitry Andric   if (GetType() == ObjectFile::eTypeObjectFile) {
939c9157d92SDimitry Andric     for (SectionHeaderCollIter I = std::next(m_section_headers.begin());
940c9157d92SDimitry Andric          I != m_section_headers.end(); ++I) {
941c9157d92SDimitry Andric       const ELFSectionHeaderInfo &header = *I;
942c9157d92SDimitry Andric       if (header.sh_flags & SHF_ALLOC)
943c9157d92SDimitry Andric         return Address(GetSectionList()->FindSectionByID(SectionIndex(I)), 0);
944c9157d92SDimitry Andric     }
945c9157d92SDimitry Andric     return LLDB_INVALID_ADDRESS;
946c9157d92SDimitry Andric   }
947c9157d92SDimitry Andric 
9480b57cec5SDimitry Andric   for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {
9490b57cec5SDimitry Andric     const ELFProgramHeader &H = EnumPHdr.value();
9500b57cec5SDimitry Andric     if (H.p_type != PT_LOAD)
9510b57cec5SDimitry Andric       continue;
9520b57cec5SDimitry Andric 
9530b57cec5SDimitry Andric     return Address(
9540b57cec5SDimitry Andric         GetSectionList()->FindSectionByID(SegmentID(EnumPHdr.index())), 0);
9550b57cec5SDimitry Andric   }
9560b57cec5SDimitry Andric   return LLDB_INVALID_ADDRESS;
9570b57cec5SDimitry Andric }
9580b57cec5SDimitry Andric 
9590b57cec5SDimitry Andric // ParseDependentModules
ParseDependentModules()9600b57cec5SDimitry Andric size_t ObjectFileELF::ParseDependentModules() {
9610b57cec5SDimitry Andric   if (m_filespec_up)
9620b57cec5SDimitry Andric     return m_filespec_up->GetSize();
9630b57cec5SDimitry Andric 
9645ffd83dbSDimitry Andric   m_filespec_up = std::make_unique<FileSpecList>();
9650b57cec5SDimitry Andric 
9660b57cec5SDimitry Andric   if (!ParseSectionHeaders())
9670b57cec5SDimitry Andric     return 0;
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
9700b57cec5SDimitry Andric   if (!section_list)
9710b57cec5SDimitry Andric     return 0;
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric   // Find the SHT_DYNAMIC section.
9740b57cec5SDimitry Andric   Section *dynsym =
9750b57cec5SDimitry Andric       section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
9760b57cec5SDimitry Andric           .get();
9770b57cec5SDimitry Andric   if (!dynsym)
9780b57cec5SDimitry Andric     return 0;
9790b57cec5SDimitry Andric   assert(dynsym->GetObjectFile() == this);
9800b57cec5SDimitry Andric 
9810b57cec5SDimitry Andric   const ELFSectionHeaderInfo *header = GetSectionHeaderByIndex(dynsym->GetID());
9820b57cec5SDimitry Andric   if (!header)
9830b57cec5SDimitry Andric     return 0;
9840b57cec5SDimitry Andric   // sh_link: section header index of string table used by entries in the
9850b57cec5SDimitry Andric   // section.
9860b57cec5SDimitry Andric   Section *dynstr = section_list->FindSectionByID(header->sh_link).get();
9870b57cec5SDimitry Andric   if (!dynstr)
9880b57cec5SDimitry Andric     return 0;
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric   DataExtractor dynsym_data;
9910b57cec5SDimitry Andric   DataExtractor dynstr_data;
9920b57cec5SDimitry Andric   if (ReadSectionData(dynsym, dynsym_data) &&
9930b57cec5SDimitry Andric       ReadSectionData(dynstr, dynstr_data)) {
9940b57cec5SDimitry Andric     ELFDynamic symbol;
9950b57cec5SDimitry Andric     const lldb::offset_t section_size = dynsym_data.GetByteSize();
9960b57cec5SDimitry Andric     lldb::offset_t offset = 0;
9970b57cec5SDimitry Andric 
9980b57cec5SDimitry Andric     // The only type of entries we are concerned with are tagged DT_NEEDED,
9990b57cec5SDimitry Andric     // yielding the name of a required library.
10000b57cec5SDimitry Andric     while (offset < section_size) {
10010b57cec5SDimitry Andric       if (!symbol.Parse(dynsym_data, &offset))
10020b57cec5SDimitry Andric         break;
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric       if (symbol.d_tag != DT_NEEDED)
10050b57cec5SDimitry Andric         continue;
10060b57cec5SDimitry Andric 
10070b57cec5SDimitry Andric       uint32_t str_index = static_cast<uint32_t>(symbol.d_val);
10080b57cec5SDimitry Andric       const char *lib_name = dynstr_data.PeekCStr(str_index);
10090b57cec5SDimitry Andric       FileSpec file_spec(lib_name);
10100b57cec5SDimitry Andric       FileSystem::Instance().Resolve(file_spec);
10110b57cec5SDimitry Andric       m_filespec_up->Append(file_spec);
10120b57cec5SDimitry Andric     }
10130b57cec5SDimitry Andric   }
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric   return m_filespec_up->GetSize();
10160b57cec5SDimitry Andric }
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric // GetProgramHeaderInfo
GetProgramHeaderInfo(ProgramHeaderColl & program_headers,DataExtractor & object_data,const ELFHeader & header)10190b57cec5SDimitry Andric size_t ObjectFileELF::GetProgramHeaderInfo(ProgramHeaderColl &program_headers,
10200b57cec5SDimitry Andric                                            DataExtractor &object_data,
10210b57cec5SDimitry Andric                                            const ELFHeader &header) {
10220b57cec5SDimitry Andric   // We have already parsed the program headers
10230b57cec5SDimitry Andric   if (!program_headers.empty())
10240b57cec5SDimitry Andric     return program_headers.size();
10250b57cec5SDimitry Andric 
10260b57cec5SDimitry Andric   // If there are no program headers to read we are done.
10270b57cec5SDimitry Andric   if (header.e_phnum == 0)
10280b57cec5SDimitry Andric     return 0;
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric   program_headers.resize(header.e_phnum);
10310b57cec5SDimitry Andric   if (program_headers.size() != header.e_phnum)
10320b57cec5SDimitry Andric     return 0;
10330b57cec5SDimitry Andric 
10340b57cec5SDimitry Andric   const size_t ph_size = header.e_phnum * header.e_phentsize;
10350b57cec5SDimitry Andric   const elf_off ph_offset = header.e_phoff;
10360b57cec5SDimitry Andric   DataExtractor data;
10370b57cec5SDimitry Andric   if (data.SetData(object_data, ph_offset, ph_size) != ph_size)
10380b57cec5SDimitry Andric     return 0;
10390b57cec5SDimitry Andric 
10400b57cec5SDimitry Andric   uint32_t idx;
10410b57cec5SDimitry Andric   lldb::offset_t offset;
10420b57cec5SDimitry Andric   for (idx = 0, offset = 0; idx < header.e_phnum; ++idx) {
10430b57cec5SDimitry Andric     if (!program_headers[idx].Parse(data, &offset))
10440b57cec5SDimitry Andric       break;
10450b57cec5SDimitry Andric   }
10460b57cec5SDimitry Andric 
10470b57cec5SDimitry Andric   if (idx < program_headers.size())
10480b57cec5SDimitry Andric     program_headers.resize(idx);
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric   return program_headers.size();
10510b57cec5SDimitry Andric }
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric // ParseProgramHeaders
ParseProgramHeaders()10540b57cec5SDimitry Andric bool ObjectFileELF::ParseProgramHeaders() {
10550b57cec5SDimitry Andric   return GetProgramHeaderInfo(m_program_headers, m_data, m_header) != 0;
10560b57cec5SDimitry Andric }
10570b57cec5SDimitry Andric 
10580b57cec5SDimitry Andric lldb_private::Status
RefineModuleDetailsFromNote(lldb_private::DataExtractor & data,lldb_private::ArchSpec & arch_spec,lldb_private::UUID & uuid)10590b57cec5SDimitry Andric ObjectFileELF::RefineModuleDetailsFromNote(lldb_private::DataExtractor &data,
10600b57cec5SDimitry Andric                                            lldb_private::ArchSpec &arch_spec,
10610b57cec5SDimitry Andric                                            lldb_private::UUID &uuid) {
106281ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Modules);
10630b57cec5SDimitry Andric   Status error;
10640b57cec5SDimitry Andric 
10650b57cec5SDimitry Andric   lldb::offset_t offset = 0;
10660b57cec5SDimitry Andric 
10670b57cec5SDimitry Andric   while (true) {
10680b57cec5SDimitry Andric     // Parse the note header.  If this fails, bail out.
10690b57cec5SDimitry Andric     const lldb::offset_t note_offset = offset;
10700b57cec5SDimitry Andric     ELFNote note = ELFNote();
10710b57cec5SDimitry Andric     if (!note.Parse(data, &offset)) {
10720b57cec5SDimitry Andric       // We're done.
10730b57cec5SDimitry Andric       return error;
10740b57cec5SDimitry Andric     }
10750b57cec5SDimitry Andric 
10769dba64beSDimitry Andric     LLDB_LOGF(log, "ObjectFileELF::%s parsing note name='%s', type=%" PRIu32,
10770b57cec5SDimitry Andric               __FUNCTION__, note.n_name.c_str(), note.n_type);
10780b57cec5SDimitry Andric 
10790b57cec5SDimitry Andric     // Process FreeBSD ELF notes.
10800b57cec5SDimitry Andric     if ((note.n_name == LLDB_NT_OWNER_FREEBSD) &&
10810b57cec5SDimitry Andric         (note.n_type == LLDB_NT_FREEBSD_ABI_TAG) &&
10820b57cec5SDimitry Andric         (note.n_descsz == LLDB_NT_FREEBSD_ABI_SIZE)) {
10830b57cec5SDimitry Andric       // Pull out the min version info.
10840b57cec5SDimitry Andric       uint32_t version_info;
10850b57cec5SDimitry Andric       if (data.GetU32(&offset, &version_info, 1) == nullptr) {
10860b57cec5SDimitry Andric         error.SetErrorString("failed to read FreeBSD ABI note payload");
10870b57cec5SDimitry Andric         return error;
10880b57cec5SDimitry Andric       }
10890b57cec5SDimitry Andric 
10900b57cec5SDimitry Andric       // Convert the version info into a major/minor number.
10910b57cec5SDimitry Andric       const uint32_t version_major = version_info / 100000;
10920b57cec5SDimitry Andric       const uint32_t version_minor = (version_info / 1000) % 100;
10930b57cec5SDimitry Andric 
10940b57cec5SDimitry Andric       char os_name[32];
10950b57cec5SDimitry Andric       snprintf(os_name, sizeof(os_name), "freebsd%" PRIu32 ".%" PRIu32,
10960b57cec5SDimitry Andric                version_major, version_minor);
10970b57cec5SDimitry Andric 
10980b57cec5SDimitry Andric       // Set the elf OS version to FreeBSD.  Also clear the vendor.
10990b57cec5SDimitry Andric       arch_spec.GetTriple().setOSName(os_name);
11000b57cec5SDimitry Andric       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
11010b57cec5SDimitry Andric 
11029dba64beSDimitry Andric       LLDB_LOGF(log,
11039dba64beSDimitry Andric                 "ObjectFileELF::%s detected FreeBSD %" PRIu32 ".%" PRIu32
11040b57cec5SDimitry Andric                 ".%" PRIu32,
11050b57cec5SDimitry Andric                 __FUNCTION__, version_major, version_minor,
11060b57cec5SDimitry Andric                 static_cast<uint32_t>(version_info % 1000));
11070b57cec5SDimitry Andric     }
11080b57cec5SDimitry Andric     // Process GNU ELF notes.
11090b57cec5SDimitry Andric     else if (note.n_name == LLDB_NT_OWNER_GNU) {
11100b57cec5SDimitry Andric       switch (note.n_type) {
11110b57cec5SDimitry Andric       case LLDB_NT_GNU_ABI_TAG:
11120b57cec5SDimitry Andric         if (note.n_descsz == LLDB_NT_GNU_ABI_SIZE) {
11130b57cec5SDimitry Andric           // Pull out the min OS version supporting the ABI.
11140b57cec5SDimitry Andric           uint32_t version_info[4];
11150b57cec5SDimitry Andric           if (data.GetU32(&offset, &version_info[0], note.n_descsz / 4) ==
11160b57cec5SDimitry Andric               nullptr) {
11170b57cec5SDimitry Andric             error.SetErrorString("failed to read GNU ABI note payload");
11180b57cec5SDimitry Andric             return error;
11190b57cec5SDimitry Andric           }
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric           // Set the OS per the OS field.
11220b57cec5SDimitry Andric           switch (version_info[0]) {
11230b57cec5SDimitry Andric           case LLDB_NT_GNU_ABI_OS_LINUX:
11240b57cec5SDimitry Andric             arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
11250b57cec5SDimitry Andric             arch_spec.GetTriple().setVendor(
11260b57cec5SDimitry Andric                 llvm::Triple::VendorType::UnknownVendor);
11279dba64beSDimitry Andric             LLDB_LOGF(log,
11280b57cec5SDimitry Andric                       "ObjectFileELF::%s detected Linux, min version %" PRIu32
11290b57cec5SDimitry Andric                       ".%" PRIu32 ".%" PRIu32,
11300b57cec5SDimitry Andric                       __FUNCTION__, version_info[1], version_info[2],
11310b57cec5SDimitry Andric                       version_info[3]);
11320b57cec5SDimitry Andric             // FIXME we have the minimal version number, we could be propagating
11330b57cec5SDimitry Andric             // that.  version_info[1] = OS Major, version_info[2] = OS Minor,
11340b57cec5SDimitry Andric             // version_info[3] = Revision.
11350b57cec5SDimitry Andric             break;
11360b57cec5SDimitry Andric           case LLDB_NT_GNU_ABI_OS_HURD:
11370b57cec5SDimitry Andric             arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
11380b57cec5SDimitry Andric             arch_spec.GetTriple().setVendor(
11390b57cec5SDimitry Andric                 llvm::Triple::VendorType::UnknownVendor);
11409dba64beSDimitry Andric             LLDB_LOGF(log,
11419dba64beSDimitry Andric                       "ObjectFileELF::%s detected Hurd (unsupported), min "
11420b57cec5SDimitry Andric                       "version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
11430b57cec5SDimitry Andric                       __FUNCTION__, version_info[1], version_info[2],
11440b57cec5SDimitry Andric                       version_info[3]);
11450b57cec5SDimitry Andric             break;
11460b57cec5SDimitry Andric           case LLDB_NT_GNU_ABI_OS_SOLARIS:
11470b57cec5SDimitry Andric             arch_spec.GetTriple().setOS(llvm::Triple::OSType::Solaris);
11480b57cec5SDimitry Andric             arch_spec.GetTriple().setVendor(
11490b57cec5SDimitry Andric                 llvm::Triple::VendorType::UnknownVendor);
11509dba64beSDimitry Andric             LLDB_LOGF(log,
11510b57cec5SDimitry Andric                       "ObjectFileELF::%s detected Solaris, min version %" PRIu32
11520b57cec5SDimitry Andric                       ".%" PRIu32 ".%" PRIu32,
11530b57cec5SDimitry Andric                       __FUNCTION__, version_info[1], version_info[2],
11540b57cec5SDimitry Andric                       version_info[3]);
11550b57cec5SDimitry Andric             break;
11560b57cec5SDimitry Andric           default:
11579dba64beSDimitry Andric             LLDB_LOGF(log,
11580b57cec5SDimitry Andric                       "ObjectFileELF::%s unrecognized OS in note, id %" PRIu32
11590b57cec5SDimitry Andric                       ", min version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
11600b57cec5SDimitry Andric                       __FUNCTION__, version_info[0], version_info[1],
11610b57cec5SDimitry Andric                       version_info[2], version_info[3]);
11620b57cec5SDimitry Andric             break;
11630b57cec5SDimitry Andric           }
11640b57cec5SDimitry Andric         }
11650b57cec5SDimitry Andric         break;
11660b57cec5SDimitry Andric 
11670b57cec5SDimitry Andric       case LLDB_NT_GNU_BUILD_ID_TAG:
11680b57cec5SDimitry Andric         // Only bother processing this if we don't already have the uuid set.
11690b57cec5SDimitry Andric         if (!uuid.IsValid()) {
11700b57cec5SDimitry Andric           // 16 bytes is UUID|MD5, 20 bytes is SHA1. Other linkers may produce a
11710b57cec5SDimitry Andric           // build-id of a different length. Accept it as long as it's at least
11720b57cec5SDimitry Andric           // 4 bytes as it will be better than our own crc32.
11730b57cec5SDimitry Andric           if (note.n_descsz >= 4) {
11740b57cec5SDimitry Andric             if (const uint8_t *buf = data.PeekData(offset, note.n_descsz)) {
11750b57cec5SDimitry Andric               // Save the build id as the UUID for the module.
1176bdd1243dSDimitry Andric               uuid = UUID(buf, note.n_descsz);
11770b57cec5SDimitry Andric             } else {
11780b57cec5SDimitry Andric               error.SetErrorString("failed to read GNU_BUILD_ID note payload");
11790b57cec5SDimitry Andric               return error;
11800b57cec5SDimitry Andric             }
11810b57cec5SDimitry Andric           }
11820b57cec5SDimitry Andric         }
11830b57cec5SDimitry Andric         break;
11840b57cec5SDimitry Andric       }
11850b57cec5SDimitry Andric       if (arch_spec.IsMIPS() &&
11860b57cec5SDimitry Andric           arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)
11870b57cec5SDimitry Andric         // The note.n_name == LLDB_NT_OWNER_GNU is valid for Linux platform
11880b57cec5SDimitry Andric         arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
11890b57cec5SDimitry Andric     }
11900b57cec5SDimitry Andric     // Process NetBSD ELF executables and shared libraries
11910b57cec5SDimitry Andric     else if ((note.n_name == LLDB_NT_OWNER_NETBSD) &&
11920b57cec5SDimitry Andric              (note.n_type == LLDB_NT_NETBSD_IDENT_TAG) &&
11930b57cec5SDimitry Andric              (note.n_descsz == LLDB_NT_NETBSD_IDENT_DESCSZ) &&
11940b57cec5SDimitry Andric              (note.n_namesz == LLDB_NT_NETBSD_IDENT_NAMESZ)) {
11950b57cec5SDimitry Andric       // Pull out the version info.
11960b57cec5SDimitry Andric       uint32_t version_info;
11970b57cec5SDimitry Andric       if (data.GetU32(&offset, &version_info, 1) == nullptr) {
11980b57cec5SDimitry Andric         error.SetErrorString("failed to read NetBSD ABI note payload");
11990b57cec5SDimitry Andric         return error;
12000b57cec5SDimitry Andric       }
12010b57cec5SDimitry Andric       // Convert the version info into a major/minor/patch number.
12020b57cec5SDimitry Andric       //     #define __NetBSD_Version__ MMmmrrpp00
12030b57cec5SDimitry Andric       //
12040b57cec5SDimitry Andric       //     M = major version
12050b57cec5SDimitry Andric       //     m = minor version; a minor number of 99 indicates current.
12060b57cec5SDimitry Andric       //     r = 0 (since NetBSD 3.0 not used)
12070b57cec5SDimitry Andric       //     p = patchlevel
12080b57cec5SDimitry Andric       const uint32_t version_major = version_info / 100000000;
12090b57cec5SDimitry Andric       const uint32_t version_minor = (version_info % 100000000) / 1000000;
12100b57cec5SDimitry Andric       const uint32_t version_patch = (version_info % 10000) / 100;
12110b57cec5SDimitry Andric       // Set the elf OS version to NetBSD.  Also clear the vendor.
12120b57cec5SDimitry Andric       arch_spec.GetTriple().setOSName(
12130b57cec5SDimitry Andric           llvm::formatv("netbsd{0}.{1}.{2}", version_major, version_minor,
12140b57cec5SDimitry Andric                         version_patch).str());
12150b57cec5SDimitry Andric       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
12160b57cec5SDimitry Andric     }
12170b57cec5SDimitry Andric     // Process NetBSD ELF core(5) notes
12180b57cec5SDimitry Andric     else if ((note.n_name == LLDB_NT_OWNER_NETBSDCORE) &&
12190b57cec5SDimitry Andric              (note.n_type == LLDB_NT_NETBSD_PROCINFO)) {
12200b57cec5SDimitry Andric       // Set the elf OS version to NetBSD.  Also clear the vendor.
12210b57cec5SDimitry Andric       arch_spec.GetTriple().setOS(llvm::Triple::OSType::NetBSD);
12220b57cec5SDimitry Andric       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
12230b57cec5SDimitry Andric     }
12240b57cec5SDimitry Andric     // Process OpenBSD ELF notes.
12250b57cec5SDimitry Andric     else if (note.n_name == LLDB_NT_OWNER_OPENBSD) {
12260b57cec5SDimitry Andric       // Set the elf OS version to OpenBSD.  Also clear the vendor.
12270b57cec5SDimitry Andric       arch_spec.GetTriple().setOS(llvm::Triple::OSType::OpenBSD);
12280b57cec5SDimitry Andric       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
12290b57cec5SDimitry Andric     } else if (note.n_name == LLDB_NT_OWNER_ANDROID) {
12300b57cec5SDimitry Andric       arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
12310b57cec5SDimitry Andric       arch_spec.GetTriple().setEnvironment(
12320b57cec5SDimitry Andric           llvm::Triple::EnvironmentType::Android);
12330b57cec5SDimitry Andric     } else if (note.n_name == LLDB_NT_OWNER_LINUX) {
12340b57cec5SDimitry Andric       // This is sometimes found in core files and usually contains extended
12350b57cec5SDimitry Andric       // register info
12360b57cec5SDimitry Andric       arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
12370b57cec5SDimitry Andric     } else if (note.n_name == LLDB_NT_OWNER_CORE) {
123881ad6265SDimitry Andric       // Parse the NT_FILE to look for stuff in paths to shared libraries
123981ad6265SDimitry Andric       // The contents look like this in a 64 bit ELF core file:
124081ad6265SDimitry Andric       //
124181ad6265SDimitry Andric       // count     = 0x000000000000000a (10)
124281ad6265SDimitry Andric       // page_size = 0x0000000000001000 (4096)
124381ad6265SDimitry Andric       // Index start              end                file_ofs           path
124481ad6265SDimitry Andric       // ===== ------------------ ------------------ ------------------ -------------------------------------
124581ad6265SDimitry Andric       // [  0] 0x0000000000401000 0x0000000000000000                    /tmp/a.out
124681ad6265SDimitry Andric       // [  1] 0x0000000000600000 0x0000000000601000 0x0000000000000000 /tmp/a.out
124781ad6265SDimitry Andric       // [  2] 0x0000000000601000 0x0000000000602000 0x0000000000000001 /tmp/a.out
124881ad6265SDimitry Andric       // [  3] 0x00007fa79c9ed000 0x00007fa79cba8000 0x0000000000000000 /lib/x86_64-linux-gnu/libc-2.19.so
124981ad6265SDimitry Andric       // [  4] 0x00007fa79cba8000 0x00007fa79cda7000 0x00000000000001bb /lib/x86_64-linux-gnu/libc-2.19.so
125081ad6265SDimitry Andric       // [  5] 0x00007fa79cda7000 0x00007fa79cdab000 0x00000000000001ba /lib/x86_64-linux-gnu/libc-2.19.so
125181ad6265SDimitry Andric       // [  6] 0x00007fa79cdab000 0x00007fa79cdad000 0x00000000000001be /lib/x86_64-linux-gnu/libc-2.19.so
125281ad6265SDimitry Andric       // [  7] 0x00007fa79cdb2000 0x00007fa79cdd5000 0x0000000000000000 /lib/x86_64-linux-gnu/ld-2.19.so
125381ad6265SDimitry Andric       // [  8] 0x00007fa79cfd4000 0x00007fa79cfd5000 0x0000000000000022 /lib/x86_64-linux-gnu/ld-2.19.so
125481ad6265SDimitry Andric       // [  9] 0x00007fa79cfd5000 0x00007fa79cfd6000 0x0000000000000023 /lib/x86_64-linux-gnu/ld-2.19.so
125581ad6265SDimitry Andric       //
125681ad6265SDimitry Andric       // In the 32 bit ELFs the count, page_size, start, end, file_ofs are
125781ad6265SDimitry Andric       // uint32_t.
125881ad6265SDimitry Andric       //
125981ad6265SDimitry Andric       // For reference: see readelf source code (in binutils).
12600b57cec5SDimitry Andric       if (note.n_type == NT_FILE) {
12610b57cec5SDimitry Andric         uint64_t count = data.GetAddress(&offset);
12620b57cec5SDimitry Andric         const char *cstr;
12630b57cec5SDimitry Andric         data.GetAddress(&offset); // Skip page size
12640b57cec5SDimitry Andric         offset += count * 3 *
12650b57cec5SDimitry Andric                   data.GetAddressByteSize(); // Skip all start/end/file_ofs
12660b57cec5SDimitry Andric         for (size_t i = 0; i < count; ++i) {
12670b57cec5SDimitry Andric           cstr = data.GetCStr(&offset);
12680b57cec5SDimitry Andric           if (cstr == nullptr) {
12690b57cec5SDimitry Andric             error.SetErrorStringWithFormat("ObjectFileELF::%s trying to read "
12700b57cec5SDimitry Andric                                            "at an offset after the end "
12710b57cec5SDimitry Andric                                            "(GetCStr returned nullptr)",
12720b57cec5SDimitry Andric                                            __FUNCTION__);
12730b57cec5SDimitry Andric             return error;
12740b57cec5SDimitry Andric           }
12750b57cec5SDimitry Andric           llvm::StringRef path(cstr);
12760b57cec5SDimitry Andric           if (path.contains("/lib/x86_64-linux-gnu") || path.contains("/lib/i386-linux-gnu")) {
12770b57cec5SDimitry Andric             arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
12780b57cec5SDimitry Andric             break;
12790b57cec5SDimitry Andric           }
12800b57cec5SDimitry Andric         }
12810b57cec5SDimitry Andric         if (arch_spec.IsMIPS() &&
12820b57cec5SDimitry Andric             arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)
12830b57cec5SDimitry Andric           // In case of MIPSR6, the LLDB_NT_OWNER_GNU note is missing for some
12840b57cec5SDimitry Andric           // cases (e.g. compile with -nostdlib) Hence set OS to Linux
12850b57cec5SDimitry Andric           arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
12860b57cec5SDimitry Andric       }
12870b57cec5SDimitry Andric     }
12880b57cec5SDimitry Andric 
12890b57cec5SDimitry Andric     // Calculate the offset of the next note just in case "offset" has been
12900b57cec5SDimitry Andric     // used to poke at the contents of the note data
12910b57cec5SDimitry Andric     offset = note_offset + note.GetByteSize();
12920b57cec5SDimitry Andric   }
12930b57cec5SDimitry Andric 
12940b57cec5SDimitry Andric   return error;
12950b57cec5SDimitry Andric }
12960b57cec5SDimitry Andric 
ParseARMAttributes(DataExtractor & data,uint64_t length,ArchSpec & arch_spec)12970b57cec5SDimitry Andric void ObjectFileELF::ParseARMAttributes(DataExtractor &data, uint64_t length,
12980b57cec5SDimitry Andric                                        ArchSpec &arch_spec) {
12990b57cec5SDimitry Andric   lldb::offset_t Offset = 0;
13000b57cec5SDimitry Andric 
13010b57cec5SDimitry Andric   uint8_t FormatVersion = data.GetU8(&Offset);
13025ffd83dbSDimitry Andric   if (FormatVersion != llvm::ELFAttrs::Format_Version)
13030b57cec5SDimitry Andric     return;
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric   Offset = Offset + sizeof(uint32_t); // Section Length
13060b57cec5SDimitry Andric   llvm::StringRef VendorName = data.GetCStr(&Offset);
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric   if (VendorName != "aeabi")
13090b57cec5SDimitry Andric     return;
13100b57cec5SDimitry Andric 
13110b57cec5SDimitry Andric   if (arch_spec.GetTriple().getEnvironment() ==
13120b57cec5SDimitry Andric       llvm::Triple::UnknownEnvironment)
13130b57cec5SDimitry Andric     arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
13140b57cec5SDimitry Andric 
13150b57cec5SDimitry Andric   while (Offset < length) {
13160b57cec5SDimitry Andric     uint8_t Tag = data.GetU8(&Offset);
13170b57cec5SDimitry Andric     uint32_t Size = data.GetU32(&Offset);
13180b57cec5SDimitry Andric 
13190b57cec5SDimitry Andric     if (Tag != llvm::ARMBuildAttrs::File || Size == 0)
13200b57cec5SDimitry Andric       continue;
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric     while (Offset < length) {
13230b57cec5SDimitry Andric       uint64_t Tag = data.GetULEB128(&Offset);
13240b57cec5SDimitry Andric       switch (Tag) {
13250b57cec5SDimitry Andric       default:
13260b57cec5SDimitry Andric         if (Tag < 32)
13270b57cec5SDimitry Andric           data.GetULEB128(&Offset);
13280b57cec5SDimitry Andric         else if (Tag % 2 == 0)
13290b57cec5SDimitry Andric           data.GetULEB128(&Offset);
13300b57cec5SDimitry Andric         else
13310b57cec5SDimitry Andric           data.GetCStr(&Offset);
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric         break;
13340b57cec5SDimitry Andric 
13350b57cec5SDimitry Andric       case llvm::ARMBuildAttrs::CPU_raw_name:
13360b57cec5SDimitry Andric       case llvm::ARMBuildAttrs::CPU_name:
13370b57cec5SDimitry Andric         data.GetCStr(&Offset);
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric         break;
13400b57cec5SDimitry Andric 
13410b57cec5SDimitry Andric       case llvm::ARMBuildAttrs::ABI_VFP_args: {
13420b57cec5SDimitry Andric         uint64_t VFPArgs = data.GetULEB128(&Offset);
13430b57cec5SDimitry Andric 
13440b57cec5SDimitry Andric         if (VFPArgs == llvm::ARMBuildAttrs::BaseAAPCS) {
13450b57cec5SDimitry Andric           if (arch_spec.GetTriple().getEnvironment() ==
13460b57cec5SDimitry Andric                   llvm::Triple::UnknownEnvironment ||
13470b57cec5SDimitry Andric               arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABIHF)
13480b57cec5SDimitry Andric             arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
13490b57cec5SDimitry Andric 
13500b57cec5SDimitry Andric           arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
13510b57cec5SDimitry Andric         } else if (VFPArgs == llvm::ARMBuildAttrs::HardFPAAPCS) {
13520b57cec5SDimitry Andric           if (arch_spec.GetTriple().getEnvironment() ==
13530b57cec5SDimitry Andric                   llvm::Triple::UnknownEnvironment ||
13540b57cec5SDimitry Andric               arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABI)
13550b57cec5SDimitry Andric             arch_spec.GetTriple().setEnvironment(llvm::Triple::EABIHF);
13560b57cec5SDimitry Andric 
13570b57cec5SDimitry Andric           arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
13580b57cec5SDimitry Andric         }
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric         break;
13610b57cec5SDimitry Andric       }
13620b57cec5SDimitry Andric       }
13630b57cec5SDimitry Andric     }
13640b57cec5SDimitry Andric   }
13650b57cec5SDimitry Andric }
13660b57cec5SDimitry Andric 
13670b57cec5SDimitry Andric // GetSectionHeaderInfo
GetSectionHeaderInfo(SectionHeaderColl & section_headers,DataExtractor & object_data,const elf::ELFHeader & header,lldb_private::UUID & uuid,std::string & gnu_debuglink_file,uint32_t & gnu_debuglink_crc,ArchSpec & arch_spec)13680b57cec5SDimitry Andric size_t ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl &section_headers,
13690b57cec5SDimitry Andric                                            DataExtractor &object_data,
13700b57cec5SDimitry Andric                                            const elf::ELFHeader &header,
13710b57cec5SDimitry Andric                                            lldb_private::UUID &uuid,
13720b57cec5SDimitry Andric                                            std::string &gnu_debuglink_file,
13730b57cec5SDimitry Andric                                            uint32_t &gnu_debuglink_crc,
13740b57cec5SDimitry Andric                                            ArchSpec &arch_spec) {
13750b57cec5SDimitry Andric   // Don't reparse the section headers if we already did that.
13760b57cec5SDimitry Andric   if (!section_headers.empty())
13770b57cec5SDimitry Andric     return section_headers.size();
13780b57cec5SDimitry Andric 
13790b57cec5SDimitry Andric   // Only initialize the arch_spec to okay defaults if they're not already set.
13800b57cec5SDimitry Andric   // We'll refine this with note data as we parse the notes.
13810b57cec5SDimitry Andric   if (arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) {
13820b57cec5SDimitry Andric     llvm::Triple::OSType ostype;
13830b57cec5SDimitry Andric     llvm::Triple::OSType spec_ostype;
13840b57cec5SDimitry Andric     const uint32_t sub_type = subTypeFromElfHeader(header);
13850b57cec5SDimitry Andric     arch_spec.SetArchitecture(eArchTypeELF, header.e_machine, sub_type,
13860b57cec5SDimitry Andric                               header.e_ident[EI_OSABI]);
13870b57cec5SDimitry Andric 
13880b57cec5SDimitry Andric     // Validate if it is ok to remove GetOsFromOSABI. Note, that now the OS is
13890b57cec5SDimitry Andric     // determined based on EI_OSABI flag and the info extracted from ELF notes
13900b57cec5SDimitry Andric     // (see RefineModuleDetailsFromNote). However in some cases that still
13910b57cec5SDimitry Andric     // might be not enough: for example a shared library might not have any
13920b57cec5SDimitry Andric     // notes at all and have EI_OSABI flag set to System V, as result the OS
13930b57cec5SDimitry Andric     // will be set to UnknownOS.
13940b57cec5SDimitry Andric     GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
13950b57cec5SDimitry Andric     spec_ostype = arch_spec.GetTriple().getOS();
13960b57cec5SDimitry Andric     assert(spec_ostype == ostype);
13970b57cec5SDimitry Andric     UNUSED_IF_ASSERT_DISABLED(spec_ostype);
13980b57cec5SDimitry Andric   }
13990b57cec5SDimitry Andric 
14000b57cec5SDimitry Andric   if (arch_spec.GetMachine() == llvm::Triple::mips ||
14010b57cec5SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::mipsel ||
14020b57cec5SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::mips64 ||
14030b57cec5SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::mips64el) {
14040b57cec5SDimitry Andric     switch (header.e_flags & llvm::ELF::EF_MIPS_ARCH_ASE) {
14050b57cec5SDimitry Andric     case llvm::ELF::EF_MIPS_MICROMIPS:
14060b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eMIPSAse_micromips);
14070b57cec5SDimitry Andric       break;
14080b57cec5SDimitry Andric     case llvm::ELF::EF_MIPS_ARCH_ASE_M16:
14090b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eMIPSAse_mips16);
14100b57cec5SDimitry Andric       break;
14110b57cec5SDimitry Andric     case llvm::ELF::EF_MIPS_ARCH_ASE_MDMX:
14120b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eMIPSAse_mdmx);
14130b57cec5SDimitry Andric       break;
14140b57cec5SDimitry Andric     default:
14150b57cec5SDimitry Andric       break;
14160b57cec5SDimitry Andric     }
14170b57cec5SDimitry Andric   }
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric   if (arch_spec.GetMachine() == llvm::Triple::arm ||
14200b57cec5SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::thumb) {
14210b57cec5SDimitry Andric     if (header.e_flags & llvm::ELF::EF_ARM_SOFT_FLOAT)
14220b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
14230b57cec5SDimitry Andric     else if (header.e_flags & llvm::ELF::EF_ARM_VFP_FLOAT)
14240b57cec5SDimitry Andric       arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
14250b57cec5SDimitry Andric   }
14260b57cec5SDimitry Andric 
142781ad6265SDimitry Andric   if (arch_spec.GetMachine() == llvm::Triple::riscv32 ||
142881ad6265SDimitry Andric       arch_spec.GetMachine() == llvm::Triple::riscv64) {
142981ad6265SDimitry Andric     uint32_t flags = arch_spec.GetFlags();
143081ad6265SDimitry Andric 
143181ad6265SDimitry Andric     if (header.e_flags & llvm::ELF::EF_RISCV_RVC)
143281ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_rvc;
143381ad6265SDimitry Andric     if (header.e_flags & llvm::ELF::EF_RISCV_RVE)
143481ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_rve;
143581ad6265SDimitry Andric 
143681ad6265SDimitry Andric     if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_SINGLE) ==
143781ad6265SDimitry Andric         llvm::ELF::EF_RISCV_FLOAT_ABI_SINGLE)
143881ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_float_abi_single;
143981ad6265SDimitry Andric     else if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_DOUBLE) ==
144081ad6265SDimitry Andric              llvm::ELF::EF_RISCV_FLOAT_ABI_DOUBLE)
144181ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_float_abi_double;
144281ad6265SDimitry Andric     else if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_QUAD) ==
144381ad6265SDimitry Andric              llvm::ELF::EF_RISCV_FLOAT_ABI_QUAD)
144481ad6265SDimitry Andric       flags |= ArchSpec::eRISCV_float_abi_quad;
144581ad6265SDimitry Andric 
144681ad6265SDimitry Andric     arch_spec.SetFlags(flags);
144781ad6265SDimitry Andric   }
144881ad6265SDimitry Andric 
14490b57cec5SDimitry Andric   // If there are no section headers we are done.
14500b57cec5SDimitry Andric   if (header.e_shnum == 0)
14510b57cec5SDimitry Andric     return 0;
14520b57cec5SDimitry Andric 
145381ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Modules);
14540b57cec5SDimitry Andric 
14550b57cec5SDimitry Andric   section_headers.resize(header.e_shnum);
14560b57cec5SDimitry Andric   if (section_headers.size() != header.e_shnum)
14570b57cec5SDimitry Andric     return 0;
14580b57cec5SDimitry Andric 
14590b57cec5SDimitry Andric   const size_t sh_size = header.e_shnum * header.e_shentsize;
14600b57cec5SDimitry Andric   const elf_off sh_offset = header.e_shoff;
14610b57cec5SDimitry Andric   DataExtractor sh_data;
14620b57cec5SDimitry Andric   if (sh_data.SetData(object_data, sh_offset, sh_size) != sh_size)
14630b57cec5SDimitry Andric     return 0;
14640b57cec5SDimitry Andric 
14650b57cec5SDimitry Andric   uint32_t idx;
14660b57cec5SDimitry Andric   lldb::offset_t offset;
14670b57cec5SDimitry Andric   for (idx = 0, offset = 0; idx < header.e_shnum; ++idx) {
14680b57cec5SDimitry Andric     if (!section_headers[idx].Parse(sh_data, &offset))
14690b57cec5SDimitry Andric       break;
14700b57cec5SDimitry Andric   }
14710b57cec5SDimitry Andric   if (idx < section_headers.size())
14720b57cec5SDimitry Andric     section_headers.resize(idx);
14730b57cec5SDimitry Andric 
14740b57cec5SDimitry Andric   const unsigned strtab_idx = header.e_shstrndx;
14750b57cec5SDimitry Andric   if (strtab_idx && strtab_idx < section_headers.size()) {
14760b57cec5SDimitry Andric     const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];
14770b57cec5SDimitry Andric     const size_t byte_size = sheader.sh_size;
14780b57cec5SDimitry Andric     const Elf64_Off offset = sheader.sh_offset;
14790b57cec5SDimitry Andric     lldb_private::DataExtractor shstr_data;
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric     if (shstr_data.SetData(object_data, offset, byte_size) == byte_size) {
14820b57cec5SDimitry Andric       for (SectionHeaderCollIter I = section_headers.begin();
14830b57cec5SDimitry Andric            I != section_headers.end(); ++I) {
14840b57cec5SDimitry Andric         static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");
14850b57cec5SDimitry Andric         const ELFSectionHeaderInfo &sheader = *I;
14860b57cec5SDimitry Andric         const uint64_t section_size =
14870b57cec5SDimitry Andric             sheader.sh_type == SHT_NOBITS ? 0 : sheader.sh_size;
14880b57cec5SDimitry Andric         ConstString name(shstr_data.PeekCStr(I->sh_name));
14890b57cec5SDimitry Andric 
14900b57cec5SDimitry Andric         I->section_name = name;
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric         if (arch_spec.IsMIPS()) {
14930b57cec5SDimitry Andric           uint32_t arch_flags = arch_spec.GetFlags();
14940b57cec5SDimitry Andric           DataExtractor data;
14950b57cec5SDimitry Andric           if (sheader.sh_type == SHT_MIPS_ABIFLAGS) {
14960b57cec5SDimitry Andric 
14970b57cec5SDimitry Andric             if (section_size && (data.SetData(object_data, sheader.sh_offset,
14980b57cec5SDimitry Andric                                               section_size) == section_size)) {
14990b57cec5SDimitry Andric               // MIPS ASE Mask is at offset 12 in MIPS.abiflags section
15000b57cec5SDimitry Andric               lldb::offset_t offset = 12; // MIPS ABI Flags Version: 0
15010b57cec5SDimitry Andric               arch_flags |= data.GetU32(&offset);
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric               // The floating point ABI is at offset 7
15040b57cec5SDimitry Andric               offset = 7;
15050b57cec5SDimitry Andric               switch (data.GetU8(&offset)) {
15060b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_ANY:
15070b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_ANY;
15080b57cec5SDimitry Andric                 break;
15090b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_DOUBLE:
15100b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_DOUBLE;
15110b57cec5SDimitry Andric                 break;
15120b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_SINGLE:
15130b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SINGLE;
15140b57cec5SDimitry Andric                 break;
15150b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_SOFT:
15160b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SOFT;
15170b57cec5SDimitry Andric                 break;
15180b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_OLD_64:
15190b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_OLD_64;
15200b57cec5SDimitry Andric                 break;
15210b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_XX:
15220b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_XX;
15230b57cec5SDimitry Andric                 break;
15240b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_64:
15250b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64;
15260b57cec5SDimitry Andric                 break;
15270b57cec5SDimitry Andric               case llvm::Mips::Val_GNU_MIPS_ABI_FP_64A:
15280b57cec5SDimitry Andric                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64A;
15290b57cec5SDimitry Andric                 break;
15300b57cec5SDimitry Andric               }
15310b57cec5SDimitry Andric             }
15320b57cec5SDimitry Andric           }
15330b57cec5SDimitry Andric           // Settings appropriate ArchSpec ABI Flags
15340b57cec5SDimitry Andric           switch (header.e_flags & llvm::ELF::EF_MIPS_ABI) {
15350b57cec5SDimitry Andric           case llvm::ELF::EF_MIPS_ABI_O32:
15360b57cec5SDimitry Andric             arch_flags |= lldb_private::ArchSpec::eMIPSABI_O32;
15370b57cec5SDimitry Andric             break;
15380b57cec5SDimitry Andric           case EF_MIPS_ABI_O64:
15390b57cec5SDimitry Andric             arch_flags |= lldb_private::ArchSpec::eMIPSABI_O64;
15400b57cec5SDimitry Andric             break;
15410b57cec5SDimitry Andric           case EF_MIPS_ABI_EABI32:
15420b57cec5SDimitry Andric             arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI32;
15430b57cec5SDimitry Andric             break;
15440b57cec5SDimitry Andric           case EF_MIPS_ABI_EABI64:
15450b57cec5SDimitry Andric             arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI64;
15460b57cec5SDimitry Andric             break;
15470b57cec5SDimitry Andric           default:
15480b57cec5SDimitry Andric             // ABI Mask doesn't cover N32 and N64 ABI.
15490b57cec5SDimitry Andric             if (header.e_ident[EI_CLASS] == llvm::ELF::ELFCLASS64)
15500b57cec5SDimitry Andric               arch_flags |= lldb_private::ArchSpec::eMIPSABI_N64;
15510b57cec5SDimitry Andric             else if (header.e_flags & llvm::ELF::EF_MIPS_ABI2)
15520b57cec5SDimitry Andric               arch_flags |= lldb_private::ArchSpec::eMIPSABI_N32;
15530b57cec5SDimitry Andric             break;
15540b57cec5SDimitry Andric           }
15550b57cec5SDimitry Andric           arch_spec.SetFlags(arch_flags);
15560b57cec5SDimitry Andric         }
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric         if (arch_spec.GetMachine() == llvm::Triple::arm ||
15590b57cec5SDimitry Andric             arch_spec.GetMachine() == llvm::Triple::thumb) {
15600b57cec5SDimitry Andric           DataExtractor data;
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric           if (sheader.sh_type == SHT_ARM_ATTRIBUTES && section_size != 0 &&
15630b57cec5SDimitry Andric               data.SetData(object_data, sheader.sh_offset, section_size) == section_size)
15640b57cec5SDimitry Andric             ParseARMAttributes(data, section_size, arch_spec);
15650b57cec5SDimitry Andric         }
15660b57cec5SDimitry Andric 
15670b57cec5SDimitry Andric         if (name == g_sect_name_gnu_debuglink) {
15680b57cec5SDimitry Andric           DataExtractor data;
15690b57cec5SDimitry Andric           if (section_size && (data.SetData(object_data, sheader.sh_offset,
15700b57cec5SDimitry Andric                                             section_size) == section_size)) {
15710b57cec5SDimitry Andric             lldb::offset_t gnu_debuglink_offset = 0;
15720b57cec5SDimitry Andric             gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);
15730b57cec5SDimitry Andric             gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
15740b57cec5SDimitry Andric             data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
15750b57cec5SDimitry Andric           }
15760b57cec5SDimitry Andric         }
15770b57cec5SDimitry Andric 
15780b57cec5SDimitry Andric         // Process ELF note section entries.
15790b57cec5SDimitry Andric         bool is_note_header = (sheader.sh_type == SHT_NOTE);
15800b57cec5SDimitry Andric 
15810b57cec5SDimitry Andric         // The section header ".note.android.ident" is stored as a
15820b57cec5SDimitry Andric         // PROGBITS type header but it is actually a note header.
15830b57cec5SDimitry Andric         static ConstString g_sect_name_android_ident(".note.android.ident");
15840b57cec5SDimitry Andric         if (!is_note_header && name == g_sect_name_android_ident)
15850b57cec5SDimitry Andric           is_note_header = true;
15860b57cec5SDimitry Andric 
15870b57cec5SDimitry Andric         if (is_note_header) {
15880b57cec5SDimitry Andric           // Allow notes to refine module info.
15890b57cec5SDimitry Andric           DataExtractor data;
15900b57cec5SDimitry Andric           if (section_size && (data.SetData(object_data, sheader.sh_offset,
15910b57cec5SDimitry Andric                                             section_size) == section_size)) {
15920b57cec5SDimitry Andric             Status error = RefineModuleDetailsFromNote(data, arch_spec, uuid);
15930b57cec5SDimitry Andric             if (error.Fail()) {
15949dba64beSDimitry Andric               LLDB_LOGF(log, "ObjectFileELF::%s ELF note processing failed: %s",
15950b57cec5SDimitry Andric                         __FUNCTION__, error.AsCString());
15960b57cec5SDimitry Andric             }
15970b57cec5SDimitry Andric           }
15980b57cec5SDimitry Andric         }
15990b57cec5SDimitry Andric       }
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric       // Make any unknown triple components to be unspecified unknowns.
16020b57cec5SDimitry Andric       if (arch_spec.GetTriple().getVendor() == llvm::Triple::UnknownVendor)
16030b57cec5SDimitry Andric         arch_spec.GetTriple().setVendorName(llvm::StringRef());
16040b57cec5SDimitry Andric       if (arch_spec.GetTriple().getOS() == llvm::Triple::UnknownOS)
16050b57cec5SDimitry Andric         arch_spec.GetTriple().setOSName(llvm::StringRef());
16060b57cec5SDimitry Andric 
16070b57cec5SDimitry Andric       return section_headers.size();
16080b57cec5SDimitry Andric     }
16090b57cec5SDimitry Andric   }
16100b57cec5SDimitry Andric 
16110b57cec5SDimitry Andric   section_headers.clear();
16120b57cec5SDimitry Andric   return 0;
16130b57cec5SDimitry Andric }
16140b57cec5SDimitry Andric 
16150b57cec5SDimitry Andric llvm::StringRef
StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const16160b57cec5SDimitry Andric ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const {
16170b57cec5SDimitry Andric   size_t pos = symbol_name.find('@');
16180b57cec5SDimitry Andric   return symbol_name.substr(0, pos);
16190b57cec5SDimitry Andric }
16200b57cec5SDimitry Andric 
16210b57cec5SDimitry Andric // ParseSectionHeaders
ParseSectionHeaders()16220b57cec5SDimitry Andric size_t ObjectFileELF::ParseSectionHeaders() {
16230b57cec5SDimitry Andric   return GetSectionHeaderInfo(m_section_headers, m_data, m_header, m_uuid,
16240b57cec5SDimitry Andric                               m_gnu_debuglink_file, m_gnu_debuglink_crc,
16250b57cec5SDimitry Andric                               m_arch_spec);
16260b57cec5SDimitry Andric }
16270b57cec5SDimitry Andric 
16280b57cec5SDimitry Andric const ObjectFileELF::ELFSectionHeaderInfo *
GetSectionHeaderByIndex(lldb::user_id_t id)16290b57cec5SDimitry Andric ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id) {
16300b57cec5SDimitry Andric   if (!ParseSectionHeaders())
16310b57cec5SDimitry Andric     return nullptr;
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric   if (id < m_section_headers.size())
16340b57cec5SDimitry Andric     return &m_section_headers[id];
16350b57cec5SDimitry Andric 
16360b57cec5SDimitry Andric   return nullptr;
16370b57cec5SDimitry Andric }
16380b57cec5SDimitry Andric 
GetSectionIndexByName(const char * name)16390b57cec5SDimitry Andric lldb::user_id_t ObjectFileELF::GetSectionIndexByName(const char *name) {
16400b57cec5SDimitry Andric   if (!name || !name[0] || !ParseSectionHeaders())
16410b57cec5SDimitry Andric     return 0;
16420b57cec5SDimitry Andric   for (size_t i = 1; i < m_section_headers.size(); ++i)
16430b57cec5SDimitry Andric     if (m_section_headers[i].section_name == ConstString(name))
16440b57cec5SDimitry Andric       return i;
16450b57cec5SDimitry Andric   return 0;
16460b57cec5SDimitry Andric }
16470b57cec5SDimitry Andric 
GetSectionTypeFromName(llvm::StringRef Name)16480b57cec5SDimitry Andric static SectionType GetSectionTypeFromName(llvm::StringRef Name) {
1649fcaf7f86SDimitry Andric   if (Name.consume_front(".debug_")) {
16500b57cec5SDimitry Andric     return llvm::StringSwitch<SectionType>(Name)
16510b57cec5SDimitry Andric         .Case("abbrev", eSectionTypeDWARFDebugAbbrev)
16520b57cec5SDimitry Andric         .Case("abbrev.dwo", eSectionTypeDWARFDebugAbbrevDwo)
16530b57cec5SDimitry Andric         .Case("addr", eSectionTypeDWARFDebugAddr)
16540b57cec5SDimitry Andric         .Case("aranges", eSectionTypeDWARFDebugAranges)
16550b57cec5SDimitry Andric         .Case("cu_index", eSectionTypeDWARFDebugCuIndex)
16560b57cec5SDimitry Andric         .Case("frame", eSectionTypeDWARFDebugFrame)
16570b57cec5SDimitry Andric         .Case("info", eSectionTypeDWARFDebugInfo)
16580b57cec5SDimitry Andric         .Case("info.dwo", eSectionTypeDWARFDebugInfoDwo)
16590b57cec5SDimitry Andric         .Cases("line", "line.dwo", eSectionTypeDWARFDebugLine)
16600b57cec5SDimitry Andric         .Cases("line_str", "line_str.dwo", eSectionTypeDWARFDebugLineStr)
1661480093f4SDimitry Andric         .Case("loc", eSectionTypeDWARFDebugLoc)
1662480093f4SDimitry Andric         .Case("loc.dwo", eSectionTypeDWARFDebugLocDwo)
1663480093f4SDimitry Andric         .Case("loclists", eSectionTypeDWARFDebugLocLists)
1664480093f4SDimitry Andric         .Case("loclists.dwo", eSectionTypeDWARFDebugLocListsDwo)
16650b57cec5SDimitry Andric         .Case("macinfo", eSectionTypeDWARFDebugMacInfo)
16660b57cec5SDimitry Andric         .Cases("macro", "macro.dwo", eSectionTypeDWARFDebugMacro)
16670b57cec5SDimitry Andric         .Case("names", eSectionTypeDWARFDebugNames)
16680b57cec5SDimitry Andric         .Case("pubnames", eSectionTypeDWARFDebugPubNames)
16690b57cec5SDimitry Andric         .Case("pubtypes", eSectionTypeDWARFDebugPubTypes)
16700b57cec5SDimitry Andric         .Case("ranges", eSectionTypeDWARFDebugRanges)
16710b57cec5SDimitry Andric         .Case("rnglists", eSectionTypeDWARFDebugRngLists)
1672480093f4SDimitry Andric         .Case("rnglists.dwo", eSectionTypeDWARFDebugRngListsDwo)
16730b57cec5SDimitry Andric         .Case("str", eSectionTypeDWARFDebugStr)
16740b57cec5SDimitry Andric         .Case("str.dwo", eSectionTypeDWARFDebugStrDwo)
16750b57cec5SDimitry Andric         .Case("str_offsets", eSectionTypeDWARFDebugStrOffsets)
16760b57cec5SDimitry Andric         .Case("str_offsets.dwo", eSectionTypeDWARFDebugStrOffsetsDwo)
16775ffd83dbSDimitry Andric         .Case("tu_index", eSectionTypeDWARFDebugTuIndex)
16780b57cec5SDimitry Andric         .Case("types", eSectionTypeDWARFDebugTypes)
16790b57cec5SDimitry Andric         .Case("types.dwo", eSectionTypeDWARFDebugTypesDwo)
16800b57cec5SDimitry Andric         .Default(eSectionTypeOther);
16810b57cec5SDimitry Andric   }
16820b57cec5SDimitry Andric   return llvm::StringSwitch<SectionType>(Name)
16830b57cec5SDimitry Andric       .Case(".ARM.exidx", eSectionTypeARMexidx)
16840b57cec5SDimitry Andric       .Case(".ARM.extab", eSectionTypeARMextab)
16850b57cec5SDimitry Andric       .Cases(".bss", ".tbss", eSectionTypeZeroFill)
1686fe013be4SDimitry Andric       .Case(".ctf", eSectionTypeDebug)
16870b57cec5SDimitry Andric       .Cases(".data", ".tdata", eSectionTypeData)
16880b57cec5SDimitry Andric       .Case(".eh_frame", eSectionTypeEHFrame)
16890b57cec5SDimitry Andric       .Case(".gnu_debugaltlink", eSectionTypeDWARFGNUDebugAltLink)
16900b57cec5SDimitry Andric       .Case(".gosymtab", eSectionTypeGoSymtab)
16910b57cec5SDimitry Andric       .Case(".text", eSectionTypeCode)
1692c9157d92SDimitry Andric       .Case(".swift_ast", eSectionTypeSwiftModules)
16930b57cec5SDimitry Andric       .Default(eSectionTypeOther);
16940b57cec5SDimitry Andric }
16950b57cec5SDimitry Andric 
GetSectionType(const ELFSectionHeaderInfo & H) const16960b57cec5SDimitry Andric SectionType ObjectFileELF::GetSectionType(const ELFSectionHeaderInfo &H) const {
16970b57cec5SDimitry Andric   switch (H.sh_type) {
16980b57cec5SDimitry Andric   case SHT_PROGBITS:
16990b57cec5SDimitry Andric     if (H.sh_flags & SHF_EXECINSTR)
17000b57cec5SDimitry Andric       return eSectionTypeCode;
17010b57cec5SDimitry Andric     break;
17020b57cec5SDimitry Andric   case SHT_SYMTAB:
17030b57cec5SDimitry Andric     return eSectionTypeELFSymbolTable;
17040b57cec5SDimitry Andric   case SHT_DYNSYM:
17050b57cec5SDimitry Andric     return eSectionTypeELFDynamicSymbols;
17060b57cec5SDimitry Andric   case SHT_RELA:
17070b57cec5SDimitry Andric   case SHT_REL:
17080b57cec5SDimitry Andric     return eSectionTypeELFRelocationEntries;
17090b57cec5SDimitry Andric   case SHT_DYNAMIC:
17100b57cec5SDimitry Andric     return eSectionTypeELFDynamicLinkInfo;
17110b57cec5SDimitry Andric   }
17120b57cec5SDimitry Andric   return GetSectionTypeFromName(H.section_name.GetStringRef());
17130b57cec5SDimitry Andric }
17140b57cec5SDimitry Andric 
GetTargetByteSize(SectionType Type,const ArchSpec & arch)17150b57cec5SDimitry Andric static uint32_t GetTargetByteSize(SectionType Type, const ArchSpec &arch) {
17160b57cec5SDimitry Andric   switch (Type) {
17170b57cec5SDimitry Andric   case eSectionTypeData:
17180b57cec5SDimitry Andric   case eSectionTypeZeroFill:
17190b57cec5SDimitry Andric     return arch.GetDataByteSize();
17200b57cec5SDimitry Andric   case eSectionTypeCode:
17210b57cec5SDimitry Andric     return arch.GetCodeByteSize();
17220b57cec5SDimitry Andric   default:
17230b57cec5SDimitry Andric     return 1;
17240b57cec5SDimitry Andric   }
17250b57cec5SDimitry Andric }
17260b57cec5SDimitry Andric 
GetPermissions(const ELFSectionHeader & H)17270b57cec5SDimitry Andric static Permissions GetPermissions(const ELFSectionHeader &H) {
17280b57cec5SDimitry Andric   Permissions Perm = Permissions(0);
17290b57cec5SDimitry Andric   if (H.sh_flags & SHF_ALLOC)
17300b57cec5SDimitry Andric     Perm |= ePermissionsReadable;
17310b57cec5SDimitry Andric   if (H.sh_flags & SHF_WRITE)
17320b57cec5SDimitry Andric     Perm |= ePermissionsWritable;
17330b57cec5SDimitry Andric   if (H.sh_flags & SHF_EXECINSTR)
17340b57cec5SDimitry Andric     Perm |= ePermissionsExecutable;
17350b57cec5SDimitry Andric   return Perm;
17360b57cec5SDimitry Andric }
17370b57cec5SDimitry Andric 
GetPermissions(const ELFProgramHeader & H)17380b57cec5SDimitry Andric static Permissions GetPermissions(const ELFProgramHeader &H) {
17390b57cec5SDimitry Andric   Permissions Perm = Permissions(0);
17400b57cec5SDimitry Andric   if (H.p_flags & PF_R)
17410b57cec5SDimitry Andric     Perm |= ePermissionsReadable;
17420b57cec5SDimitry Andric   if (H.p_flags & PF_W)
17430b57cec5SDimitry Andric     Perm |= ePermissionsWritable;
17440b57cec5SDimitry Andric   if (H.p_flags & PF_X)
17450b57cec5SDimitry Andric     Perm |= ePermissionsExecutable;
17460b57cec5SDimitry Andric   return Perm;
17470b57cec5SDimitry Andric }
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric namespace {
17500b57cec5SDimitry Andric 
17510b57cec5SDimitry Andric using VMRange = lldb_private::Range<addr_t, addr_t>;
17520b57cec5SDimitry Andric 
17530b57cec5SDimitry Andric struct SectionAddressInfo {
17540b57cec5SDimitry Andric   SectionSP Segment;
17550b57cec5SDimitry Andric   VMRange Range;
17560b57cec5SDimitry Andric };
17570b57cec5SDimitry Andric 
17580b57cec5SDimitry Andric // (Unlinked) ELF object files usually have 0 for every section address, meaning
17590b57cec5SDimitry Andric // we need to compute synthetic addresses in order for "file addresses" from
17600b57cec5SDimitry Andric // different sections to not overlap. This class handles that logic.
17610b57cec5SDimitry Andric class VMAddressProvider {
17620b57cec5SDimitry Andric   using VMMap = llvm::IntervalMap<addr_t, SectionSP, 4,
17630b57cec5SDimitry Andric                                        llvm::IntervalMapHalfOpenInfo<addr_t>>;
17640b57cec5SDimitry Andric 
17650b57cec5SDimitry Andric   ObjectFile::Type ObjectType;
17660b57cec5SDimitry Andric   addr_t NextVMAddress = 0;
17670b57cec5SDimitry Andric   VMMap::Allocator Alloc;
176881ad6265SDimitry Andric   VMMap Segments{Alloc};
176981ad6265SDimitry Andric   VMMap Sections{Alloc};
177081ad6265SDimitry Andric   lldb_private::Log *Log = GetLog(LLDBLog::Modules);
17719dba64beSDimitry Andric   size_t SegmentCount = 0;
17729dba64beSDimitry Andric   std::string SegmentName;
17730b57cec5SDimitry Andric 
GetVMRange(const ELFSectionHeader & H)17740b57cec5SDimitry Andric   VMRange GetVMRange(const ELFSectionHeader &H) {
17750b57cec5SDimitry Andric     addr_t Address = H.sh_addr;
17760b57cec5SDimitry Andric     addr_t Size = H.sh_flags & SHF_ALLOC ? H.sh_size : 0;
1777c9157d92SDimitry Andric 
1778c9157d92SDimitry Andric     // When this is a debug file for relocatable file, the address is all zero
1779c9157d92SDimitry Andric     // and thus needs to use accumulate method
1780c9157d92SDimitry Andric     if ((ObjectType == ObjectFile::Type::eTypeObjectFile ||
1781c9157d92SDimitry Andric          (ObjectType == ObjectFile::Type::eTypeDebugInfo && H.sh_addr == 0)) &&
1782c9157d92SDimitry Andric         Segments.empty() && (H.sh_flags & SHF_ALLOC)) {
17830b57cec5SDimitry Andric       NextVMAddress =
17840b57cec5SDimitry Andric           llvm::alignTo(NextVMAddress, std::max<addr_t>(H.sh_addralign, 1));
17850b57cec5SDimitry Andric       Address = NextVMAddress;
17860b57cec5SDimitry Andric       NextVMAddress += Size;
17870b57cec5SDimitry Andric     }
17880b57cec5SDimitry Andric     return VMRange(Address, Size);
17890b57cec5SDimitry Andric   }
17900b57cec5SDimitry Andric 
17910b57cec5SDimitry Andric public:
VMAddressProvider(ObjectFile::Type Type,llvm::StringRef SegmentName)17929dba64beSDimitry Andric   VMAddressProvider(ObjectFile::Type Type, llvm::StringRef SegmentName)
17935ffd83dbSDimitry Andric       : ObjectType(Type), SegmentName(std::string(SegmentName)) {}
17949dba64beSDimitry Andric 
GetNextSegmentName() const17959dba64beSDimitry Andric   std::string GetNextSegmentName() const {
17969dba64beSDimitry Andric     return llvm::formatv("{0}[{1}]", SegmentName, SegmentCount).str();
17979dba64beSDimitry Andric   }
17980b57cec5SDimitry Andric 
GetAddressInfo(const ELFProgramHeader & H)1799bdd1243dSDimitry Andric   std::optional<VMRange> GetAddressInfo(const ELFProgramHeader &H) {
18000b57cec5SDimitry Andric     if (H.p_memsz == 0) {
18019dba64beSDimitry Andric       LLDB_LOG(Log, "Ignoring zero-sized {0} segment. Corrupt object file?",
18029dba64beSDimitry Andric                SegmentName);
1803bdd1243dSDimitry Andric       return std::nullopt;
18040b57cec5SDimitry Andric     }
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric     if (Segments.overlaps(H.p_vaddr, H.p_vaddr + H.p_memsz)) {
18079dba64beSDimitry Andric       LLDB_LOG(Log, "Ignoring overlapping {0} segment. Corrupt object file?",
18089dba64beSDimitry Andric                SegmentName);
1809bdd1243dSDimitry Andric       return std::nullopt;
18100b57cec5SDimitry Andric     }
18110b57cec5SDimitry Andric     return VMRange(H.p_vaddr, H.p_memsz);
18120b57cec5SDimitry Andric   }
18130b57cec5SDimitry Andric 
GetAddressInfo(const ELFSectionHeader & H)1814bdd1243dSDimitry Andric   std::optional<SectionAddressInfo> GetAddressInfo(const ELFSectionHeader &H) {
18150b57cec5SDimitry Andric     VMRange Range = GetVMRange(H);
18160b57cec5SDimitry Andric     SectionSP Segment;
18170b57cec5SDimitry Andric     auto It = Segments.find(Range.GetRangeBase());
18180b57cec5SDimitry Andric     if ((H.sh_flags & SHF_ALLOC) && It.valid()) {
18190b57cec5SDimitry Andric       addr_t MaxSize;
18200b57cec5SDimitry Andric       if (It.start() <= Range.GetRangeBase()) {
18210b57cec5SDimitry Andric         MaxSize = It.stop() - Range.GetRangeBase();
18220b57cec5SDimitry Andric         Segment = *It;
18230b57cec5SDimitry Andric       } else
18240b57cec5SDimitry Andric         MaxSize = It.start() - Range.GetRangeBase();
18250b57cec5SDimitry Andric       if (Range.GetByteSize() > MaxSize) {
18260b57cec5SDimitry Andric         LLDB_LOG(Log, "Shortening section crossing segment boundaries. "
18270b57cec5SDimitry Andric                       "Corrupt object file?");
18280b57cec5SDimitry Andric         Range.SetByteSize(MaxSize);
18290b57cec5SDimitry Andric       }
18300b57cec5SDimitry Andric     }
18310b57cec5SDimitry Andric     if (Range.GetByteSize() > 0 &&
18320b57cec5SDimitry Andric         Sections.overlaps(Range.GetRangeBase(), Range.GetRangeEnd())) {
18330b57cec5SDimitry Andric       LLDB_LOG(Log, "Ignoring overlapping section. Corrupt object file?");
1834bdd1243dSDimitry Andric       return std::nullopt;
18350b57cec5SDimitry Andric     }
18360b57cec5SDimitry Andric     if (Segment)
18370b57cec5SDimitry Andric       Range.Slide(-Segment->GetFileAddress());
18380b57cec5SDimitry Andric     return SectionAddressInfo{Segment, Range};
18390b57cec5SDimitry Andric   }
18400b57cec5SDimitry Andric 
AddSegment(const VMRange & Range,SectionSP Seg)18410b57cec5SDimitry Andric   void AddSegment(const VMRange &Range, SectionSP Seg) {
18420b57cec5SDimitry Andric     Segments.insert(Range.GetRangeBase(), Range.GetRangeEnd(), std::move(Seg));
18439dba64beSDimitry Andric     ++SegmentCount;
18440b57cec5SDimitry Andric   }
18450b57cec5SDimitry Andric 
AddSection(SectionAddressInfo Info,SectionSP Sect)18460b57cec5SDimitry Andric   void AddSection(SectionAddressInfo Info, SectionSP Sect) {
18470b57cec5SDimitry Andric     if (Info.Range.GetByteSize() == 0)
18480b57cec5SDimitry Andric       return;
18490b57cec5SDimitry Andric     if (Info.Segment)
18500b57cec5SDimitry Andric       Info.Range.Slide(Info.Segment->GetFileAddress());
18510b57cec5SDimitry Andric     Sections.insert(Info.Range.GetRangeBase(), Info.Range.GetRangeEnd(),
18520b57cec5SDimitry Andric                     std::move(Sect));
18530b57cec5SDimitry Andric   }
18540b57cec5SDimitry Andric };
18550b57cec5SDimitry Andric }
18560b57cec5SDimitry Andric 
CreateSections(SectionList & unified_section_list)18570b57cec5SDimitry Andric void ObjectFileELF::CreateSections(SectionList &unified_section_list) {
18580b57cec5SDimitry Andric   if (m_sections_up)
18590b57cec5SDimitry Andric     return;
18600b57cec5SDimitry Andric 
18619dba64beSDimitry Andric   m_sections_up = std::make_unique<SectionList>();
18629dba64beSDimitry Andric   VMAddressProvider regular_provider(GetType(), "PT_LOAD");
18639dba64beSDimitry Andric   VMAddressProvider tls_provider(GetType(), "PT_TLS");
18640b57cec5SDimitry Andric 
18650b57cec5SDimitry Andric   for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {
18660b57cec5SDimitry Andric     const ELFProgramHeader &PHdr = EnumPHdr.value();
18679dba64beSDimitry Andric     if (PHdr.p_type != PT_LOAD && PHdr.p_type != PT_TLS)
18680b57cec5SDimitry Andric       continue;
18690b57cec5SDimitry Andric 
18709dba64beSDimitry Andric     VMAddressProvider &provider =
18719dba64beSDimitry Andric         PHdr.p_type == PT_TLS ? tls_provider : regular_provider;
18729dba64beSDimitry Andric     auto InfoOr = provider.GetAddressInfo(PHdr);
18730b57cec5SDimitry Andric     if (!InfoOr)
18740b57cec5SDimitry Andric       continue;
18750b57cec5SDimitry Andric 
18760b57cec5SDimitry Andric     uint32_t Log2Align = llvm::Log2_64(std::max<elf_xword>(PHdr.p_align, 1));
18770b57cec5SDimitry Andric     SectionSP Segment = std::make_shared<Section>(
18789dba64beSDimitry Andric         GetModule(), this, SegmentID(EnumPHdr.index()),
18799dba64beSDimitry Andric         ConstString(provider.GetNextSegmentName()), eSectionTypeContainer,
18809dba64beSDimitry Andric         InfoOr->GetRangeBase(), InfoOr->GetByteSize(), PHdr.p_offset,
18819dba64beSDimitry Andric         PHdr.p_filesz, Log2Align, /*flags*/ 0);
18820b57cec5SDimitry Andric     Segment->SetPermissions(GetPermissions(PHdr));
18839dba64beSDimitry Andric     Segment->SetIsThreadSpecific(PHdr.p_type == PT_TLS);
18840b57cec5SDimitry Andric     m_sections_up->AddSection(Segment);
18850b57cec5SDimitry Andric 
18869dba64beSDimitry Andric     provider.AddSegment(*InfoOr, std::move(Segment));
18870b57cec5SDimitry Andric   }
18880b57cec5SDimitry Andric 
18890b57cec5SDimitry Andric   ParseSectionHeaders();
18900b57cec5SDimitry Andric   if (m_section_headers.empty())
18910b57cec5SDimitry Andric     return;
18920b57cec5SDimitry Andric 
18930b57cec5SDimitry Andric   for (SectionHeaderCollIter I = std::next(m_section_headers.begin());
18940b57cec5SDimitry Andric        I != m_section_headers.end(); ++I) {
18950b57cec5SDimitry Andric     const ELFSectionHeaderInfo &header = *I;
18960b57cec5SDimitry Andric 
18970b57cec5SDimitry Andric     ConstString &name = I->section_name;
18980b57cec5SDimitry Andric     const uint64_t file_size =
18990b57cec5SDimitry Andric         header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
19000b57cec5SDimitry Andric 
19019dba64beSDimitry Andric     VMAddressProvider &provider =
19029dba64beSDimitry Andric         header.sh_flags & SHF_TLS ? tls_provider : regular_provider;
19039dba64beSDimitry Andric     auto InfoOr = provider.GetAddressInfo(header);
19040b57cec5SDimitry Andric     if (!InfoOr)
19050b57cec5SDimitry Andric       continue;
19060b57cec5SDimitry Andric 
19070b57cec5SDimitry Andric     SectionType sect_type = GetSectionType(header);
19080b57cec5SDimitry Andric 
19090b57cec5SDimitry Andric     const uint32_t target_bytes_size =
19100b57cec5SDimitry Andric         GetTargetByteSize(sect_type, m_arch_spec);
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric     elf::elf_xword log2align =
19130b57cec5SDimitry Andric         (header.sh_addralign == 0) ? 0 : llvm::Log2_64(header.sh_addralign);
19140b57cec5SDimitry Andric 
19150b57cec5SDimitry Andric     SectionSP section_sp(new Section(
19160b57cec5SDimitry Andric         InfoOr->Segment, GetModule(), // Module to which this section belongs.
19170b57cec5SDimitry Andric         this,            // ObjectFile to which this section belongs and should
19180b57cec5SDimitry Andric                          // read section data from.
19190b57cec5SDimitry Andric         SectionIndex(I), // Section ID.
19200b57cec5SDimitry Andric         name,            // Section name.
19210b57cec5SDimitry Andric         sect_type,       // Section type.
19220b57cec5SDimitry Andric         InfoOr->Range.GetRangeBase(), // VM address.
19230b57cec5SDimitry Andric         InfoOr->Range.GetByteSize(),  // VM size in bytes of this section.
19240b57cec5SDimitry Andric         header.sh_offset,             // Offset of this section in the file.
19250b57cec5SDimitry Andric         file_size,           // Size of the section as found in the file.
19260b57cec5SDimitry Andric         log2align,           // Alignment of the section
19270b57cec5SDimitry Andric         header.sh_flags,     // Flags for this section.
19280b57cec5SDimitry Andric         target_bytes_size)); // Number of host bytes per target byte
19290b57cec5SDimitry Andric 
19300b57cec5SDimitry Andric     section_sp->SetPermissions(GetPermissions(header));
19310b57cec5SDimitry Andric     section_sp->SetIsThreadSpecific(header.sh_flags & SHF_TLS);
19320b57cec5SDimitry Andric     (InfoOr->Segment ? InfoOr->Segment->GetChildren() : *m_sections_up)
19330b57cec5SDimitry Andric         .AddSection(section_sp);
19349dba64beSDimitry Andric     provider.AddSection(std::move(*InfoOr), std::move(section_sp));
19350b57cec5SDimitry Andric   }
19360b57cec5SDimitry Andric 
19370b57cec5SDimitry Andric   // For eTypeDebugInfo files, the Symbol Vendor will take care of updating the
19380b57cec5SDimitry Andric   // unified section list.
19390b57cec5SDimitry Andric   if (GetType() != eTypeDebugInfo)
19400b57cec5SDimitry Andric     unified_section_list = *m_sections_up;
19419dba64beSDimitry Andric 
19429dba64beSDimitry Andric   // If there's a .gnu_debugdata section, we'll try to read the .symtab that's
19439dba64beSDimitry Andric   // embedded in there and replace the one in the original object file (if any).
19449dba64beSDimitry Andric   // If there's none in the orignal object file, we add it to it.
19459dba64beSDimitry Andric   if (auto gdd_obj_file = GetGnuDebugDataObjectFile()) {
19469dba64beSDimitry Andric     if (auto gdd_objfile_section_list = gdd_obj_file->GetSectionList()) {
19479dba64beSDimitry Andric       if (SectionSP symtab_section_sp =
19489dba64beSDimitry Andric               gdd_objfile_section_list->FindSectionByType(
19499dba64beSDimitry Andric                   eSectionTypeELFSymbolTable, true)) {
19509dba64beSDimitry Andric         SectionSP module_section_sp = unified_section_list.FindSectionByType(
19519dba64beSDimitry Andric             eSectionTypeELFSymbolTable, true);
19529dba64beSDimitry Andric         if (module_section_sp)
19539dba64beSDimitry Andric           unified_section_list.ReplaceSection(module_section_sp->GetID(),
19549dba64beSDimitry Andric                                               symtab_section_sp);
19559dba64beSDimitry Andric         else
19569dba64beSDimitry Andric           unified_section_list.AddSection(symtab_section_sp);
19579dba64beSDimitry Andric       }
19589dba64beSDimitry Andric     }
19599dba64beSDimitry Andric   }
19609dba64beSDimitry Andric }
19619dba64beSDimitry Andric 
GetGnuDebugDataObjectFile()19629dba64beSDimitry Andric std::shared_ptr<ObjectFileELF> ObjectFileELF::GetGnuDebugDataObjectFile() {
19639dba64beSDimitry Andric   if (m_gnu_debug_data_object_file != nullptr)
19649dba64beSDimitry Andric     return m_gnu_debug_data_object_file;
19659dba64beSDimitry Andric 
19669dba64beSDimitry Andric   SectionSP section =
19679dba64beSDimitry Andric       GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata"));
19689dba64beSDimitry Andric   if (!section)
19699dba64beSDimitry Andric     return nullptr;
19709dba64beSDimitry Andric 
19719dba64beSDimitry Andric   if (!lldb_private::lzma::isAvailable()) {
19729dba64beSDimitry Andric     GetModule()->ReportWarning(
19739dba64beSDimitry Andric         "No LZMA support found for reading .gnu_debugdata section");
19749dba64beSDimitry Andric     return nullptr;
19759dba64beSDimitry Andric   }
19769dba64beSDimitry Andric 
19779dba64beSDimitry Andric   // Uncompress the data
19789dba64beSDimitry Andric   DataExtractor data;
19799dba64beSDimitry Andric   section->GetSectionData(data);
19809dba64beSDimitry Andric   llvm::SmallVector<uint8_t, 0> uncompressedData;
19819dba64beSDimitry Andric   auto err = lldb_private::lzma::uncompress(data.GetData(), uncompressedData);
19829dba64beSDimitry Andric   if (err) {
19839dba64beSDimitry Andric     GetModule()->ReportWarning(
1984bdd1243dSDimitry Andric         "An error occurred while decompression the section {0}: {1}",
19859dba64beSDimitry Andric         section->GetName().AsCString(), llvm::toString(std::move(err)).c_str());
19869dba64beSDimitry Andric     return nullptr;
19879dba64beSDimitry Andric   }
19889dba64beSDimitry Andric 
19899dba64beSDimitry Andric   // Construct ObjectFileELF object from decompressed buffer
19909dba64beSDimitry Andric   DataBufferSP gdd_data_buf(
19919dba64beSDimitry Andric       new DataBufferHeap(uncompressedData.data(), uncompressedData.size()));
19929dba64beSDimitry Andric   auto fspec = GetFileSpec().CopyByAppendingPathComponent(
19939dba64beSDimitry Andric       llvm::StringRef("gnu_debugdata"));
19949dba64beSDimitry Andric   m_gnu_debug_data_object_file.reset(new ObjectFileELF(
19959dba64beSDimitry Andric       GetModule(), gdd_data_buf, 0, &fspec, 0, gdd_data_buf->GetByteSize()));
19969dba64beSDimitry Andric 
19979dba64beSDimitry Andric   // This line is essential; otherwise a breakpoint can be set but not hit.
19989dba64beSDimitry Andric   m_gnu_debug_data_object_file->SetType(ObjectFile::eTypeDebugInfo);
19999dba64beSDimitry Andric 
20009dba64beSDimitry Andric   ArchSpec spec = m_gnu_debug_data_object_file->GetArchitecture();
20019dba64beSDimitry Andric   if (spec && m_gnu_debug_data_object_file->SetModulesArchitecture(spec))
20029dba64beSDimitry Andric     return m_gnu_debug_data_object_file;
20039dba64beSDimitry Andric 
20049dba64beSDimitry Andric   return nullptr;
20050b57cec5SDimitry Andric }
20060b57cec5SDimitry Andric 
20070b57cec5SDimitry Andric // Find the arm/aarch64 mapping symbol character in the given symbol name.
20080b57cec5SDimitry Andric // Mapping symbols have the form of "$<char>[.<any>]*". Additionally we
20090b57cec5SDimitry Andric // recognize cases when the mapping symbol prefixed by an arbitrary string
20100b57cec5SDimitry Andric // because if a symbol prefix added to each symbol in the object file with
20110b57cec5SDimitry Andric // objcopy then the mapping symbols are also prefixed.
FindArmAarch64MappingSymbol(const char * symbol_name)20120b57cec5SDimitry Andric static char FindArmAarch64MappingSymbol(const char *symbol_name) {
20130b57cec5SDimitry Andric   if (!symbol_name)
20140b57cec5SDimitry Andric     return '\0';
20150b57cec5SDimitry Andric 
20160b57cec5SDimitry Andric   const char *dollar_pos = ::strchr(symbol_name, '$');
20170b57cec5SDimitry Andric   if (!dollar_pos || dollar_pos[1] == '\0')
20180b57cec5SDimitry Andric     return '\0';
20190b57cec5SDimitry Andric 
20200b57cec5SDimitry Andric   if (dollar_pos[2] == '\0' || dollar_pos[2] == '.')
20210b57cec5SDimitry Andric     return dollar_pos[1];
20220b57cec5SDimitry Andric   return '\0';
20230b57cec5SDimitry Andric }
20240b57cec5SDimitry Andric 
20250b57cec5SDimitry Andric #define STO_MIPS_ISA (3 << 6)
20260b57cec5SDimitry Andric #define STO_MICROMIPS (2 << 6)
20270b57cec5SDimitry Andric #define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS)
20280b57cec5SDimitry Andric 
20290b57cec5SDimitry Andric // private
ParseSymbols(Symtab * symtab,user_id_t start_id,SectionList * section_list,const size_t num_symbols,const DataExtractor & symtab_data,const DataExtractor & strtab_data)20300b57cec5SDimitry Andric unsigned ObjectFileELF::ParseSymbols(Symtab *symtab, user_id_t start_id,
20310b57cec5SDimitry Andric                                      SectionList *section_list,
20320b57cec5SDimitry Andric                                      const size_t num_symbols,
20330b57cec5SDimitry Andric                                      const DataExtractor &symtab_data,
20340b57cec5SDimitry Andric                                      const DataExtractor &strtab_data) {
20350b57cec5SDimitry Andric   ELFSymbol symbol;
20360b57cec5SDimitry Andric   lldb::offset_t offset = 0;
20370b57cec5SDimitry Andric 
20380b57cec5SDimitry Andric   static ConstString text_section_name(".text");
20390b57cec5SDimitry Andric   static ConstString init_section_name(".init");
20400b57cec5SDimitry Andric   static ConstString fini_section_name(".fini");
20410b57cec5SDimitry Andric   static ConstString ctors_section_name(".ctors");
20420b57cec5SDimitry Andric   static ConstString dtors_section_name(".dtors");
20430b57cec5SDimitry Andric 
20440b57cec5SDimitry Andric   static ConstString data_section_name(".data");
20450b57cec5SDimitry Andric   static ConstString rodata_section_name(".rodata");
20460b57cec5SDimitry Andric   static ConstString rodata1_section_name(".rodata1");
20470b57cec5SDimitry Andric   static ConstString data2_section_name(".data1");
20480b57cec5SDimitry Andric   static ConstString bss_section_name(".bss");
20490b57cec5SDimitry Andric   static ConstString opd_section_name(".opd"); // For ppc64
20500b57cec5SDimitry Andric 
20510b57cec5SDimitry Andric   // On Android the oatdata and the oatexec symbols in the oat and odex files
20520b57cec5SDimitry Andric   // covers the full .text section what causes issues with displaying unusable
20530b57cec5SDimitry Andric   // symbol name to the user and very slow unwinding speed because the
20540b57cec5SDimitry Andric   // instruction emulation based unwind plans try to emulate all instructions
20550b57cec5SDimitry Andric   // in these symbols. Don't add these symbols to the symbol list as they have
20560b57cec5SDimitry Andric   // no use for the debugger and they are causing a lot of trouble. Filtering
20570b57cec5SDimitry Andric   // can't be restricted to Android because this special object file don't
20580b57cec5SDimitry Andric   // contain the note section specifying the environment to Android but the
20590b57cec5SDimitry Andric   // custom extension and file name makes it highly unlikely that this will
20600b57cec5SDimitry Andric   // collide with anything else.
2061fe013be4SDimitry Andric   llvm::StringRef file_extension = m_file.GetFileNameExtension();
20620b57cec5SDimitry Andric   bool skip_oatdata_oatexec =
20630b57cec5SDimitry Andric       file_extension == ".oat" || file_extension == ".odex";
20640b57cec5SDimitry Andric 
20650b57cec5SDimitry Andric   ArchSpec arch = GetArchitecture();
20660b57cec5SDimitry Andric   ModuleSP module_sp(GetModule());
20670b57cec5SDimitry Andric   SectionList *module_section_list =
20680b57cec5SDimitry Andric       module_sp ? module_sp->GetSectionList() : nullptr;
20690b57cec5SDimitry Andric 
20700b57cec5SDimitry Andric   // Local cache to avoid doing a FindSectionByName for each symbol. The "const
20710b57cec5SDimitry Andric   // char*" key must came from a ConstString object so they can be compared by
20720b57cec5SDimitry Andric   // pointer
20730b57cec5SDimitry Andric   std::unordered_map<const char *, lldb::SectionSP> section_name_to_section;
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric   unsigned i;
20760b57cec5SDimitry Andric   for (i = 0; i < num_symbols; ++i) {
20770b57cec5SDimitry Andric     if (!symbol.Parse(symtab_data, &offset))
20780b57cec5SDimitry Andric       break;
20790b57cec5SDimitry Andric 
20800b57cec5SDimitry Andric     const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
20810b57cec5SDimitry Andric     if (!symbol_name)
20820b57cec5SDimitry Andric       symbol_name = "";
20830b57cec5SDimitry Andric 
20840b57cec5SDimitry Andric     // No need to add non-section symbols that have no names
20850b57cec5SDimitry Andric     if (symbol.getType() != STT_SECTION &&
20860b57cec5SDimitry Andric         (symbol_name == nullptr || symbol_name[0] == '\0'))
20870b57cec5SDimitry Andric       continue;
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric     // Skipping oatdata and oatexec sections if it is requested. See details
20900b57cec5SDimitry Andric     // above the definition of skip_oatdata_oatexec for the reasons.
20910b57cec5SDimitry Andric     if (skip_oatdata_oatexec && (::strcmp(symbol_name, "oatdata") == 0 ||
20920b57cec5SDimitry Andric                                  ::strcmp(symbol_name, "oatexec") == 0))
20930b57cec5SDimitry Andric       continue;
20940b57cec5SDimitry Andric 
20950b57cec5SDimitry Andric     SectionSP symbol_section_sp;
20960b57cec5SDimitry Andric     SymbolType symbol_type = eSymbolTypeInvalid;
20970b57cec5SDimitry Andric     Elf64_Half shndx = symbol.st_shndx;
20980b57cec5SDimitry Andric 
20990b57cec5SDimitry Andric     switch (shndx) {
21000b57cec5SDimitry Andric     case SHN_ABS:
21010b57cec5SDimitry Andric       symbol_type = eSymbolTypeAbsolute;
21020b57cec5SDimitry Andric       break;
21030b57cec5SDimitry Andric     case SHN_UNDEF:
21040b57cec5SDimitry Andric       symbol_type = eSymbolTypeUndefined;
21050b57cec5SDimitry Andric       break;
21060b57cec5SDimitry Andric     default:
21070b57cec5SDimitry Andric       symbol_section_sp = section_list->FindSectionByID(shndx);
21080b57cec5SDimitry Andric       break;
21090b57cec5SDimitry Andric     }
21100b57cec5SDimitry Andric 
21110b57cec5SDimitry Andric     // If a symbol is undefined do not process it further even if it has a STT
21120b57cec5SDimitry Andric     // type
21130b57cec5SDimitry Andric     if (symbol_type != eSymbolTypeUndefined) {
21140b57cec5SDimitry Andric       switch (symbol.getType()) {
21150b57cec5SDimitry Andric       default:
21160b57cec5SDimitry Andric       case STT_NOTYPE:
21170b57cec5SDimitry Andric         // The symbol's type is not specified.
21180b57cec5SDimitry Andric         break;
21190b57cec5SDimitry Andric 
21200b57cec5SDimitry Andric       case STT_OBJECT:
21210b57cec5SDimitry Andric         // The symbol is associated with a data object, such as a variable, an
21220b57cec5SDimitry Andric         // array, etc.
21230b57cec5SDimitry Andric         symbol_type = eSymbolTypeData;
21240b57cec5SDimitry Andric         break;
21250b57cec5SDimitry Andric 
21260b57cec5SDimitry Andric       case STT_FUNC:
21270b57cec5SDimitry Andric         // The symbol is associated with a function or other executable code.
21280b57cec5SDimitry Andric         symbol_type = eSymbolTypeCode;
21290b57cec5SDimitry Andric         break;
21300b57cec5SDimitry Andric 
21310b57cec5SDimitry Andric       case STT_SECTION:
21320b57cec5SDimitry Andric         // The symbol is associated with a section. Symbol table entries of
21330b57cec5SDimitry Andric         // this type exist primarily for relocation and normally have STB_LOCAL
21340b57cec5SDimitry Andric         // binding.
21350b57cec5SDimitry Andric         break;
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric       case STT_FILE:
21380b57cec5SDimitry Andric         // Conventionally, the symbol's name gives the name of the source file
21390b57cec5SDimitry Andric         // associated with the object file. A file symbol has STB_LOCAL
21400b57cec5SDimitry Andric         // binding, its section index is SHN_ABS, and it precedes the other
21410b57cec5SDimitry Andric         // STB_LOCAL symbols for the file, if it is present.
21420b57cec5SDimitry Andric         symbol_type = eSymbolTypeSourceFile;
21430b57cec5SDimitry Andric         break;
21440b57cec5SDimitry Andric 
21450b57cec5SDimitry Andric       case STT_GNU_IFUNC:
21460b57cec5SDimitry Andric         // The symbol is associated with an indirect function. The actual
21470b57cec5SDimitry Andric         // function will be resolved if it is referenced.
21480b57cec5SDimitry Andric         symbol_type = eSymbolTypeResolver;
21490b57cec5SDimitry Andric         break;
21500b57cec5SDimitry Andric       }
21510b57cec5SDimitry Andric     }
21520b57cec5SDimitry Andric 
21530b57cec5SDimitry Andric     if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) {
21540b57cec5SDimitry Andric       if (symbol_section_sp) {
21550b57cec5SDimitry Andric         ConstString sect_name = symbol_section_sp->GetName();
21560b57cec5SDimitry Andric         if (sect_name == text_section_name || sect_name == init_section_name ||
21570b57cec5SDimitry Andric             sect_name == fini_section_name || sect_name == ctors_section_name ||
21580b57cec5SDimitry Andric             sect_name == dtors_section_name) {
21590b57cec5SDimitry Andric           symbol_type = eSymbolTypeCode;
21600b57cec5SDimitry Andric         } else if (sect_name == data_section_name ||
21610b57cec5SDimitry Andric                    sect_name == data2_section_name ||
21620b57cec5SDimitry Andric                    sect_name == rodata_section_name ||
21630b57cec5SDimitry Andric                    sect_name == rodata1_section_name ||
21640b57cec5SDimitry Andric                    sect_name == bss_section_name) {
21650b57cec5SDimitry Andric           symbol_type = eSymbolTypeData;
21660b57cec5SDimitry Andric         }
21670b57cec5SDimitry Andric       }
21680b57cec5SDimitry Andric     }
21690b57cec5SDimitry Andric 
21700b57cec5SDimitry Andric     int64_t symbol_value_offset = 0;
21710b57cec5SDimitry Andric     uint32_t additional_flags = 0;
21720b57cec5SDimitry Andric 
21730b57cec5SDimitry Andric     if (arch.IsValid()) {
21740b57cec5SDimitry Andric       if (arch.GetMachine() == llvm::Triple::arm) {
21750b57cec5SDimitry Andric         if (symbol.getBinding() == STB_LOCAL) {
21760b57cec5SDimitry Andric           char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
21770b57cec5SDimitry Andric           if (symbol_type == eSymbolTypeCode) {
21780b57cec5SDimitry Andric             switch (mapping_symbol) {
21790b57cec5SDimitry Andric             case 'a':
21800b57cec5SDimitry Andric               // $a[.<any>]* - marks an ARM instruction sequence
21810b57cec5SDimitry Andric               m_address_class_map[symbol.st_value] = AddressClass::eCode;
21820b57cec5SDimitry Andric               break;
21830b57cec5SDimitry Andric             case 'b':
21840b57cec5SDimitry Andric             case 't':
21850b57cec5SDimitry Andric               // $b[.<any>]* - marks a THUMB BL instruction sequence
21860b57cec5SDimitry Andric               // $t[.<any>]* - marks a THUMB instruction sequence
21870b57cec5SDimitry Andric               m_address_class_map[symbol.st_value] =
21880b57cec5SDimitry Andric                   AddressClass::eCodeAlternateISA;
21890b57cec5SDimitry Andric               break;
21900b57cec5SDimitry Andric             case 'd':
21910b57cec5SDimitry Andric               // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
21920b57cec5SDimitry Andric               m_address_class_map[symbol.st_value] = AddressClass::eData;
21930b57cec5SDimitry Andric               break;
21940b57cec5SDimitry Andric             }
21950b57cec5SDimitry Andric           }
21960b57cec5SDimitry Andric           if (mapping_symbol)
21970b57cec5SDimitry Andric             continue;
21980b57cec5SDimitry Andric         }
21990b57cec5SDimitry Andric       } else if (arch.GetMachine() == llvm::Triple::aarch64) {
22000b57cec5SDimitry Andric         if (symbol.getBinding() == STB_LOCAL) {
22010b57cec5SDimitry Andric           char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
22020b57cec5SDimitry Andric           if (symbol_type == eSymbolTypeCode) {
22030b57cec5SDimitry Andric             switch (mapping_symbol) {
22040b57cec5SDimitry Andric             case 'x':
22050b57cec5SDimitry Andric               // $x[.<any>]* - marks an A64 instruction sequence
22060b57cec5SDimitry Andric               m_address_class_map[symbol.st_value] = AddressClass::eCode;
22070b57cec5SDimitry Andric               break;
22080b57cec5SDimitry Andric             case 'd':
22090b57cec5SDimitry Andric               // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
22100b57cec5SDimitry Andric               m_address_class_map[symbol.st_value] = AddressClass::eData;
22110b57cec5SDimitry Andric               break;
22120b57cec5SDimitry Andric             }
22130b57cec5SDimitry Andric           }
22140b57cec5SDimitry Andric           if (mapping_symbol)
22150b57cec5SDimitry Andric             continue;
22160b57cec5SDimitry Andric         }
22170b57cec5SDimitry Andric       }
22180b57cec5SDimitry Andric 
22190b57cec5SDimitry Andric       if (arch.GetMachine() == llvm::Triple::arm) {
22200b57cec5SDimitry Andric         if (symbol_type == eSymbolTypeCode) {
22210b57cec5SDimitry Andric           if (symbol.st_value & 1) {
22220b57cec5SDimitry Andric             // Subtracting 1 from the address effectively unsets the low order
22230b57cec5SDimitry Andric             // bit, which results in the address actually pointing to the
22240b57cec5SDimitry Andric             // beginning of the symbol. This delta will be used below in
22250b57cec5SDimitry Andric             // conjunction with symbol.st_value to produce the final
22260b57cec5SDimitry Andric             // symbol_value that we store in the symtab.
22270b57cec5SDimitry Andric             symbol_value_offset = -1;
22280b57cec5SDimitry Andric             m_address_class_map[symbol.st_value ^ 1] =
22290b57cec5SDimitry Andric                 AddressClass::eCodeAlternateISA;
22300b57cec5SDimitry Andric           } else {
22310b57cec5SDimitry Andric             // This address is ARM
22320b57cec5SDimitry Andric             m_address_class_map[symbol.st_value] = AddressClass::eCode;
22330b57cec5SDimitry Andric           }
22340b57cec5SDimitry Andric         }
22350b57cec5SDimitry Andric       }
22360b57cec5SDimitry Andric 
22370b57cec5SDimitry Andric       /*
22380b57cec5SDimitry Andric        * MIPS:
22390b57cec5SDimitry Andric        * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for
22400b57cec5SDimitry Andric        * MIPS).
22410b57cec5SDimitry Andric        * This allows processor to switch between microMIPS and MIPS without any
22420b57cec5SDimitry Andric        * need
22430b57cec5SDimitry Andric        * for special mode-control register. However, apart from .debug_line,
22440b57cec5SDimitry Andric        * none of
22450b57cec5SDimitry Andric        * the ELF/DWARF sections set the ISA bit (for symbol or section). Use
22460b57cec5SDimitry Andric        * st_other
22470b57cec5SDimitry Andric        * flag to check whether the symbol is microMIPS and then set the address
22480b57cec5SDimitry Andric        * class
22490b57cec5SDimitry Andric        * accordingly.
22500b57cec5SDimitry Andric       */
22510b57cec5SDimitry Andric       if (arch.IsMIPS()) {
22520b57cec5SDimitry Andric         if (IS_MICROMIPS(symbol.st_other))
22530b57cec5SDimitry Andric           m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
22540b57cec5SDimitry Andric         else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) {
22550b57cec5SDimitry Andric           symbol.st_value = symbol.st_value & (~1ull);
22560b57cec5SDimitry Andric           m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
22570b57cec5SDimitry Andric         } else {
22580b57cec5SDimitry Andric           if (symbol_type == eSymbolTypeCode)
22590b57cec5SDimitry Andric             m_address_class_map[symbol.st_value] = AddressClass::eCode;
22600b57cec5SDimitry Andric           else if (symbol_type == eSymbolTypeData)
22610b57cec5SDimitry Andric             m_address_class_map[symbol.st_value] = AddressClass::eData;
22620b57cec5SDimitry Andric           else
22630b57cec5SDimitry Andric             m_address_class_map[symbol.st_value] = AddressClass::eUnknown;
22640b57cec5SDimitry Andric         }
22650b57cec5SDimitry Andric       }
22660b57cec5SDimitry Andric     }
22670b57cec5SDimitry Andric 
22680b57cec5SDimitry Andric     // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB
22690b57cec5SDimitry Andric     // symbols. See above for more details.
22700b57cec5SDimitry Andric     uint64_t symbol_value = symbol.st_value + symbol_value_offset;
22710b57cec5SDimitry Andric 
22720b57cec5SDimitry Andric     if (symbol_section_sp &&
22730b57cec5SDimitry Andric         CalculateType() != ObjectFile::Type::eTypeObjectFile)
22740b57cec5SDimitry Andric       symbol_value -= symbol_section_sp->GetFileAddress();
22750b57cec5SDimitry Andric 
22760b57cec5SDimitry Andric     if (symbol_section_sp && module_section_list &&
22770b57cec5SDimitry Andric         module_section_list != section_list) {
22780b57cec5SDimitry Andric       ConstString sect_name = symbol_section_sp->GetName();
22790b57cec5SDimitry Andric       auto section_it = section_name_to_section.find(sect_name.GetCString());
22800b57cec5SDimitry Andric       if (section_it == section_name_to_section.end())
22810b57cec5SDimitry Andric         section_it =
22820b57cec5SDimitry Andric             section_name_to_section
22830b57cec5SDimitry Andric                 .emplace(sect_name.GetCString(),
22840b57cec5SDimitry Andric                          module_section_list->FindSectionByName(sect_name))
22850b57cec5SDimitry Andric                 .first;
22860b57cec5SDimitry Andric       if (section_it->second)
22870b57cec5SDimitry Andric         symbol_section_sp = section_it->second;
22880b57cec5SDimitry Andric     }
22890b57cec5SDimitry Andric 
22900b57cec5SDimitry Andric     bool is_global = symbol.getBinding() == STB_GLOBAL;
22910b57cec5SDimitry Andric     uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags;
22920b57cec5SDimitry Andric     llvm::StringRef symbol_ref(symbol_name);
22930b57cec5SDimitry Andric 
22940b57cec5SDimitry Andric     // Symbol names may contain @VERSION suffixes. Find those and strip them
22950b57cec5SDimitry Andric     // temporarily.
22960b57cec5SDimitry Andric     size_t version_pos = symbol_ref.find('@');
22970b57cec5SDimitry Andric     bool has_suffix = version_pos != llvm::StringRef::npos;
22980b57cec5SDimitry Andric     llvm::StringRef symbol_bare = symbol_ref.substr(0, version_pos);
22999dba64beSDimitry Andric     Mangled mangled(symbol_bare);
23000b57cec5SDimitry Andric 
23010b57cec5SDimitry Andric     // Now append the suffix back to mangled and unmangled names. Only do it if
23020b57cec5SDimitry Andric     // the demangling was successful (string is not empty).
23030b57cec5SDimitry Andric     if (has_suffix) {
23040b57cec5SDimitry Andric       llvm::StringRef suffix = symbol_ref.substr(version_pos);
23050b57cec5SDimitry Andric 
23060b57cec5SDimitry Andric       llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef();
23070b57cec5SDimitry Andric       if (!mangled_name.empty())
23080b57cec5SDimitry Andric         mangled.SetMangledName(ConstString((mangled_name + suffix).str()));
23090b57cec5SDimitry Andric 
23105ffd83dbSDimitry Andric       ConstString demangled = mangled.GetDemangledName();
23110b57cec5SDimitry Andric       llvm::StringRef demangled_name = demangled.GetStringRef();
23120b57cec5SDimitry Andric       if (!demangled_name.empty())
23130b57cec5SDimitry Andric         mangled.SetDemangledName(ConstString((demangled_name + suffix).str()));
23140b57cec5SDimitry Andric     }
23150b57cec5SDimitry Andric 
23160b57cec5SDimitry Andric     // In ELF all symbol should have a valid size but it is not true for some
23170b57cec5SDimitry Andric     // function symbols coming from hand written assembly. As none of the
23180b57cec5SDimitry Andric     // function symbol should have 0 size we try to calculate the size for
23190b57cec5SDimitry Andric     // these symbols in the symtab with saying that their original size is not
23200b57cec5SDimitry Andric     // valid.
23210b57cec5SDimitry Andric     bool symbol_size_valid =
23220b57cec5SDimitry Andric         symbol.st_size != 0 || symbol.getType() != STT_FUNC;
23230b57cec5SDimitry Andric 
23240b57cec5SDimitry Andric     Symbol dc_symbol(
23250b57cec5SDimitry Andric         i + start_id, // ID is the original symbol table index.
23260b57cec5SDimitry Andric         mangled,
23270b57cec5SDimitry Andric         symbol_type,                    // Type of this symbol
23280b57cec5SDimitry Andric         is_global,                      // Is this globally visible?
23290b57cec5SDimitry Andric         false,                          // Is this symbol debug info?
23300b57cec5SDimitry Andric         false,                          // Is this symbol a trampoline?
23310b57cec5SDimitry Andric         false,                          // Is this symbol artificial?
23320b57cec5SDimitry Andric         AddressRange(symbol_section_sp, // Section in which this symbol is
23330b57cec5SDimitry Andric                                         // defined or null.
23340b57cec5SDimitry Andric                      symbol_value,      // Offset in section or symbol value.
23350b57cec5SDimitry Andric                      symbol.st_size),   // Size in bytes of this symbol.
23360b57cec5SDimitry Andric         symbol_size_valid,              // Symbol size is valid
23370b57cec5SDimitry Andric         has_suffix,                     // Contains linker annotations?
23380b57cec5SDimitry Andric         flags);                         // Symbol flags.
2339480093f4SDimitry Andric     if (symbol.getBinding() == STB_WEAK)
2340480093f4SDimitry Andric       dc_symbol.SetIsWeak(true);
23410b57cec5SDimitry Andric     symtab->AddSymbol(dc_symbol);
23420b57cec5SDimitry Andric   }
23430b57cec5SDimitry Andric   return i;
23440b57cec5SDimitry Andric }
23450b57cec5SDimitry Andric 
ParseSymbolTable(Symtab * symbol_table,user_id_t start_id,lldb_private::Section * symtab)23460b57cec5SDimitry Andric unsigned ObjectFileELF::ParseSymbolTable(Symtab *symbol_table,
23470b57cec5SDimitry Andric                                          user_id_t start_id,
23480b57cec5SDimitry Andric                                          lldb_private::Section *symtab) {
23490b57cec5SDimitry Andric   if (symtab->GetObjectFile() != this) {
23500b57cec5SDimitry Andric     // If the symbol table section is owned by a different object file, have it
23510b57cec5SDimitry Andric     // do the parsing.
23520b57cec5SDimitry Andric     ObjectFileELF *obj_file_elf =
23530b57cec5SDimitry Andric         static_cast<ObjectFileELF *>(symtab->GetObjectFile());
23540b57cec5SDimitry Andric     return obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab);
23550b57cec5SDimitry Andric   }
23560b57cec5SDimitry Andric 
23570b57cec5SDimitry Andric   // Get section list for this object file.
23580b57cec5SDimitry Andric   SectionList *section_list = m_sections_up.get();
23590b57cec5SDimitry Andric   if (!section_list)
23600b57cec5SDimitry Andric     return 0;
23610b57cec5SDimitry Andric 
23620b57cec5SDimitry Andric   user_id_t symtab_id = symtab->GetID();
23630b57cec5SDimitry Andric   const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
23640b57cec5SDimitry Andric   assert(symtab_hdr->sh_type == SHT_SYMTAB ||
23650b57cec5SDimitry Andric          symtab_hdr->sh_type == SHT_DYNSYM);
23660b57cec5SDimitry Andric 
23670b57cec5SDimitry Andric   // sh_link: section header index of associated string table.
23680b57cec5SDimitry Andric   user_id_t strtab_id = symtab_hdr->sh_link;
23690b57cec5SDimitry Andric   Section *strtab = section_list->FindSectionByID(strtab_id).get();
23700b57cec5SDimitry Andric 
23710b57cec5SDimitry Andric   if (symtab && strtab) {
23720b57cec5SDimitry Andric     assert(symtab->GetObjectFile() == this);
23730b57cec5SDimitry Andric     assert(strtab->GetObjectFile() == this);
23740b57cec5SDimitry Andric 
23750b57cec5SDimitry Andric     DataExtractor symtab_data;
23760b57cec5SDimitry Andric     DataExtractor strtab_data;
23770b57cec5SDimitry Andric     if (ReadSectionData(symtab, symtab_data) &&
23780b57cec5SDimitry Andric         ReadSectionData(strtab, strtab_data)) {
23790b57cec5SDimitry Andric       size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
23800b57cec5SDimitry Andric 
23810b57cec5SDimitry Andric       return ParseSymbols(symbol_table, start_id, section_list, num_symbols,
23820b57cec5SDimitry Andric                           symtab_data, strtab_data);
23830b57cec5SDimitry Andric     }
23840b57cec5SDimitry Andric   }
23850b57cec5SDimitry Andric 
23860b57cec5SDimitry Andric   return 0;
23870b57cec5SDimitry Andric }
23880b57cec5SDimitry Andric 
ParseDynamicSymbols()23890b57cec5SDimitry Andric size_t ObjectFileELF::ParseDynamicSymbols() {
23900b57cec5SDimitry Andric   if (m_dynamic_symbols.size())
23910b57cec5SDimitry Andric     return m_dynamic_symbols.size();
23920b57cec5SDimitry Andric 
23930b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
23940b57cec5SDimitry Andric   if (!section_list)
23950b57cec5SDimitry Andric     return 0;
23960b57cec5SDimitry Andric 
23970b57cec5SDimitry Andric   // Find the SHT_DYNAMIC section.
23980b57cec5SDimitry Andric   Section *dynsym =
23990b57cec5SDimitry Andric       section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
24000b57cec5SDimitry Andric           .get();
24010b57cec5SDimitry Andric   if (!dynsym)
24020b57cec5SDimitry Andric     return 0;
24030b57cec5SDimitry Andric   assert(dynsym->GetObjectFile() == this);
24040b57cec5SDimitry Andric 
24050b57cec5SDimitry Andric   ELFDynamic symbol;
24060b57cec5SDimitry Andric   DataExtractor dynsym_data;
24070b57cec5SDimitry Andric   if (ReadSectionData(dynsym, dynsym_data)) {
24080b57cec5SDimitry Andric     const lldb::offset_t section_size = dynsym_data.GetByteSize();
24090b57cec5SDimitry Andric     lldb::offset_t cursor = 0;
24100b57cec5SDimitry Andric 
24110b57cec5SDimitry Andric     while (cursor < section_size) {
24120b57cec5SDimitry Andric       if (!symbol.Parse(dynsym_data, &cursor))
24130b57cec5SDimitry Andric         break;
24140b57cec5SDimitry Andric 
24150b57cec5SDimitry Andric       m_dynamic_symbols.push_back(symbol);
24160b57cec5SDimitry Andric     }
24170b57cec5SDimitry Andric   }
24180b57cec5SDimitry Andric 
24190b57cec5SDimitry Andric   return m_dynamic_symbols.size();
24200b57cec5SDimitry Andric }
24210b57cec5SDimitry Andric 
FindDynamicSymbol(unsigned tag)24220b57cec5SDimitry Andric const ELFDynamic *ObjectFileELF::FindDynamicSymbol(unsigned tag) {
24230b57cec5SDimitry Andric   if (!ParseDynamicSymbols())
24240b57cec5SDimitry Andric     return nullptr;
24250b57cec5SDimitry Andric 
24260b57cec5SDimitry Andric   DynamicSymbolCollIter I = m_dynamic_symbols.begin();
24270b57cec5SDimitry Andric   DynamicSymbolCollIter E = m_dynamic_symbols.end();
24280b57cec5SDimitry Andric   for (; I != E; ++I) {
24290b57cec5SDimitry Andric     ELFDynamic *symbol = &*I;
24300b57cec5SDimitry Andric 
24310b57cec5SDimitry Andric     if (symbol->d_tag == tag)
24320b57cec5SDimitry Andric       return symbol;
24330b57cec5SDimitry Andric   }
24340b57cec5SDimitry Andric 
24350b57cec5SDimitry Andric   return nullptr;
24360b57cec5SDimitry Andric }
24370b57cec5SDimitry Andric 
PLTRelocationType()24380b57cec5SDimitry Andric unsigned ObjectFileELF::PLTRelocationType() {
24390b57cec5SDimitry Andric   // DT_PLTREL
24400b57cec5SDimitry Andric   //  This member specifies the type of relocation entry to which the
24410b57cec5SDimitry Andric   //  procedure linkage table refers. The d_val member holds DT_REL or
24420b57cec5SDimitry Andric   //  DT_RELA, as appropriate. All relocations in a procedure linkage table
24430b57cec5SDimitry Andric   //  must use the same relocation.
24440b57cec5SDimitry Andric   const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
24450b57cec5SDimitry Andric 
24460b57cec5SDimitry Andric   if (symbol)
24470b57cec5SDimitry Andric     return symbol->d_val;
24480b57cec5SDimitry Andric 
24490b57cec5SDimitry Andric   return 0;
24500b57cec5SDimitry Andric }
24510b57cec5SDimitry Andric 
24520b57cec5SDimitry Andric // Returns the size of the normal plt entries and the offset of the first
24530b57cec5SDimitry Andric // normal plt entry. The 0th entry in the plt table is usually a resolution
24540b57cec5SDimitry Andric // entry which have different size in some architectures then the rest of the
24550b57cec5SDimitry Andric // plt entries.
24560b57cec5SDimitry Andric static std::pair<uint64_t, uint64_t>
GetPltEntrySizeAndOffset(const ELFSectionHeader * rel_hdr,const ELFSectionHeader * plt_hdr)24570b57cec5SDimitry Andric GetPltEntrySizeAndOffset(const ELFSectionHeader *rel_hdr,
24580b57cec5SDimitry Andric                          const ELFSectionHeader *plt_hdr) {
24590b57cec5SDimitry Andric   const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
24600b57cec5SDimitry Andric 
24610b57cec5SDimitry Andric   // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are
24620b57cec5SDimitry Andric   // 16 bytes. So round the entsize up by the alignment if addralign is set.
24630b57cec5SDimitry Andric   elf_xword plt_entsize =
24640b57cec5SDimitry Andric       plt_hdr->sh_addralign
24650b57cec5SDimitry Andric           ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign)
24660b57cec5SDimitry Andric           : plt_hdr->sh_entsize;
24670b57cec5SDimitry Andric 
24680b57cec5SDimitry Andric   // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly.
24690b57cec5SDimitry Andric   // PLT entries relocation code in general requires multiple instruction and
24700b57cec5SDimitry Andric   // should be greater than 4 bytes in most cases. Try to guess correct size
24710b57cec5SDimitry Andric   // just in case.
24720b57cec5SDimitry Andric   if (plt_entsize <= 4) {
24730b57cec5SDimitry Andric     // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the
24740b57cec5SDimitry Andric     // size of the plt entries based on the number of entries and the size of
24750b57cec5SDimitry Andric     // the plt section with the assumption that the size of the 0th entry is at
24760b57cec5SDimitry Andric     // least as big as the size of the normal entries and it isn't much bigger
24770b57cec5SDimitry Andric     // then that.
24780b57cec5SDimitry Andric     if (plt_hdr->sh_addralign)
24790b57cec5SDimitry Andric       plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign /
24800b57cec5SDimitry Andric                     (num_relocations + 1) * plt_hdr->sh_addralign;
24810b57cec5SDimitry Andric     else
24820b57cec5SDimitry Andric       plt_entsize = plt_hdr->sh_size / (num_relocations + 1);
24830b57cec5SDimitry Andric   }
24840b57cec5SDimitry Andric 
24850b57cec5SDimitry Andric   elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize;
24860b57cec5SDimitry Andric 
24870b57cec5SDimitry Andric   return std::make_pair(plt_entsize, plt_offset);
24880b57cec5SDimitry Andric }
24890b57cec5SDimitry Andric 
ParsePLTRelocations(Symtab * symbol_table,user_id_t start_id,unsigned rel_type,const ELFHeader * hdr,const ELFSectionHeader * rel_hdr,const ELFSectionHeader * plt_hdr,const ELFSectionHeader * sym_hdr,const lldb::SectionSP & plt_section_sp,DataExtractor & rel_data,DataExtractor & symtab_data,DataExtractor & strtab_data)24900b57cec5SDimitry Andric static unsigned ParsePLTRelocations(
24910b57cec5SDimitry Andric     Symtab *symbol_table, user_id_t start_id, unsigned rel_type,
24920b57cec5SDimitry Andric     const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
24930b57cec5SDimitry Andric     const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr,
24940b57cec5SDimitry Andric     const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data,
24950b57cec5SDimitry Andric     DataExtractor &symtab_data, DataExtractor &strtab_data) {
24960b57cec5SDimitry Andric   ELFRelocation rel(rel_type);
24970b57cec5SDimitry Andric   ELFSymbol symbol;
24980b57cec5SDimitry Andric   lldb::offset_t offset = 0;
24990b57cec5SDimitry Andric 
25000b57cec5SDimitry Andric   uint64_t plt_offset, plt_entsize;
25010b57cec5SDimitry Andric   std::tie(plt_entsize, plt_offset) =
25020b57cec5SDimitry Andric       GetPltEntrySizeAndOffset(rel_hdr, plt_hdr);
25030b57cec5SDimitry Andric   const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
25040b57cec5SDimitry Andric 
25050b57cec5SDimitry Andric   typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
25060b57cec5SDimitry Andric   reloc_info_fn reloc_type;
25070b57cec5SDimitry Andric   reloc_info_fn reloc_symbol;
25080b57cec5SDimitry Andric 
25090b57cec5SDimitry Andric   if (hdr->Is32Bit()) {
25100b57cec5SDimitry Andric     reloc_type = ELFRelocation::RelocType32;
25110b57cec5SDimitry Andric     reloc_symbol = ELFRelocation::RelocSymbol32;
25120b57cec5SDimitry Andric   } else {
25130b57cec5SDimitry Andric     reloc_type = ELFRelocation::RelocType64;
25140b57cec5SDimitry Andric     reloc_symbol = ELFRelocation::RelocSymbol64;
25150b57cec5SDimitry Andric   }
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric   unsigned slot_type = hdr->GetRelocationJumpSlotType();
25180b57cec5SDimitry Andric   unsigned i;
25190b57cec5SDimitry Andric   for (i = 0; i < num_relocations; ++i) {
25200b57cec5SDimitry Andric     if (!rel.Parse(rel_data, &offset))
25210b57cec5SDimitry Andric       break;
25220b57cec5SDimitry Andric 
25230b57cec5SDimitry Andric     if (reloc_type(rel) != slot_type)
25240b57cec5SDimitry Andric       continue;
25250b57cec5SDimitry Andric 
25260b57cec5SDimitry Andric     lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
25270b57cec5SDimitry Andric     if (!symbol.Parse(symtab_data, &symbol_offset))
25280b57cec5SDimitry Andric       break;
25290b57cec5SDimitry Andric 
25300b57cec5SDimitry Andric     const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
25310b57cec5SDimitry Andric     uint64_t plt_index = plt_offset + i * plt_entsize;
25320b57cec5SDimitry Andric 
25330b57cec5SDimitry Andric     Symbol jump_symbol(
25340b57cec5SDimitry Andric         i + start_id,          // Symbol table index
25350b57cec5SDimitry Andric         symbol_name,           // symbol name.
25360b57cec5SDimitry Andric         eSymbolTypeTrampoline, // Type of this symbol
25370b57cec5SDimitry Andric         false,                 // Is this globally visible?
25380b57cec5SDimitry Andric         false,                 // Is this symbol debug info?
25390b57cec5SDimitry Andric         true,                  // Is this symbol a trampoline?
25400b57cec5SDimitry Andric         true,                  // Is this symbol artificial?
25410b57cec5SDimitry Andric         plt_section_sp, // Section in which this symbol is defined or null.
25420b57cec5SDimitry Andric         plt_index,      // Offset in section or symbol value.
25430b57cec5SDimitry Andric         plt_entsize,    // Size in bytes of this symbol.
25440b57cec5SDimitry Andric         true,           // Size is valid
25450b57cec5SDimitry Andric         false,          // Contains linker annotations?
25460b57cec5SDimitry Andric         0);             // Symbol flags.
25470b57cec5SDimitry Andric 
25480b57cec5SDimitry Andric     symbol_table->AddSymbol(jump_symbol);
25490b57cec5SDimitry Andric   }
25500b57cec5SDimitry Andric 
25510b57cec5SDimitry Andric   return i;
25520b57cec5SDimitry Andric }
25530b57cec5SDimitry Andric 
25540b57cec5SDimitry Andric unsigned
ParseTrampolineSymbols(Symtab * symbol_table,user_id_t start_id,const ELFSectionHeaderInfo * rel_hdr,user_id_t rel_id)25550b57cec5SDimitry Andric ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table, user_id_t start_id,
25560b57cec5SDimitry Andric                                       const ELFSectionHeaderInfo *rel_hdr,
25570b57cec5SDimitry Andric                                       user_id_t rel_id) {
25580b57cec5SDimitry Andric   assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
25590b57cec5SDimitry Andric 
25600b57cec5SDimitry Andric   // The link field points to the associated symbol table.
25610b57cec5SDimitry Andric   user_id_t symtab_id = rel_hdr->sh_link;
25620b57cec5SDimitry Andric 
25630b57cec5SDimitry Andric   // If the link field doesn't point to the appropriate symbol name table then
25640b57cec5SDimitry Andric   // try to find it by name as some compiler don't fill in the link fields.
25650b57cec5SDimitry Andric   if (!symtab_id)
25660b57cec5SDimitry Andric     symtab_id = GetSectionIndexByName(".dynsym");
25670b57cec5SDimitry Andric 
25680b57cec5SDimitry Andric   // Get PLT section.  We cannot use rel_hdr->sh_info, since current linkers
25690b57cec5SDimitry Andric   // point that to the .got.plt or .got section instead of .plt.
25700b57cec5SDimitry Andric   user_id_t plt_id = GetSectionIndexByName(".plt");
25710b57cec5SDimitry Andric 
25720b57cec5SDimitry Andric   if (!symtab_id || !plt_id)
25730b57cec5SDimitry Andric     return 0;
25740b57cec5SDimitry Andric 
25750b57cec5SDimitry Andric   const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
25760b57cec5SDimitry Andric   if (!plt_hdr)
25770b57cec5SDimitry Andric     return 0;
25780b57cec5SDimitry Andric 
25790b57cec5SDimitry Andric   const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
25800b57cec5SDimitry Andric   if (!sym_hdr)
25810b57cec5SDimitry Andric     return 0;
25820b57cec5SDimitry Andric 
25830b57cec5SDimitry Andric   SectionList *section_list = m_sections_up.get();
25840b57cec5SDimitry Andric   if (!section_list)
25850b57cec5SDimitry Andric     return 0;
25860b57cec5SDimitry Andric 
25870b57cec5SDimitry Andric   Section *rel_section = section_list->FindSectionByID(rel_id).get();
25880b57cec5SDimitry Andric   if (!rel_section)
25890b57cec5SDimitry Andric     return 0;
25900b57cec5SDimitry Andric 
25910b57cec5SDimitry Andric   SectionSP plt_section_sp(section_list->FindSectionByID(plt_id));
25920b57cec5SDimitry Andric   if (!plt_section_sp)
25930b57cec5SDimitry Andric     return 0;
25940b57cec5SDimitry Andric 
25950b57cec5SDimitry Andric   Section *symtab = section_list->FindSectionByID(symtab_id).get();
25960b57cec5SDimitry Andric   if (!symtab)
25970b57cec5SDimitry Andric     return 0;
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric   // sh_link points to associated string table.
26000b57cec5SDimitry Andric   Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link).get();
26010b57cec5SDimitry Andric   if (!strtab)
26020b57cec5SDimitry Andric     return 0;
26030b57cec5SDimitry Andric 
26040b57cec5SDimitry Andric   DataExtractor rel_data;
26050b57cec5SDimitry Andric   if (!ReadSectionData(rel_section, rel_data))
26060b57cec5SDimitry Andric     return 0;
26070b57cec5SDimitry Andric 
26080b57cec5SDimitry Andric   DataExtractor symtab_data;
26090b57cec5SDimitry Andric   if (!ReadSectionData(symtab, symtab_data))
26100b57cec5SDimitry Andric     return 0;
26110b57cec5SDimitry Andric 
26120b57cec5SDimitry Andric   DataExtractor strtab_data;
26130b57cec5SDimitry Andric   if (!ReadSectionData(strtab, strtab_data))
26140b57cec5SDimitry Andric     return 0;
26150b57cec5SDimitry Andric 
26160b57cec5SDimitry Andric   unsigned rel_type = PLTRelocationType();
26170b57cec5SDimitry Andric   if (!rel_type)
26180b57cec5SDimitry Andric     return 0;
26190b57cec5SDimitry Andric 
26200b57cec5SDimitry Andric   return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header,
26210b57cec5SDimitry Andric                              rel_hdr, plt_hdr, sym_hdr, plt_section_sp,
26220b57cec5SDimitry Andric                              rel_data, symtab_data, strtab_data);
26230b57cec5SDimitry Andric }
26240b57cec5SDimitry Andric 
ApplyELF64ABS64Relocation(Symtab * symtab,ELFRelocation & rel,DataExtractor & debug_data,Section * rel_section)26251ac55f4cSDimitry Andric static void ApplyELF64ABS64Relocation(Symtab *symtab, ELFRelocation &rel,
26261ac55f4cSDimitry Andric                                       DataExtractor &debug_data,
26271ac55f4cSDimitry Andric                                       Section *rel_section) {
26281ac55f4cSDimitry Andric   Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol64(rel));
26291ac55f4cSDimitry Andric   if (symbol) {
26301ac55f4cSDimitry Andric     addr_t value = symbol->GetAddressRef().GetFileAddress();
26311ac55f4cSDimitry Andric     DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
26321ac55f4cSDimitry Andric     // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
26331ac55f4cSDimitry Andric     WritableDataBuffer *data_buffer =
26341ac55f4cSDimitry Andric         llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
26351ac55f4cSDimitry Andric     uint64_t *dst = reinterpret_cast<uint64_t *>(
26361ac55f4cSDimitry Andric         data_buffer->GetBytes() + rel_section->GetFileOffset() +
26371ac55f4cSDimitry Andric         ELFRelocation::RelocOffset64(rel));
26381ac55f4cSDimitry Andric     uint64_t val_offset = value + ELFRelocation::RelocAddend64(rel);
26391ac55f4cSDimitry Andric     memcpy(dst, &val_offset, sizeof(uint64_t));
26401ac55f4cSDimitry Andric   }
26411ac55f4cSDimitry Andric }
26421ac55f4cSDimitry Andric 
ApplyELF64ABS32Relocation(Symtab * symtab,ELFRelocation & rel,DataExtractor & debug_data,Section * rel_section,bool is_signed)26431ac55f4cSDimitry Andric static void ApplyELF64ABS32Relocation(Symtab *symtab, ELFRelocation &rel,
26441ac55f4cSDimitry Andric                                       DataExtractor &debug_data,
26451ac55f4cSDimitry Andric                                       Section *rel_section, bool is_signed) {
26461ac55f4cSDimitry Andric   Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol64(rel));
26471ac55f4cSDimitry Andric   if (symbol) {
26481ac55f4cSDimitry Andric     addr_t value = symbol->GetAddressRef().GetFileAddress();
26491ac55f4cSDimitry Andric     value += ELFRelocation::RelocAddend32(rel);
26501ac55f4cSDimitry Andric     if ((!is_signed && (value > UINT32_MAX)) ||
26511ac55f4cSDimitry Andric         (is_signed &&
26521ac55f4cSDimitry Andric          ((int64_t)value > INT32_MAX || (int64_t)value < INT32_MIN))) {
26531ac55f4cSDimitry Andric       Log *log = GetLog(LLDBLog::Modules);
26541ac55f4cSDimitry Andric       LLDB_LOGF(log, "Failed to apply debug info relocations");
26551ac55f4cSDimitry Andric       return;
26561ac55f4cSDimitry Andric     }
26571ac55f4cSDimitry Andric     uint32_t truncated_addr = (value & 0xFFFFFFFF);
26581ac55f4cSDimitry Andric     DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
26591ac55f4cSDimitry Andric     // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
26601ac55f4cSDimitry Andric     WritableDataBuffer *data_buffer =
26611ac55f4cSDimitry Andric         llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
26621ac55f4cSDimitry Andric     uint32_t *dst = reinterpret_cast<uint32_t *>(
26631ac55f4cSDimitry Andric         data_buffer->GetBytes() + rel_section->GetFileOffset() +
26641ac55f4cSDimitry Andric         ELFRelocation::RelocOffset32(rel));
26651ac55f4cSDimitry Andric     memcpy(dst, &truncated_addr, sizeof(uint32_t));
26661ac55f4cSDimitry Andric   }
26671ac55f4cSDimitry Andric }
26681ac55f4cSDimitry Andric 
ApplyELF32ABS32RelRelocation(Symtab * symtab,ELFRelocation & rel,DataExtractor & debug_data,Section * rel_section)2669fe013be4SDimitry Andric static void ApplyELF32ABS32RelRelocation(Symtab *symtab, ELFRelocation &rel,
2670fe013be4SDimitry Andric                                          DataExtractor &debug_data,
2671fe013be4SDimitry Andric                                          Section *rel_section) {
2672fe013be4SDimitry Andric   Log *log = GetLog(LLDBLog::Modules);
2673fe013be4SDimitry Andric   Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol32(rel));
2674fe013be4SDimitry Andric   if (symbol) {
2675fe013be4SDimitry Andric     addr_t value = symbol->GetAddressRef().GetFileAddress();
2676fe013be4SDimitry Andric     if (value == LLDB_INVALID_ADDRESS) {
2677fe013be4SDimitry Andric       const char *name = symbol->GetName().GetCString();
2678fe013be4SDimitry Andric       LLDB_LOGF(log, "Debug info symbol invalid: %s", name);
2679fe013be4SDimitry Andric       return;
2680fe013be4SDimitry Andric     }
2681fe013be4SDimitry Andric     assert(llvm::isUInt<32>(value) && "Valid addresses are 32-bit");
2682fe013be4SDimitry Andric     DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2683fe013be4SDimitry Andric     // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
2684fe013be4SDimitry Andric     WritableDataBuffer *data_buffer =
2685fe013be4SDimitry Andric         llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
2686fe013be4SDimitry Andric     uint8_t *dst = data_buffer->GetBytes() + rel_section->GetFileOffset() +
2687fe013be4SDimitry Andric                    ELFRelocation::RelocOffset32(rel);
2688fe013be4SDimitry Andric     // Implicit addend is stored inline as a signed value.
2689fe013be4SDimitry Andric     int32_t addend;
2690fe013be4SDimitry Andric     memcpy(&addend, dst, sizeof(int32_t));
2691fe013be4SDimitry Andric     // The sum must be positive. This extra check prevents UB from overflow in
2692fe013be4SDimitry Andric     // the actual range check below.
2693fe013be4SDimitry Andric     if (addend < 0 && static_cast<uint32_t>(-addend) > value) {
2694fe013be4SDimitry Andric       LLDB_LOGF(log, "Debug info relocation overflow: 0x%" PRIx64,
2695fe013be4SDimitry Andric                 static_cast<int64_t>(value) + addend);
2696fe013be4SDimitry Andric       return;
2697fe013be4SDimitry Andric     }
2698fe013be4SDimitry Andric     if (!llvm::isUInt<32>(value + addend)) {
2699fe013be4SDimitry Andric       LLDB_LOGF(log, "Debug info relocation out of range: 0x%" PRIx64, value);
2700fe013be4SDimitry Andric       return;
2701fe013be4SDimitry Andric     }
2702fe013be4SDimitry Andric     uint32_t addr = value + addend;
2703fe013be4SDimitry Andric     memcpy(dst, &addr, sizeof(uint32_t));
2704fe013be4SDimitry Andric   }
2705fe013be4SDimitry Andric }
2706fe013be4SDimitry Andric 
ApplyRelocations(Symtab * symtab,const ELFHeader * hdr,const ELFSectionHeader * rel_hdr,const ELFSectionHeader * symtab_hdr,const ELFSectionHeader * debug_hdr,DataExtractor & rel_data,DataExtractor & symtab_data,DataExtractor & debug_data,Section * rel_section)27070b57cec5SDimitry Andric unsigned ObjectFileELF::ApplyRelocations(
27080b57cec5SDimitry Andric     Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
27090b57cec5SDimitry Andric     const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr,
27100b57cec5SDimitry Andric     DataExtractor &rel_data, DataExtractor &symtab_data,
27110b57cec5SDimitry Andric     DataExtractor &debug_data, Section *rel_section) {
27120b57cec5SDimitry Andric   ELFRelocation rel(rel_hdr->sh_type);
27130b57cec5SDimitry Andric   lldb::addr_t offset = 0;
27140b57cec5SDimitry Andric   const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
27150b57cec5SDimitry Andric   typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
27160b57cec5SDimitry Andric   reloc_info_fn reloc_type;
27170b57cec5SDimitry Andric   reloc_info_fn reloc_symbol;
27180b57cec5SDimitry Andric 
27190b57cec5SDimitry Andric   if (hdr->Is32Bit()) {
27200b57cec5SDimitry Andric     reloc_type = ELFRelocation::RelocType32;
27210b57cec5SDimitry Andric     reloc_symbol = ELFRelocation::RelocSymbol32;
27220b57cec5SDimitry Andric   } else {
27230b57cec5SDimitry Andric     reloc_type = ELFRelocation::RelocType64;
27240b57cec5SDimitry Andric     reloc_symbol = ELFRelocation::RelocSymbol64;
27250b57cec5SDimitry Andric   }
27260b57cec5SDimitry Andric 
27270b57cec5SDimitry Andric   for (unsigned i = 0; i < num_relocations; ++i) {
2728bdd1243dSDimitry Andric     if (!rel.Parse(rel_data, &offset)) {
2729bdd1243dSDimitry Andric       GetModule()->ReportError(".rel{0}[{1:d}] failed to parse relocation",
2730bdd1243dSDimitry Andric                                rel_section->GetName().AsCString(), i);
27310b57cec5SDimitry Andric       break;
2732bdd1243dSDimitry Andric     }
27330b57cec5SDimitry Andric     Symbol *symbol = nullptr;
27340b57cec5SDimitry Andric 
27350b57cec5SDimitry Andric     if (hdr->Is32Bit()) {
2736fe013be4SDimitry Andric       switch (hdr->e_machine) {
2737fe013be4SDimitry Andric       case llvm::ELF::EM_ARM:
2738fe013be4SDimitry Andric         switch (reloc_type(rel)) {
2739fe013be4SDimitry Andric         case R_ARM_ABS32:
2740fe013be4SDimitry Andric           ApplyELF32ABS32RelRelocation(symtab, rel, debug_data, rel_section);
2741fe013be4SDimitry Andric           break;
2742fe013be4SDimitry Andric         case R_ARM_REL32:
2743fe013be4SDimitry Andric           GetModule()->ReportError("unsupported AArch32 relocation:"
2744fe013be4SDimitry Andric                                    " .rel{0}[{1}], type {2}",
2745fe013be4SDimitry Andric                                    rel_section->GetName().AsCString(), i,
2746fe013be4SDimitry Andric                                    reloc_type(rel));
2747fe013be4SDimitry Andric           break;
2748fe013be4SDimitry Andric         default:
2749fe013be4SDimitry Andric           assert(false && "unexpected relocation type");
2750fe013be4SDimitry Andric         }
2751fe013be4SDimitry Andric         break;
2752fe013be4SDimitry Andric       case llvm::ELF::EM_386:
27530b57cec5SDimitry Andric         switch (reloc_type(rel)) {
27540b57cec5SDimitry Andric         case R_386_32:
2755bdd1243dSDimitry Andric           symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2756bdd1243dSDimitry Andric           if (symbol) {
2757bdd1243dSDimitry Andric             addr_t f_offset =
2758bdd1243dSDimitry Andric                 rel_section->GetFileOffset() + ELFRelocation::RelocOffset32(rel);
2759bdd1243dSDimitry Andric             DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2760bdd1243dSDimitry Andric             // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
2761bdd1243dSDimitry Andric             WritableDataBuffer *data_buffer =
2762bdd1243dSDimitry Andric                 llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
2763bdd1243dSDimitry Andric             uint32_t *dst = reinterpret_cast<uint32_t *>(
2764bdd1243dSDimitry Andric                 data_buffer->GetBytes() + f_offset);
2765bdd1243dSDimitry Andric 
2766bdd1243dSDimitry Andric             addr_t value = symbol->GetAddressRef().GetFileAddress();
2767bdd1243dSDimitry Andric             if (rel.IsRela()) {
2768bdd1243dSDimitry Andric               value += ELFRelocation::RelocAddend32(rel);
2769bdd1243dSDimitry Andric             } else {
2770bdd1243dSDimitry Andric               value += *dst;
2771bdd1243dSDimitry Andric             }
2772bdd1243dSDimitry Andric             *dst = value;
2773bdd1243dSDimitry Andric           } else {
2774bdd1243dSDimitry Andric             GetModule()->ReportError(".rel{0}[{1}] unknown symbol id: {2:d}",
2775bdd1243dSDimitry Andric                                     rel_section->GetName().AsCString(), i,
2776bdd1243dSDimitry Andric                                     reloc_symbol(rel));
2777bdd1243dSDimitry Andric           }
2778bdd1243dSDimitry Andric           break;
2779fe013be4SDimitry Andric         case R_386_NONE:
27800b57cec5SDimitry Andric         case R_386_PC32:
2781fe013be4SDimitry Andric           GetModule()->ReportError("unsupported i386 relocation:"
2782bdd1243dSDimitry Andric                                    " .rel{0}[{1}], type {2}",
2783bdd1243dSDimitry Andric                                    rel_section->GetName().AsCString(), i,
2784bdd1243dSDimitry Andric                                    reloc_type(rel));
2785fe013be4SDimitry Andric           break;
2786fe013be4SDimitry Andric         default:
2787fe013be4SDimitry Andric           assert(false && "unexpected relocation type");
2788fe013be4SDimitry Andric           break;
2789fe013be4SDimitry Andric         }
2790fe013be4SDimitry Andric         break;
2791fe013be4SDimitry Andric       default:
2792fe013be4SDimitry Andric         GetModule()->ReportError("unsupported 32-bit ELF machine arch: {0}", hdr->e_machine);
2793fe013be4SDimitry Andric         break;
27940b57cec5SDimitry Andric       }
27950b57cec5SDimitry Andric     } else {
27961ac55f4cSDimitry Andric       switch (hdr->e_machine) {
27971ac55f4cSDimitry Andric       case llvm::ELF::EM_AARCH64:
27980b57cec5SDimitry Andric         switch (reloc_type(rel)) {
27990b57cec5SDimitry Andric         case R_AARCH64_ABS64:
28001ac55f4cSDimitry Andric           ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
28011ac55f4cSDimitry Andric           break;
28021ac55f4cSDimitry Andric         case R_AARCH64_ABS32:
28031ac55f4cSDimitry Andric           ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
28041ac55f4cSDimitry Andric           break;
28051ac55f4cSDimitry Andric         default:
28061ac55f4cSDimitry Andric           assert(false && "unexpected relocation type");
28070b57cec5SDimitry Andric         }
28080b57cec5SDimitry Andric         break;
28091ac55f4cSDimitry Andric       case llvm::ELF::EM_LOONGARCH:
28101ac55f4cSDimitry Andric         switch (reloc_type(rel)) {
28111ac55f4cSDimitry Andric         case R_LARCH_64:
28121ac55f4cSDimitry Andric           ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
28131ac55f4cSDimitry Andric           break;
28141ac55f4cSDimitry Andric         case R_LARCH_32:
28151ac55f4cSDimitry Andric           ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
28161ac55f4cSDimitry Andric           break;
28171ac55f4cSDimitry Andric         default:
28181ac55f4cSDimitry Andric           assert(false && "unexpected relocation type");
28190b57cec5SDimitry Andric         }
28201ac55f4cSDimitry Andric         break;
28211ac55f4cSDimitry Andric       case llvm::ELF::EM_X86_64:
28221ac55f4cSDimitry Andric         switch (reloc_type(rel)) {
28231ac55f4cSDimitry Andric         case R_X86_64_64:
28241ac55f4cSDimitry Andric           ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
28251ac55f4cSDimitry Andric           break;
28260b57cec5SDimitry Andric         case R_X86_64_32:
28271ac55f4cSDimitry Andric           ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section,
28281ac55f4cSDimitry Andric                                     false);
28291ac55f4cSDimitry Andric           break;
28300b57cec5SDimitry Andric         case R_X86_64_32S:
28311ac55f4cSDimitry Andric           ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
28320b57cec5SDimitry Andric           break;
28330b57cec5SDimitry Andric         case R_X86_64_PC32:
28340b57cec5SDimitry Andric         default:
28350b57cec5SDimitry Andric           assert(false && "unexpected relocation type");
28360b57cec5SDimitry Andric         }
28371ac55f4cSDimitry Andric         break;
28381ac55f4cSDimitry Andric       default:
2839fe013be4SDimitry Andric         GetModule()->ReportError("unsupported 64-bit ELF machine arch: {0}", hdr->e_machine);
2840fe013be4SDimitry Andric         break;
28411ac55f4cSDimitry Andric       }
28420b57cec5SDimitry Andric     }
28430b57cec5SDimitry Andric   }
28440b57cec5SDimitry Andric 
28450b57cec5SDimitry Andric   return 0;
28460b57cec5SDimitry Andric }
28470b57cec5SDimitry Andric 
RelocateDebugSections(const ELFSectionHeader * rel_hdr,user_id_t rel_id,lldb_private::Symtab * thetab)28480b57cec5SDimitry Andric unsigned ObjectFileELF::RelocateDebugSections(const ELFSectionHeader *rel_hdr,
28490b57cec5SDimitry Andric                                               user_id_t rel_id,
28500b57cec5SDimitry Andric                                               lldb_private::Symtab *thetab) {
28510b57cec5SDimitry Andric   assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
28520b57cec5SDimitry Andric 
28530b57cec5SDimitry Andric   // Parse in the section list if needed.
28540b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
28550b57cec5SDimitry Andric   if (!section_list)
28560b57cec5SDimitry Andric     return 0;
28570b57cec5SDimitry Andric 
28580b57cec5SDimitry Andric   user_id_t symtab_id = rel_hdr->sh_link;
28590b57cec5SDimitry Andric   user_id_t debug_id = rel_hdr->sh_info;
28600b57cec5SDimitry Andric 
28610b57cec5SDimitry Andric   const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
28620b57cec5SDimitry Andric   if (!symtab_hdr)
28630b57cec5SDimitry Andric     return 0;
28640b57cec5SDimitry Andric 
28650b57cec5SDimitry Andric   const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id);
28660b57cec5SDimitry Andric   if (!debug_hdr)
28670b57cec5SDimitry Andric     return 0;
28680b57cec5SDimitry Andric 
28690b57cec5SDimitry Andric   Section *rel = section_list->FindSectionByID(rel_id).get();
28700b57cec5SDimitry Andric   if (!rel)
28710b57cec5SDimitry Andric     return 0;
28720b57cec5SDimitry Andric 
28730b57cec5SDimitry Andric   Section *symtab = section_list->FindSectionByID(symtab_id).get();
28740b57cec5SDimitry Andric   if (!symtab)
28750b57cec5SDimitry Andric     return 0;
28760b57cec5SDimitry Andric 
28770b57cec5SDimitry Andric   Section *debug = section_list->FindSectionByID(debug_id).get();
28780b57cec5SDimitry Andric   if (!debug)
28790b57cec5SDimitry Andric     return 0;
28800b57cec5SDimitry Andric 
28810b57cec5SDimitry Andric   DataExtractor rel_data;
28820b57cec5SDimitry Andric   DataExtractor symtab_data;
28830b57cec5SDimitry Andric   DataExtractor debug_data;
28840b57cec5SDimitry Andric 
28850b57cec5SDimitry Andric   if (GetData(rel->GetFileOffset(), rel->GetFileSize(), rel_data) &&
28860b57cec5SDimitry Andric       GetData(symtab->GetFileOffset(), symtab->GetFileSize(), symtab_data) &&
28870b57cec5SDimitry Andric       GetData(debug->GetFileOffset(), debug->GetFileSize(), debug_data)) {
28880b57cec5SDimitry Andric     ApplyRelocations(thetab, &m_header, rel_hdr, symtab_hdr, debug_hdr,
28890b57cec5SDimitry Andric                      rel_data, symtab_data, debug_data, debug);
28900b57cec5SDimitry Andric   }
28910b57cec5SDimitry Andric 
28920b57cec5SDimitry Andric   return 0;
28930b57cec5SDimitry Andric }
28940b57cec5SDimitry Andric 
ParseSymtab(Symtab & lldb_symtab)28954824e7fdSDimitry Andric void ObjectFileELF::ParseSymtab(Symtab &lldb_symtab) {
28960b57cec5SDimitry Andric   ModuleSP module_sp(GetModule());
28970b57cec5SDimitry Andric   if (!module_sp)
28984824e7fdSDimitry Andric     return;
28994824e7fdSDimitry Andric 
2900*a58f00eaSDimitry Andric   Progress progress("Parsing symbol table",
2901*a58f00eaSDimitry Andric                     m_file.GetFilename().AsCString("<Unknown>"));
29024824e7fdSDimitry Andric   ElapsedTime elapsed(module_sp->GetSymtabParseTime());
29030b57cec5SDimitry Andric 
29040b57cec5SDimitry Andric   // We always want to use the main object file so we (hopefully) only have one
29050b57cec5SDimitry Andric   // cached copy of our symtab, dynamic sections, etc.
29060b57cec5SDimitry Andric   ObjectFile *module_obj_file = module_sp->GetObjectFile();
29070b57cec5SDimitry Andric   if (module_obj_file && module_obj_file != this)
29084824e7fdSDimitry Andric     return module_obj_file->ParseSymtab(lldb_symtab);
29090b57cec5SDimitry Andric 
29100b57cec5SDimitry Andric   SectionList *section_list = module_sp->GetSectionList();
29110b57cec5SDimitry Andric   if (!section_list)
29124824e7fdSDimitry Andric     return;
29130b57cec5SDimitry Andric 
29140b57cec5SDimitry Andric   uint64_t symbol_id = 0;
29150b57cec5SDimitry Andric 
29160b57cec5SDimitry Andric   // Sharable objects and dynamic executables usually have 2 distinct symbol
29170b57cec5SDimitry Andric   // tables, one named ".symtab", and the other ".dynsym". The dynsym is a
29180b57cec5SDimitry Andric   // smaller version of the symtab that only contains global symbols. The
29190b57cec5SDimitry Andric   // information found in the dynsym is therefore also found in the symtab,
29200b57cec5SDimitry Andric   // while the reverse is not necessarily true.
29210b57cec5SDimitry Andric   Section *symtab =
29220b57cec5SDimitry Andric       section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get();
29234824e7fdSDimitry Andric   if (symtab)
29244824e7fdSDimitry Andric     symbol_id += ParseSymbolTable(&lldb_symtab, symbol_id, symtab);
29250b57cec5SDimitry Andric 
29269dba64beSDimitry Andric   // The symtab section is non-allocable and can be stripped, while the
29279dba64beSDimitry Andric   // .dynsym section which should always be always be there. To support the
29289dba64beSDimitry Andric   // minidebuginfo case we parse .dynsym when there's a .gnu_debuginfo
29299dba64beSDimitry Andric   // section, nomatter if .symtab was already parsed or not. This is because
29309dba64beSDimitry Andric   // minidebuginfo normally removes the .symtab symbols which have their
29319dba64beSDimitry Andric   // matching .dynsym counterparts.
29329dba64beSDimitry Andric   if (!symtab ||
29339dba64beSDimitry Andric       GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata"))) {
29349dba64beSDimitry Andric     Section *dynsym =
29359dba64beSDimitry Andric         section_list->FindSectionByType(eSectionTypeELFDynamicSymbols, true)
29369dba64beSDimitry Andric             .get();
29374824e7fdSDimitry Andric     if (dynsym)
29384824e7fdSDimitry Andric       symbol_id += ParseSymbolTable(&lldb_symtab, symbol_id, dynsym);
29399dba64beSDimitry Andric   }
29409dba64beSDimitry Andric 
29410b57cec5SDimitry Andric   // DT_JMPREL
29420b57cec5SDimitry Andric   //      If present, this entry's d_ptr member holds the address of
29430b57cec5SDimitry Andric   //      relocation
29440b57cec5SDimitry Andric   //      entries associated solely with the procedure linkage table.
29450b57cec5SDimitry Andric   //      Separating
29460b57cec5SDimitry Andric   //      these relocation entries lets the dynamic linker ignore them during
29470b57cec5SDimitry Andric   //      process initialization, if lazy binding is enabled. If this entry is
29480b57cec5SDimitry Andric   //      present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
29490b57cec5SDimitry Andric   //      also be present.
29500b57cec5SDimitry Andric   const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
29510b57cec5SDimitry Andric   if (symbol) {
29520b57cec5SDimitry Andric     // Synthesize trampoline symbols to help navigate the PLT.
29530b57cec5SDimitry Andric     addr_t addr = symbol->d_ptr;
29540b57cec5SDimitry Andric     Section *reloc_section =
29550b57cec5SDimitry Andric         section_list->FindSectionContainingFileAddress(addr).get();
29560b57cec5SDimitry Andric     if (reloc_section) {
29570b57cec5SDimitry Andric       user_id_t reloc_id = reloc_section->GetID();
29580b57cec5SDimitry Andric       const ELFSectionHeaderInfo *reloc_header =
29590b57cec5SDimitry Andric           GetSectionHeaderByIndex(reloc_id);
29604824e7fdSDimitry Andric       if (reloc_header)
29614824e7fdSDimitry Andric         ParseTrampolineSymbols(&lldb_symtab, symbol_id, reloc_header, reloc_id);
29620b57cec5SDimitry Andric     }
2963fe6060f1SDimitry Andric   }
29640b57cec5SDimitry Andric 
29650b57cec5SDimitry Andric   if (DWARFCallFrameInfo *eh_frame =
29660b57cec5SDimitry Andric           GetModule()->GetUnwindTable().GetEHFrameInfo()) {
29674824e7fdSDimitry Andric     ParseUnwindSymbols(&lldb_symtab, eh_frame);
29680b57cec5SDimitry Andric   }
29690b57cec5SDimitry Andric 
29709dba64beSDimitry Andric   // In the event that there's no symbol entry for the entry point we'll
29715ffd83dbSDimitry Andric   // artificially create one. We delegate to the symtab object the figuring
29729dba64beSDimitry Andric   // out of the proper size, this will usually make it span til the next
29739dba64beSDimitry Andric   // symbol it finds in the section. This means that if there are missing
29749dba64beSDimitry Andric   // symbols the entry point might span beyond its function definition.
29759dba64beSDimitry Andric   // We're fine with this as it doesn't make it worse than not having a
29769dba64beSDimitry Andric   // symbol entry at all.
29779dba64beSDimitry Andric   if (CalculateType() == eTypeExecutable) {
29789dba64beSDimitry Andric     ArchSpec arch = GetArchitecture();
29799dba64beSDimitry Andric     auto entry_point_addr = GetEntryPointAddress();
29809dba64beSDimitry Andric     bool is_valid_entry_point =
29819dba64beSDimitry Andric         entry_point_addr.IsValid() && entry_point_addr.IsSectionOffset();
29829dba64beSDimitry Andric     addr_t entry_point_file_addr = entry_point_addr.GetFileAddress();
29834824e7fdSDimitry Andric     if (is_valid_entry_point && !lldb_symtab.FindSymbolContainingFileAddress(
29849dba64beSDimitry Andric                                     entry_point_file_addr)) {
29854824e7fdSDimitry Andric       uint64_t symbol_id = lldb_symtab.GetNumSymbols();
2986fe6060f1SDimitry Andric       // Don't set the name for any synthetic symbols, the Symbol
2987fe6060f1SDimitry Andric       // object will generate one if needed when the name is accessed
2988fe6060f1SDimitry Andric       // via accessors.
2989fe6060f1SDimitry Andric       SectionSP section_sp = entry_point_addr.GetSection();
2990fe6060f1SDimitry Andric       Symbol symbol(
2991fe6060f1SDimitry Andric           /*symID=*/symbol_id,
2992fe6060f1SDimitry Andric           /*name=*/llvm::StringRef(), // Name will be auto generated.
2993fe6060f1SDimitry Andric           /*type=*/eSymbolTypeCode,
2994fe6060f1SDimitry Andric           /*external=*/true,
2995fe6060f1SDimitry Andric           /*is_debug=*/false,
2996fe6060f1SDimitry Andric           /*is_trampoline=*/false,
2997fe6060f1SDimitry Andric           /*is_artificial=*/true,
2998fe6060f1SDimitry Andric           /*section_sp=*/section_sp,
2999fe6060f1SDimitry Andric           /*offset=*/0,
3000fe6060f1SDimitry Andric           /*size=*/0, // FDE can span multiple symbols so don't use its size.
3001fe6060f1SDimitry Andric           /*size_is_valid=*/false,
3002fe6060f1SDimitry Andric           /*contains_linker_annotations=*/false,
3003fe6060f1SDimitry Andric           /*flags=*/0);
30049dba64beSDimitry Andric       // When the entry point is arm thumb we need to explicitly set its
30059dba64beSDimitry Andric       // class address to reflect that. This is important because expression
30069dba64beSDimitry Andric       // evaluation relies on correctly setting a breakpoint at this
30079dba64beSDimitry Andric       // address.
30089dba64beSDimitry Andric       if (arch.GetMachine() == llvm::Triple::arm &&
3009fe6060f1SDimitry Andric           (entry_point_file_addr & 1)) {
3010fe6060f1SDimitry Andric         symbol.GetAddressRef().SetOffset(entry_point_addr.GetOffset() ^ 1);
30119dba64beSDimitry Andric         m_address_class_map[entry_point_file_addr ^ 1] =
30129dba64beSDimitry Andric             AddressClass::eCodeAlternateISA;
3013fe6060f1SDimitry Andric       } else {
30149dba64beSDimitry Andric         m_address_class_map[entry_point_file_addr] = AddressClass::eCode;
30159dba64beSDimitry Andric       }
30164824e7fdSDimitry Andric       lldb_symtab.AddSymbol(symbol);
3017fe6060f1SDimitry Andric     }
30189dba64beSDimitry Andric   }
30190b57cec5SDimitry Andric }
30200b57cec5SDimitry Andric 
RelocateSection(lldb_private::Section * section)30210b57cec5SDimitry Andric void ObjectFileELF::RelocateSection(lldb_private::Section *section)
30220b57cec5SDimitry Andric {
30230b57cec5SDimitry Andric   static const char *debug_prefix = ".debug";
30240b57cec5SDimitry Andric 
30250b57cec5SDimitry Andric   // Set relocated bit so we stop getting called, regardless of whether we
30260b57cec5SDimitry Andric   // actually relocate.
30270b57cec5SDimitry Andric   section->SetIsRelocated(true);
30280b57cec5SDimitry Andric 
30290b57cec5SDimitry Andric   // We only relocate in ELF relocatable files
30300b57cec5SDimitry Andric   if (CalculateType() != eTypeObjectFile)
30310b57cec5SDimitry Andric     return;
30320b57cec5SDimitry Andric 
30330b57cec5SDimitry Andric   const char *section_name = section->GetName().GetCString();
30340b57cec5SDimitry Andric   // Can't relocate that which can't be named
30350b57cec5SDimitry Andric   if (section_name == nullptr)
30360b57cec5SDimitry Andric     return;
30370b57cec5SDimitry Andric 
30380b57cec5SDimitry Andric   // We don't relocate non-debug sections at the moment
30390b57cec5SDimitry Andric   if (strncmp(section_name, debug_prefix, strlen(debug_prefix)))
30400b57cec5SDimitry Andric     return;
30410b57cec5SDimitry Andric 
30420b57cec5SDimitry Andric   // Relocation section names to look for
30430b57cec5SDimitry Andric   std::string needle = std::string(".rel") + section_name;
30440b57cec5SDimitry Andric   std::string needlea = std::string(".rela") + section_name;
30450b57cec5SDimitry Andric 
30460b57cec5SDimitry Andric   for (SectionHeaderCollIter I = m_section_headers.begin();
30470b57cec5SDimitry Andric        I != m_section_headers.end(); ++I) {
30480b57cec5SDimitry Andric     if (I->sh_type == SHT_RELA || I->sh_type == SHT_REL) {
30490b57cec5SDimitry Andric       const char *hay_name = I->section_name.GetCString();
30500b57cec5SDimitry Andric       if (hay_name == nullptr)
30510b57cec5SDimitry Andric         continue;
30520b57cec5SDimitry Andric       if (needle == hay_name || needlea == hay_name) {
30530b57cec5SDimitry Andric         const ELFSectionHeader &reloc_header = *I;
30540b57cec5SDimitry Andric         user_id_t reloc_id = SectionIndex(I);
30550b57cec5SDimitry Andric         RelocateDebugSections(&reloc_header, reloc_id, GetSymtab());
30560b57cec5SDimitry Andric         break;
30570b57cec5SDimitry Andric       }
30580b57cec5SDimitry Andric     }
30590b57cec5SDimitry Andric   }
30600b57cec5SDimitry Andric }
30610b57cec5SDimitry Andric 
ParseUnwindSymbols(Symtab * symbol_table,DWARFCallFrameInfo * eh_frame)30620b57cec5SDimitry Andric void ObjectFileELF::ParseUnwindSymbols(Symtab *symbol_table,
30630b57cec5SDimitry Andric                                        DWARFCallFrameInfo *eh_frame) {
30640b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
30650b57cec5SDimitry Andric   if (!section_list)
30660b57cec5SDimitry Andric     return;
30670b57cec5SDimitry Andric 
30680b57cec5SDimitry Andric   // First we save the new symbols into a separate list and add them to the
30695ffd83dbSDimitry Andric   // symbol table after we collected all symbols we want to add. This is
30700b57cec5SDimitry Andric   // neccessary because adding a new symbol invalidates the internal index of
30710b57cec5SDimitry Andric   // the symtab what causing the next lookup to be slow because it have to
30720b57cec5SDimitry Andric   // recalculate the index first.
30730b57cec5SDimitry Andric   std::vector<Symbol> new_symbols;
30740b57cec5SDimitry Andric 
3075fe6060f1SDimitry Andric   size_t num_symbols = symbol_table->GetNumSymbols();
3076fe6060f1SDimitry Andric   uint64_t last_symbol_id =
3077fe6060f1SDimitry Andric       num_symbols ? symbol_table->SymbolAtIndex(num_symbols - 1)->GetID() : 0;
3078fe6060f1SDimitry Andric   eh_frame->ForEachFDEEntries([&](lldb::addr_t file_addr, uint32_t size,
3079fe6060f1SDimitry Andric                                   dw_offset_t) {
30800b57cec5SDimitry Andric     Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr);
30810b57cec5SDimitry Andric     if (symbol) {
30820b57cec5SDimitry Andric       if (!symbol->GetByteSizeIsValid()) {
30830b57cec5SDimitry Andric         symbol->SetByteSize(size);
30840b57cec5SDimitry Andric         symbol->SetSizeIsSynthesized(true);
30850b57cec5SDimitry Andric       }
30860b57cec5SDimitry Andric     } else {
30870b57cec5SDimitry Andric       SectionSP section_sp =
30880b57cec5SDimitry Andric           section_list->FindSectionContainingFileAddress(file_addr);
30890b57cec5SDimitry Andric       if (section_sp) {
30900b57cec5SDimitry Andric         addr_t offset = file_addr - section_sp->GetFileAddress();
3091fe6060f1SDimitry Andric         uint64_t symbol_id = ++last_symbol_id;
3092fe6060f1SDimitry Andric         // Don't set the name for any synthetic symbols, the Symbol
3093fe6060f1SDimitry Andric         // object will generate one if needed when the name is accessed
3094fe6060f1SDimitry Andric         // via accessors.
30950b57cec5SDimitry Andric         Symbol eh_symbol(
3096fe6060f1SDimitry Andric             /*symID=*/symbol_id,
3097fe6060f1SDimitry Andric             /*name=*/llvm::StringRef(), // Name will be auto generated.
3098fe6060f1SDimitry Andric             /*type=*/eSymbolTypeCode,
3099fe6060f1SDimitry Andric             /*external=*/true,
3100fe6060f1SDimitry Andric             /*is_debug=*/false,
3101fe6060f1SDimitry Andric             /*is_trampoline=*/false,
3102fe6060f1SDimitry Andric             /*is_artificial=*/true,
3103fe6060f1SDimitry Andric             /*section_sp=*/section_sp,
3104fe6060f1SDimitry Andric             /*offset=*/offset,
3105fe6060f1SDimitry Andric             /*size=*/0, // FDE can span multiple symbols so don't use its size.
3106fe6060f1SDimitry Andric             /*size_is_valid=*/false,
3107fe6060f1SDimitry Andric             /*contains_linker_annotations=*/false,
3108fe6060f1SDimitry Andric             /*flags=*/0);
31090b57cec5SDimitry Andric         new_symbols.push_back(eh_symbol);
31100b57cec5SDimitry Andric       }
31110b57cec5SDimitry Andric     }
31120b57cec5SDimitry Andric     return true;
31130b57cec5SDimitry Andric   });
31140b57cec5SDimitry Andric 
31150b57cec5SDimitry Andric   for (const Symbol &s : new_symbols)
31160b57cec5SDimitry Andric     symbol_table->AddSymbol(s);
31170b57cec5SDimitry Andric }
31180b57cec5SDimitry Andric 
IsStripped()31190b57cec5SDimitry Andric bool ObjectFileELF::IsStripped() {
31200b57cec5SDimitry Andric   // TODO: determine this for ELF
31210b57cec5SDimitry Andric   return false;
31220b57cec5SDimitry Andric }
31230b57cec5SDimitry Andric 
31240b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
31250b57cec5SDimitry Andric // Dump
31260b57cec5SDimitry Andric //
31270b57cec5SDimitry Andric // Dump the specifics of the runtime file container (such as any headers
31280b57cec5SDimitry Andric // segments, sections, etc).
Dump(Stream * s)31290b57cec5SDimitry Andric void ObjectFileELF::Dump(Stream *s) {
31300b57cec5SDimitry Andric   ModuleSP module_sp(GetModule());
31310b57cec5SDimitry Andric   if (!module_sp) {
31320b57cec5SDimitry Andric     return;
31330b57cec5SDimitry Andric   }
31340b57cec5SDimitry Andric 
31350b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
31360b57cec5SDimitry Andric   s->Printf("%p: ", static_cast<void *>(this));
31370b57cec5SDimitry Andric   s->Indent();
31380b57cec5SDimitry Andric   s->PutCString("ObjectFileELF");
31390b57cec5SDimitry Andric 
31400b57cec5SDimitry Andric   ArchSpec header_arch = GetArchitecture();
31410b57cec5SDimitry Andric 
31420b57cec5SDimitry Andric   *s << ", file = '" << m_file
31430b57cec5SDimitry Andric      << "', arch = " << header_arch.GetArchitectureName() << "\n";
31440b57cec5SDimitry Andric 
31450b57cec5SDimitry Andric   DumpELFHeader(s, m_header);
31460b57cec5SDimitry Andric   s->EOL();
31470b57cec5SDimitry Andric   DumpELFProgramHeaders(s);
31480b57cec5SDimitry Andric   s->EOL();
31490b57cec5SDimitry Andric   DumpELFSectionHeaders(s);
31500b57cec5SDimitry Andric   s->EOL();
31510b57cec5SDimitry Andric   SectionList *section_list = GetSectionList();
31520b57cec5SDimitry Andric   if (section_list)
31535ffd83dbSDimitry Andric     section_list->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
31545ffd83dbSDimitry Andric                        UINT32_MAX);
31550b57cec5SDimitry Andric   Symtab *symtab = GetSymtab();
31560b57cec5SDimitry Andric   if (symtab)
31570b57cec5SDimitry Andric     symtab->Dump(s, nullptr, eSortOrderNone);
31580b57cec5SDimitry Andric   s->EOL();
31590b57cec5SDimitry Andric   DumpDependentModules(s);
31600b57cec5SDimitry Andric   s->EOL();
31610b57cec5SDimitry Andric }
31620b57cec5SDimitry Andric 
31630b57cec5SDimitry Andric // DumpELFHeader
31640b57cec5SDimitry Andric //
31650b57cec5SDimitry Andric // Dump the ELF header to the specified output stream
DumpELFHeader(Stream * s,const ELFHeader & header)31660b57cec5SDimitry Andric void ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header) {
31670b57cec5SDimitry Andric   s->PutCString("ELF Header\n");
31680b57cec5SDimitry Andric   s->Printf("e_ident[EI_MAG0   ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
31690b57cec5SDimitry Andric   s->Printf("e_ident[EI_MAG1   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG1],
31700b57cec5SDimitry Andric             header.e_ident[EI_MAG1]);
31710b57cec5SDimitry Andric   s->Printf("e_ident[EI_MAG2   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG2],
31720b57cec5SDimitry Andric             header.e_ident[EI_MAG2]);
31730b57cec5SDimitry Andric   s->Printf("e_ident[EI_MAG3   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG3],
31740b57cec5SDimitry Andric             header.e_ident[EI_MAG3]);
31750b57cec5SDimitry Andric 
31760b57cec5SDimitry Andric   s->Printf("e_ident[EI_CLASS  ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
31770b57cec5SDimitry Andric   s->Printf("e_ident[EI_DATA   ] = 0x%2.2x ", header.e_ident[EI_DATA]);
31780b57cec5SDimitry Andric   DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
31790b57cec5SDimitry Andric   s->Printf("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
31800b57cec5SDimitry Andric   s->Printf("e_ident[EI_PAD    ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
31810b57cec5SDimitry Andric 
31820b57cec5SDimitry Andric   s->Printf("e_type      = 0x%4.4x ", header.e_type);
31830b57cec5SDimitry Andric   DumpELFHeader_e_type(s, header.e_type);
31840b57cec5SDimitry Andric   s->Printf("\ne_machine   = 0x%4.4x\n", header.e_machine);
31850b57cec5SDimitry Andric   s->Printf("e_version   = 0x%8.8x\n", header.e_version);
31860b57cec5SDimitry Andric   s->Printf("e_entry     = 0x%8.8" PRIx64 "\n", header.e_entry);
31870b57cec5SDimitry Andric   s->Printf("e_phoff     = 0x%8.8" PRIx64 "\n", header.e_phoff);
31880b57cec5SDimitry Andric   s->Printf("e_shoff     = 0x%8.8" PRIx64 "\n", header.e_shoff);
31890b57cec5SDimitry Andric   s->Printf("e_flags     = 0x%8.8x\n", header.e_flags);
31900b57cec5SDimitry Andric   s->Printf("e_ehsize    = 0x%4.4x\n", header.e_ehsize);
31910b57cec5SDimitry Andric   s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
31920b57cec5SDimitry Andric   s->Printf("e_phnum     = 0x%8.8x\n", header.e_phnum);
31930b57cec5SDimitry Andric   s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
31940b57cec5SDimitry Andric   s->Printf("e_shnum     = 0x%8.8x\n", header.e_shnum);
31950b57cec5SDimitry Andric   s->Printf("e_shstrndx  = 0x%8.8x\n", header.e_shstrndx);
31960b57cec5SDimitry Andric }
31970b57cec5SDimitry Andric 
31980b57cec5SDimitry Andric // DumpELFHeader_e_type
31990b57cec5SDimitry Andric //
32000b57cec5SDimitry Andric // Dump an token value for the ELF header member e_type
DumpELFHeader_e_type(Stream * s,elf_half e_type)32010b57cec5SDimitry Andric void ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type) {
32020b57cec5SDimitry Andric   switch (e_type) {
32030b57cec5SDimitry Andric   case ET_NONE:
32040b57cec5SDimitry Andric     *s << "ET_NONE";
32050b57cec5SDimitry Andric     break;
32060b57cec5SDimitry Andric   case ET_REL:
32070b57cec5SDimitry Andric     *s << "ET_REL";
32080b57cec5SDimitry Andric     break;
32090b57cec5SDimitry Andric   case ET_EXEC:
32100b57cec5SDimitry Andric     *s << "ET_EXEC";
32110b57cec5SDimitry Andric     break;
32120b57cec5SDimitry Andric   case ET_DYN:
32130b57cec5SDimitry Andric     *s << "ET_DYN";
32140b57cec5SDimitry Andric     break;
32150b57cec5SDimitry Andric   case ET_CORE:
32160b57cec5SDimitry Andric     *s << "ET_CORE";
32170b57cec5SDimitry Andric     break;
32180b57cec5SDimitry Andric   default:
32190b57cec5SDimitry Andric     break;
32200b57cec5SDimitry Andric   }
32210b57cec5SDimitry Andric }
32220b57cec5SDimitry Andric 
32230b57cec5SDimitry Andric // DumpELFHeader_e_ident_EI_DATA
32240b57cec5SDimitry Andric //
32250b57cec5SDimitry Andric // Dump an token value for the ELF header member e_ident[EI_DATA]
DumpELFHeader_e_ident_EI_DATA(Stream * s,unsigned char ei_data)32260b57cec5SDimitry Andric void ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s,
32270b57cec5SDimitry Andric                                                   unsigned char ei_data) {
32280b57cec5SDimitry Andric   switch (ei_data) {
32290b57cec5SDimitry Andric   case ELFDATANONE:
32300b57cec5SDimitry Andric     *s << "ELFDATANONE";
32310b57cec5SDimitry Andric     break;
32320b57cec5SDimitry Andric   case ELFDATA2LSB:
32330b57cec5SDimitry Andric     *s << "ELFDATA2LSB - Little Endian";
32340b57cec5SDimitry Andric     break;
32350b57cec5SDimitry Andric   case ELFDATA2MSB:
32360b57cec5SDimitry Andric     *s << "ELFDATA2MSB - Big Endian";
32370b57cec5SDimitry Andric     break;
32380b57cec5SDimitry Andric   default:
32390b57cec5SDimitry Andric     break;
32400b57cec5SDimitry Andric   }
32410b57cec5SDimitry Andric }
32420b57cec5SDimitry Andric 
32430b57cec5SDimitry Andric // DumpELFProgramHeader
32440b57cec5SDimitry Andric //
32450b57cec5SDimitry Andric // Dump a single ELF program header to the specified output stream
DumpELFProgramHeader(Stream * s,const ELFProgramHeader & ph)32460b57cec5SDimitry Andric void ObjectFileELF::DumpELFProgramHeader(Stream *s,
32470b57cec5SDimitry Andric                                          const ELFProgramHeader &ph) {
32480b57cec5SDimitry Andric   DumpELFProgramHeader_p_type(s, ph.p_type);
32490b57cec5SDimitry Andric   s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset,
32500b57cec5SDimitry Andric             ph.p_vaddr, ph.p_paddr);
32510b57cec5SDimitry Andric   s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz,
32520b57cec5SDimitry Andric             ph.p_flags);
32530b57cec5SDimitry Andric 
32540b57cec5SDimitry Andric   DumpELFProgramHeader_p_flags(s, ph.p_flags);
32550b57cec5SDimitry Andric   s->Printf(") %8.8" PRIx64, ph.p_align);
32560b57cec5SDimitry Andric }
32570b57cec5SDimitry Andric 
32580b57cec5SDimitry Andric // DumpELFProgramHeader_p_type
32590b57cec5SDimitry Andric //
32600b57cec5SDimitry Andric // Dump an token value for the ELF program header member p_type which describes
32610b57cec5SDimitry Andric // the type of the program header
DumpELFProgramHeader_p_type(Stream * s,elf_word p_type)32620b57cec5SDimitry Andric void ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type) {
32630b57cec5SDimitry Andric   const int kStrWidth = 15;
32640b57cec5SDimitry Andric   switch (p_type) {
32650b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_NULL, kStrWidth);
32660b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_LOAD, kStrWidth);
32670b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_DYNAMIC, kStrWidth);
32680b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_INTERP, kStrWidth);
32690b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_NOTE, kStrWidth);
32700b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_SHLIB, kStrWidth);
32710b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_PHDR, kStrWidth);
32720b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_TLS, kStrWidth);
32730b57cec5SDimitry Andric     CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
32740b57cec5SDimitry Andric   default:
32750b57cec5SDimitry Andric     s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
32760b57cec5SDimitry Andric     break;
32770b57cec5SDimitry Andric   }
32780b57cec5SDimitry Andric }
32790b57cec5SDimitry Andric 
32800b57cec5SDimitry Andric // DumpELFProgramHeader_p_flags
32810b57cec5SDimitry Andric //
32820b57cec5SDimitry Andric // Dump an token value for the ELF program header member p_flags
DumpELFProgramHeader_p_flags(Stream * s,elf_word p_flags)32830b57cec5SDimitry Andric void ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags) {
32840b57cec5SDimitry Andric   *s << ((p_flags & PF_X) ? "PF_X" : "    ")
32850b57cec5SDimitry Andric      << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
32860b57cec5SDimitry Andric      << ((p_flags & PF_W) ? "PF_W" : "    ")
32870b57cec5SDimitry Andric      << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
32880b57cec5SDimitry Andric      << ((p_flags & PF_R) ? "PF_R" : "    ");
32890b57cec5SDimitry Andric }
32900b57cec5SDimitry Andric 
32910b57cec5SDimitry Andric // DumpELFProgramHeaders
32920b57cec5SDimitry Andric //
32930b57cec5SDimitry Andric // Dump all of the ELF program header to the specified output stream
DumpELFProgramHeaders(Stream * s)32940b57cec5SDimitry Andric void ObjectFileELF::DumpELFProgramHeaders(Stream *s) {
32950b57cec5SDimitry Andric   if (!ParseProgramHeaders())
32960b57cec5SDimitry Andric     return;
32970b57cec5SDimitry Andric 
32980b57cec5SDimitry Andric   s->PutCString("Program Headers\n");
32990b57cec5SDimitry Andric   s->PutCString("IDX  p_type          p_offset p_vaddr  p_paddr  "
33000b57cec5SDimitry Andric                 "p_filesz p_memsz  p_flags                   p_align\n");
33010b57cec5SDimitry Andric   s->PutCString("==== --------------- -------- -------- -------- "
33020b57cec5SDimitry Andric                 "-------- -------- ------------------------- --------\n");
33030b57cec5SDimitry Andric 
33040b57cec5SDimitry Andric   for (const auto &H : llvm::enumerate(m_program_headers)) {
33050b57cec5SDimitry Andric     s->Format("[{0,2}] ", H.index());
33060b57cec5SDimitry Andric     ObjectFileELF::DumpELFProgramHeader(s, H.value());
33070b57cec5SDimitry Andric     s->EOL();
33080b57cec5SDimitry Andric   }
33090b57cec5SDimitry Andric }
33100b57cec5SDimitry Andric 
33110b57cec5SDimitry Andric // DumpELFSectionHeader
33120b57cec5SDimitry Andric //
33130b57cec5SDimitry Andric // Dump a single ELF section header to the specified output stream
DumpELFSectionHeader(Stream * s,const ELFSectionHeaderInfo & sh)33140b57cec5SDimitry Andric void ObjectFileELF::DumpELFSectionHeader(Stream *s,
33150b57cec5SDimitry Andric                                          const ELFSectionHeaderInfo &sh) {
33160b57cec5SDimitry Andric   s->Printf("%8.8x ", sh.sh_name);
33170b57cec5SDimitry Andric   DumpELFSectionHeader_sh_type(s, sh.sh_type);
33180b57cec5SDimitry Andric   s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
33190b57cec5SDimitry Andric   DumpELFSectionHeader_sh_flags(s, sh.sh_flags);
33200b57cec5SDimitry Andric   s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr,
33210b57cec5SDimitry Andric             sh.sh_offset, sh.sh_size);
33220b57cec5SDimitry Andric   s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
33230b57cec5SDimitry Andric   s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
33240b57cec5SDimitry Andric }
33250b57cec5SDimitry Andric 
33260b57cec5SDimitry Andric // DumpELFSectionHeader_sh_type
33270b57cec5SDimitry Andric //
33280b57cec5SDimitry Andric // Dump an token value for the ELF section header member sh_type which
33290b57cec5SDimitry Andric // describes the type of the section
DumpELFSectionHeader_sh_type(Stream * s,elf_word sh_type)33300b57cec5SDimitry Andric void ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type) {
33310b57cec5SDimitry Andric   const int kStrWidth = 12;
33320b57cec5SDimitry Andric   switch (sh_type) {
33330b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_NULL, kStrWidth);
33340b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_PROGBITS, kStrWidth);
33350b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_SYMTAB, kStrWidth);
33360b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_STRTAB, kStrWidth);
33370b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_RELA, kStrWidth);
33380b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_HASH, kStrWidth);
33390b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_DYNAMIC, kStrWidth);
33400b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_NOTE, kStrWidth);
33410b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_NOBITS, kStrWidth);
33420b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_REL, kStrWidth);
33430b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth);
33440b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_DYNSYM, kStrWidth);
33450b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth);
33460b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth);
33470b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth);
33480b57cec5SDimitry Andric     CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth);
33490b57cec5SDimitry Andric   default:
33500b57cec5SDimitry Andric     s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
33510b57cec5SDimitry Andric     break;
33520b57cec5SDimitry Andric   }
33530b57cec5SDimitry Andric }
33540b57cec5SDimitry Andric 
33550b57cec5SDimitry Andric // DumpELFSectionHeader_sh_flags
33560b57cec5SDimitry Andric //
33570b57cec5SDimitry Andric // Dump an token value for the ELF section header member sh_flags
DumpELFSectionHeader_sh_flags(Stream * s,elf_xword sh_flags)33580b57cec5SDimitry Andric void ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s,
33590b57cec5SDimitry Andric                                                   elf_xword sh_flags) {
33600b57cec5SDimitry Andric   *s << ((sh_flags & SHF_WRITE) ? "WRITE" : "     ")
33610b57cec5SDimitry Andric      << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
33620b57cec5SDimitry Andric      << ((sh_flags & SHF_ALLOC) ? "ALLOC" : "     ")
33630b57cec5SDimitry Andric      << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
33640b57cec5SDimitry Andric      << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : "         ");
33650b57cec5SDimitry Andric }
33660b57cec5SDimitry Andric 
33670b57cec5SDimitry Andric // DumpELFSectionHeaders
33680b57cec5SDimitry Andric //
33690b57cec5SDimitry Andric // Dump all of the ELF section header to the specified output stream
DumpELFSectionHeaders(Stream * s)33700b57cec5SDimitry Andric void ObjectFileELF::DumpELFSectionHeaders(Stream *s) {
33710b57cec5SDimitry Andric   if (!ParseSectionHeaders())
33720b57cec5SDimitry Andric     return;
33730b57cec5SDimitry Andric 
33740b57cec5SDimitry Andric   s->PutCString("Section Headers\n");
33750b57cec5SDimitry Andric   s->PutCString("IDX  name     type         flags                            "
33760b57cec5SDimitry Andric                 "addr     offset   size     link     info     addralgn "
33770b57cec5SDimitry Andric                 "entsize  Name\n");
33780b57cec5SDimitry Andric   s->PutCString("==== -------- ------------ -------------------------------- "
33790b57cec5SDimitry Andric                 "-------- -------- -------- -------- -------- -------- "
33800b57cec5SDimitry Andric                 "-------- ====================\n");
33810b57cec5SDimitry Andric 
33820b57cec5SDimitry Andric   uint32_t idx = 0;
33830b57cec5SDimitry Andric   for (SectionHeaderCollConstIter I = m_section_headers.begin();
33840b57cec5SDimitry Andric        I != m_section_headers.end(); ++I, ++idx) {
33850b57cec5SDimitry Andric     s->Printf("[%2u] ", idx);
33860b57cec5SDimitry Andric     ObjectFileELF::DumpELFSectionHeader(s, *I);
33870b57cec5SDimitry Andric     const char *section_name = I->section_name.AsCString("");
33880b57cec5SDimitry Andric     if (section_name)
33890b57cec5SDimitry Andric       *s << ' ' << section_name << "\n";
33900b57cec5SDimitry Andric   }
33910b57cec5SDimitry Andric }
33920b57cec5SDimitry Andric 
DumpDependentModules(lldb_private::Stream * s)33930b57cec5SDimitry Andric void ObjectFileELF::DumpDependentModules(lldb_private::Stream *s) {
33940b57cec5SDimitry Andric   size_t num_modules = ParseDependentModules();
33950b57cec5SDimitry Andric 
33960b57cec5SDimitry Andric   if (num_modules > 0) {
33970b57cec5SDimitry Andric     s->PutCString("Dependent Modules:\n");
33980b57cec5SDimitry Andric     for (unsigned i = 0; i < num_modules; ++i) {
33990b57cec5SDimitry Andric       const FileSpec &spec = m_filespec_up->GetFileSpecAtIndex(i);
34000b57cec5SDimitry Andric       s->Printf("   %s\n", spec.GetFilename().GetCString());
34010b57cec5SDimitry Andric     }
34020b57cec5SDimitry Andric   }
34030b57cec5SDimitry Andric }
34040b57cec5SDimitry Andric 
GetArchitecture()34050b57cec5SDimitry Andric ArchSpec ObjectFileELF::GetArchitecture() {
34060b57cec5SDimitry Andric   if (!ParseHeader())
34070b57cec5SDimitry Andric     return ArchSpec();
34080b57cec5SDimitry Andric 
34090b57cec5SDimitry Andric   if (m_section_headers.empty()) {
34100b57cec5SDimitry Andric     // Allow elf notes to be parsed which may affect the detected architecture.
34110b57cec5SDimitry Andric     ParseSectionHeaders();
34120b57cec5SDimitry Andric   }
34130b57cec5SDimitry Andric 
34140b57cec5SDimitry Andric   if (CalculateType() == eTypeCoreFile &&
34150b57cec5SDimitry Andric       !m_arch_spec.TripleOSWasSpecified()) {
34160b57cec5SDimitry Andric     // Core files don't have section headers yet they have PT_NOTE program
34170b57cec5SDimitry Andric     // headers that might shed more light on the architecture
34180b57cec5SDimitry Andric     for (const elf::ELFProgramHeader &H : ProgramHeaders()) {
34190b57cec5SDimitry Andric       if (H.p_type != PT_NOTE || H.p_offset == 0 || H.p_filesz == 0)
34200b57cec5SDimitry Andric         continue;
34210b57cec5SDimitry Andric       DataExtractor data;
34220b57cec5SDimitry Andric       if (data.SetData(m_data, H.p_offset, H.p_filesz) == H.p_filesz) {
34230b57cec5SDimitry Andric         UUID uuid;
34240b57cec5SDimitry Andric         RefineModuleDetailsFromNote(data, m_arch_spec, uuid);
34250b57cec5SDimitry Andric       }
34260b57cec5SDimitry Andric     }
34270b57cec5SDimitry Andric   }
34280b57cec5SDimitry Andric   return m_arch_spec;
34290b57cec5SDimitry Andric }
34300b57cec5SDimitry Andric 
CalculateType()34310b57cec5SDimitry Andric ObjectFile::Type ObjectFileELF::CalculateType() {
34320b57cec5SDimitry Andric   switch (m_header.e_type) {
34330b57cec5SDimitry Andric   case llvm::ELF::ET_NONE:
34340b57cec5SDimitry Andric     // 0 - No file type
34350b57cec5SDimitry Andric     return eTypeUnknown;
34360b57cec5SDimitry Andric 
34370b57cec5SDimitry Andric   case llvm::ELF::ET_REL:
34380b57cec5SDimitry Andric     // 1 - Relocatable file
34390b57cec5SDimitry Andric     return eTypeObjectFile;
34400b57cec5SDimitry Andric 
34410b57cec5SDimitry Andric   case llvm::ELF::ET_EXEC:
34420b57cec5SDimitry Andric     // 2 - Executable file
34430b57cec5SDimitry Andric     return eTypeExecutable;
34440b57cec5SDimitry Andric 
34450b57cec5SDimitry Andric   case llvm::ELF::ET_DYN:
34460b57cec5SDimitry Andric     // 3 - Shared object file
34470b57cec5SDimitry Andric     return eTypeSharedLibrary;
34480b57cec5SDimitry Andric 
34490b57cec5SDimitry Andric   case ET_CORE:
34500b57cec5SDimitry Andric     // 4 - Core file
34510b57cec5SDimitry Andric     return eTypeCoreFile;
34520b57cec5SDimitry Andric 
34530b57cec5SDimitry Andric   default:
34540b57cec5SDimitry Andric     break;
34550b57cec5SDimitry Andric   }
34560b57cec5SDimitry Andric   return eTypeUnknown;
34570b57cec5SDimitry Andric }
34580b57cec5SDimitry Andric 
CalculateStrata()34590b57cec5SDimitry Andric ObjectFile::Strata ObjectFileELF::CalculateStrata() {
34600b57cec5SDimitry Andric   switch (m_header.e_type) {
34610b57cec5SDimitry Andric   case llvm::ELF::ET_NONE:
34620b57cec5SDimitry Andric     // 0 - No file type
34630b57cec5SDimitry Andric     return eStrataUnknown;
34640b57cec5SDimitry Andric 
34650b57cec5SDimitry Andric   case llvm::ELF::ET_REL:
34660b57cec5SDimitry Andric     // 1 - Relocatable file
34670b57cec5SDimitry Andric     return eStrataUnknown;
34680b57cec5SDimitry Andric 
34690b57cec5SDimitry Andric   case llvm::ELF::ET_EXEC:
34700b57cec5SDimitry Andric     // 2 - Executable file
3471c9157d92SDimitry Andric     {
3472c9157d92SDimitry Andric       SectionList *section_list = GetSectionList();
3473c9157d92SDimitry Andric       if (section_list) {
3474c9157d92SDimitry Andric         static ConstString loader_section_name(".interp");
3475c9157d92SDimitry Andric         SectionSP loader_section =
3476c9157d92SDimitry Andric             section_list->FindSectionByName(loader_section_name);
3477c9157d92SDimitry Andric         if (loader_section) {
3478c9157d92SDimitry Andric           char buffer[256];
3479c9157d92SDimitry Andric           size_t read_size =
3480c9157d92SDimitry Andric               ReadSectionData(loader_section.get(), 0, buffer, sizeof(buffer));
3481c9157d92SDimitry Andric 
3482c9157d92SDimitry Andric           // We compare the content of .interp section
3483c9157d92SDimitry Andric           // It will contains \0 when counting read_size, so the size needs to
3484c9157d92SDimitry Andric           // decrease by one
3485c9157d92SDimitry Andric           llvm::StringRef loader_name(buffer, read_size - 1);
3486c9157d92SDimitry Andric           llvm::StringRef freebsd_kernel_loader_name("/red/herring");
3487c9157d92SDimitry Andric           if (loader_name.equals(freebsd_kernel_loader_name))
3488c9157d92SDimitry Andric             return eStrataKernel;
3489c9157d92SDimitry Andric         }
3490c9157d92SDimitry Andric       }
34910b57cec5SDimitry Andric       return eStrataUser;
3492c9157d92SDimitry Andric     }
34930b57cec5SDimitry Andric 
34940b57cec5SDimitry Andric   case llvm::ELF::ET_DYN:
34950b57cec5SDimitry Andric     // 3 - Shared object file
34960b57cec5SDimitry Andric     // TODO: is there any way to detect that an shared library is a kernel
34970b57cec5SDimitry Andric     // related executable by inspecting the program headers, section headers,
34980b57cec5SDimitry Andric     // symbols, or any other flag bits???
34990b57cec5SDimitry Andric     return eStrataUnknown;
35000b57cec5SDimitry Andric 
35010b57cec5SDimitry Andric   case ET_CORE:
35020b57cec5SDimitry Andric     // 4 - Core file
35030b57cec5SDimitry Andric     // TODO: is there any way to detect that an core file is a kernel
35040b57cec5SDimitry Andric     // related executable by inspecting the program headers, section headers,
35050b57cec5SDimitry Andric     // symbols, or any other flag bits???
35060b57cec5SDimitry Andric     return eStrataUnknown;
35070b57cec5SDimitry Andric 
35080b57cec5SDimitry Andric   default:
35090b57cec5SDimitry Andric     break;
35100b57cec5SDimitry Andric   }
35110b57cec5SDimitry Andric   return eStrataUnknown;
35120b57cec5SDimitry Andric }
35130b57cec5SDimitry Andric 
ReadSectionData(Section * section,lldb::offset_t section_offset,void * dst,size_t dst_len)35140b57cec5SDimitry Andric size_t ObjectFileELF::ReadSectionData(Section *section,
35150b57cec5SDimitry Andric                        lldb::offset_t section_offset, void *dst,
35160b57cec5SDimitry Andric                        size_t dst_len) {
35170b57cec5SDimitry Andric   // If some other objectfile owns this data, pass this to them.
35180b57cec5SDimitry Andric   if (section->GetObjectFile() != this)
35190b57cec5SDimitry Andric     return section->GetObjectFile()->ReadSectionData(section, section_offset,
35200b57cec5SDimitry Andric                                                      dst, dst_len);
35210b57cec5SDimitry Andric 
35220b57cec5SDimitry Andric   if (!section->Test(SHF_COMPRESSED))
35230b57cec5SDimitry Andric     return ObjectFile::ReadSectionData(section, section_offset, dst, dst_len);
35240b57cec5SDimitry Andric 
35250b57cec5SDimitry Andric   // For compressed sections we need to read to full data to be able to
35260b57cec5SDimitry Andric   // decompress.
35270b57cec5SDimitry Andric   DataExtractor data;
35280b57cec5SDimitry Andric   ReadSectionData(section, data);
35290b57cec5SDimitry Andric   return data.CopyData(section_offset, dst_len, dst);
35300b57cec5SDimitry Andric }
35310b57cec5SDimitry Andric 
ReadSectionData(Section * section,DataExtractor & section_data)35320b57cec5SDimitry Andric size_t ObjectFileELF::ReadSectionData(Section *section,
35330b57cec5SDimitry Andric                                       DataExtractor &section_data) {
35340b57cec5SDimitry Andric   // If some other objectfile owns this data, pass this to them.
35350b57cec5SDimitry Andric   if (section->GetObjectFile() != this)
35360b57cec5SDimitry Andric     return section->GetObjectFile()->ReadSectionData(section, section_data);
35370b57cec5SDimitry Andric 
35380b57cec5SDimitry Andric   size_t result = ObjectFile::ReadSectionData(section, section_data);
3539fcaf7f86SDimitry Andric   if (result == 0 || !(section->Get() & llvm::ELF::SHF_COMPRESSED))
35400b57cec5SDimitry Andric     return result;
35410b57cec5SDimitry Andric 
35420b57cec5SDimitry Andric   auto Decompressor = llvm::object::Decompressor::create(
35430b57cec5SDimitry Andric       section->GetName().GetStringRef(),
35440b57cec5SDimitry Andric       {reinterpret_cast<const char *>(section_data.GetDataStart()),
35450b57cec5SDimitry Andric        size_t(section_data.GetByteSize())},
35460b57cec5SDimitry Andric       GetByteOrder() == eByteOrderLittle, GetAddressByteSize() == 8);
35470b57cec5SDimitry Andric   if (!Decompressor) {
35480b57cec5SDimitry Andric     GetModule()->ReportWarning(
3549bdd1243dSDimitry Andric         "Unable to initialize decompressor for section '{0}': {1}",
35500b57cec5SDimitry Andric         section->GetName().GetCString(),
35510b57cec5SDimitry Andric         llvm::toString(Decompressor.takeError()).c_str());
35520b57cec5SDimitry Andric     section_data.Clear();
35530b57cec5SDimitry Andric     return 0;
35540b57cec5SDimitry Andric   }
35550b57cec5SDimitry Andric 
35560b57cec5SDimitry Andric   auto buffer_sp =
35570b57cec5SDimitry Andric       std::make_shared<DataBufferHeap>(Decompressor->getDecompressedSize(), 0);
35580b57cec5SDimitry Andric   if (auto error = Decompressor->decompress(
3559753f127fSDimitry Andric           {buffer_sp->GetBytes(), size_t(buffer_sp->GetByteSize())})) {
3560bdd1243dSDimitry Andric     GetModule()->ReportWarning("Decompression of section '{0}' failed: {1}",
35610b57cec5SDimitry Andric                                section->GetName().GetCString(),
35620b57cec5SDimitry Andric                                llvm::toString(std::move(error)).c_str());
35630b57cec5SDimitry Andric     section_data.Clear();
35640b57cec5SDimitry Andric     return 0;
35650b57cec5SDimitry Andric   }
35660b57cec5SDimitry Andric 
35670b57cec5SDimitry Andric   section_data.SetData(buffer_sp);
35680b57cec5SDimitry Andric   return buffer_sp->GetByteSize();
35690b57cec5SDimitry Andric }
35700b57cec5SDimitry Andric 
ProgramHeaders()35710b57cec5SDimitry Andric llvm::ArrayRef<ELFProgramHeader> ObjectFileELF::ProgramHeaders() {
35720b57cec5SDimitry Andric   ParseProgramHeaders();
35730b57cec5SDimitry Andric   return m_program_headers;
35740b57cec5SDimitry Andric }
35750b57cec5SDimitry Andric 
GetSegmentData(const ELFProgramHeader & H)35760b57cec5SDimitry Andric DataExtractor ObjectFileELF::GetSegmentData(const ELFProgramHeader &H) {
35770b57cec5SDimitry Andric   return DataExtractor(m_data, H.p_offset, H.p_filesz);
35780b57cec5SDimitry Andric }
35790b57cec5SDimitry Andric 
AnySegmentHasPhysicalAddress()35800b57cec5SDimitry Andric bool ObjectFileELF::AnySegmentHasPhysicalAddress() {
35810b57cec5SDimitry Andric   for (const ELFProgramHeader &H : ProgramHeaders()) {
35820b57cec5SDimitry Andric     if (H.p_paddr != 0)
35830b57cec5SDimitry Andric       return true;
35840b57cec5SDimitry Andric   }
35850b57cec5SDimitry Andric   return false;
35860b57cec5SDimitry Andric }
35870b57cec5SDimitry Andric 
35880b57cec5SDimitry Andric std::vector<ObjectFile::LoadableData>
GetLoadableData(Target & target)35890b57cec5SDimitry Andric ObjectFileELF::GetLoadableData(Target &target) {
35900b57cec5SDimitry Andric   // Create a list of loadable data from loadable segments, using physical
35910b57cec5SDimitry Andric   // addresses if they aren't all null
35920b57cec5SDimitry Andric   std::vector<LoadableData> loadables;
35930b57cec5SDimitry Andric   bool should_use_paddr = AnySegmentHasPhysicalAddress();
35940b57cec5SDimitry Andric   for (const ELFProgramHeader &H : ProgramHeaders()) {
35950b57cec5SDimitry Andric     LoadableData loadable;
35960b57cec5SDimitry Andric     if (H.p_type != llvm::ELF::PT_LOAD)
35970b57cec5SDimitry Andric       continue;
35980b57cec5SDimitry Andric     loadable.Dest = should_use_paddr ? H.p_paddr : H.p_vaddr;
35990b57cec5SDimitry Andric     if (loadable.Dest == LLDB_INVALID_ADDRESS)
36000b57cec5SDimitry Andric       continue;
36010b57cec5SDimitry Andric     if (H.p_filesz == 0)
36020b57cec5SDimitry Andric       continue;
36030b57cec5SDimitry Andric     auto segment_data = GetSegmentData(H);
36040b57cec5SDimitry Andric     loadable.Contents = llvm::ArrayRef<uint8_t>(segment_data.GetDataStart(),
36050b57cec5SDimitry Andric                                                 segment_data.GetByteSize());
36060b57cec5SDimitry Andric     loadables.push_back(loadable);
36070b57cec5SDimitry Andric   }
36080b57cec5SDimitry Andric   return loadables;
36090b57cec5SDimitry Andric }
361081ad6265SDimitry Andric 
361181ad6265SDimitry Andric lldb::WritableDataBufferSP
MapFileDataWritable(const FileSpec & file,uint64_t Size,uint64_t Offset)361281ad6265SDimitry Andric ObjectFileELF::MapFileDataWritable(const FileSpec &file, uint64_t Size,
361381ad6265SDimitry Andric                                    uint64_t Offset) {
361481ad6265SDimitry Andric   return FileSystem::Instance().CreateWritableDataBuffer(file.GetPath(), Size,
361581ad6265SDimitry Andric                                                          Offset);
361681ad6265SDimitry Andric }
3617