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