xref: /llvm-project/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp (revision a08ba42f1a7b7fd200563758b0573bb4b2048822)
1 //===-- ObjectFileELF.cpp ------------------------------------- -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "ObjectFileELF.h"
11 
12 #include <algorithm>
13 #include <cassert>
14 #include <unordered_map>
15 
16 #include "lldb/Core/ArchSpec.h"
17 #include "lldb/Core/DataBuffer.h"
18 #include "lldb/Core/Error.h"
19 #include "lldb/Core/FileSpecList.h"
20 #include "lldb/Core/Log.h"
21 #include "lldb/Core/Module.h"
22 #include "lldb/Core/ModuleSpec.h"
23 #include "lldb/Core/PluginManager.h"
24 #include "lldb/Core/Section.h"
25 #include "lldb/Core/Stream.h"
26 #include "lldb/Core/Timer.h"
27 #include "lldb/Symbol/DWARFCallFrameInfo.h"
28 #include "lldb/Symbol/SymbolContext.h"
29 #include "lldb/Target/SectionLoadList.h"
30 #include "lldb/Target/Target.h"
31 
32 #include "llvm/ADT/PointerUnion.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/Support/ARMBuildAttributes.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/MipsABIFlags.h"
37 
38 #define CASE_AND_STREAM(s, def, width)                                         \
39   case def:                                                                    \
40     s->Printf("%-*s", width, #def);                                            \
41     break;
42 
43 using namespace lldb;
44 using namespace lldb_private;
45 using namespace elf;
46 using namespace llvm::ELF;
47 
48 namespace {
49 
50 // ELF note owner definitions
51 const char *const LLDB_NT_OWNER_FREEBSD = "FreeBSD";
52 const char *const LLDB_NT_OWNER_GNU = "GNU";
53 const char *const LLDB_NT_OWNER_NETBSD = "NetBSD";
54 const char *const LLDB_NT_OWNER_CSR = "csr";
55 const char *const LLDB_NT_OWNER_ANDROID = "Android";
56 const char *const LLDB_NT_OWNER_CORE = "CORE";
57 const char *const LLDB_NT_OWNER_LINUX = "LINUX";
58 
59 // ELF note type definitions
60 const elf_word LLDB_NT_FREEBSD_ABI_TAG = 0x01;
61 const elf_word LLDB_NT_FREEBSD_ABI_SIZE = 4;
62 
63 const elf_word LLDB_NT_GNU_ABI_TAG = 0x01;
64 const elf_word LLDB_NT_GNU_ABI_SIZE = 16;
65 
66 const elf_word LLDB_NT_GNU_BUILD_ID_TAG = 0x03;
67 
68 const elf_word LLDB_NT_NETBSD_ABI_TAG = 0x01;
69 const elf_word LLDB_NT_NETBSD_ABI_SIZE = 4;
70 
71 // GNU ABI note OS constants
72 const elf_word LLDB_NT_GNU_ABI_OS_LINUX = 0x00;
73 const elf_word LLDB_NT_GNU_ABI_OS_HURD = 0x01;
74 const elf_word LLDB_NT_GNU_ABI_OS_SOLARIS = 0x02;
75 
76 // LLDB_NT_OWNER_CORE and LLDB_NT_OWNER_LINUX note contants
77 #define NT_PRSTATUS 1
78 #define NT_PRFPREG 2
79 #define NT_PRPSINFO 3
80 #define NT_TASKSTRUCT 4
81 #define NT_AUXV 6
82 #define NT_SIGINFO 0x53494749
83 #define NT_FILE 0x46494c45
84 #define NT_PRXFPREG 0x46e62b7f
85 #define NT_PPC_VMX 0x100
86 #define NT_PPC_SPE 0x101
87 #define NT_PPC_VSX 0x102
88 #define NT_386_TLS 0x200
89 #define NT_386_IOPERM 0x201
90 #define NT_X86_XSTATE 0x202
91 #define NT_S390_HIGH_GPRS 0x300
92 #define NT_S390_TIMER 0x301
93 #define NT_S390_TODCMP 0x302
94 #define NT_S390_TODPREG 0x303
95 #define NT_S390_CTRS 0x304
96 #define NT_S390_PREFIX 0x305
97 #define NT_S390_LAST_BREAK 0x306
98 #define NT_S390_SYSTEM_CALL 0x307
99 #define NT_S390_TDB 0x308
100 #define NT_S390_VXRS_LOW 0x309
101 #define NT_S390_VXRS_HIGH 0x30a
102 #define NT_ARM_VFP 0x400
103 #define NT_ARM_TLS 0x401
104 #define NT_ARM_HW_BREAK 0x402
105 #define NT_ARM_HW_WATCH 0x403
106 #define NT_ARM_SYSTEM_CALL 0x404
107 #define NT_METAG_CBUF 0x500
108 #define NT_METAG_RPIPE 0x501
109 #define NT_METAG_TLS 0x502
110 
111 //===----------------------------------------------------------------------===//
112 /// @class ELFRelocation
113 /// @brief Generic wrapper for ELFRel and ELFRela.
114 ///
115 /// This helper class allows us to parse both ELFRel and ELFRela relocation
116 /// entries in a generic manner.
117 class ELFRelocation {
118 public:
119   /// Constructs an ELFRelocation entry with a personality as given by @p
120   /// type.
121   ///
122   /// @param type Either DT_REL or DT_RELA.  Any other value is invalid.
123   ELFRelocation(unsigned type);
124 
125   ~ELFRelocation();
126 
127   bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset);
128 
129   static unsigned RelocType32(const ELFRelocation &rel);
130 
131   static unsigned RelocType64(const ELFRelocation &rel);
132 
133   static unsigned RelocSymbol32(const ELFRelocation &rel);
134 
135   static unsigned RelocSymbol64(const ELFRelocation &rel);
136 
137   static unsigned RelocOffset32(const ELFRelocation &rel);
138 
139   static unsigned RelocOffset64(const ELFRelocation &rel);
140 
141   static unsigned RelocAddend32(const ELFRelocation &rel);
142 
143   static unsigned RelocAddend64(const ELFRelocation &rel);
144 
145 private:
146   typedef llvm::PointerUnion<ELFRel *, ELFRela *> RelocUnion;
147 
148   RelocUnion reloc;
149 };
150 
151 ELFRelocation::ELFRelocation(unsigned type) {
152   if (type == DT_REL || type == SHT_REL)
153     reloc = new ELFRel();
154   else if (type == DT_RELA || type == SHT_RELA)
155     reloc = new ELFRela();
156   else {
157     assert(false && "unexpected relocation type");
158     reloc = static_cast<ELFRel *>(NULL);
159   }
160 }
161 
162 ELFRelocation::~ELFRelocation() {
163   if (reloc.is<ELFRel *>())
164     delete reloc.get<ELFRel *>();
165   else
166     delete reloc.get<ELFRela *>();
167 }
168 
169 bool ELFRelocation::Parse(const lldb_private::DataExtractor &data,
170                           lldb::offset_t *offset) {
171   if (reloc.is<ELFRel *>())
172     return reloc.get<ELFRel *>()->Parse(data, offset);
173   else
174     return reloc.get<ELFRela *>()->Parse(data, offset);
175 }
176 
177 unsigned ELFRelocation::RelocType32(const ELFRelocation &rel) {
178   if (rel.reloc.is<ELFRel *>())
179     return ELFRel::RelocType32(*rel.reloc.get<ELFRel *>());
180   else
181     return ELFRela::RelocType32(*rel.reloc.get<ELFRela *>());
182 }
183 
184 unsigned ELFRelocation::RelocType64(const ELFRelocation &rel) {
185   if (rel.reloc.is<ELFRel *>())
186     return ELFRel::RelocType64(*rel.reloc.get<ELFRel *>());
187   else
188     return ELFRela::RelocType64(*rel.reloc.get<ELFRela *>());
189 }
190 
191 unsigned ELFRelocation::RelocSymbol32(const ELFRelocation &rel) {
192   if (rel.reloc.is<ELFRel *>())
193     return ELFRel::RelocSymbol32(*rel.reloc.get<ELFRel *>());
194   else
195     return ELFRela::RelocSymbol32(*rel.reloc.get<ELFRela *>());
196 }
197 
198 unsigned ELFRelocation::RelocSymbol64(const ELFRelocation &rel) {
199   if (rel.reloc.is<ELFRel *>())
200     return ELFRel::RelocSymbol64(*rel.reloc.get<ELFRel *>());
201   else
202     return ELFRela::RelocSymbol64(*rel.reloc.get<ELFRela *>());
203 }
204 
205 unsigned ELFRelocation::RelocOffset32(const ELFRelocation &rel) {
206   if (rel.reloc.is<ELFRel *>())
207     return rel.reloc.get<ELFRel *>()->r_offset;
208   else
209     return rel.reloc.get<ELFRela *>()->r_offset;
210 }
211 
212 unsigned ELFRelocation::RelocOffset64(const ELFRelocation &rel) {
213   if (rel.reloc.is<ELFRel *>())
214     return rel.reloc.get<ELFRel *>()->r_offset;
215   else
216     return rel.reloc.get<ELFRela *>()->r_offset;
217 }
218 
219 unsigned ELFRelocation::RelocAddend32(const ELFRelocation &rel) {
220   if (rel.reloc.is<ELFRel *>())
221     return 0;
222   else
223     return rel.reloc.get<ELFRela *>()->r_addend;
224 }
225 
226 unsigned ELFRelocation::RelocAddend64(const ELFRelocation &rel) {
227   if (rel.reloc.is<ELFRel *>())
228     return 0;
229   else
230     return rel.reloc.get<ELFRela *>()->r_addend;
231 }
232 
233 } // end anonymous namespace
234 
235 bool ELFNote::Parse(const DataExtractor &data, lldb::offset_t *offset) {
236   // Read all fields.
237   if (data.GetU32(offset, &n_namesz, 3) == NULL)
238     return false;
239 
240   // The name field is required to be nul-terminated, and n_namesz
241   // includes the terminating nul in observed implementations (contrary
242   // to the ELF-64 spec).  A special case is needed for cores generated
243   // by some older Linux versions, which write a note named "CORE"
244   // without a nul terminator and n_namesz = 4.
245   if (n_namesz == 4) {
246     char buf[4];
247     if (data.ExtractBytes(*offset, 4, data.GetByteOrder(), buf) != 4)
248       return false;
249     if (strncmp(buf, "CORE", 4) == 0) {
250       n_name = "CORE";
251       *offset += 4;
252       return true;
253     }
254   }
255 
256   const char *cstr = data.GetCStr(offset, llvm::alignTo(n_namesz, 4));
257   if (cstr == NULL) {
258     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
259     if (log)
260       log->Printf("Failed to parse note name lacking nul terminator");
261 
262     return false;
263   }
264   n_name = cstr;
265   return true;
266 }
267 
268 static uint32_t kalimbaVariantFromElfFlags(const elf::elf_word e_flags) {
269   const uint32_t dsp_rev = e_flags & 0xFF;
270   uint32_t kal_arch_variant = LLDB_INVALID_CPUTYPE;
271   switch (dsp_rev) {
272   // TODO(mg11) Support more variants
273   case 10:
274     kal_arch_variant = llvm::Triple::KalimbaSubArch_v3;
275     break;
276   case 14:
277     kal_arch_variant = llvm::Triple::KalimbaSubArch_v4;
278     break;
279   case 17:
280   case 20:
281     kal_arch_variant = llvm::Triple::KalimbaSubArch_v5;
282     break;
283   default:
284     break;
285   }
286   return kal_arch_variant;
287 }
288 
289 static uint32_t mipsVariantFromElfFlags(const elf::elf_word e_flags,
290                                         uint32_t endian) {
291   const uint32_t mips_arch = e_flags & llvm::ELF::EF_MIPS_ARCH;
292   uint32_t arch_variant = ArchSpec::eMIPSSubType_unknown;
293 
294   switch (mips_arch) {
295   case llvm::ELF::EF_MIPS_ARCH_1:
296   case llvm::ELF::EF_MIPS_ARCH_2:
297   case llvm::ELF::EF_MIPS_ARCH_32:
298     return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el
299                                    : ArchSpec::eMIPSSubType_mips32;
300   case llvm::ELF::EF_MIPS_ARCH_32R2:
301     return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r2el
302                                    : ArchSpec::eMIPSSubType_mips32r2;
303   case llvm::ELF::EF_MIPS_ARCH_32R6:
304     return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r6el
305                                    : ArchSpec::eMIPSSubType_mips32r6;
306   case llvm::ELF::EF_MIPS_ARCH_3:
307   case llvm::ELF::EF_MIPS_ARCH_4:
308   case llvm::ELF::EF_MIPS_ARCH_5:
309   case llvm::ELF::EF_MIPS_ARCH_64:
310     return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el
311                                    : ArchSpec::eMIPSSubType_mips64;
312   case llvm::ELF::EF_MIPS_ARCH_64R2:
313     return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r2el
314                                    : ArchSpec::eMIPSSubType_mips64r2;
315   case llvm::ELF::EF_MIPS_ARCH_64R6:
316     return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r6el
317                                    : ArchSpec::eMIPSSubType_mips64r6;
318   default:
319     break;
320   }
321 
322   return arch_variant;
323 }
324 
325 static uint32_t subTypeFromElfHeader(const elf::ELFHeader &header) {
326   if (header.e_machine == llvm::ELF::EM_MIPS)
327     return mipsVariantFromElfFlags(header.e_flags, header.e_ident[EI_DATA]);
328 
329   return llvm::ELF::EM_CSR_KALIMBA == header.e_machine
330              ? kalimbaVariantFromElfFlags(header.e_flags)
331              : LLDB_INVALID_CPUTYPE;
332 }
333 
334 //! The kalimba toolchain identifies a code section as being
335 //! one with the SHT_PROGBITS set in the section sh_type and the top
336 //! bit in the 32-bit address field set.
337 static lldb::SectionType
338 kalimbaSectionType(const elf::ELFHeader &header,
339                    const elf::ELFSectionHeader &sect_hdr) {
340   if (llvm::ELF::EM_CSR_KALIMBA != header.e_machine) {
341     return eSectionTypeOther;
342   }
343 
344   if (llvm::ELF::SHT_NOBITS == sect_hdr.sh_type) {
345     return eSectionTypeZeroFill;
346   }
347 
348   if (llvm::ELF::SHT_PROGBITS == sect_hdr.sh_type) {
349     const lldb::addr_t KAL_CODE_BIT = 1 << 31;
350     return KAL_CODE_BIT & sect_hdr.sh_addr ? eSectionTypeCode
351                                            : eSectionTypeData;
352   }
353 
354   return eSectionTypeOther;
355 }
356 
357 // Arbitrary constant used as UUID prefix for core files.
358 const uint32_t ObjectFileELF::g_core_uuid_magic(0xE210C);
359 
360 //------------------------------------------------------------------
361 // Static methods.
362 //------------------------------------------------------------------
363 void ObjectFileELF::Initialize() {
364   PluginManager::RegisterPlugin(GetPluginNameStatic(),
365                                 GetPluginDescriptionStatic(), CreateInstance,
366                                 CreateMemoryInstance, GetModuleSpecifications);
367 }
368 
369 void ObjectFileELF::Terminate() {
370   PluginManager::UnregisterPlugin(CreateInstance);
371 }
372 
373 lldb_private::ConstString ObjectFileELF::GetPluginNameStatic() {
374   static ConstString g_name("elf");
375   return g_name;
376 }
377 
378 const char *ObjectFileELF::GetPluginDescriptionStatic() {
379   return "ELF object file reader.";
380 }
381 
382 ObjectFile *ObjectFileELF::CreateInstance(const lldb::ModuleSP &module_sp,
383                                           DataBufferSP &data_sp,
384                                           lldb::offset_t data_offset,
385                                           const lldb_private::FileSpec *file,
386                                           lldb::offset_t file_offset,
387                                           lldb::offset_t length) {
388   if (!data_sp) {
389     data_sp = file->MemoryMapFileContentsIfLocal(file_offset, length);
390     data_offset = 0;
391   }
392 
393   if (data_sp &&
394       data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset)) {
395     const uint8_t *magic = data_sp->GetBytes() + data_offset;
396     if (ELFHeader::MagicBytesMatch(magic)) {
397       // Update the data to contain the entire file if it doesn't already
398       if (data_sp->GetByteSize() < length) {
399         data_sp = file->MemoryMapFileContentsIfLocal(file_offset, length);
400         data_offset = 0;
401         magic = data_sp->GetBytes();
402       }
403       unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
404       if (address_size == 4 || address_size == 8) {
405         std::unique_ptr<ObjectFileELF> objfile_ap(new ObjectFileELF(
406             module_sp, data_sp, data_offset, file, file_offset, length));
407         ArchSpec spec;
408         if (objfile_ap->GetArchitecture(spec) &&
409             objfile_ap->SetModulesArchitecture(spec))
410           return objfile_ap.release();
411       }
412     }
413   }
414   return NULL;
415 }
416 
417 ObjectFile *ObjectFileELF::CreateMemoryInstance(
418     const lldb::ModuleSP &module_sp, DataBufferSP &data_sp,
419     const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {
420   if (data_sp && data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT)) {
421     const uint8_t *magic = data_sp->GetBytes();
422     if (ELFHeader::MagicBytesMatch(magic)) {
423       unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
424       if (address_size == 4 || address_size == 8) {
425         std::auto_ptr<ObjectFileELF> objfile_ap(
426             new ObjectFileELF(module_sp, data_sp, process_sp, header_addr));
427         ArchSpec spec;
428         if (objfile_ap->GetArchitecture(spec) &&
429             objfile_ap->SetModulesArchitecture(spec))
430           return objfile_ap.release();
431       }
432     }
433   }
434   return NULL;
435 }
436 
437 bool ObjectFileELF::MagicBytesMatch(DataBufferSP &data_sp,
438                                     lldb::addr_t data_offset,
439                                     lldb::addr_t data_length) {
440   if (data_sp &&
441       data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset)) {
442     const uint8_t *magic = data_sp->GetBytes() + data_offset;
443     return ELFHeader::MagicBytesMatch(magic);
444   }
445   return false;
446 }
447 
448 /*
449  * crc function from http://svnweb.freebsd.org/base/head/sys/libkern/crc32.c
450  *
451  *   COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or
452  *   code or tables extracted from it, as desired without restriction.
453  */
454 static uint32_t calc_crc32(uint32_t crc, const void *buf, size_t size) {
455   static const uint32_t g_crc32_tab[] = {
456       0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
457       0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
458       0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
459       0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
460       0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
461       0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
462       0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
463       0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
464       0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
465       0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
466       0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
467       0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
468       0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
469       0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
470       0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
471       0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
472       0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
473       0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
474       0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
475       0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
476       0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
477       0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
478       0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
479       0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
480       0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
481       0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
482       0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
483       0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
484       0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
485       0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
486       0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
487       0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
488       0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
489       0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
490       0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
491       0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
492       0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
493       0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
494       0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
495       0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
496       0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
497       0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
498       0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d};
499   const uint8_t *p = (const uint8_t *)buf;
500 
501   crc = crc ^ ~0U;
502   while (size--)
503     crc = g_crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8);
504   return crc ^ ~0U;
505 }
506 
507 static uint32_t calc_gnu_debuglink_crc32(const void *buf, size_t size) {
508   return calc_crc32(0U, buf, size);
509 }
510 
511 uint32_t ObjectFileELF::CalculateELFNotesSegmentsCRC32(
512     const ProgramHeaderColl &program_headers, DataExtractor &object_data) {
513   typedef ProgramHeaderCollConstIter Iter;
514 
515   uint32_t core_notes_crc = 0;
516 
517   for (Iter I = program_headers.begin(); I != program_headers.end(); ++I) {
518     if (I->p_type == llvm::ELF::PT_NOTE) {
519       const elf_off ph_offset = I->p_offset;
520       const size_t ph_size = I->p_filesz;
521 
522       DataExtractor segment_data;
523       if (segment_data.SetData(object_data, ph_offset, ph_size) != ph_size) {
524         // The ELF program header contained incorrect data,
525         // probably corefile is incomplete or corrupted.
526         break;
527       }
528 
529       core_notes_crc = calc_crc32(core_notes_crc, segment_data.GetDataStart(),
530                                   segment_data.GetByteSize());
531     }
532   }
533 
534   return core_notes_crc;
535 }
536 
537 static const char *OSABIAsCString(unsigned char osabi_byte) {
538 #define _MAKE_OSABI_CASE(x)                                                    \
539   case x:                                                                      \
540     return #x
541   switch (osabi_byte) {
542     _MAKE_OSABI_CASE(ELFOSABI_NONE);
543     _MAKE_OSABI_CASE(ELFOSABI_HPUX);
544     _MAKE_OSABI_CASE(ELFOSABI_NETBSD);
545     _MAKE_OSABI_CASE(ELFOSABI_GNU);
546     _MAKE_OSABI_CASE(ELFOSABI_HURD);
547     _MAKE_OSABI_CASE(ELFOSABI_SOLARIS);
548     _MAKE_OSABI_CASE(ELFOSABI_AIX);
549     _MAKE_OSABI_CASE(ELFOSABI_IRIX);
550     _MAKE_OSABI_CASE(ELFOSABI_FREEBSD);
551     _MAKE_OSABI_CASE(ELFOSABI_TRU64);
552     _MAKE_OSABI_CASE(ELFOSABI_MODESTO);
553     _MAKE_OSABI_CASE(ELFOSABI_OPENBSD);
554     _MAKE_OSABI_CASE(ELFOSABI_OPENVMS);
555     _MAKE_OSABI_CASE(ELFOSABI_NSK);
556     _MAKE_OSABI_CASE(ELFOSABI_AROS);
557     _MAKE_OSABI_CASE(ELFOSABI_FENIXOS);
558     _MAKE_OSABI_CASE(ELFOSABI_C6000_ELFABI);
559     _MAKE_OSABI_CASE(ELFOSABI_C6000_LINUX);
560     _MAKE_OSABI_CASE(ELFOSABI_ARM);
561     _MAKE_OSABI_CASE(ELFOSABI_STANDALONE);
562   default:
563     return "<unknown-osabi>";
564   }
565 #undef _MAKE_OSABI_CASE
566 }
567 
568 //
569 // WARNING : This function is being deprecated
570 // It's functionality has moved to ArchSpec::SetArchitecture
571 // This function is only being kept to validate the move.
572 //
573 // TODO : Remove this function
574 static bool GetOsFromOSABI(unsigned char osabi_byte,
575                            llvm::Triple::OSType &ostype) {
576   switch (osabi_byte) {
577   case ELFOSABI_AIX:
578     ostype = llvm::Triple::OSType::AIX;
579     break;
580   case ELFOSABI_FREEBSD:
581     ostype = llvm::Triple::OSType::FreeBSD;
582     break;
583   case ELFOSABI_GNU:
584     ostype = llvm::Triple::OSType::Linux;
585     break;
586   case ELFOSABI_NETBSD:
587     ostype = llvm::Triple::OSType::NetBSD;
588     break;
589   case ELFOSABI_OPENBSD:
590     ostype = llvm::Triple::OSType::OpenBSD;
591     break;
592   case ELFOSABI_SOLARIS:
593     ostype = llvm::Triple::OSType::Solaris;
594     break;
595   default:
596     ostype = llvm::Triple::OSType::UnknownOS;
597   }
598   return ostype != llvm::Triple::OSType::UnknownOS;
599 }
600 
601 size_t ObjectFileELF::GetModuleSpecifications(
602     const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
603     lldb::offset_t data_offset, lldb::offset_t file_offset,
604     lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
605   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
606 
607   const size_t initial_count = specs.GetSize();
608 
609   if (ObjectFileELF::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
610     DataExtractor data;
611     data.SetData(data_sp);
612     elf::ELFHeader header;
613     if (header.Parse(data, &data_offset)) {
614       if (data_sp) {
615         ModuleSpec spec(file);
616 
617         const uint32_t sub_type = subTypeFromElfHeader(header);
618         spec.GetArchitecture().SetArchitecture(
619             eArchTypeELF, header.e_machine, sub_type, header.e_ident[EI_OSABI]);
620 
621         if (spec.GetArchitecture().IsValid()) {
622           llvm::Triple::OSType ostype;
623           llvm::Triple::VendorType vendor;
624           llvm::Triple::OSType spec_ostype =
625               spec.GetArchitecture().GetTriple().getOS();
626 
627           if (log)
628             log->Printf("ObjectFileELF::%s file '%s' module OSABI: %s",
629                         __FUNCTION__, file.GetPath().c_str(),
630                         OSABIAsCString(header.e_ident[EI_OSABI]));
631 
632           // SetArchitecture should have set the vendor to unknown
633           vendor = spec.GetArchitecture().GetTriple().getVendor();
634           assert(vendor == llvm::Triple::UnknownVendor);
635 
636           //
637           // Validate it is ok to remove GetOsFromOSABI
638           GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
639           assert(spec_ostype == ostype);
640           if (spec_ostype != llvm::Triple::OSType::UnknownOS) {
641             if (log)
642               log->Printf("ObjectFileELF::%s file '%s' set ELF module OS type "
643                           "from ELF header OSABI.",
644                           __FUNCTION__, file.GetPath().c_str());
645           }
646 
647           // Try to get the UUID from the section list. Usually that's at the
648           // end, so
649           // map the file in if we don't have it already.
650           size_t section_header_end =
651               header.e_shoff + header.e_shnum * header.e_shentsize;
652           if (section_header_end > data_sp->GetByteSize()) {
653             data_sp = file.MemoryMapFileContentsIfLocal(file_offset,
654                                                         section_header_end);
655             data.SetData(data_sp);
656           }
657 
658           uint32_t gnu_debuglink_crc = 0;
659           std::string gnu_debuglink_file;
660           SectionHeaderColl section_headers;
661           lldb_private::UUID &uuid = spec.GetUUID();
662 
663           using namespace std::placeholders;
664           const SetDataFunction set_data =
665               std::bind(&ObjectFileELF::SetData, std::cref(data), _1, _2, _3);
666           GetSectionHeaderInfo(section_headers, set_data, header, uuid,
667                                gnu_debuglink_file, gnu_debuglink_crc,
668                                spec.GetArchitecture());
669 
670           llvm::Triple &spec_triple = spec.GetArchitecture().GetTriple();
671 
672           if (log)
673             log->Printf("ObjectFileELF::%s file '%s' module set to triple: %s "
674                         "(architecture %s)",
675                         __FUNCTION__, file.GetPath().c_str(),
676                         spec_triple.getTriple().c_str(),
677                         spec.GetArchitecture().GetArchitectureName());
678 
679           if (!uuid.IsValid()) {
680             uint32_t core_notes_crc = 0;
681 
682             if (!gnu_debuglink_crc) {
683               lldb_private::Timer scoped_timer(
684                   LLVM_PRETTY_FUNCTION,
685                   "Calculating module crc32 %s with size %" PRIu64 " KiB",
686                   file.GetLastPathComponent().AsCString(),
687                   (file.GetByteSize() - file_offset) / 1024);
688 
689               // For core files - which usually don't happen to have a
690               // gnu_debuglink,
691               // and are pretty bulky - calculating whole contents crc32 would
692               // be too much of luxury.
693               // Thus we will need to fallback to something simpler.
694               if (header.e_type == llvm::ELF::ET_CORE) {
695                 size_t program_headers_end =
696                     header.e_phoff + header.e_phnum * header.e_phentsize;
697                 if (program_headers_end > data_sp->GetByteSize()) {
698                   data_sp = file.MemoryMapFileContentsIfLocal(
699                       file_offset, program_headers_end);
700                   data.SetData(data_sp);
701                 }
702                 ProgramHeaderColl program_headers;
703                 GetProgramHeaderInfo(program_headers, set_data, header);
704 
705                 size_t segment_data_end = 0;
706                 for (ProgramHeaderCollConstIter I = program_headers.begin();
707                      I != program_headers.end(); ++I) {
708                   segment_data_end = std::max<unsigned long long>(
709                       I->p_offset + I->p_filesz, segment_data_end);
710                 }
711 
712                 if (segment_data_end > data_sp->GetByteSize()) {
713                   data_sp = file.MemoryMapFileContentsIfLocal(file_offset,
714                                                               segment_data_end);
715                   data.SetData(data_sp);
716                 }
717 
718                 core_notes_crc =
719                     CalculateELFNotesSegmentsCRC32(program_headers, data);
720               } else {
721                 // Need to map entire file into memory to calculate the crc.
722                 data_sp =
723                     file.MemoryMapFileContentsIfLocal(file_offset, SIZE_MAX);
724                 data.SetData(data_sp);
725                 gnu_debuglink_crc = calc_gnu_debuglink_crc32(
726                     data.GetDataStart(), data.GetByteSize());
727               }
728             }
729             if (gnu_debuglink_crc) {
730               // Use 4 bytes of crc from the .gnu_debuglink section.
731               uint32_t uuidt[4] = {gnu_debuglink_crc, 0, 0, 0};
732               uuid.SetBytes(uuidt, sizeof(uuidt));
733             } else if (core_notes_crc) {
734               // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make
735               // it look different form
736               // .gnu_debuglink crc followed by 4 bytes of note segments crc.
737               uint32_t uuidt[4] = {g_core_uuid_magic, core_notes_crc, 0, 0};
738               uuid.SetBytes(uuidt, sizeof(uuidt));
739             }
740           }
741 
742           specs.Append(spec);
743         }
744       }
745     }
746   }
747 
748   return specs.GetSize() - initial_count;
749 }
750 
751 //------------------------------------------------------------------
752 // PluginInterface protocol
753 //------------------------------------------------------------------
754 lldb_private::ConstString ObjectFileELF::GetPluginName() {
755   return GetPluginNameStatic();
756 }
757 
758 uint32_t ObjectFileELF::GetPluginVersion() { return m_plugin_version; }
759 //------------------------------------------------------------------
760 // ObjectFile protocol
761 //------------------------------------------------------------------
762 
763 ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,
764                              DataBufferSP &data_sp, lldb::offset_t data_offset,
765                              const FileSpec *file, lldb::offset_t file_offset,
766                              lldb::offset_t length)
767     : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
768       m_header(), m_uuid(), m_gnu_debuglink_file(), m_gnu_debuglink_crc(0),
769       m_program_headers(), m_section_headers(), m_dynamic_symbols(),
770       m_filespec_ap(), m_entry_point_address(), m_arch_spec() {
771   if (file)
772     m_file = *file;
773   ::memset(&m_header, 0, sizeof(m_header));
774 }
775 
776 ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,
777                              DataBufferSP &header_data_sp,
778                              const lldb::ProcessSP &process_sp,
779                              addr_t header_addr)
780     : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
781       m_header(), m_uuid(), m_gnu_debuglink_file(), m_gnu_debuglink_crc(0),
782       m_program_headers(), m_section_headers(), m_dynamic_symbols(),
783       m_filespec_ap(), m_entry_point_address(), m_arch_spec() {
784   ::memset(&m_header, 0, sizeof(m_header));
785 }
786 
787 ObjectFileELF::~ObjectFileELF() {}
788 
789 bool ObjectFileELF::IsExecutable() const {
790   return ((m_header.e_type & ET_EXEC) != 0) || (m_header.e_entry != 0);
791 }
792 
793 bool ObjectFileELF::SetLoadAddress(Target &target, lldb::addr_t value,
794                                    bool value_is_offset) {
795   ModuleSP module_sp = GetModule();
796   if (module_sp) {
797     size_t num_loaded_sections = 0;
798     SectionList *section_list = GetSectionList();
799     if (section_list) {
800       if (!value_is_offset) {
801         bool found_offset = false;
802         for (size_t i = 0, count = GetProgramHeaderCount(); i < count; ++i) {
803           const elf::ELFProgramHeader *header = GetProgramHeaderByIndex(i);
804           if (header == nullptr)
805             continue;
806 
807           if (header->p_type != PT_LOAD || header->p_offset != 0)
808             continue;
809 
810           value = value - header->p_vaddr;
811           found_offset = true;
812           break;
813         }
814         if (!found_offset)
815           return false;
816       }
817 
818       const size_t num_sections = section_list->GetSize();
819       size_t sect_idx = 0;
820 
821       for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
822         // Iterate through the object file sections to find all
823         // of the sections that have SHF_ALLOC in their flag bits.
824         SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
825         if (section_sp && section_sp->Test(SHF_ALLOC)) {
826           lldb::addr_t load_addr = section_sp->GetFileAddress();
827           // We don't want to update the load address of a section with type
828           // eSectionTypeAbsoluteAddress as they already have the absolute load
829           // address
830           // already specified
831           if (section_sp->GetType() != eSectionTypeAbsoluteAddress)
832             load_addr += value;
833 
834           // On 32-bit systems the load address have to fit into 4 bytes. The
835           // rest of
836           // the bytes are the overflow from the addition.
837           if (GetAddressByteSize() == 4)
838             load_addr &= 0xFFFFFFFF;
839 
840           if (target.GetSectionLoadList().SetSectionLoadAddress(section_sp,
841                                                                 load_addr))
842             ++num_loaded_sections;
843         }
844       }
845       return num_loaded_sections > 0;
846     }
847   }
848   return false;
849 }
850 
851 ByteOrder ObjectFileELF::GetByteOrder() const {
852   if (m_header.e_ident[EI_DATA] == ELFDATA2MSB)
853     return eByteOrderBig;
854   if (m_header.e_ident[EI_DATA] == ELFDATA2LSB)
855     return eByteOrderLittle;
856   return eByteOrderInvalid;
857 }
858 
859 uint32_t ObjectFileELF::GetAddressByteSize() const {
860   return m_data.GetAddressByteSize();
861 }
862 
863 AddressClass ObjectFileELF::GetAddressClass(addr_t file_addr) {
864   Symtab *symtab = GetSymtab();
865   if (!symtab)
866     return eAddressClassUnknown;
867 
868   // The address class is determined based on the symtab. Ask it from the object
869   // file what
870   // contains the symtab information.
871   ObjectFile *symtab_objfile = symtab->GetObjectFile();
872   if (symtab_objfile != nullptr && symtab_objfile != this)
873     return symtab_objfile->GetAddressClass(file_addr);
874 
875   auto res = ObjectFile::GetAddressClass(file_addr);
876   if (res != eAddressClassCode)
877     return res;
878 
879   auto ub = m_address_class_map.upper_bound(file_addr);
880   if (ub == m_address_class_map.begin()) {
881     // No entry in the address class map before the address. Return
882     // default address class for an address in a code section.
883     return eAddressClassCode;
884   }
885 
886   // Move iterator to the address class entry preceding address
887   --ub;
888 
889   return ub->second;
890 }
891 
892 size_t ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I) {
893   return std::distance(m_section_headers.begin(), I) + 1u;
894 }
895 
896 size_t ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const {
897   return std::distance(m_section_headers.begin(), I) + 1u;
898 }
899 
900 bool ObjectFileELF::ParseHeader() {
901   lldb::offset_t offset = 0;
902   if (!m_header.Parse(m_data, &offset))
903     return false;
904 
905   if (!IsInMemory())
906     return true;
907 
908   // For in memory object files m_data might not contain the full object file.
909   // Try to load it
910   // until the end of the "Section header table" what is at the end of the ELF
911   // file.
912   addr_t file_size = m_header.e_shoff + m_header.e_shnum * m_header.e_shentsize;
913   if (m_data.GetByteSize() < file_size) {
914     ProcessSP process_sp(m_process_wp.lock());
915     if (!process_sp)
916       return false;
917 
918     DataBufferSP data_sp = ReadMemory(process_sp, m_memory_addr, file_size);
919     if (!data_sp)
920       return false;
921     m_data.SetData(data_sp, 0, file_size);
922   }
923 
924   return true;
925 }
926 
927 bool ObjectFileELF::GetUUID(lldb_private::UUID *uuid) {
928   // Need to parse the section list to get the UUIDs, so make sure that's been
929   // done.
930   if (!ParseSectionHeaders() && GetType() != ObjectFile::eTypeCoreFile)
931     return false;
932 
933   if (m_uuid.IsValid()) {
934     // We have the full build id uuid.
935     *uuid = m_uuid;
936     return true;
937   } else if (GetType() == ObjectFile::eTypeCoreFile) {
938     uint32_t core_notes_crc = 0;
939 
940     if (!ParseProgramHeaders())
941       return false;
942 
943     core_notes_crc = CalculateELFNotesSegmentsCRC32(m_program_headers, m_data);
944 
945     if (core_notes_crc) {
946       // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it
947       // look different form .gnu_debuglink crc - followed by 4 bytes of note
948       // segments crc.
949       uint32_t uuidt[4] = {g_core_uuid_magic, core_notes_crc, 0, 0};
950       m_uuid.SetBytes(uuidt, sizeof(uuidt));
951     }
952   } else {
953     if (!m_gnu_debuglink_crc)
954       m_gnu_debuglink_crc =
955           calc_gnu_debuglink_crc32(m_data.GetDataStart(), m_data.GetByteSize());
956     if (m_gnu_debuglink_crc) {
957       // Use 4 bytes of crc from the .gnu_debuglink section.
958       uint32_t uuidt[4] = {m_gnu_debuglink_crc, 0, 0, 0};
959       m_uuid.SetBytes(uuidt, sizeof(uuidt));
960     }
961   }
962 
963   if (m_uuid.IsValid()) {
964     *uuid = m_uuid;
965     return true;
966   }
967 
968   return false;
969 }
970 
971 lldb_private::FileSpecList ObjectFileELF::GetDebugSymbolFilePaths() {
972   FileSpecList file_spec_list;
973 
974   if (!m_gnu_debuglink_file.empty()) {
975     FileSpec file_spec(m_gnu_debuglink_file, false);
976     file_spec_list.Append(file_spec);
977   }
978   return file_spec_list;
979 }
980 
981 uint32_t ObjectFileELF::GetDependentModules(FileSpecList &files) {
982   size_t num_modules = ParseDependentModules();
983   uint32_t num_specs = 0;
984 
985   for (unsigned i = 0; i < num_modules; ++i) {
986     if (files.AppendIfUnique(m_filespec_ap->GetFileSpecAtIndex(i)))
987       num_specs++;
988   }
989 
990   return num_specs;
991 }
992 
993 Address ObjectFileELF::GetImageInfoAddress(Target *target) {
994   if (!ParseDynamicSymbols())
995     return Address();
996 
997   SectionList *section_list = GetSectionList();
998   if (!section_list)
999     return Address();
1000 
1001   // Find the SHT_DYNAMIC (.dynamic) section.
1002   SectionSP dynsym_section_sp(
1003       section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true));
1004   if (!dynsym_section_sp)
1005     return Address();
1006   assert(dynsym_section_sp->GetObjectFile() == this);
1007 
1008   user_id_t dynsym_id = dynsym_section_sp->GetID();
1009   const ELFSectionHeaderInfo *dynsym_hdr = GetSectionHeaderByIndex(dynsym_id);
1010   if (!dynsym_hdr)
1011     return Address();
1012 
1013   for (size_t i = 0; i < m_dynamic_symbols.size(); ++i) {
1014     ELFDynamic &symbol = m_dynamic_symbols[i];
1015 
1016     if (symbol.d_tag == DT_DEBUG) {
1017       // Compute the offset as the number of previous entries plus the
1018       // size of d_tag.
1019       addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
1020       return Address(dynsym_section_sp, offset);
1021     }
1022     // MIPS executables uses DT_MIPS_RLD_MAP_REL to support PIE. DT_MIPS_RLD_MAP
1023     // exists in non-PIE.
1024     else if ((symbol.d_tag == DT_MIPS_RLD_MAP ||
1025               symbol.d_tag == DT_MIPS_RLD_MAP_REL) &&
1026              target) {
1027       addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
1028       addr_t dyn_base = dynsym_section_sp->GetLoadBaseAddress(target);
1029       if (dyn_base == LLDB_INVALID_ADDRESS)
1030         return Address();
1031 
1032       Error error;
1033       if (symbol.d_tag == DT_MIPS_RLD_MAP) {
1034         // DT_MIPS_RLD_MAP tag stores an absolute address of the debug pointer.
1035         Address addr;
1036         if (target->ReadPointerFromMemory(dyn_base + offset, false, error,
1037                                           addr))
1038           return addr;
1039       }
1040       if (symbol.d_tag == DT_MIPS_RLD_MAP_REL) {
1041         // DT_MIPS_RLD_MAP_REL tag stores the offset to the debug pointer,
1042         // relative to the address of the tag.
1043         uint64_t rel_offset;
1044         rel_offset = target->ReadUnsignedIntegerFromMemory(
1045             dyn_base + offset, false, GetAddressByteSize(), UINT64_MAX, error);
1046         if (error.Success() && rel_offset != UINT64_MAX) {
1047           Address addr;
1048           addr_t debug_ptr_address =
1049               dyn_base + (offset - GetAddressByteSize()) + rel_offset;
1050           addr.SetOffset(debug_ptr_address);
1051           return addr;
1052         }
1053       }
1054     }
1055   }
1056 
1057   return Address();
1058 }
1059 
1060 lldb_private::Address ObjectFileELF::GetEntryPointAddress() {
1061   if (m_entry_point_address.IsValid())
1062     return m_entry_point_address;
1063 
1064   if (!ParseHeader() || !IsExecutable())
1065     return m_entry_point_address;
1066 
1067   SectionList *section_list = GetSectionList();
1068   addr_t offset = m_header.e_entry;
1069 
1070   if (!section_list)
1071     m_entry_point_address.SetOffset(offset);
1072   else
1073     m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list);
1074   return m_entry_point_address;
1075 }
1076 
1077 //----------------------------------------------------------------------
1078 // ParseDependentModules
1079 //----------------------------------------------------------------------
1080 size_t ObjectFileELF::ParseDependentModules() {
1081   if (m_filespec_ap.get())
1082     return m_filespec_ap->GetSize();
1083 
1084   m_filespec_ap.reset(new FileSpecList());
1085 
1086   if (!ParseSectionHeaders())
1087     return 0;
1088 
1089   SectionList *section_list = GetSectionList();
1090   if (!section_list)
1091     return 0;
1092 
1093   // Find the SHT_DYNAMIC section.
1094   Section *dynsym =
1095       section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
1096           .get();
1097   if (!dynsym)
1098     return 0;
1099   assert(dynsym->GetObjectFile() == this);
1100 
1101   const ELFSectionHeaderInfo *header = GetSectionHeaderByIndex(dynsym->GetID());
1102   if (!header)
1103     return 0;
1104   // sh_link: section header index of string table used by entries in the
1105   // section.
1106   Section *dynstr = section_list->FindSectionByID(header->sh_link + 1).get();
1107   if (!dynstr)
1108     return 0;
1109 
1110   DataExtractor dynsym_data;
1111   DataExtractor dynstr_data;
1112   if (ReadSectionData(dynsym, dynsym_data) &&
1113       ReadSectionData(dynstr, dynstr_data)) {
1114     ELFDynamic symbol;
1115     const lldb::offset_t section_size = dynsym_data.GetByteSize();
1116     lldb::offset_t offset = 0;
1117 
1118     // The only type of entries we are concerned with are tagged DT_NEEDED,
1119     // yielding the name of a required library.
1120     while (offset < section_size) {
1121       if (!symbol.Parse(dynsym_data, &offset))
1122         break;
1123 
1124       if (symbol.d_tag != DT_NEEDED)
1125         continue;
1126 
1127       uint32_t str_index = static_cast<uint32_t>(symbol.d_val);
1128       const char *lib_name = dynstr_data.PeekCStr(str_index);
1129       m_filespec_ap->Append(FileSpec(lib_name, true));
1130     }
1131   }
1132 
1133   return m_filespec_ap->GetSize();
1134 }
1135 
1136 //----------------------------------------------------------------------
1137 // GetProgramHeaderInfo
1138 //----------------------------------------------------------------------
1139 size_t ObjectFileELF::GetProgramHeaderInfo(ProgramHeaderColl &program_headers,
1140                                            const SetDataFunction &set_data,
1141                                            const ELFHeader &header) {
1142   // We have already parsed the program headers
1143   if (!program_headers.empty())
1144     return program_headers.size();
1145 
1146   // If there are no program headers to read we are done.
1147   if (header.e_phnum == 0)
1148     return 0;
1149 
1150   program_headers.resize(header.e_phnum);
1151   if (program_headers.size() != header.e_phnum)
1152     return 0;
1153 
1154   const size_t ph_size = header.e_phnum * header.e_phentsize;
1155   const elf_off ph_offset = header.e_phoff;
1156   DataExtractor data;
1157   if (set_data(data, ph_offset, ph_size) != ph_size)
1158     return 0;
1159 
1160   uint32_t idx;
1161   lldb::offset_t offset;
1162   for (idx = 0, offset = 0; idx < header.e_phnum; ++idx) {
1163     if (program_headers[idx].Parse(data, &offset) == false)
1164       break;
1165   }
1166 
1167   if (idx < program_headers.size())
1168     program_headers.resize(idx);
1169 
1170   return program_headers.size();
1171 }
1172 
1173 //----------------------------------------------------------------------
1174 // ParseProgramHeaders
1175 //----------------------------------------------------------------------
1176 size_t ObjectFileELF::ParseProgramHeaders() {
1177   using namespace std::placeholders;
1178   return GetProgramHeaderInfo(
1179       m_program_headers,
1180       std::bind(&ObjectFileELF::SetDataWithReadMemoryFallback, this, _1, _2,
1181                 _3),
1182       m_header);
1183 }
1184 
1185 lldb_private::Error
1186 ObjectFileELF::RefineModuleDetailsFromNote(lldb_private::DataExtractor &data,
1187                                            lldb_private::ArchSpec &arch_spec,
1188                                            lldb_private::UUID &uuid) {
1189   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
1190   Error error;
1191 
1192   lldb::offset_t offset = 0;
1193 
1194   while (true) {
1195     // Parse the note header.  If this fails, bail out.
1196     const lldb::offset_t note_offset = offset;
1197     ELFNote note = ELFNote();
1198     if (!note.Parse(data, &offset)) {
1199       // We're done.
1200       return error;
1201     }
1202 
1203     if (log)
1204       log->Printf("ObjectFileELF::%s parsing note name='%s', type=%" PRIu32,
1205                   __FUNCTION__, note.n_name.c_str(), note.n_type);
1206 
1207     // Process FreeBSD ELF notes.
1208     if ((note.n_name == LLDB_NT_OWNER_FREEBSD) &&
1209         (note.n_type == LLDB_NT_FREEBSD_ABI_TAG) &&
1210         (note.n_descsz == LLDB_NT_FREEBSD_ABI_SIZE)) {
1211       // Pull out the min version info.
1212       uint32_t version_info;
1213       if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1214         error.SetErrorString("failed to read FreeBSD ABI note payload");
1215         return error;
1216       }
1217 
1218       // Convert the version info into a major/minor number.
1219       const uint32_t version_major = version_info / 100000;
1220       const uint32_t version_minor = (version_info / 1000) % 100;
1221 
1222       char os_name[32];
1223       snprintf(os_name, sizeof(os_name), "freebsd%" PRIu32 ".%" PRIu32,
1224                version_major, version_minor);
1225 
1226       // Set the elf OS version to FreeBSD.  Also clear the vendor.
1227       arch_spec.GetTriple().setOSName(os_name);
1228       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1229 
1230       if (log)
1231         log->Printf("ObjectFileELF::%s detected FreeBSD %" PRIu32 ".%" PRIu32
1232                     ".%" PRIu32,
1233                     __FUNCTION__, version_major, version_minor,
1234                     static_cast<uint32_t>(version_info % 1000));
1235     }
1236     // Process GNU ELF notes.
1237     else if (note.n_name == LLDB_NT_OWNER_GNU) {
1238       switch (note.n_type) {
1239       case LLDB_NT_GNU_ABI_TAG:
1240         if (note.n_descsz == LLDB_NT_GNU_ABI_SIZE) {
1241           // Pull out the min OS version supporting the ABI.
1242           uint32_t version_info[4];
1243           if (data.GetU32(&offset, &version_info[0], note.n_descsz / 4) ==
1244               nullptr) {
1245             error.SetErrorString("failed to read GNU ABI note payload");
1246             return error;
1247           }
1248 
1249           // Set the OS per the OS field.
1250           switch (version_info[0]) {
1251           case LLDB_NT_GNU_ABI_OS_LINUX:
1252             arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1253             arch_spec.GetTriple().setVendor(
1254                 llvm::Triple::VendorType::UnknownVendor);
1255             if (log)
1256               log->Printf(
1257                   "ObjectFileELF::%s detected Linux, min version %" PRIu32
1258                   ".%" PRIu32 ".%" PRIu32,
1259                   __FUNCTION__, version_info[1], version_info[2],
1260                   version_info[3]);
1261             // FIXME we have the minimal version number, we could be propagating
1262             // that.  version_info[1] = OS Major, version_info[2] = OS Minor,
1263             // version_info[3] = Revision.
1264             break;
1265           case LLDB_NT_GNU_ABI_OS_HURD:
1266             arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
1267             arch_spec.GetTriple().setVendor(
1268                 llvm::Triple::VendorType::UnknownVendor);
1269             if (log)
1270               log->Printf("ObjectFileELF::%s detected Hurd (unsupported), min "
1271                           "version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1272                           __FUNCTION__, version_info[1], version_info[2],
1273                           version_info[3]);
1274             break;
1275           case LLDB_NT_GNU_ABI_OS_SOLARIS:
1276             arch_spec.GetTriple().setOS(llvm::Triple::OSType::Solaris);
1277             arch_spec.GetTriple().setVendor(
1278                 llvm::Triple::VendorType::UnknownVendor);
1279             if (log)
1280               log->Printf(
1281                   "ObjectFileELF::%s detected Solaris, min version %" PRIu32
1282                   ".%" PRIu32 ".%" PRIu32,
1283                   __FUNCTION__, version_info[1], version_info[2],
1284                   version_info[3]);
1285             break;
1286           default:
1287             if (log)
1288               log->Printf(
1289                   "ObjectFileELF::%s unrecognized OS in note, id %" PRIu32
1290                   ", min version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1291                   __FUNCTION__, version_info[0], version_info[1],
1292                   version_info[2], version_info[3]);
1293             break;
1294           }
1295         }
1296         break;
1297 
1298       case LLDB_NT_GNU_BUILD_ID_TAG:
1299         // Only bother processing this if we don't already have the uuid set.
1300         if (!uuid.IsValid()) {
1301           // 16 bytes is UUID|MD5, 20 bytes is SHA1. Other linkers may produce a
1302           // build-id of a different
1303           // length. Accept it as long as it's at least 4 bytes as it will be
1304           // better than our own crc32.
1305           if (note.n_descsz >= 4 && note.n_descsz <= 20) {
1306             uint8_t uuidbuf[20];
1307             if (data.GetU8(&offset, &uuidbuf, note.n_descsz) == nullptr) {
1308               error.SetErrorString("failed to read GNU_BUILD_ID note payload");
1309               return error;
1310             }
1311 
1312             // Save the build id as the UUID for the module.
1313             uuid.SetBytes(uuidbuf, note.n_descsz);
1314           }
1315         }
1316         break;
1317       }
1318     }
1319     // Process NetBSD ELF notes.
1320     else if ((note.n_name == LLDB_NT_OWNER_NETBSD) &&
1321              (note.n_type == LLDB_NT_NETBSD_ABI_TAG) &&
1322              (note.n_descsz == LLDB_NT_NETBSD_ABI_SIZE)) {
1323       // Pull out the min version info.
1324       uint32_t version_info;
1325       if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1326         error.SetErrorString("failed to read NetBSD ABI note payload");
1327         return error;
1328       }
1329 
1330       // Set the elf OS version to NetBSD.  Also clear the vendor.
1331       arch_spec.GetTriple().setOS(llvm::Triple::OSType::NetBSD);
1332       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1333 
1334       if (log)
1335         log->Printf(
1336             "ObjectFileELF::%s detected NetBSD, min version constant %" PRIu32,
1337             __FUNCTION__, version_info);
1338     }
1339     // Process CSR kalimba notes
1340     else if ((note.n_type == LLDB_NT_GNU_ABI_TAG) &&
1341              (note.n_name == LLDB_NT_OWNER_CSR)) {
1342       arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
1343       arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::CSR);
1344 
1345       // TODO At some point the description string could be processed.
1346       // It could provide a steer towards the kalimba variant which
1347       // this ELF targets.
1348       if (note.n_descsz) {
1349         const char *cstr =
1350             data.GetCStr(&offset, llvm::alignTo(note.n_descsz, 4));
1351         (void)cstr;
1352       }
1353     } else if (note.n_name == LLDB_NT_OWNER_ANDROID) {
1354       arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1355       arch_spec.GetTriple().setEnvironment(
1356           llvm::Triple::EnvironmentType::Android);
1357     } else if (note.n_name == LLDB_NT_OWNER_LINUX) {
1358       // This is sometimes found in core files and usually contains extended
1359       // register info
1360       arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1361     } else if (note.n_name == LLDB_NT_OWNER_CORE) {
1362       // Parse the NT_FILE to look for stuff in paths to shared libraries
1363       // As the contents look like this in a 64 bit ELF core file:
1364       // count     = 0x000000000000000a (10)
1365       // page_size = 0x0000000000001000 (4096)
1366       // Index start              end                file_ofs           path
1367       // ===== ------------------ ------------------ ------------------
1368       // -------------------------------------
1369       // [  0] 0x0000000000400000 0x0000000000401000 0x0000000000000000
1370       // /tmp/a.out
1371       // [  1] 0x0000000000600000 0x0000000000601000 0x0000000000000000
1372       // /tmp/a.out
1373       // [  2] 0x0000000000601000 0x0000000000602000 0x0000000000000001
1374       // /tmp/a.out
1375       // [  3] 0x00007fa79c9ed000 0x00007fa79cba8000 0x0000000000000000
1376       // /lib/x86_64-linux-gnu/libc-2.19.so
1377       // [  4] 0x00007fa79cba8000 0x00007fa79cda7000 0x00000000000001bb
1378       // /lib/x86_64-linux-gnu/libc-2.19.so
1379       // [  5] 0x00007fa79cda7000 0x00007fa79cdab000 0x00000000000001ba
1380       // /lib/x86_64-linux-gnu/libc-2.19.so
1381       // [  6] 0x00007fa79cdab000 0x00007fa79cdad000 0x00000000000001be
1382       // /lib/x86_64-linux-gnu/libc-2.19.so
1383       // [  7] 0x00007fa79cdb2000 0x00007fa79cdd5000 0x0000000000000000
1384       // /lib/x86_64-linux-gnu/ld-2.19.so
1385       // [  8] 0x00007fa79cfd4000 0x00007fa79cfd5000 0x0000000000000022
1386       // /lib/x86_64-linux-gnu/ld-2.19.so
1387       // [  9] 0x00007fa79cfd5000 0x00007fa79cfd6000 0x0000000000000023
1388       // /lib/x86_64-linux-gnu/ld-2.19.so
1389       // In the 32 bit ELFs the count, page_size, start, end, file_ofs are
1390       // uint32_t
1391       // For reference: see readelf source code (in binutils).
1392       if (note.n_type == NT_FILE) {
1393         uint64_t count = data.GetAddress(&offset);
1394         const char *cstr;
1395         data.GetAddress(&offset); // Skip page size
1396         offset += count * 3 *
1397                   data.GetAddressByteSize(); // Skip all start/end/file_ofs
1398         for (size_t i = 0; i < count; ++i) {
1399           cstr = data.GetCStr(&offset);
1400           if (cstr == nullptr) {
1401             error.SetErrorStringWithFormat("ObjectFileELF::%s trying to read "
1402                                            "at an offset after the end "
1403                                            "(GetCStr returned nullptr)",
1404                                            __FUNCTION__);
1405             return error;
1406           }
1407           llvm::StringRef path(cstr);
1408           if (path.contains("/lib/x86_64-linux-gnu") || path.contains("/lib/i386-linux-gnu")) {
1409             arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1410             break;
1411           }
1412         }
1413       }
1414     }
1415 
1416     // Calculate the offset of the next note just in case "offset" has been used
1417     // to poke at the contents of the note data
1418     offset = note_offset + note.GetByteSize();
1419   }
1420 
1421   return error;
1422 }
1423 
1424 void ObjectFileELF::ParseARMAttributes(DataExtractor &data, uint64_t length,
1425                                        ArchSpec &arch_spec) {
1426   lldb::offset_t Offset = 0;
1427 
1428   uint8_t FormatVersion = data.GetU8(&Offset);
1429   if (FormatVersion != llvm::ARMBuildAttrs::Format_Version)
1430     return;
1431 
1432   Offset = Offset + sizeof(uint32_t); // Section Length
1433   llvm::StringRef VendorName = data.GetCStr(&Offset);
1434 
1435   if (VendorName != "aeabi")
1436     return;
1437 
1438   if (arch_spec.GetTriple().getEnvironment() ==
1439       llvm::Triple::UnknownEnvironment)
1440     arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
1441 
1442   while (Offset < length) {
1443     uint8_t Tag = data.GetU8(&Offset);
1444     uint32_t Size = data.GetU32(&Offset);
1445 
1446     if (Tag != llvm::ARMBuildAttrs::File || Size == 0)
1447       continue;
1448 
1449     while (Offset < length) {
1450       uint64_t Tag = data.GetULEB128(&Offset);
1451       switch (Tag) {
1452       default:
1453         if (Tag < 32)
1454           data.GetULEB128(&Offset);
1455         else if (Tag % 2 == 0)
1456           data.GetULEB128(&Offset);
1457         else
1458           data.GetCStr(&Offset);
1459 
1460         break;
1461 
1462       case llvm::ARMBuildAttrs::CPU_raw_name:
1463       case llvm::ARMBuildAttrs::CPU_name:
1464         data.GetCStr(&Offset);
1465 
1466         break;
1467 
1468       case llvm::ARMBuildAttrs::ABI_VFP_args: {
1469         uint64_t VFPArgs = data.GetULEB128(&Offset);
1470 
1471         if (VFPArgs == llvm::ARMBuildAttrs::BaseAAPCS) {
1472           if (arch_spec.GetTriple().getEnvironment() ==
1473                   llvm::Triple::UnknownEnvironment ||
1474               arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABIHF)
1475             arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
1476 
1477           arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
1478         } else if (VFPArgs == llvm::ARMBuildAttrs::HardFPAAPCS) {
1479           if (arch_spec.GetTriple().getEnvironment() ==
1480                   llvm::Triple::UnknownEnvironment ||
1481               arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABI)
1482             arch_spec.GetTriple().setEnvironment(llvm::Triple::EABIHF);
1483 
1484           arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
1485         }
1486 
1487         break;
1488       }
1489       }
1490     }
1491   }
1492 }
1493 
1494 //----------------------------------------------------------------------
1495 // GetSectionHeaderInfo
1496 //----------------------------------------------------------------------
1497 size_t ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl &section_headers,
1498                                            const SetDataFunction &set_data,
1499                                            const elf::ELFHeader &header,
1500                                            lldb_private::UUID &uuid,
1501                                            std::string &gnu_debuglink_file,
1502                                            uint32_t &gnu_debuglink_crc,
1503                                            ArchSpec &arch_spec) {
1504   // Don't reparse the section headers if we already did that.
1505   if (!section_headers.empty())
1506     return section_headers.size();
1507 
1508   // Only initialize the arch_spec to okay defaults if they're not already set.
1509   // We'll refine this with note data as we parse the notes.
1510   if (arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) {
1511     llvm::Triple::OSType ostype;
1512     llvm::Triple::OSType spec_ostype;
1513     const uint32_t sub_type = subTypeFromElfHeader(header);
1514     arch_spec.SetArchitecture(eArchTypeELF, header.e_machine, sub_type,
1515                               header.e_ident[EI_OSABI]);
1516 
1517     // Validate if it is ok to remove GetOsFromOSABI.
1518     // Note, that now the OS is determined based on EI_OSABI flag and
1519     // the info extracted from ELF notes (see RefineModuleDetailsFromNote).
1520     // However in some cases that still might be not enough: for example
1521     // a shared library might not have any notes at all
1522     // and have EI_OSABI flag set to System V,
1523     // as result the OS will be set to UnknownOS.
1524     GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
1525     spec_ostype = arch_spec.GetTriple().getOS();
1526     assert(spec_ostype == ostype);
1527   }
1528 
1529   if (arch_spec.GetMachine() == llvm::Triple::mips ||
1530       arch_spec.GetMachine() == llvm::Triple::mipsel ||
1531       arch_spec.GetMachine() == llvm::Triple::mips64 ||
1532       arch_spec.GetMachine() == llvm::Triple::mips64el) {
1533     switch (header.e_flags & llvm::ELF::EF_MIPS_ARCH_ASE) {
1534     case llvm::ELF::EF_MIPS_MICROMIPS:
1535       arch_spec.SetFlags(ArchSpec::eMIPSAse_micromips);
1536       break;
1537     case llvm::ELF::EF_MIPS_ARCH_ASE_M16:
1538       arch_spec.SetFlags(ArchSpec::eMIPSAse_mips16);
1539       break;
1540     case llvm::ELF::EF_MIPS_ARCH_ASE_MDMX:
1541       arch_spec.SetFlags(ArchSpec::eMIPSAse_mdmx);
1542       break;
1543     default:
1544       break;
1545     }
1546   }
1547 
1548   if (arch_spec.GetMachine() == llvm::Triple::arm ||
1549       arch_spec.GetMachine() == llvm::Triple::thumb) {
1550     if (header.e_flags & llvm::ELF::EF_ARM_SOFT_FLOAT)
1551       arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
1552     else if (header.e_flags & llvm::ELF::EF_ARM_VFP_FLOAT)
1553       arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
1554   }
1555 
1556   // If there are no section headers we are done.
1557   if (header.e_shnum == 0)
1558     return 0;
1559 
1560   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
1561 
1562   section_headers.resize(header.e_shnum);
1563   if (section_headers.size() != header.e_shnum)
1564     return 0;
1565 
1566   const size_t sh_size = header.e_shnum * header.e_shentsize;
1567   const elf_off sh_offset = header.e_shoff;
1568   DataExtractor sh_data;
1569   if (set_data(sh_data, sh_offset, sh_size) != sh_size)
1570     return 0;
1571 
1572   uint32_t idx;
1573   lldb::offset_t offset;
1574   for (idx = 0, offset = 0; idx < header.e_shnum; ++idx) {
1575     if (section_headers[idx].Parse(sh_data, &offset) == false)
1576       break;
1577   }
1578   if (idx < section_headers.size())
1579     section_headers.resize(idx);
1580 
1581   const unsigned strtab_idx = header.e_shstrndx;
1582   if (strtab_idx && strtab_idx < section_headers.size()) {
1583     const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];
1584     const size_t byte_size = sheader.sh_size;
1585     const Elf64_Off offset = sheader.sh_offset;
1586     lldb_private::DataExtractor shstr_data;
1587 
1588     if (set_data(shstr_data, offset, byte_size) == byte_size) {
1589       for (SectionHeaderCollIter I = section_headers.begin();
1590            I != section_headers.end(); ++I) {
1591         static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");
1592         const ELFSectionHeaderInfo &sheader = *I;
1593         const uint64_t section_size =
1594             sheader.sh_type == SHT_NOBITS ? 0 : sheader.sh_size;
1595         ConstString name(shstr_data.PeekCStr(I->sh_name));
1596 
1597         I->section_name = name;
1598 
1599         if (arch_spec.IsMIPS()) {
1600           uint32_t arch_flags = arch_spec.GetFlags();
1601           DataExtractor data;
1602           if (sheader.sh_type == SHT_MIPS_ABIFLAGS) {
1603 
1604             if (section_size && (set_data(data, sheader.sh_offset,
1605                                           section_size) == section_size)) {
1606               // MIPS ASE Mask is at offset 12 in MIPS.abiflags section
1607               lldb::offset_t offset = 12; // MIPS ABI Flags Version: 0
1608               arch_flags |= data.GetU32(&offset);
1609 
1610               // The floating point ABI is at offset 7
1611               offset = 7;
1612               switch (data.GetU8(&offset)) {
1613               case llvm::Mips::Val_GNU_MIPS_ABI_FP_ANY:
1614                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_ANY;
1615                 break;
1616               case llvm::Mips::Val_GNU_MIPS_ABI_FP_DOUBLE:
1617                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_DOUBLE;
1618                 break;
1619               case llvm::Mips::Val_GNU_MIPS_ABI_FP_SINGLE:
1620                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SINGLE;
1621                 break;
1622               case llvm::Mips::Val_GNU_MIPS_ABI_FP_SOFT:
1623                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SOFT;
1624                 break;
1625               case llvm::Mips::Val_GNU_MIPS_ABI_FP_OLD_64:
1626                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_OLD_64;
1627                 break;
1628               case llvm::Mips::Val_GNU_MIPS_ABI_FP_XX:
1629                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_XX;
1630                 break;
1631               case llvm::Mips::Val_GNU_MIPS_ABI_FP_64:
1632                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64;
1633                 break;
1634               case llvm::Mips::Val_GNU_MIPS_ABI_FP_64A:
1635                 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64A;
1636                 break;
1637               }
1638             }
1639           }
1640           // Settings appropriate ArchSpec ABI Flags
1641           switch (header.e_flags & llvm::ELF::EF_MIPS_ABI) {
1642           case llvm::ELF::EF_MIPS_ABI_O32:
1643             arch_flags |= lldb_private::ArchSpec::eMIPSABI_O32;
1644             break;
1645           case EF_MIPS_ABI_O64:
1646             arch_flags |= lldb_private::ArchSpec::eMIPSABI_O64;
1647             break;
1648           case EF_MIPS_ABI_EABI32:
1649             arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI32;
1650             break;
1651           case EF_MIPS_ABI_EABI64:
1652             arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI64;
1653             break;
1654           default:
1655             // ABI Mask doesn't cover N32 and N64 ABI.
1656             if (header.e_ident[EI_CLASS] == llvm::ELF::ELFCLASS64)
1657               arch_flags |= lldb_private::ArchSpec::eMIPSABI_N64;
1658             else if (header.e_flags && llvm::ELF::EF_MIPS_ABI2)
1659               arch_flags |= lldb_private::ArchSpec::eMIPSABI_N32;
1660             break;
1661           }
1662           arch_spec.SetFlags(arch_flags);
1663         }
1664 
1665         if (arch_spec.GetMachine() == llvm::Triple::arm ||
1666             arch_spec.GetMachine() == llvm::Triple::thumb) {
1667           DataExtractor data;
1668 
1669           if (sheader.sh_type == SHT_ARM_ATTRIBUTES && section_size != 0 &&
1670               set_data(data, sheader.sh_offset, section_size) == section_size)
1671             ParseARMAttributes(data, section_size, arch_spec);
1672         }
1673 
1674         if (name == g_sect_name_gnu_debuglink) {
1675           DataExtractor data;
1676           if (section_size && (set_data(data, sheader.sh_offset,
1677                                         section_size) == section_size)) {
1678             lldb::offset_t gnu_debuglink_offset = 0;
1679             gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);
1680             gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
1681             data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
1682           }
1683         }
1684 
1685         // Process ELF note section entries.
1686         bool is_note_header = (sheader.sh_type == SHT_NOTE);
1687 
1688         // The section header ".note.android.ident" is stored as a
1689         // PROGBITS type header but it is actually a note header.
1690         static ConstString g_sect_name_android_ident(".note.android.ident");
1691         if (!is_note_header && name == g_sect_name_android_ident)
1692           is_note_header = true;
1693 
1694         if (is_note_header) {
1695           // Allow notes to refine module info.
1696           DataExtractor data;
1697           if (section_size && (set_data(data, sheader.sh_offset,
1698                                         section_size) == section_size)) {
1699             Error error = RefineModuleDetailsFromNote(data, arch_spec, uuid);
1700             if (error.Fail()) {
1701               if (log)
1702                 log->Printf("ObjectFileELF::%s ELF note processing failed: %s",
1703                             __FUNCTION__, error.AsCString());
1704             }
1705           }
1706         }
1707       }
1708 
1709       // Make any unknown triple components to be unspecified unknowns.
1710       if (arch_spec.GetTriple().getVendor() == llvm::Triple::UnknownVendor)
1711         arch_spec.GetTriple().setVendorName(llvm::StringRef());
1712       if (arch_spec.GetTriple().getOS() == llvm::Triple::UnknownOS)
1713         arch_spec.GetTriple().setOSName(llvm::StringRef());
1714 
1715       return section_headers.size();
1716     }
1717   }
1718 
1719   section_headers.clear();
1720   return 0;
1721 }
1722 
1723 size_t ObjectFileELF::GetProgramHeaderCount() { return ParseProgramHeaders(); }
1724 
1725 const elf::ELFProgramHeader *
1726 ObjectFileELF::GetProgramHeaderByIndex(lldb::user_id_t id) {
1727   if (!id || !ParseProgramHeaders())
1728     return NULL;
1729 
1730   if (--id < m_program_headers.size())
1731     return &m_program_headers[id];
1732 
1733   return NULL;
1734 }
1735 
1736 DataExtractor ObjectFileELF::GetSegmentDataByIndex(lldb::user_id_t id) {
1737   const elf::ELFProgramHeader *segment_header = GetProgramHeaderByIndex(id);
1738   if (segment_header == NULL)
1739     return DataExtractor();
1740   return DataExtractor(m_data, segment_header->p_offset,
1741                        segment_header->p_filesz);
1742 }
1743 
1744 std::string
1745 ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const {
1746   size_t pos = symbol_name.find('@');
1747   return symbol_name.substr(0, pos).str();
1748 }
1749 
1750 //----------------------------------------------------------------------
1751 // ParseSectionHeaders
1752 //----------------------------------------------------------------------
1753 size_t ObjectFileELF::ParseSectionHeaders() {
1754   using namespace std::placeholders;
1755 
1756   return GetSectionHeaderInfo(
1757       m_section_headers,
1758       std::bind(&ObjectFileELF::SetDataWithReadMemoryFallback, this, _1, _2,
1759                 _3),
1760       m_header, m_uuid, m_gnu_debuglink_file, m_gnu_debuglink_crc, m_arch_spec);
1761 }
1762 
1763 lldb::offset_t ObjectFileELF::SetData(const lldb_private::DataExtractor &src,
1764                                       lldb_private::DataExtractor &dst,
1765                                       lldb::offset_t offset,
1766                                       lldb::offset_t length) {
1767   return dst.SetData(src, offset, length);
1768 }
1769 
1770 lldb::offset_t
1771 ObjectFileELF::SetDataWithReadMemoryFallback(lldb_private::DataExtractor &dst,
1772                                              lldb::offset_t offset,
1773                                              lldb::offset_t length) {
1774   if (offset + length <= m_data.GetByteSize())
1775     return dst.SetData(m_data, offset, length);
1776 
1777   const auto process_sp = m_process_wp.lock();
1778   if (process_sp != nullptr) {
1779     addr_t file_size = offset + length;
1780 
1781     DataBufferSP data_sp = ReadMemory(process_sp, m_memory_addr, file_size);
1782     if (!data_sp)
1783       return false;
1784     m_data.SetData(data_sp, 0, file_size);
1785   }
1786 
1787   return dst.SetData(m_data, offset, length);
1788 }
1789 
1790 const ObjectFileELF::ELFSectionHeaderInfo *
1791 ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id) {
1792   if (!id || !ParseSectionHeaders())
1793     return NULL;
1794 
1795   if (--id < m_section_headers.size())
1796     return &m_section_headers[id];
1797 
1798   return NULL;
1799 }
1800 
1801 lldb::user_id_t ObjectFileELF::GetSectionIndexByName(const char *name) {
1802   if (!name || !name[0] || !ParseSectionHeaders())
1803     return 0;
1804   for (size_t i = 1; i < m_section_headers.size(); ++i)
1805     if (m_section_headers[i].section_name == ConstString(name))
1806       return i;
1807   return 0;
1808 }
1809 
1810 void ObjectFileELF::CreateSections(SectionList &unified_section_list) {
1811   if (!m_sections_ap.get() && ParseSectionHeaders()) {
1812     m_sections_ap.reset(new SectionList());
1813 
1814     for (SectionHeaderCollIter I = m_section_headers.begin();
1815          I != m_section_headers.end(); ++I) {
1816       const ELFSectionHeaderInfo &header = *I;
1817 
1818       ConstString &name = I->section_name;
1819       const uint64_t file_size =
1820           header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
1821       const uint64_t vm_size = header.sh_flags & SHF_ALLOC ? header.sh_size : 0;
1822 
1823       static ConstString g_sect_name_text(".text");
1824       static ConstString g_sect_name_data(".data");
1825       static ConstString g_sect_name_bss(".bss");
1826       static ConstString g_sect_name_tdata(".tdata");
1827       static ConstString g_sect_name_tbss(".tbss");
1828       static ConstString g_sect_name_dwarf_debug_abbrev(".debug_abbrev");
1829       static ConstString g_sect_name_dwarf_debug_addr(".debug_addr");
1830       static ConstString g_sect_name_dwarf_debug_aranges(".debug_aranges");
1831       static ConstString g_sect_name_dwarf_debug_frame(".debug_frame");
1832       static ConstString g_sect_name_dwarf_debug_info(".debug_info");
1833       static ConstString g_sect_name_dwarf_debug_line(".debug_line");
1834       static ConstString g_sect_name_dwarf_debug_loc(".debug_loc");
1835       static ConstString g_sect_name_dwarf_debug_macinfo(".debug_macinfo");
1836       static ConstString g_sect_name_dwarf_debug_macro(".debug_macro");
1837       static ConstString g_sect_name_dwarf_debug_pubnames(".debug_pubnames");
1838       static ConstString g_sect_name_dwarf_debug_pubtypes(".debug_pubtypes");
1839       static ConstString g_sect_name_dwarf_debug_ranges(".debug_ranges");
1840       static ConstString g_sect_name_dwarf_debug_str(".debug_str");
1841       static ConstString g_sect_name_dwarf_debug_str_offsets(
1842           ".debug_str_offsets");
1843       static ConstString g_sect_name_dwarf_debug_abbrev_dwo(
1844           ".debug_abbrev.dwo");
1845       static ConstString g_sect_name_dwarf_debug_info_dwo(".debug_info.dwo");
1846       static ConstString g_sect_name_dwarf_debug_line_dwo(".debug_line.dwo");
1847       static ConstString g_sect_name_dwarf_debug_macro_dwo(".debug_macro.dwo");
1848       static ConstString g_sect_name_dwarf_debug_loc_dwo(".debug_loc.dwo");
1849       static ConstString g_sect_name_dwarf_debug_str_dwo(".debug_str.dwo");
1850       static ConstString g_sect_name_dwarf_debug_str_offsets_dwo(
1851           ".debug_str_offsets.dwo");
1852       static ConstString g_sect_name_eh_frame(".eh_frame");
1853       static ConstString g_sect_name_arm_exidx(".ARM.exidx");
1854       static ConstString g_sect_name_arm_extab(".ARM.extab");
1855       static ConstString g_sect_name_go_symtab(".gosymtab");
1856 
1857       SectionType sect_type = eSectionTypeOther;
1858 
1859       bool is_thread_specific = false;
1860 
1861       if (name == g_sect_name_text)
1862         sect_type = eSectionTypeCode;
1863       else if (name == g_sect_name_data)
1864         sect_type = eSectionTypeData;
1865       else if (name == g_sect_name_bss)
1866         sect_type = eSectionTypeZeroFill;
1867       else if (name == g_sect_name_tdata) {
1868         sect_type = eSectionTypeData;
1869         is_thread_specific = true;
1870       } else if (name == g_sect_name_tbss) {
1871         sect_type = eSectionTypeZeroFill;
1872         is_thread_specific = true;
1873       }
1874       // .debug_abbrev – Abbreviations used in the .debug_info section
1875       // .debug_aranges – Lookup table for mapping addresses to compilation
1876       // units
1877       // .debug_frame – Call frame information
1878       // .debug_info – The core DWARF information section
1879       // .debug_line – Line number information
1880       // .debug_loc – Location lists used in DW_AT_location attributes
1881       // .debug_macinfo – Macro information
1882       // .debug_pubnames – Lookup table for mapping object and function names to
1883       // compilation units
1884       // .debug_pubtypes – Lookup table for mapping type names to compilation
1885       // units
1886       // .debug_ranges – Address ranges used in DW_AT_ranges attributes
1887       // .debug_str – String table used in .debug_info
1888       // MISSING? .gnu_debugdata - "mini debuginfo / MiniDebugInfo" section,
1889       // http://sourceware.org/gdb/onlinedocs/gdb/MiniDebugInfo.html
1890       // MISSING? .debug-index -
1891       // http://src.chromium.org/viewvc/chrome/trunk/src/build/gdb-add-index?pathrev=144644
1892       // MISSING? .debug_types - Type descriptions from DWARF 4? See
1893       // http://gcc.gnu.org/wiki/DwarfSeparateTypeInfo
1894       else if (name == g_sect_name_dwarf_debug_abbrev)
1895         sect_type = eSectionTypeDWARFDebugAbbrev;
1896       else if (name == g_sect_name_dwarf_debug_addr)
1897         sect_type = eSectionTypeDWARFDebugAddr;
1898       else if (name == g_sect_name_dwarf_debug_aranges)
1899         sect_type = eSectionTypeDWARFDebugAranges;
1900       else if (name == g_sect_name_dwarf_debug_frame)
1901         sect_type = eSectionTypeDWARFDebugFrame;
1902       else if (name == g_sect_name_dwarf_debug_info)
1903         sect_type = eSectionTypeDWARFDebugInfo;
1904       else if (name == g_sect_name_dwarf_debug_line)
1905         sect_type = eSectionTypeDWARFDebugLine;
1906       else if (name == g_sect_name_dwarf_debug_loc)
1907         sect_type = eSectionTypeDWARFDebugLoc;
1908       else if (name == g_sect_name_dwarf_debug_macinfo)
1909         sect_type = eSectionTypeDWARFDebugMacInfo;
1910       else if (name == g_sect_name_dwarf_debug_macro)
1911         sect_type = eSectionTypeDWARFDebugMacro;
1912       else if (name == g_sect_name_dwarf_debug_pubnames)
1913         sect_type = eSectionTypeDWARFDebugPubNames;
1914       else if (name == g_sect_name_dwarf_debug_pubtypes)
1915         sect_type = eSectionTypeDWARFDebugPubTypes;
1916       else if (name == g_sect_name_dwarf_debug_ranges)
1917         sect_type = eSectionTypeDWARFDebugRanges;
1918       else if (name == g_sect_name_dwarf_debug_str)
1919         sect_type = eSectionTypeDWARFDebugStr;
1920       else if (name == g_sect_name_dwarf_debug_str_offsets)
1921         sect_type = eSectionTypeDWARFDebugStrOffsets;
1922       else if (name == g_sect_name_dwarf_debug_abbrev_dwo)
1923         sect_type = eSectionTypeDWARFDebugAbbrev;
1924       else if (name == g_sect_name_dwarf_debug_info_dwo)
1925         sect_type = eSectionTypeDWARFDebugInfo;
1926       else if (name == g_sect_name_dwarf_debug_line_dwo)
1927         sect_type = eSectionTypeDWARFDebugLine;
1928       else if (name == g_sect_name_dwarf_debug_macro_dwo)
1929         sect_type = eSectionTypeDWARFDebugMacro;
1930       else if (name == g_sect_name_dwarf_debug_loc_dwo)
1931         sect_type = eSectionTypeDWARFDebugLoc;
1932       else if (name == g_sect_name_dwarf_debug_str_dwo)
1933         sect_type = eSectionTypeDWARFDebugStr;
1934       else if (name == g_sect_name_dwarf_debug_str_offsets_dwo)
1935         sect_type = eSectionTypeDWARFDebugStrOffsets;
1936       else if (name == g_sect_name_eh_frame)
1937         sect_type = eSectionTypeEHFrame;
1938       else if (name == g_sect_name_arm_exidx)
1939         sect_type = eSectionTypeARMexidx;
1940       else if (name == g_sect_name_arm_extab)
1941         sect_type = eSectionTypeARMextab;
1942       else if (name == g_sect_name_go_symtab)
1943         sect_type = eSectionTypeGoSymtab;
1944 
1945       const uint32_t permissions =
1946           ((header.sh_flags & SHF_ALLOC) ? ePermissionsReadable : 0u) |
1947           ((header.sh_flags & SHF_WRITE) ? ePermissionsWritable : 0u) |
1948           ((header.sh_flags & SHF_EXECINSTR) ? ePermissionsExecutable : 0u);
1949       switch (header.sh_type) {
1950       case SHT_SYMTAB:
1951         assert(sect_type == eSectionTypeOther);
1952         sect_type = eSectionTypeELFSymbolTable;
1953         break;
1954       case SHT_DYNSYM:
1955         assert(sect_type == eSectionTypeOther);
1956         sect_type = eSectionTypeELFDynamicSymbols;
1957         break;
1958       case SHT_RELA:
1959       case SHT_REL:
1960         assert(sect_type == eSectionTypeOther);
1961         sect_type = eSectionTypeELFRelocationEntries;
1962         break;
1963       case SHT_DYNAMIC:
1964         assert(sect_type == eSectionTypeOther);
1965         sect_type = eSectionTypeELFDynamicLinkInfo;
1966         break;
1967       }
1968 
1969       if (eSectionTypeOther == sect_type) {
1970         // the kalimba toolchain assumes that ELF section names are free-form.
1971         // It does
1972         // support linkscripts which (can) give rise to various arbitrarily
1973         // named
1974         // sections being "Code" or "Data".
1975         sect_type = kalimbaSectionType(m_header, header);
1976       }
1977 
1978       const uint32_t target_bytes_size =
1979           (eSectionTypeData == sect_type || eSectionTypeZeroFill == sect_type)
1980               ? m_arch_spec.GetDataByteSize()
1981               : eSectionTypeCode == sect_type ? m_arch_spec.GetCodeByteSize()
1982                                               : 1;
1983 
1984       elf::elf_xword log2align =
1985           (header.sh_addralign == 0) ? 0 : llvm::Log2_64(header.sh_addralign);
1986       SectionSP section_sp(new Section(
1987           GetModule(), // Module to which this section belongs.
1988           this, // ObjectFile to which this section belongs and should read
1989                 // section data from.
1990           SectionIndex(I),     // Section ID.
1991           name,                // Section name.
1992           sect_type,           // Section type.
1993           header.sh_addr,      // VM address.
1994           vm_size,             // VM size in bytes of this section.
1995           header.sh_offset,    // Offset of this section in the file.
1996           file_size,           // Size of the section as found in the file.
1997           log2align,           // Alignment of the section
1998           header.sh_flags,     // Flags for this section.
1999           target_bytes_size)); // Number of host bytes per target byte
2000 
2001       section_sp->SetPermissions(permissions);
2002       if (is_thread_specific)
2003         section_sp->SetIsThreadSpecific(is_thread_specific);
2004       m_sections_ap->AddSection(section_sp);
2005     }
2006   }
2007 
2008   if (m_sections_ap.get()) {
2009     if (GetType() == eTypeDebugInfo) {
2010       static const SectionType g_sections[] = {
2011           eSectionTypeDWARFDebugAbbrev,     eSectionTypeDWARFDebugAddr,
2012           eSectionTypeDWARFDebugAranges,    eSectionTypeDWARFDebugFrame,
2013           eSectionTypeDWARFDebugInfo,       eSectionTypeDWARFDebugLine,
2014           eSectionTypeDWARFDebugLoc,        eSectionTypeDWARFDebugMacInfo,
2015           eSectionTypeDWARFDebugPubNames,   eSectionTypeDWARFDebugPubTypes,
2016           eSectionTypeDWARFDebugRanges,     eSectionTypeDWARFDebugStr,
2017           eSectionTypeDWARFDebugStrOffsets, eSectionTypeELFSymbolTable,
2018       };
2019       SectionList *elf_section_list = m_sections_ap.get();
2020       for (size_t idx = 0; idx < sizeof(g_sections) / sizeof(g_sections[0]);
2021            ++idx) {
2022         SectionType section_type = g_sections[idx];
2023         SectionSP section_sp(
2024             elf_section_list->FindSectionByType(section_type, true));
2025         if (section_sp) {
2026           SectionSP module_section_sp(
2027               unified_section_list.FindSectionByType(section_type, true));
2028           if (module_section_sp)
2029             unified_section_list.ReplaceSection(module_section_sp->GetID(),
2030                                                 section_sp);
2031           else
2032             unified_section_list.AddSection(section_sp);
2033         }
2034       }
2035     } else {
2036       unified_section_list = *m_sections_ap;
2037     }
2038   }
2039 }
2040 
2041 // Find the arm/aarch64 mapping symbol character in the given symbol name.
2042 // Mapping symbols have the
2043 // form of "$<char>[.<any>]*". Additionally we recognize cases when the mapping
2044 // symbol prefixed by
2045 // an arbitrary string because if a symbol prefix added to each symbol in the
2046 // object file with
2047 // objcopy then the mapping symbols are also prefixed.
2048 static char FindArmAarch64MappingSymbol(const char *symbol_name) {
2049   if (!symbol_name)
2050     return '\0';
2051 
2052   const char *dollar_pos = ::strchr(symbol_name, '$');
2053   if (!dollar_pos || dollar_pos[1] == '\0')
2054     return '\0';
2055 
2056   if (dollar_pos[2] == '\0' || dollar_pos[2] == '.')
2057     return dollar_pos[1];
2058   return '\0';
2059 }
2060 
2061 #define STO_MIPS_ISA (3 << 6)
2062 #define STO_MICROMIPS (2 << 6)
2063 #define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS)
2064 
2065 // private
2066 unsigned ObjectFileELF::ParseSymbols(Symtab *symtab, user_id_t start_id,
2067                                      SectionList *section_list,
2068                                      const size_t num_symbols,
2069                                      const DataExtractor &symtab_data,
2070                                      const DataExtractor &strtab_data) {
2071   ELFSymbol symbol;
2072   lldb::offset_t offset = 0;
2073 
2074   static ConstString text_section_name(".text");
2075   static ConstString init_section_name(".init");
2076   static ConstString fini_section_name(".fini");
2077   static ConstString ctors_section_name(".ctors");
2078   static ConstString dtors_section_name(".dtors");
2079 
2080   static ConstString data_section_name(".data");
2081   static ConstString rodata_section_name(".rodata");
2082   static ConstString rodata1_section_name(".rodata1");
2083   static ConstString data2_section_name(".data1");
2084   static ConstString bss_section_name(".bss");
2085   static ConstString opd_section_name(".opd"); // For ppc64
2086 
2087   // On Android the oatdata and the oatexec symbols in the oat and odex files
2088   // covers the full
2089   // .text section what causes issues with displaying unusable symbol name to
2090   // the user and very
2091   // slow unwinding speed because the instruction emulation based unwind plans
2092   // try to emulate all
2093   // instructions in these symbols. Don't add these symbols to the symbol list
2094   // as they have no
2095   // use for the debugger and they are causing a lot of trouble.
2096   // Filtering can't be restricted to Android because this special object file
2097   // don't contain the
2098   // note section specifying the environment to Android but the custom extension
2099   // and file name
2100   // makes it highly unlikely that this will collide with anything else.
2101   ConstString file_extension = m_file.GetFileNameExtension();
2102   bool skip_oatdata_oatexec = file_extension == ConstString("oat") ||
2103                               file_extension == ConstString("odex");
2104 
2105   ArchSpec arch;
2106   GetArchitecture(arch);
2107   ModuleSP module_sp(GetModule());
2108   SectionList *module_section_list =
2109       module_sp ? module_sp->GetSectionList() : nullptr;
2110 
2111   // Local cache to avoid doing a FindSectionByName for each symbol. The "const
2112   // char*" key must
2113   // came from a ConstString object so they can be compared by pointer
2114   std::unordered_map<const char *, lldb::SectionSP> section_name_to_section;
2115 
2116   unsigned i;
2117   for (i = 0; i < num_symbols; ++i) {
2118     if (symbol.Parse(symtab_data, &offset) == false)
2119       break;
2120 
2121     const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
2122     if (!symbol_name)
2123       symbol_name = "";
2124 
2125     // No need to add non-section symbols that have no names
2126     if (symbol.getType() != STT_SECTION &&
2127         (symbol_name == nullptr || symbol_name[0] == '\0'))
2128       continue;
2129 
2130     // Skipping oatdata and oatexec sections if it is requested. See details
2131     // above the
2132     // definition of skip_oatdata_oatexec for the reasons.
2133     if (skip_oatdata_oatexec && (::strcmp(symbol_name, "oatdata") == 0 ||
2134                                  ::strcmp(symbol_name, "oatexec") == 0))
2135       continue;
2136 
2137     SectionSP symbol_section_sp;
2138     SymbolType symbol_type = eSymbolTypeInvalid;
2139     Elf64_Half section_idx = symbol.st_shndx;
2140 
2141     switch (section_idx) {
2142     case SHN_ABS:
2143       symbol_type = eSymbolTypeAbsolute;
2144       break;
2145     case SHN_UNDEF:
2146       symbol_type = eSymbolTypeUndefined;
2147       break;
2148     default:
2149       symbol_section_sp = section_list->GetSectionAtIndex(section_idx);
2150       break;
2151     }
2152 
2153     // If a symbol is undefined do not process it further even if it has a STT
2154     // type
2155     if (symbol_type != eSymbolTypeUndefined) {
2156       switch (symbol.getType()) {
2157       default:
2158       case STT_NOTYPE:
2159         // The symbol's type is not specified.
2160         break;
2161 
2162       case STT_OBJECT:
2163         // The symbol is associated with a data object, such as a variable,
2164         // an array, etc.
2165         symbol_type = eSymbolTypeData;
2166         break;
2167 
2168       case STT_FUNC:
2169         // The symbol is associated with a function or other executable code.
2170         symbol_type = eSymbolTypeCode;
2171         break;
2172 
2173       case STT_SECTION:
2174         // The symbol is associated with a section. Symbol table entries of
2175         // this type exist primarily for relocation and normally have
2176         // STB_LOCAL binding.
2177         break;
2178 
2179       case STT_FILE:
2180         // Conventionally, the symbol's name gives the name of the source
2181         // file associated with the object file. A file symbol has STB_LOCAL
2182         // binding, its section index is SHN_ABS, and it precedes the other
2183         // STB_LOCAL symbols for the file, if it is present.
2184         symbol_type = eSymbolTypeSourceFile;
2185         break;
2186 
2187       case STT_GNU_IFUNC:
2188         // The symbol is associated with an indirect function. The actual
2189         // function will be resolved if it is referenced.
2190         symbol_type = eSymbolTypeResolver;
2191         break;
2192       }
2193     }
2194 
2195     if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) {
2196       if (symbol_section_sp) {
2197         const ConstString &sect_name = symbol_section_sp->GetName();
2198         if (sect_name == text_section_name || sect_name == init_section_name ||
2199             sect_name == fini_section_name || sect_name == ctors_section_name ||
2200             sect_name == dtors_section_name) {
2201           symbol_type = eSymbolTypeCode;
2202         } else if (sect_name == data_section_name ||
2203                    sect_name == data2_section_name ||
2204                    sect_name == rodata_section_name ||
2205                    sect_name == rodata1_section_name ||
2206                    sect_name == bss_section_name) {
2207           symbol_type = eSymbolTypeData;
2208         }
2209       }
2210     }
2211 
2212     int64_t symbol_value_offset = 0;
2213     uint32_t additional_flags = 0;
2214 
2215     if (arch.IsValid()) {
2216       if (arch.GetMachine() == llvm::Triple::arm) {
2217         if (symbol.getBinding() == STB_LOCAL) {
2218           char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2219           if (symbol_type == eSymbolTypeCode) {
2220             switch (mapping_symbol) {
2221             case 'a':
2222               // $a[.<any>]* - marks an ARM instruction sequence
2223               m_address_class_map[symbol.st_value] = eAddressClassCode;
2224               break;
2225             case 'b':
2226             case 't':
2227               // $b[.<any>]* - marks a THUMB BL instruction sequence
2228               // $t[.<any>]* - marks a THUMB instruction sequence
2229               m_address_class_map[symbol.st_value] =
2230                   eAddressClassCodeAlternateISA;
2231               break;
2232             case 'd':
2233               // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2234               m_address_class_map[symbol.st_value] = eAddressClassData;
2235               break;
2236             }
2237           }
2238           if (mapping_symbol)
2239             continue;
2240         }
2241       } else if (arch.GetMachine() == llvm::Triple::aarch64) {
2242         if (symbol.getBinding() == STB_LOCAL) {
2243           char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2244           if (symbol_type == eSymbolTypeCode) {
2245             switch (mapping_symbol) {
2246             case 'x':
2247               // $x[.<any>]* - marks an A64 instruction sequence
2248               m_address_class_map[symbol.st_value] = eAddressClassCode;
2249               break;
2250             case 'd':
2251               // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2252               m_address_class_map[symbol.st_value] = eAddressClassData;
2253               break;
2254             }
2255           }
2256           if (mapping_symbol)
2257             continue;
2258         }
2259       }
2260 
2261       if (arch.GetMachine() == llvm::Triple::arm) {
2262         if (symbol_type == eSymbolTypeCode) {
2263           if (symbol.st_value & 1) {
2264             // Subtracting 1 from the address effectively unsets
2265             // the low order bit, which results in the address
2266             // actually pointing to the beginning of the symbol.
2267             // This delta will be used below in conjunction with
2268             // symbol.st_value to produce the final symbol_value
2269             // that we store in the symtab.
2270             symbol_value_offset = -1;
2271             m_address_class_map[symbol.st_value ^ 1] =
2272                 eAddressClassCodeAlternateISA;
2273           } else {
2274             // This address is ARM
2275             m_address_class_map[symbol.st_value] = eAddressClassCode;
2276           }
2277         }
2278       }
2279 
2280       /*
2281        * MIPS:
2282        * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for
2283        * MIPS).
2284        * This allows processor to switch between microMIPS and MIPS without any
2285        * need
2286        * for special mode-control register. However, apart from .debug_line,
2287        * none of
2288        * the ELF/DWARF sections set the ISA bit (for symbol or section). Use
2289        * st_other
2290        * flag to check whether the symbol is microMIPS and then set the address
2291        * class
2292        * accordingly.
2293       */
2294       const llvm::Triple::ArchType llvm_arch = arch.GetMachine();
2295       if (llvm_arch == llvm::Triple::mips ||
2296           llvm_arch == llvm::Triple::mipsel ||
2297           llvm_arch == llvm::Triple::mips64 ||
2298           llvm_arch == llvm::Triple::mips64el) {
2299         if (IS_MICROMIPS(symbol.st_other))
2300           m_address_class_map[symbol.st_value] = eAddressClassCodeAlternateISA;
2301         else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) {
2302           symbol.st_value = symbol.st_value & (~1ull);
2303           m_address_class_map[symbol.st_value] = eAddressClassCodeAlternateISA;
2304         } else {
2305           if (symbol_type == eSymbolTypeCode)
2306             m_address_class_map[symbol.st_value] = eAddressClassCode;
2307           else if (symbol_type == eSymbolTypeData)
2308             m_address_class_map[symbol.st_value] = eAddressClassData;
2309           else
2310             m_address_class_map[symbol.st_value] = eAddressClassUnknown;
2311         }
2312       }
2313     }
2314 
2315     // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB
2316     // symbols. See above for
2317     // more details.
2318     uint64_t symbol_value = symbol.st_value + symbol_value_offset;
2319 
2320     if (symbol_section_sp == nullptr && section_idx == SHN_ABS &&
2321         symbol.st_size != 0) {
2322       // We don't have a section for a symbol with non-zero size. Create a new
2323       // section for it
2324       // so the address range covered by the symbol is also covered by the
2325       // module (represented
2326       // through the section list). It is needed so module lookup for the
2327       // addresses covered
2328       // by this symbol will be successfull. This case happens for absolute
2329       // symbols.
2330       ConstString fake_section_name(std::string(".absolute.") + symbol_name);
2331       symbol_section_sp =
2332           std::make_shared<Section>(module_sp, this, SHN_ABS, fake_section_name,
2333                                     eSectionTypeAbsoluteAddress, symbol_value,
2334                                     symbol.st_size, 0, 0, 0, SHF_ALLOC);
2335 
2336       module_section_list->AddSection(symbol_section_sp);
2337       section_list->AddSection(symbol_section_sp);
2338     }
2339 
2340     if (symbol_section_sp &&
2341         CalculateType() != ObjectFile::Type::eTypeObjectFile)
2342       symbol_value -= symbol_section_sp->GetFileAddress();
2343 
2344     if (symbol_section_sp && module_section_list &&
2345         module_section_list != section_list) {
2346       const ConstString &sect_name = symbol_section_sp->GetName();
2347       auto section_it = section_name_to_section.find(sect_name.GetCString());
2348       if (section_it == section_name_to_section.end())
2349         section_it =
2350             section_name_to_section
2351                 .emplace(sect_name.GetCString(),
2352                          module_section_list->FindSectionByName(sect_name))
2353                 .first;
2354       if (section_it->second && section_it->second->GetFileSize())
2355         symbol_section_sp = section_it->second;
2356     }
2357 
2358     bool is_global = symbol.getBinding() == STB_GLOBAL;
2359     uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags;
2360     bool is_mangled = (symbol_name[0] == '_' && symbol_name[1] == 'Z');
2361 
2362     llvm::StringRef symbol_ref(symbol_name);
2363 
2364     // Symbol names may contain @VERSION suffixes. Find those and strip them
2365     // temporarily.
2366     size_t version_pos = symbol_ref.find('@');
2367     bool has_suffix = version_pos != llvm::StringRef::npos;
2368     llvm::StringRef symbol_bare = symbol_ref.substr(0, version_pos);
2369     Mangled mangled(ConstString(symbol_bare), is_mangled);
2370 
2371     // Now append the suffix back to mangled and unmangled names. Only do it if
2372     // the
2373     // demangling was successful (string is not empty).
2374     if (has_suffix) {
2375       llvm::StringRef suffix = symbol_ref.substr(version_pos);
2376 
2377       llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef();
2378       if (!mangled_name.empty())
2379         mangled.SetMangledName(ConstString((mangled_name + suffix).str()));
2380 
2381       ConstString demangled =
2382           mangled.GetDemangledName(lldb::eLanguageTypeUnknown);
2383       llvm::StringRef demangled_name = demangled.GetStringRef();
2384       if (!demangled_name.empty())
2385         mangled.SetDemangledName(ConstString((demangled_name + suffix).str()));
2386     }
2387 
2388     // In ELF all symbol should have a valid size but it is not true for some
2389     // function symbols
2390     // coming from hand written assembly. As none of the function symbol should
2391     // have 0 size we
2392     // try to calculate the size for these symbols in the symtab with saying
2393     // that their original
2394     // size is not valid.
2395     bool symbol_size_valid =
2396         symbol.st_size != 0 || symbol.getType() != STT_FUNC;
2397 
2398     Symbol dc_symbol(
2399         i + start_id, // ID is the original symbol table index.
2400         mangled,
2401         symbol_type,                    // Type of this symbol
2402         is_global,                      // Is this globally visible?
2403         false,                          // Is this symbol debug info?
2404         false,                          // Is this symbol a trampoline?
2405         false,                          // Is this symbol artificial?
2406         AddressRange(symbol_section_sp, // Section in which this symbol is
2407                                         // defined or null.
2408                      symbol_value,      // Offset in section or symbol value.
2409                      symbol.st_size),   // Size in bytes of this symbol.
2410         symbol_size_valid,              // Symbol size is valid
2411         has_suffix,                     // Contains linker annotations?
2412         flags);                         // Symbol flags.
2413     symtab->AddSymbol(dc_symbol);
2414   }
2415   return i;
2416 }
2417 
2418 unsigned ObjectFileELF::ParseSymbolTable(Symtab *symbol_table,
2419                                          user_id_t start_id,
2420                                          lldb_private::Section *symtab) {
2421   if (symtab->GetObjectFile() != this) {
2422     // If the symbol table section is owned by a different object file, have it
2423     // do the
2424     // parsing.
2425     ObjectFileELF *obj_file_elf =
2426         static_cast<ObjectFileELF *>(symtab->GetObjectFile());
2427     return obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab);
2428   }
2429 
2430   // Get section list for this object file.
2431   SectionList *section_list = m_sections_ap.get();
2432   if (!section_list)
2433     return 0;
2434 
2435   user_id_t symtab_id = symtab->GetID();
2436   const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2437   assert(symtab_hdr->sh_type == SHT_SYMTAB ||
2438          symtab_hdr->sh_type == SHT_DYNSYM);
2439 
2440   // sh_link: section header index of associated string table.
2441   // Section ID's are ones based.
2442   user_id_t strtab_id = symtab_hdr->sh_link + 1;
2443   Section *strtab = section_list->FindSectionByID(strtab_id).get();
2444 
2445   if (symtab && strtab) {
2446     assert(symtab->GetObjectFile() == this);
2447     assert(strtab->GetObjectFile() == this);
2448 
2449     DataExtractor symtab_data;
2450     DataExtractor strtab_data;
2451     if (ReadSectionData(symtab, symtab_data) &&
2452         ReadSectionData(strtab, strtab_data)) {
2453       size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
2454 
2455       return ParseSymbols(symbol_table, start_id, section_list, num_symbols,
2456                           symtab_data, strtab_data);
2457     }
2458   }
2459 
2460   return 0;
2461 }
2462 
2463 size_t ObjectFileELF::ParseDynamicSymbols() {
2464   if (m_dynamic_symbols.size())
2465     return m_dynamic_symbols.size();
2466 
2467   SectionList *section_list = GetSectionList();
2468   if (!section_list)
2469     return 0;
2470 
2471   // Find the SHT_DYNAMIC section.
2472   Section *dynsym =
2473       section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
2474           .get();
2475   if (!dynsym)
2476     return 0;
2477   assert(dynsym->GetObjectFile() == this);
2478 
2479   ELFDynamic symbol;
2480   DataExtractor dynsym_data;
2481   if (ReadSectionData(dynsym, dynsym_data)) {
2482     const lldb::offset_t section_size = dynsym_data.GetByteSize();
2483     lldb::offset_t cursor = 0;
2484 
2485     while (cursor < section_size) {
2486       if (!symbol.Parse(dynsym_data, &cursor))
2487         break;
2488 
2489       m_dynamic_symbols.push_back(symbol);
2490     }
2491   }
2492 
2493   return m_dynamic_symbols.size();
2494 }
2495 
2496 const ELFDynamic *ObjectFileELF::FindDynamicSymbol(unsigned tag) {
2497   if (!ParseDynamicSymbols())
2498     return NULL;
2499 
2500   DynamicSymbolCollIter I = m_dynamic_symbols.begin();
2501   DynamicSymbolCollIter E = m_dynamic_symbols.end();
2502   for (; I != E; ++I) {
2503     ELFDynamic *symbol = &*I;
2504 
2505     if (symbol->d_tag == tag)
2506       return symbol;
2507   }
2508 
2509   return NULL;
2510 }
2511 
2512 unsigned ObjectFileELF::PLTRelocationType() {
2513   // DT_PLTREL
2514   //  This member specifies the type of relocation entry to which the
2515   //  procedure linkage table refers. The d_val member holds DT_REL or
2516   //  DT_RELA, as appropriate. All relocations in a procedure linkage table
2517   //  must use the same relocation.
2518   const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
2519 
2520   if (symbol)
2521     return symbol->d_val;
2522 
2523   return 0;
2524 }
2525 
2526 // Returns the size of the normal plt entries and the offset of the first normal
2527 // plt entry. The
2528 // 0th entry in the plt table is usually a resolution entry which have different
2529 // size in some
2530 // architectures then the rest of the plt entries.
2531 static std::pair<uint64_t, uint64_t>
2532 GetPltEntrySizeAndOffset(const ELFSectionHeader *rel_hdr,
2533                          const ELFSectionHeader *plt_hdr) {
2534   const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2535 
2536   // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are 16
2537   // bytes.
2538   // So round the entsize up by the alignment if addralign is set.
2539   elf_xword plt_entsize =
2540       plt_hdr->sh_addralign
2541           ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign)
2542           : plt_hdr->sh_entsize;
2543 
2544   // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly.
2545   // PLT entries relocation code in general requires multiple instruction and
2546   // should be greater than 4 bytes in most cases. Try to guess correct size
2547   // just in case.
2548   if (plt_entsize <= 4) {
2549     // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the
2550     // size of the plt
2551     // entries based on the number of entries and the size of the plt section
2552     // with the
2553     // assumption that the size of the 0th entry is at least as big as the size
2554     // of the normal
2555     // entries and it isn't much bigger then that.
2556     if (plt_hdr->sh_addralign)
2557       plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign /
2558                     (num_relocations + 1) * plt_hdr->sh_addralign;
2559     else
2560       plt_entsize = plt_hdr->sh_size / (num_relocations + 1);
2561   }
2562 
2563   elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize;
2564 
2565   return std::make_pair(plt_entsize, plt_offset);
2566 }
2567 
2568 static unsigned ParsePLTRelocations(
2569     Symtab *symbol_table, user_id_t start_id, unsigned rel_type,
2570     const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2571     const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr,
2572     const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data,
2573     DataExtractor &symtab_data, DataExtractor &strtab_data) {
2574   ELFRelocation rel(rel_type);
2575   ELFSymbol symbol;
2576   lldb::offset_t offset = 0;
2577 
2578   uint64_t plt_offset, plt_entsize;
2579   std::tie(plt_entsize, plt_offset) =
2580       GetPltEntrySizeAndOffset(rel_hdr, plt_hdr);
2581   const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2582 
2583   typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2584   reloc_info_fn reloc_type;
2585   reloc_info_fn reloc_symbol;
2586 
2587   if (hdr->Is32Bit()) {
2588     reloc_type = ELFRelocation::RelocType32;
2589     reloc_symbol = ELFRelocation::RelocSymbol32;
2590   } else {
2591     reloc_type = ELFRelocation::RelocType64;
2592     reloc_symbol = ELFRelocation::RelocSymbol64;
2593   }
2594 
2595   unsigned slot_type = hdr->GetRelocationJumpSlotType();
2596   unsigned i;
2597   for (i = 0; i < num_relocations; ++i) {
2598     if (rel.Parse(rel_data, &offset) == false)
2599       break;
2600 
2601     if (reloc_type(rel) != slot_type)
2602       continue;
2603 
2604     lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
2605     if (!symbol.Parse(symtab_data, &symbol_offset))
2606       break;
2607 
2608     const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
2609     bool is_mangled =
2610         symbol_name ? (symbol_name[0] == '_' && symbol_name[1] == 'Z') : false;
2611     uint64_t plt_index = plt_offset + i * plt_entsize;
2612 
2613     Symbol jump_symbol(
2614         i + start_id,          // Symbol table index
2615         symbol_name,           // symbol name.
2616         is_mangled,            // is the symbol name mangled?
2617         eSymbolTypeTrampoline, // Type of this symbol
2618         false,                 // Is this globally visible?
2619         false,                 // Is this symbol debug info?
2620         true,                  // Is this symbol a trampoline?
2621         true,                  // Is this symbol artificial?
2622         plt_section_sp, // Section in which this symbol is defined or null.
2623         plt_index,      // Offset in section or symbol value.
2624         plt_entsize,    // Size in bytes of this symbol.
2625         true,           // Size is valid
2626         false,          // Contains linker annotations?
2627         0);             // Symbol flags.
2628 
2629     symbol_table->AddSymbol(jump_symbol);
2630   }
2631 
2632   return i;
2633 }
2634 
2635 unsigned
2636 ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table, user_id_t start_id,
2637                                       const ELFSectionHeaderInfo *rel_hdr,
2638                                       user_id_t rel_id) {
2639   assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2640 
2641   // The link field points to the associated symbol table.
2642   user_id_t symtab_id = rel_hdr->sh_link;
2643 
2644   // If the link field doesn't point to the appropriate symbol name table then
2645   // try to find it by name as some compiler don't fill in the link fields.
2646   if (!symtab_id)
2647     symtab_id = GetSectionIndexByName(".dynsym");
2648 
2649   // Get PLT section.  We cannot use rel_hdr->sh_info, since current linkers
2650   // point that to the .got.plt or .got section instead of .plt.
2651   user_id_t plt_id = GetSectionIndexByName(".plt");
2652 
2653   if (!symtab_id || !plt_id)
2654     return 0;
2655 
2656   // Section ID's are ones based;
2657   symtab_id++;
2658   plt_id++;
2659 
2660   const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
2661   if (!plt_hdr)
2662     return 0;
2663 
2664   const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
2665   if (!sym_hdr)
2666     return 0;
2667 
2668   SectionList *section_list = m_sections_ap.get();
2669   if (!section_list)
2670     return 0;
2671 
2672   Section *rel_section = section_list->FindSectionByID(rel_id).get();
2673   if (!rel_section)
2674     return 0;
2675 
2676   SectionSP plt_section_sp(section_list->FindSectionByID(plt_id));
2677   if (!plt_section_sp)
2678     return 0;
2679 
2680   Section *symtab = section_list->FindSectionByID(symtab_id).get();
2681   if (!symtab)
2682     return 0;
2683 
2684   // sh_link points to associated string table.
2685   Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link + 1).get();
2686   if (!strtab)
2687     return 0;
2688 
2689   DataExtractor rel_data;
2690   if (!ReadSectionData(rel_section, rel_data))
2691     return 0;
2692 
2693   DataExtractor symtab_data;
2694   if (!ReadSectionData(symtab, symtab_data))
2695     return 0;
2696 
2697   DataExtractor strtab_data;
2698   if (!ReadSectionData(strtab, strtab_data))
2699     return 0;
2700 
2701   unsigned rel_type = PLTRelocationType();
2702   if (!rel_type)
2703     return 0;
2704 
2705   return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header,
2706                              rel_hdr, plt_hdr, sym_hdr, plt_section_sp,
2707                              rel_data, symtab_data, strtab_data);
2708 }
2709 
2710 unsigned ObjectFileELF::RelocateSection(
2711     Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2712     const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr,
2713     DataExtractor &rel_data, DataExtractor &symtab_data,
2714     DataExtractor &debug_data, Section *rel_section) {
2715   ELFRelocation rel(rel_hdr->sh_type);
2716   lldb::addr_t offset = 0;
2717   const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2718   typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2719   reloc_info_fn reloc_type;
2720   reloc_info_fn reloc_symbol;
2721 
2722   if (hdr->Is32Bit()) {
2723     reloc_type = ELFRelocation::RelocType32;
2724     reloc_symbol = ELFRelocation::RelocSymbol32;
2725   } else {
2726     reloc_type = ELFRelocation::RelocType64;
2727     reloc_symbol = ELFRelocation::RelocSymbol64;
2728   }
2729 
2730   for (unsigned i = 0; i < num_relocations; ++i) {
2731     if (rel.Parse(rel_data, &offset) == false)
2732       break;
2733 
2734     Symbol *symbol = NULL;
2735 
2736     if (hdr->Is32Bit()) {
2737       switch (reloc_type(rel)) {
2738       case R_386_32:
2739       case R_386_PC32:
2740       default:
2741         assert(false && "unexpected relocation type");
2742       }
2743     } else {
2744       switch (reloc_type(rel)) {
2745       case R_X86_64_64: {
2746         symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2747         if (symbol) {
2748           addr_t value = symbol->GetAddressRef().GetFileAddress();
2749           DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2750           uint64_t *dst = reinterpret_cast<uint64_t *>(
2751               data_buffer_sp->GetBytes() + rel_section->GetFileOffset() +
2752               ELFRelocation::RelocOffset64(rel));
2753           *dst = value + ELFRelocation::RelocAddend64(rel);
2754         }
2755         break;
2756       }
2757       case R_X86_64_32:
2758       case R_X86_64_32S: {
2759         symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2760         if (symbol) {
2761           addr_t value = symbol->GetAddressRef().GetFileAddress();
2762           value += ELFRelocation::RelocAddend32(rel);
2763           assert(
2764               (reloc_type(rel) == R_X86_64_32 && (value <= UINT32_MAX)) ||
2765               (reloc_type(rel) == R_X86_64_32S &&
2766                ((int64_t)value <= INT32_MAX && (int64_t)value >= INT32_MIN)));
2767           uint32_t truncated_addr = (value & 0xFFFFFFFF);
2768           DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2769           uint32_t *dst = reinterpret_cast<uint32_t *>(
2770               data_buffer_sp->GetBytes() + rel_section->GetFileOffset() +
2771               ELFRelocation::RelocOffset32(rel));
2772           *dst = truncated_addr;
2773         }
2774         break;
2775       }
2776       case R_X86_64_PC32:
2777       default:
2778         assert(false && "unexpected relocation type");
2779       }
2780     }
2781   }
2782 
2783   return 0;
2784 }
2785 
2786 unsigned ObjectFileELF::RelocateDebugSections(const ELFSectionHeader *rel_hdr,
2787                                               user_id_t rel_id) {
2788   assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2789 
2790   // Parse in the section list if needed.
2791   SectionList *section_list = GetSectionList();
2792   if (!section_list)
2793     return 0;
2794 
2795   // Section ID's are ones based.
2796   user_id_t symtab_id = rel_hdr->sh_link + 1;
2797   user_id_t debug_id = rel_hdr->sh_info + 1;
2798 
2799   const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2800   if (!symtab_hdr)
2801     return 0;
2802 
2803   const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id);
2804   if (!debug_hdr)
2805     return 0;
2806 
2807   Section *rel = section_list->FindSectionByID(rel_id).get();
2808   if (!rel)
2809     return 0;
2810 
2811   Section *symtab = section_list->FindSectionByID(symtab_id).get();
2812   if (!symtab)
2813     return 0;
2814 
2815   Section *debug = section_list->FindSectionByID(debug_id).get();
2816   if (!debug)
2817     return 0;
2818 
2819   DataExtractor rel_data;
2820   DataExtractor symtab_data;
2821   DataExtractor debug_data;
2822 
2823   if (ReadSectionData(rel, rel_data) && ReadSectionData(symtab, symtab_data) &&
2824       ReadSectionData(debug, debug_data)) {
2825     RelocateSection(m_symtab_ap.get(), &m_header, rel_hdr, symtab_hdr,
2826                     debug_hdr, rel_data, symtab_data, debug_data, debug);
2827   }
2828 
2829   return 0;
2830 }
2831 
2832 Symtab *ObjectFileELF::GetSymtab() {
2833   ModuleSP module_sp(GetModule());
2834   if (!module_sp)
2835     return NULL;
2836 
2837   // We always want to use the main object file so we (hopefully) only have one
2838   // cached copy
2839   // of our symtab, dynamic sections, etc.
2840   ObjectFile *module_obj_file = module_sp->GetObjectFile();
2841   if (module_obj_file && module_obj_file != this)
2842     return module_obj_file->GetSymtab();
2843 
2844   if (m_symtab_ap.get() == NULL) {
2845     SectionList *section_list = module_sp->GetSectionList();
2846     if (!section_list)
2847       return NULL;
2848 
2849     uint64_t symbol_id = 0;
2850     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
2851 
2852     // Sharable objects and dynamic executables usually have 2 distinct symbol
2853     // tables, one named ".symtab", and the other ".dynsym". The dynsym is a
2854     // smaller
2855     // version of the symtab that only contains global symbols. The information
2856     // found
2857     // in the dynsym is therefore also found in the symtab, while the reverse is
2858     // not
2859     // necessarily true.
2860     Section *symtab =
2861         section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get();
2862     if (!symtab) {
2863       // The symtab section is non-allocable and can be stripped, so if it
2864       // doesn't exist
2865       // then use the dynsym section which should always be there.
2866       symtab =
2867           section_list->FindSectionByType(eSectionTypeELFDynamicSymbols, true)
2868               .get();
2869     }
2870     if (symtab) {
2871       m_symtab_ap.reset(new Symtab(symtab->GetObjectFile()));
2872       symbol_id += ParseSymbolTable(m_symtab_ap.get(), symbol_id, symtab);
2873     }
2874 
2875     // DT_JMPREL
2876     //      If present, this entry's d_ptr member holds the address of
2877     //      relocation
2878     //      entries associated solely with the procedure linkage table.
2879     //      Separating
2880     //      these relocation entries lets the dynamic linker ignore them during
2881     //      process initialization, if lazy binding is enabled. If this entry is
2882     //      present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
2883     //      also be present.
2884     const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
2885     if (symbol) {
2886       // Synthesize trampoline symbols to help navigate the PLT.
2887       addr_t addr = symbol->d_ptr;
2888       Section *reloc_section =
2889           section_list->FindSectionContainingFileAddress(addr).get();
2890       if (reloc_section) {
2891         user_id_t reloc_id = reloc_section->GetID();
2892         const ELFSectionHeaderInfo *reloc_header =
2893             GetSectionHeaderByIndex(reloc_id);
2894         assert(reloc_header);
2895 
2896         if (m_symtab_ap == nullptr)
2897           m_symtab_ap.reset(new Symtab(reloc_section->GetObjectFile()));
2898 
2899         ParseTrampolineSymbols(m_symtab_ap.get(), symbol_id, reloc_header,
2900                                reloc_id);
2901       }
2902     }
2903 
2904     DWARFCallFrameInfo *eh_frame = GetUnwindTable().GetEHFrameInfo();
2905     if (eh_frame) {
2906       if (m_symtab_ap == nullptr)
2907         m_symtab_ap.reset(new Symtab(this));
2908       ParseUnwindSymbols(m_symtab_ap.get(), eh_frame);
2909     }
2910 
2911     // If we still don't have any symtab then create an empty instance to avoid
2912     // do the section
2913     // lookup next time.
2914     if (m_symtab_ap == nullptr)
2915       m_symtab_ap.reset(new Symtab(this));
2916 
2917     m_symtab_ap->CalculateSymbolSizes();
2918   }
2919 
2920   for (SectionHeaderCollIter I = m_section_headers.begin();
2921        I != m_section_headers.end(); ++I) {
2922     if (I->sh_type == SHT_RELA || I->sh_type == SHT_REL) {
2923       if (CalculateType() == eTypeObjectFile) {
2924         const char *section_name = I->section_name.AsCString("");
2925         if (strstr(section_name, ".rela.debug") ||
2926             strstr(section_name, ".rel.debug")) {
2927           const ELFSectionHeader &reloc_header = *I;
2928           user_id_t reloc_id = SectionIndex(I);
2929           RelocateDebugSections(&reloc_header, reloc_id);
2930         }
2931       }
2932     }
2933   }
2934   return m_symtab_ap.get();
2935 }
2936 
2937 void ObjectFileELF::ParseUnwindSymbols(Symtab *symbol_table,
2938                                        DWARFCallFrameInfo *eh_frame) {
2939   SectionList *section_list = GetSectionList();
2940   if (!section_list)
2941     return;
2942 
2943   // First we save the new symbols into a separate list and add them to the
2944   // symbol table after
2945   // we colleced all symbols we want to add. This is neccessary because adding a
2946   // new symbol
2947   // invalidates the internal index of the symtab what causing the next lookup
2948   // to be slow because
2949   // it have to recalculate the index first.
2950   std::vector<Symbol> new_symbols;
2951 
2952   eh_frame->ForEachFDEEntries([this, symbol_table, section_list, &new_symbols](
2953       lldb::addr_t file_addr, uint32_t size, dw_offset_t) {
2954     Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr);
2955     if (symbol) {
2956       if (!symbol->GetByteSizeIsValid()) {
2957         symbol->SetByteSize(size);
2958         symbol->SetSizeIsSynthesized(true);
2959       }
2960     } else {
2961       SectionSP section_sp =
2962           section_list->FindSectionContainingFileAddress(file_addr);
2963       if (section_sp) {
2964         addr_t offset = file_addr - section_sp->GetFileAddress();
2965         const char *symbol_name = GetNextSyntheticSymbolName().GetCString();
2966         uint64_t symbol_id = symbol_table->GetNumSymbols();
2967         Symbol eh_symbol(
2968             symbol_id,       // Symbol table index.
2969             symbol_name,     // Symbol name.
2970             false,           // Is the symbol name mangled?
2971             eSymbolTypeCode, // Type of this symbol.
2972             true,            // Is this globally visible?
2973             false,           // Is this symbol debug info?
2974             false,           // Is this symbol a trampoline?
2975             true,            // Is this symbol artificial?
2976             section_sp,      // Section in which this symbol is defined or null.
2977             offset,          // Offset in section or symbol value.
2978             0,     // Size:          Don't specify the size as an FDE can
2979             false, // Size is valid: cover multiple symbols.
2980             false, // Contains linker annotations?
2981             0);    // Symbol flags.
2982         new_symbols.push_back(eh_symbol);
2983       }
2984     }
2985     return true;
2986   });
2987 
2988   for (const Symbol &s : new_symbols)
2989     symbol_table->AddSymbol(s);
2990 }
2991 
2992 bool ObjectFileELF::IsStripped() {
2993   // TODO: determine this for ELF
2994   return false;
2995 }
2996 
2997 //===----------------------------------------------------------------------===//
2998 // Dump
2999 //
3000 // Dump the specifics of the runtime file container (such as any headers
3001 // segments, sections, etc).
3002 //----------------------------------------------------------------------
3003 void ObjectFileELF::Dump(Stream *s) {
3004   ModuleSP module_sp(GetModule());
3005   if (!module_sp) {
3006     return;
3007   }
3008 
3009   std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
3010   s->Printf("%p: ", static_cast<void *>(this));
3011   s->Indent();
3012   s->PutCString("ObjectFileELF");
3013 
3014   ArchSpec header_arch;
3015   GetArchitecture(header_arch);
3016 
3017   *s << ", file = '" << m_file
3018      << "', arch = " << header_arch.GetArchitectureName() << "\n";
3019 
3020   DumpELFHeader(s, m_header);
3021   s->EOL();
3022   DumpELFProgramHeaders(s);
3023   s->EOL();
3024   DumpELFSectionHeaders(s);
3025   s->EOL();
3026   SectionList *section_list = GetSectionList();
3027   if (section_list)
3028     section_list->Dump(s, NULL, true, UINT32_MAX);
3029   Symtab *symtab = GetSymtab();
3030   if (symtab)
3031     symtab->Dump(s, NULL, eSortOrderNone);
3032   s->EOL();
3033   DumpDependentModules(s);
3034   s->EOL();
3035 }
3036 
3037 //----------------------------------------------------------------------
3038 // DumpELFHeader
3039 //
3040 // Dump the ELF header to the specified output stream
3041 //----------------------------------------------------------------------
3042 void ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header) {
3043   s->PutCString("ELF Header\n");
3044   s->Printf("e_ident[EI_MAG0   ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
3045   s->Printf("e_ident[EI_MAG1   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG1],
3046             header.e_ident[EI_MAG1]);
3047   s->Printf("e_ident[EI_MAG2   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG2],
3048             header.e_ident[EI_MAG2]);
3049   s->Printf("e_ident[EI_MAG3   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG3],
3050             header.e_ident[EI_MAG3]);
3051 
3052   s->Printf("e_ident[EI_CLASS  ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
3053   s->Printf("e_ident[EI_DATA   ] = 0x%2.2x ", header.e_ident[EI_DATA]);
3054   DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
3055   s->Printf("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
3056   s->Printf("e_ident[EI_PAD    ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
3057 
3058   s->Printf("e_type      = 0x%4.4x ", header.e_type);
3059   DumpELFHeader_e_type(s, header.e_type);
3060   s->Printf("\ne_machine   = 0x%4.4x\n", header.e_machine);
3061   s->Printf("e_version   = 0x%8.8x\n", header.e_version);
3062   s->Printf("e_entry     = 0x%8.8" PRIx64 "\n", header.e_entry);
3063   s->Printf("e_phoff     = 0x%8.8" PRIx64 "\n", header.e_phoff);
3064   s->Printf("e_shoff     = 0x%8.8" PRIx64 "\n", header.e_shoff);
3065   s->Printf("e_flags     = 0x%8.8x\n", header.e_flags);
3066   s->Printf("e_ehsize    = 0x%4.4x\n", header.e_ehsize);
3067   s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
3068   s->Printf("e_phnum     = 0x%4.4x\n", header.e_phnum);
3069   s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
3070   s->Printf("e_shnum     = 0x%4.4x\n", header.e_shnum);
3071   s->Printf("e_shstrndx  = 0x%4.4x\n", header.e_shstrndx);
3072 }
3073 
3074 //----------------------------------------------------------------------
3075 // DumpELFHeader_e_type
3076 //
3077 // Dump an token value for the ELF header member e_type
3078 //----------------------------------------------------------------------
3079 void ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type) {
3080   switch (e_type) {
3081   case ET_NONE:
3082     *s << "ET_NONE";
3083     break;
3084   case ET_REL:
3085     *s << "ET_REL";
3086     break;
3087   case ET_EXEC:
3088     *s << "ET_EXEC";
3089     break;
3090   case ET_DYN:
3091     *s << "ET_DYN";
3092     break;
3093   case ET_CORE:
3094     *s << "ET_CORE";
3095     break;
3096   default:
3097     break;
3098   }
3099 }
3100 
3101 //----------------------------------------------------------------------
3102 // DumpELFHeader_e_ident_EI_DATA
3103 //
3104 // Dump an token value for the ELF header member e_ident[EI_DATA]
3105 //----------------------------------------------------------------------
3106 void ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s,
3107                                                   unsigned char ei_data) {
3108   switch (ei_data) {
3109   case ELFDATANONE:
3110     *s << "ELFDATANONE";
3111     break;
3112   case ELFDATA2LSB:
3113     *s << "ELFDATA2LSB - Little Endian";
3114     break;
3115   case ELFDATA2MSB:
3116     *s << "ELFDATA2MSB - Big Endian";
3117     break;
3118   default:
3119     break;
3120   }
3121 }
3122 
3123 //----------------------------------------------------------------------
3124 // DumpELFProgramHeader
3125 //
3126 // Dump a single ELF program header to the specified output stream
3127 //----------------------------------------------------------------------
3128 void ObjectFileELF::DumpELFProgramHeader(Stream *s,
3129                                          const ELFProgramHeader &ph) {
3130   DumpELFProgramHeader_p_type(s, ph.p_type);
3131   s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset,
3132             ph.p_vaddr, ph.p_paddr);
3133   s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz,
3134             ph.p_flags);
3135 
3136   DumpELFProgramHeader_p_flags(s, ph.p_flags);
3137   s->Printf(") %8.8" PRIx64, ph.p_align);
3138 }
3139 
3140 //----------------------------------------------------------------------
3141 // DumpELFProgramHeader_p_type
3142 //
3143 // Dump an token value for the ELF program header member p_type which
3144 // describes the type of the program header
3145 // ----------------------------------------------------------------------
3146 void ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type) {
3147   const int kStrWidth = 15;
3148   switch (p_type) {
3149     CASE_AND_STREAM(s, PT_NULL, kStrWidth);
3150     CASE_AND_STREAM(s, PT_LOAD, kStrWidth);
3151     CASE_AND_STREAM(s, PT_DYNAMIC, kStrWidth);
3152     CASE_AND_STREAM(s, PT_INTERP, kStrWidth);
3153     CASE_AND_STREAM(s, PT_NOTE, kStrWidth);
3154     CASE_AND_STREAM(s, PT_SHLIB, kStrWidth);
3155     CASE_AND_STREAM(s, PT_PHDR, kStrWidth);
3156     CASE_AND_STREAM(s, PT_TLS, kStrWidth);
3157     CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
3158   default:
3159     s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
3160     break;
3161   }
3162 }
3163 
3164 //----------------------------------------------------------------------
3165 // DumpELFProgramHeader_p_flags
3166 //
3167 // Dump an token value for the ELF program header member p_flags
3168 //----------------------------------------------------------------------
3169 void ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags) {
3170   *s << ((p_flags & PF_X) ? "PF_X" : "    ")
3171      << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
3172      << ((p_flags & PF_W) ? "PF_W" : "    ")
3173      << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
3174      << ((p_flags & PF_R) ? "PF_R" : "    ");
3175 }
3176 
3177 //----------------------------------------------------------------------
3178 // DumpELFProgramHeaders
3179 //
3180 // Dump all of the ELF program header to the specified output stream
3181 //----------------------------------------------------------------------
3182 void ObjectFileELF::DumpELFProgramHeaders(Stream *s) {
3183   if (!ParseProgramHeaders())
3184     return;
3185 
3186   s->PutCString("Program Headers\n");
3187   s->PutCString("IDX  p_type          p_offset p_vaddr  p_paddr  "
3188                 "p_filesz p_memsz  p_flags                   p_align\n");
3189   s->PutCString("==== --------------- -------- -------- -------- "
3190                 "-------- -------- ------------------------- --------\n");
3191 
3192   uint32_t idx = 0;
3193   for (ProgramHeaderCollConstIter I = m_program_headers.begin();
3194        I != m_program_headers.end(); ++I, ++idx) {
3195     s->Printf("[%2u] ", idx);
3196     ObjectFileELF::DumpELFProgramHeader(s, *I);
3197     s->EOL();
3198   }
3199 }
3200 
3201 //----------------------------------------------------------------------
3202 // DumpELFSectionHeader
3203 //
3204 // Dump a single ELF section header to the specified output stream
3205 //----------------------------------------------------------------------
3206 void ObjectFileELF::DumpELFSectionHeader(Stream *s,
3207                                          const ELFSectionHeaderInfo &sh) {
3208   s->Printf("%8.8x ", sh.sh_name);
3209   DumpELFSectionHeader_sh_type(s, sh.sh_type);
3210   s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
3211   DumpELFSectionHeader_sh_flags(s, sh.sh_flags);
3212   s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr,
3213             sh.sh_offset, sh.sh_size);
3214   s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
3215   s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
3216 }
3217 
3218 //----------------------------------------------------------------------
3219 // DumpELFSectionHeader_sh_type
3220 //
3221 // Dump an token value for the ELF section header member sh_type which
3222 // describes the type of the section
3223 //----------------------------------------------------------------------
3224 void ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type) {
3225   const int kStrWidth = 12;
3226   switch (sh_type) {
3227     CASE_AND_STREAM(s, SHT_NULL, kStrWidth);
3228     CASE_AND_STREAM(s, SHT_PROGBITS, kStrWidth);
3229     CASE_AND_STREAM(s, SHT_SYMTAB, kStrWidth);
3230     CASE_AND_STREAM(s, SHT_STRTAB, kStrWidth);
3231     CASE_AND_STREAM(s, SHT_RELA, kStrWidth);
3232     CASE_AND_STREAM(s, SHT_HASH, kStrWidth);
3233     CASE_AND_STREAM(s, SHT_DYNAMIC, kStrWidth);
3234     CASE_AND_STREAM(s, SHT_NOTE, kStrWidth);
3235     CASE_AND_STREAM(s, SHT_NOBITS, kStrWidth);
3236     CASE_AND_STREAM(s, SHT_REL, kStrWidth);
3237     CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth);
3238     CASE_AND_STREAM(s, SHT_DYNSYM, kStrWidth);
3239     CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth);
3240     CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth);
3241     CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth);
3242     CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth);
3243   default:
3244     s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
3245     break;
3246   }
3247 }
3248 
3249 //----------------------------------------------------------------------
3250 // DumpELFSectionHeader_sh_flags
3251 //
3252 // Dump an token value for the ELF section header member sh_flags
3253 //----------------------------------------------------------------------
3254 void ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s,
3255                                                   elf_xword sh_flags) {
3256   *s << ((sh_flags & SHF_WRITE) ? "WRITE" : "     ")
3257      << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
3258      << ((sh_flags & SHF_ALLOC) ? "ALLOC" : "     ")
3259      << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
3260      << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : "         ");
3261 }
3262 
3263 //----------------------------------------------------------------------
3264 // DumpELFSectionHeaders
3265 //
3266 // Dump all of the ELF section header to the specified output stream
3267 //----------------------------------------------------------------------
3268 void ObjectFileELF::DumpELFSectionHeaders(Stream *s) {
3269   if (!ParseSectionHeaders())
3270     return;
3271 
3272   s->PutCString("Section Headers\n");
3273   s->PutCString("IDX  name     type         flags                            "
3274                 "addr     offset   size     link     info     addralgn "
3275                 "entsize  Name\n");
3276   s->PutCString("==== -------- ------------ -------------------------------- "
3277                 "-------- -------- -------- -------- -------- -------- "
3278                 "-------- ====================\n");
3279 
3280   uint32_t idx = 0;
3281   for (SectionHeaderCollConstIter I = m_section_headers.begin();
3282        I != m_section_headers.end(); ++I, ++idx) {
3283     s->Printf("[%2u] ", idx);
3284     ObjectFileELF::DumpELFSectionHeader(s, *I);
3285     const char *section_name = I->section_name.AsCString("");
3286     if (section_name)
3287       *s << ' ' << section_name << "\n";
3288   }
3289 }
3290 
3291 void ObjectFileELF::DumpDependentModules(lldb_private::Stream *s) {
3292   size_t num_modules = ParseDependentModules();
3293 
3294   if (num_modules > 0) {
3295     s->PutCString("Dependent Modules:\n");
3296     for (unsigned i = 0; i < num_modules; ++i) {
3297       const FileSpec &spec = m_filespec_ap->GetFileSpecAtIndex(i);
3298       s->Printf("   %s\n", spec.GetFilename().GetCString());
3299     }
3300   }
3301 }
3302 
3303 bool ObjectFileELF::GetArchitecture(ArchSpec &arch) {
3304   if (!ParseHeader())
3305     return false;
3306 
3307   if (m_section_headers.empty()) {
3308     // Allow elf notes to be parsed which may affect the detected architecture.
3309     ParseSectionHeaders();
3310   }
3311 
3312   if (CalculateType() == eTypeCoreFile &&
3313       m_arch_spec.TripleOSIsUnspecifiedUnknown()) {
3314     // Core files don't have section headers yet they have PT_NOTE program
3315     // headers
3316     // that might shed more light on the architecture
3317     if (ParseProgramHeaders()) {
3318       for (size_t i = 0, count = GetProgramHeaderCount(); i < count; ++i) {
3319         const elf::ELFProgramHeader *header = GetProgramHeaderByIndex(i);
3320         if (header && header->p_type == PT_NOTE && header->p_offset != 0 &&
3321             header->p_filesz > 0) {
3322           DataExtractor data;
3323           if (data.SetData(m_data, header->p_offset, header->p_filesz) ==
3324               header->p_filesz) {
3325             lldb_private::UUID uuid;
3326             RefineModuleDetailsFromNote(data, m_arch_spec, uuid);
3327           }
3328         }
3329       }
3330     }
3331   }
3332   arch = m_arch_spec;
3333   return true;
3334 }
3335 
3336 ObjectFile::Type ObjectFileELF::CalculateType() {
3337   switch (m_header.e_type) {
3338   case llvm::ELF::ET_NONE:
3339     // 0 - No file type
3340     return eTypeUnknown;
3341 
3342   case llvm::ELF::ET_REL:
3343     // 1 - Relocatable file
3344     return eTypeObjectFile;
3345 
3346   case llvm::ELF::ET_EXEC:
3347     // 2 - Executable file
3348     return eTypeExecutable;
3349 
3350   case llvm::ELF::ET_DYN:
3351     // 3 - Shared object file
3352     return eTypeSharedLibrary;
3353 
3354   case ET_CORE:
3355     // 4 - Core file
3356     return eTypeCoreFile;
3357 
3358   default:
3359     break;
3360   }
3361   return eTypeUnknown;
3362 }
3363 
3364 ObjectFile::Strata ObjectFileELF::CalculateStrata() {
3365   switch (m_header.e_type) {
3366   case llvm::ELF::ET_NONE:
3367     // 0 - No file type
3368     return eStrataUnknown;
3369 
3370   case llvm::ELF::ET_REL:
3371     // 1 - Relocatable file
3372     return eStrataUnknown;
3373 
3374   case llvm::ELF::ET_EXEC:
3375     // 2 - Executable file
3376     // TODO: is there any way to detect that an executable is a kernel
3377     // related executable by inspecting the program headers, section
3378     // headers, symbols, or any other flag bits???
3379     return eStrataUser;
3380 
3381   case llvm::ELF::ET_DYN:
3382     // 3 - Shared object file
3383     // TODO: is there any way to detect that an shared library is a kernel
3384     // related executable by inspecting the program headers, section
3385     // headers, symbols, or any other flag bits???
3386     return eStrataUnknown;
3387 
3388   case ET_CORE:
3389     // 4 - Core file
3390     // TODO: is there any way to detect that an core file is a kernel
3391     // related executable by inspecting the program headers, section
3392     // headers, symbols, or any other flag bits???
3393     return eStrataUnknown;
3394 
3395   default:
3396     break;
3397   }
3398   return eStrataUnknown;
3399 }
3400