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