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