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