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