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