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