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