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