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