LLDB mainline
ObjectFileELF.cpp
Go to the documentation of this file.
1//===-- ObjectFileELF.cpp -------------------------------------------------===//
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 <optional>
14#include <unordered_map>
15
16#include "lldb/Core/Module.h"
19#include "lldb/Core/Progress.h"
20#include "lldb/Core/Section.h"
22#include "lldb/Host/LZMA.h"
25#include "lldb/Target/Process.h"
27#include "lldb/Target/Target.h"
32#include "lldb/Utility/Log.h"
34#include "lldb/Utility/Status.h"
35#include "lldb/Utility/Stream.h"
36#include "lldb/Utility/Timer.h"
37#include "llvm/ADT/IntervalMap.h"
38#include "llvm/ADT/PointerUnion.h"
39#include "llvm/ADT/StringRef.h"
40#include "llvm/BinaryFormat/ELF.h"
41#include "llvm/Object/Decompressor.h"
42#include "llvm/Support/ARMBuildAttributes.h"
43#include "llvm/Support/CRC.h"
44#include "llvm/Support/FormatVariadic.h"
45#include "llvm/Support/MathExtras.h"
46#include "llvm/Support/MemoryBuffer.h"
47#include "llvm/Support/MipsABIFlags.h"
48
49#define CASE_AND_STREAM(s, def, width) \
50 case def: \
51 s->Printf("%-*s", width, #def); \
52 break;
53
54using namespace lldb;
55using namespace lldb_private;
56using namespace elf;
57using namespace llvm::ELF;
58
60
61// ELF note owner definitions
62static const char *const LLDB_NT_OWNER_FREEBSD = "FreeBSD";
63static const char *const LLDB_NT_OWNER_GNU = "GNU";
64static const char *const LLDB_NT_OWNER_NETBSD = "NetBSD";
65static const char *const LLDB_NT_OWNER_NETBSDCORE = "NetBSD-CORE";
66static const char *const LLDB_NT_OWNER_OPENBSD = "OpenBSD";
67static const char *const LLDB_NT_OWNER_ANDROID = "Android";
68static const char *const LLDB_NT_OWNER_CORE = "CORE";
69static const char *const LLDB_NT_OWNER_LINUX = "LINUX";
70
71// ELF note type definitions
74
75static const elf_word LLDB_NT_GNU_ABI_TAG = 0x01;
77
79
84
85// GNU ABI note OS constants
89
90namespace {
91
92//===----------------------------------------------------------------------===//
93/// \class ELFRelocation
94/// Generic wrapper for ELFRel and ELFRela.
95///
96/// This helper class allows us to parse both ELFRel and ELFRela relocation
97/// entries in a generic manner.
98class ELFRelocation {
99public:
100 /// Constructs an ELFRelocation entry with a personality as given by @p
101 /// type.
102 ///
103 /// \param type Either DT_REL or DT_RELA. Any other value is invalid.
104 ELFRelocation(unsigned type);
105
106 ~ELFRelocation();
107
108 bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset);
109
110 static unsigned RelocType32(const ELFRelocation &rel);
111
112 static unsigned RelocType64(const ELFRelocation &rel);
113
114 static unsigned RelocSymbol32(const ELFRelocation &rel);
115
116 static unsigned RelocSymbol64(const ELFRelocation &rel);
117
118 static elf_addr RelocOffset32(const ELFRelocation &rel);
119
120 static elf_addr RelocOffset64(const ELFRelocation &rel);
121
122 static elf_sxword RelocAddend32(const ELFRelocation &rel);
123
124 static elf_sxword RelocAddend64(const ELFRelocation &rel);
125
126 bool IsRela() { return (llvm::isa<ELFRela *>(reloc)); }
127
128private:
129 typedef llvm::PointerUnion<ELFRel *, ELFRela *> RelocUnion;
130
131 RelocUnion reloc;
132};
133
134lldb::SectionSP MergeSections(lldb::SectionSP lhs, lldb::SectionSP rhs) {
135 assert(lhs && rhs);
136
137 lldb::ModuleSP lhs_module_parent = lhs->GetModule();
138 lldb::ModuleSP rhs_module_parent = rhs->GetModule();
139 assert(lhs_module_parent && rhs_module_parent);
140
141 // Do a sanity check, these should be the same.
142 if (lhs->GetFileAddress() != rhs->GetFileAddress())
143 lhs_module_parent->ReportWarning(
144 "Mismatch addresses for section {0} when "
145 "merging with {1}, expected: {2:x}, "
146 "actual: {3:x}",
147 lhs->GetTypeAsCString(),
148 rhs_module_parent->GetFileSpec().GetPathAsConstString().GetCString(),
149 lhs->GetByteSize(), rhs->GetByteSize());
150
151 // We want to take the greater of two sections. If LHS and RHS are both
152 // SHT_NOBITS, we should default to LHS. If RHS has a bigger section,
153 // indicating it has data that wasn't stripped, we should take that instead.
154 return rhs->GetFileSize() > lhs->GetFileSize() ? rhs : lhs;
155}
156} // end anonymous namespace
157
158ELFRelocation::ELFRelocation(unsigned type) {
159 if (type == DT_REL || type == SHT_REL)
160 reloc = new ELFRel();
161 else if (type == DT_RELA || type == SHT_RELA)
162 reloc = new ELFRela();
163 else {
164 assert(false && "unexpected relocation type");
165 reloc = static_cast<ELFRel *>(nullptr);
166 }
167}
168
169ELFRelocation::~ELFRelocation() {
170 if (auto *elfrel = llvm::dyn_cast<ELFRel *>(reloc))
171 delete elfrel;
172 else
173 delete llvm::cast<ELFRela *>(reloc);
174}
175
176bool ELFRelocation::Parse(const lldb_private::DataExtractor &data,
177 lldb::offset_t *offset) {
178 if (auto *elfrel = llvm::dyn_cast<ELFRel *>(reloc))
179 return elfrel->Parse(data, offset);
180 else
181 return llvm::cast<ELFRela *>(reloc)->Parse(data, offset);
182}
183
184unsigned ELFRelocation::RelocType32(const ELFRelocation &rel) {
185 if (auto *elfrel = llvm::dyn_cast<ELFRel *>(rel.reloc))
186 return ELFRel::RelocType32(*elfrel);
187 else
188 return ELFRela::RelocType32(*llvm::cast<ELFRela *>(rel.reloc));
189}
190
191unsigned ELFRelocation::RelocType64(const ELFRelocation &rel) {
192 if (auto *elfrel = llvm::dyn_cast<ELFRel *>(rel.reloc))
193 return ELFRel::RelocType64(*elfrel);
194 else
195 return ELFRela::RelocType64(*llvm::cast<ELFRela *>(rel.reloc));
196}
197
198unsigned ELFRelocation::RelocSymbol32(const ELFRelocation &rel) {
199 if (auto *elfrel = llvm::dyn_cast<ELFRel *>(rel.reloc))
200 return ELFRel::RelocSymbol32(*elfrel);
201 else
202 return ELFRela::RelocSymbol32(*llvm::cast<ELFRela *>(rel.reloc));
203}
204
205unsigned ELFRelocation::RelocSymbol64(const ELFRelocation &rel) {
206 if (auto *elfrel = llvm::dyn_cast<ELFRel *>(rel.reloc))
207 return ELFRel::RelocSymbol64(*elfrel);
208 else
209 return ELFRela::RelocSymbol64(*llvm::cast<ELFRela *>(rel.reloc));
210}
211
212elf_addr ELFRelocation::RelocOffset32(const ELFRelocation &rel) {
213 if (auto *elfrel = llvm::dyn_cast<ELFRel *>(rel.reloc))
214 return elfrel->r_offset;
215 else
216 return llvm::cast<ELFRela *>(rel.reloc)->r_offset;
217}
218
219elf_addr ELFRelocation::RelocOffset64(const ELFRelocation &rel) {
220 if (auto *elfrel = llvm::dyn_cast<ELFRel *>(rel.reloc))
221 return elfrel->r_offset;
222 else
223 return llvm::cast<ELFRela *>(rel.reloc)->r_offset;
224}
225
226elf_sxword ELFRelocation::RelocAddend32(const ELFRelocation &rel) {
227 if (llvm::isa<ELFRel *>(rel.reloc))
228 return 0;
229 else
230 return llvm::cast<ELFRela *>(rel.reloc)->r_addend;
231}
232
233elf_sxword ELFRelocation::RelocAddend64(const ELFRelocation &rel) {
234 if (llvm::isa<ELFRel *>(rel.reloc))
235 return 0;
236 else
237 return llvm::cast<ELFRela *>(rel.reloc)->r_addend;
238}
239
240static user_id_t SegmentID(size_t PHdrIndex) {
241 return ~user_id_t(PHdrIndex);
242}
243
244bool ELFNote::Parse(const DataExtractor &data, lldb::offset_t *offset) {
245 // Read all fields.
246 if (data.GetU32(offset, &n_namesz, 3) == nullptr)
247 return false;
248
249 // The name field is required to be nul-terminated, and n_namesz includes the
250 // terminating nul in observed implementations (contrary to the ELF-64 spec).
251 // A special case is needed for cores generated by some older Linux versions,
252 // which write a note named "CORE" without a nul terminator and n_namesz = 4.
253 if (n_namesz == 4) {
254 char buf[4];
255 if (data.ExtractBytes(*offset, 4, data.GetByteOrder(), buf) != 4)
256 return false;
257 if (strncmp(buf, "CORE", 4) == 0) {
258 n_name = "CORE";
259 *offset += 4;
260 return true;
261 }
262 }
263
264 const char *cstr = data.GetCStr(offset, llvm::alignTo(n_namesz, 4));
265 if (cstr == nullptr) {
267 LLDB_LOGF(log, "Failed to parse note name lacking nul terminator");
268
269 return false;
270 }
271 n_name = cstr;
272 return true;
273}
274
275static uint32_t mipsVariantFromElfFlags (const elf::ELFHeader &header) {
276 const uint32_t mips_arch = header.e_flags & llvm::ELF::EF_MIPS_ARCH;
277 uint32_t endian = header.e_ident[EI_DATA];
278 uint32_t arch_variant = ArchSpec::eMIPSSubType_unknown;
279 uint32_t fileclass = header.e_ident[EI_CLASS];
280
281 // If there aren't any elf flags available (e.g core elf file) then return
282 // default
283 // 32 or 64 bit arch (without any architecture revision) based on object file's class.
284 if (header.e_type == ET_CORE) {
285 switch (fileclass) {
286 case llvm::ELF::ELFCLASS32:
287 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el
289 case llvm::ELF::ELFCLASS64:
290 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el
292 default:
293 return arch_variant;
294 }
295 }
296
297 switch (mips_arch) {
298 case llvm::ELF::EF_MIPS_ARCH_1:
299 case llvm::ELF::EF_MIPS_ARCH_2:
300 case llvm::ELF::EF_MIPS_ARCH_32:
301 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el
303 case llvm::ELF::EF_MIPS_ARCH_32R2:
304 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r2el
306 case llvm::ELF::EF_MIPS_ARCH_32R6:
307 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r6el
309 case llvm::ELF::EF_MIPS_ARCH_3:
310 case llvm::ELF::EF_MIPS_ARCH_4:
311 case llvm::ELF::EF_MIPS_ARCH_5:
312 case llvm::ELF::EF_MIPS_ARCH_64:
313 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el
315 case llvm::ELF::EF_MIPS_ARCH_64R2:
316 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r2el
318 case llvm::ELF::EF_MIPS_ARCH_64R6:
319 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r6el
321 default:
322 break;
323 }
324
325 return arch_variant;
326}
327
328static uint32_t riscvVariantFromElfFlags(const elf::ELFHeader &header) {
329 uint32_t fileclass = header.e_ident[EI_CLASS];
330 switch (fileclass) {
331 case llvm::ELF::ELFCLASS32:
333 case llvm::ELF::ELFCLASS64:
335 default:
337 }
338}
339
340static uint32_t ppc64VariantFromElfFlags(const elf::ELFHeader &header) {
341 uint32_t endian = header.e_ident[EI_DATA];
342 if (endian == ELFDATA2LSB)
344 else
346}
347
348static uint32_t loongarchVariantFromElfFlags(const elf::ELFHeader &header) {
349 uint32_t fileclass = header.e_ident[EI_CLASS];
350 switch (fileclass) {
351 case llvm::ELF::ELFCLASS32:
353 case llvm::ELF::ELFCLASS64:
355 default:
357 }
358}
359
360static uint32_t subTypeFromElfHeader(const elf::ELFHeader &header) {
361 if (header.e_machine == llvm::ELF::EM_MIPS)
362 return mipsVariantFromElfFlags(header);
363 else if (header.e_machine == llvm::ELF::EM_PPC64)
364 return ppc64VariantFromElfFlags(header);
365 else if (header.e_machine == llvm::ELF::EM_RISCV)
366 return riscvVariantFromElfFlags(header);
367 else if (header.e_machine == llvm::ELF::EM_LOONGARCH)
368 return loongarchVariantFromElfFlags(header);
369
371}
372
374
375// Arbitrary constant used as UUID prefix for core files.
376const uint32_t ObjectFileELF::g_core_uuid_magic(0xE210C);
377
378// Static methods.
384
388
390 DataBufferSP data_sp,
391 lldb::offset_t data_offset,
392 const lldb_private::FileSpec *file,
393 lldb::offset_t file_offset,
394 lldb::offset_t length) {
395 bool mapped_writable = false;
396 if (!data_sp) {
397 data_sp = MapFileDataWritable(*file, length, file_offset);
398 if (!data_sp)
399 return nullptr;
400 data_offset = 0;
401 mapped_writable = true;
402 }
403
404 assert(data_sp);
405
406 if (data_sp->GetByteSize() <= (llvm::ELF::EI_NIDENT + data_offset))
407 return nullptr;
408
409 const uint8_t *magic = data_sp->GetBytes() + data_offset;
410 if (!ELFHeader::MagicBytesMatch(magic))
411 return nullptr;
412
413 // Update the data to contain the entire file if it doesn't already
414 if (data_sp->GetByteSize() < length) {
415 data_sp = MapFileDataWritable(*file, length, file_offset);
416 if (!data_sp)
417 return nullptr;
418 data_offset = 0;
419 mapped_writable = true;
420 magic = data_sp->GetBytes();
421 }
422
423 // If we didn't map the data as writable take ownership of the buffer.
424 if (!mapped_writable) {
425 data_sp = std::make_shared<DataBufferHeap>(data_sp->GetBytes(),
426 data_sp->GetByteSize());
427 data_offset = 0;
428 magic = data_sp->GetBytes();
429 }
430
431 unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
432 if (address_size == 4 || address_size == 8) {
433 std::unique_ptr<ObjectFileELF> objfile_up(new ObjectFileELF(
434 module_sp, data_sp, data_offset, file, file_offset, length));
435 ArchSpec spec = objfile_up->GetArchitecture();
436 if (spec && objfile_up->SetModulesArchitecture(spec))
437 return objfile_up.release();
438 }
439
440 return nullptr;
441}
442
444 const lldb::ModuleSP &module_sp, WritableDataBufferSP data_sp,
445 const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {
446 if (!data_sp || data_sp->GetByteSize() < (llvm::ELF::EI_NIDENT))
447 return nullptr;
448 const uint8_t *magic = data_sp->GetBytes();
449 if (!ELFHeader::MagicBytesMatch(magic))
450 return nullptr;
451 // Read the ELF header first so we can figure out how many bytes we need
452 // to read to get as least the ELF header + program headers.
453 DataExtractor data;
454 data.SetData(data_sp);
455 elf::ELFHeader hdr;
456 lldb::offset_t offset = 0;
457 if (!hdr.Parse(data, &offset))
458 return nullptr;
459
460 // Make sure the address size is set correctly in the ELF header.
461 if (!hdr.Is32Bit() && !hdr.Is64Bit())
462 return nullptr;
463 // Figure out where the program headers end and read enough bytes to get the
464 // program headers in their entirety.
465 lldb::offset_t end_phdrs = hdr.e_phoff + (hdr.e_phentsize * hdr.e_phnum);
466 if (end_phdrs > data_sp->GetByteSize())
467 data_sp = ReadMemory(process_sp, header_addr, end_phdrs);
468
469 std::unique_ptr<ObjectFileELF> objfile_up(
470 new ObjectFileELF(module_sp, data_sp, process_sp, header_addr));
471 ArchSpec spec = objfile_up->GetArchitecture();
472 if (spec && objfile_up->SetModulesArchitecture(spec))
473 return objfile_up.release();
474
475 return nullptr;
476}
477
479 lldb::addr_t data_offset,
480 lldb::addr_t data_length) {
481 if (data_sp &&
482 data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset)) {
483 const uint8_t *magic = data_sp->GetBytes() + data_offset;
484 return ELFHeader::MagicBytesMatch(magic);
485 }
486 return false;
487}
488
489static uint32_t calc_crc32(uint32_t init, const DataExtractor &data) {
490 return llvm::crc32(init,
491 llvm::ArrayRef(data.GetDataStart(), data.GetByteSize()));
492}
493
495 const ProgramHeaderColl &program_headers, DataExtractor &object_data) {
496
497 uint32_t core_notes_crc = 0;
498
499 for (const ELFProgramHeader &H : program_headers) {
500 if (H.p_type == llvm::ELF::PT_NOTE) {
501 const elf_off ph_offset = H.p_offset;
502 const size_t ph_size = H.p_filesz;
503
504 DataExtractor segment_data;
505 if (segment_data.SetData(object_data, ph_offset, ph_size) != ph_size) {
506 // The ELF program header contained incorrect data, probably corefile
507 // is incomplete or corrupted.
508 break;
509 }
510
511 core_notes_crc = calc_crc32(core_notes_crc, segment_data);
512 }
513 }
514
515 return core_notes_crc;
516}
517
518static const char *OSABIAsCString(unsigned char osabi_byte) {
519#define _MAKE_OSABI_CASE(x) \
520 case x: \
521 return #x
522 switch (osabi_byte) {
523 _MAKE_OSABI_CASE(ELFOSABI_NONE);
524 _MAKE_OSABI_CASE(ELFOSABI_HPUX);
525 _MAKE_OSABI_CASE(ELFOSABI_NETBSD);
526 _MAKE_OSABI_CASE(ELFOSABI_GNU);
527 _MAKE_OSABI_CASE(ELFOSABI_HURD);
528 _MAKE_OSABI_CASE(ELFOSABI_SOLARIS);
529 _MAKE_OSABI_CASE(ELFOSABI_AIX);
530 _MAKE_OSABI_CASE(ELFOSABI_IRIX);
531 _MAKE_OSABI_CASE(ELFOSABI_FREEBSD);
532 _MAKE_OSABI_CASE(ELFOSABI_TRU64);
533 _MAKE_OSABI_CASE(ELFOSABI_MODESTO);
534 _MAKE_OSABI_CASE(ELFOSABI_OPENBSD);
535 _MAKE_OSABI_CASE(ELFOSABI_OPENVMS);
536 _MAKE_OSABI_CASE(ELFOSABI_NSK);
537 _MAKE_OSABI_CASE(ELFOSABI_AROS);
538 _MAKE_OSABI_CASE(ELFOSABI_FENIXOS);
539 _MAKE_OSABI_CASE(ELFOSABI_C6000_ELFABI);
540 _MAKE_OSABI_CASE(ELFOSABI_C6000_LINUX);
541 _MAKE_OSABI_CASE(ELFOSABI_ARM);
542 _MAKE_OSABI_CASE(ELFOSABI_STANDALONE);
543 default:
544 return "<unknown-osabi>";
545 }
546#undef _MAKE_OSABI_CASE
547}
548
549//
550// WARNING : This function is being deprecated
551// It's functionality has moved to ArchSpec::SetArchitecture This function is
552// only being kept to validate the move.
553//
554// TODO : Remove this function
555static bool GetOsFromOSABI(unsigned char osabi_byte,
556 llvm::Triple::OSType &ostype) {
557 switch (osabi_byte) {
558 case ELFOSABI_AIX:
559 ostype = llvm::Triple::OSType::AIX;
560 break;
561 case ELFOSABI_FREEBSD:
562 ostype = llvm::Triple::OSType::FreeBSD;
563 break;
564 case ELFOSABI_GNU:
565 ostype = llvm::Triple::OSType::Linux;
566 break;
567 case ELFOSABI_NETBSD:
568 ostype = llvm::Triple::OSType::NetBSD;
569 break;
570 case ELFOSABI_OPENBSD:
571 ostype = llvm::Triple::OSType::OpenBSD;
572 break;
573 case ELFOSABI_SOLARIS:
574 ostype = llvm::Triple::OSType::Solaris;
575 break;
576 default:
577 ostype = llvm::Triple::OSType::UnknownOS;
578 }
579 return ostype != llvm::Triple::OSType::UnknownOS;
580}
581
583 const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
584 lldb::offset_t data_offset, lldb::offset_t file_offset,
587
588 const size_t initial_count = specs.GetSize();
589
590 if (ObjectFileELF::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
591 DataExtractor data;
592 data.SetData(data_sp);
593 elf::ELFHeader header;
594 lldb::offset_t header_offset = data_offset;
595 if (header.Parse(data, &header_offset)) {
596 if (data_sp) {
597 ModuleSpec spec(file);
598 // In Android API level 23 and above, bionic dynamic linker is able to
599 // load .so file directly from zip file. In that case, .so file is
600 // page aligned and uncompressed, and this module spec should retain the
601 // .so file offset and file size to pass through the information from
602 // lldb-server to LLDB. For normal file, file_offset should be 0,
603 // length should be the size of the file.
604 spec.SetObjectOffset(file_offset);
605 spec.SetObjectSize(length);
606
607 const uint32_t sub_type = subTypeFromElfHeader(header);
609 eArchTypeELF, header.e_machine, sub_type, header.e_ident[EI_OSABI]);
610
611 if (spec.GetArchitecture().IsValid()) {
612 llvm::Triple::OSType ostype;
613 llvm::Triple::VendorType vendor;
614 llvm::Triple::OSType spec_ostype =
615 spec.GetArchitecture().GetTriple().getOS();
616
617 LLDB_LOGF(log, "ObjectFileELF::%s file '%s' module OSABI: %s",
618 __FUNCTION__, file.GetPath().c_str(),
619 OSABIAsCString(header.e_ident[EI_OSABI]));
620
621 // SetArchitecture should have set the vendor to unknown
622 vendor = spec.GetArchitecture().GetTriple().getVendor();
623 assert(vendor == llvm::Triple::UnknownVendor);
625
626 //
627 // Validate it is ok to remove GetOsFromOSABI
628 GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
629 assert(spec_ostype == ostype);
630 if (spec_ostype != llvm::Triple::OSType::UnknownOS) {
631 LLDB_LOGF(log,
632 "ObjectFileELF::%s file '%s' set ELF module OS type "
633 "from ELF header OSABI.",
634 __FUNCTION__, file.GetPath().c_str());
635 }
636
637 // When ELF file does not contain GNU build ID, the later code will
638 // calculate CRC32 with this data_sp file_offset and length. It is
639 // important for Android zip .so file, which is a slice of a file,
640 // to not access the outside of the file slice range.
641 if (data_sp->GetByteSize() < length)
642 data_sp = MapFileData(file, length, file_offset);
643 if (data_sp)
644 data.SetData(data_sp);
645 // In case there is header extension in the section #0, the header we
646 // parsed above could have sentinel values for e_phnum, e_shnum, and
647 // e_shstrndx. In this case we need to reparse the header with a
648 // bigger data source to get the actual values.
649 if (header.HasHeaderExtension()) {
650 lldb::offset_t header_offset = data_offset;
651 header.Parse(data, &header_offset);
652 }
653
654 uint32_t gnu_debuglink_crc = 0;
655 std::string gnu_debuglink_file;
656 SectionHeaderColl section_headers;
657 lldb_private::UUID &uuid = spec.GetUUID();
658
659 GetSectionHeaderInfo(section_headers, data, header, uuid,
660 gnu_debuglink_file, gnu_debuglink_crc,
661 spec.GetArchitecture());
662
663 llvm::Triple &spec_triple = spec.GetArchitecture().GetTriple();
664
665 LLDB_LOGF(log,
666 "ObjectFileELF::%s file '%s' module set to triple: %s "
667 "(architecture %s)",
668 __FUNCTION__, file.GetPath().c_str(),
669 spec_triple.getTriple().c_str(),
671
672 if (!uuid.IsValid()) {
673 uint32_t core_notes_crc = 0;
674
675 if (!gnu_debuglink_crc) {
677 "Calculating module crc32 %s with size %" PRIu64 " KiB",
678 file.GetFilename().AsCString(),
679 (length - file_offset) / 1024);
680
681 // For core files - which usually don't happen to have a
682 // gnu_debuglink, and are pretty bulky - calculating whole
683 // contents crc32 would be too much of luxury. Thus we will need
684 // to fallback to something simpler.
685 if (header.e_type == llvm::ELF::ET_CORE) {
686 ProgramHeaderColl program_headers;
687 GetProgramHeaderInfo(program_headers, data, header);
688
689 core_notes_crc =
690 CalculateELFNotesSegmentsCRC32(program_headers, data);
691 } else {
692 gnu_debuglink_crc = calc_crc32(0, data);
693 }
694 }
695 using u32le = llvm::support::ulittle32_t;
696 if (gnu_debuglink_crc) {
697 // Use 4 bytes of crc from the .gnu_debuglink section.
698 u32le data(gnu_debuglink_crc);
699 uuid = UUID(&data, sizeof(data));
700 } else if (core_notes_crc) {
701 // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make
702 // it look different form .gnu_debuglink crc followed by 4 bytes
703 // of note segments crc.
704 u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)};
705 uuid = UUID(data, sizeof(data));
706 }
707 }
708
709 specs.Append(spec);
710 }
711 }
712 }
713 }
714
715 return specs.GetSize() - initial_count;
716}
717
718// ObjectFile protocol
719
721 DataBufferSP data_sp, lldb::offset_t data_offset,
722 const FileSpec *file, lldb::offset_t file_offset,
723 lldb::offset_t length)
724 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset) {
725 if (file)
726 m_file = *file;
727}
728
730 DataBufferSP header_data_sp,
731 const lldb::ProcessSP &process_sp,
732 addr_t header_addr)
733 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp) {}
734
736 return ((m_header.e_type & ET_EXEC) != 0) || (m_header.e_entry != 0);
737}
738
740 bool value_is_offset) {
741 ModuleSP module_sp = GetModule();
742 if (module_sp) {
743 size_t num_loaded_sections = 0;
744 SectionList *section_list = GetSectionList();
745 if (section_list) {
746 if (!value_is_offset) {
748 if (base == LLDB_INVALID_ADDRESS)
749 return false;
750 value -= base;
751 }
752
753 const size_t num_sections = section_list->GetSize();
754 size_t sect_idx = 0;
755
756 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
757 // Iterate through the object file sections to find all of the sections
758 // that have SHF_ALLOC in their flag bits.
759 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
760
761 // PT_TLS segments can have the same p_vaddr and p_paddr as other
762 // PT_LOAD segments so we shouldn't load them. If we do load them, then
763 // the SectionLoadList will incorrectly fill in the instance variable
764 // SectionLoadList::m_addr_to_sect with the same address as a PT_LOAD
765 // segment and we won't be able to resolve addresses in the PT_LOAD
766 // segment whose p_vaddr entry matches that of the PT_TLS. Any variables
767 // that appear in the PT_TLS segments get resolved by the DWARF
768 // expressions. If this ever changes we will need to fix all object
769 // file plug-ins, but until then, we don't want PT_TLS segments to
770 // remove the entry from SectionLoadList::m_addr_to_sect when we call
771 // SetSectionLoadAddress() below.
772 if (section_sp->IsThreadSpecific())
773 continue;
774 if (section_sp->Test(SHF_ALLOC) ||
775 section_sp->GetType() == eSectionTypeContainer) {
776 lldb::addr_t load_addr = section_sp->GetFileAddress();
777 // We don't want to update the load address of a section with type
778 // eSectionTypeAbsoluteAddress as they already have the absolute load
779 // address already specified
780 if (section_sp->GetType() != eSectionTypeAbsoluteAddress)
781 load_addr += value;
782
783 // On 32-bit systems the load address have to fit into 4 bytes. The
784 // rest of the bytes are the overflow from the addition.
785 if (GetAddressByteSize() == 4)
786 load_addr &= 0xFFFFFFFF;
787
788 if (target.SetSectionLoadAddress(section_sp, load_addr))
789 ++num_loaded_sections;
790 }
791 }
792 return num_loaded_sections > 0;
793 }
794 }
795 return false;
796}
797
799 if (m_header.e_ident[EI_DATA] == ELFDATA2MSB)
800 return eByteOrderBig;
801 if (m_header.e_ident[EI_DATA] == ELFDATA2LSB)
802 return eByteOrderLittle;
803 return eByteOrderInvalid;
804}
805
807 return m_data.GetAddressByteSize();
808}
809
811 Symtab *symtab = GetSymtab();
812 if (!symtab)
814
815 // The address class is determined based on the symtab. Ask it from the
816 // object file what contains the symtab information.
817 ObjectFile *symtab_objfile = symtab->GetObjectFile();
818 if (symtab_objfile != nullptr && symtab_objfile != this)
819 return symtab_objfile->GetAddressClass(file_addr);
820
821 auto res = ObjectFile::GetAddressClass(file_addr);
822 if (res != AddressClass::eCode)
823 return res;
824
825 auto ub = m_address_class_map.upper_bound(file_addr);
826 if (ub == m_address_class_map.begin()) {
827 // No entry in the address class map before the address. Return default
828 // address class for an address in a code section.
829 return AddressClass::eCode;
830 }
831
832 // Move iterator to the address class entry preceding address
833 --ub;
834
835 return ub->second;
836}
837
839 return std::distance(m_section_headers.begin(), I);
840}
841
843 return std::distance(m_section_headers.begin(), I);
844}
845
847 lldb::offset_t offset = 0;
848 return m_header.Parse(m_data, &offset);
849}
850
852 if (m_uuid)
853 return m_uuid;
854
855 // Try loading note info from any PT_NOTE program headers. This is more
856 // friendly to ELF files that have no section headers, like ELF files that
857 // are loaded from memory.
858 for (const ELFProgramHeader &H : ProgramHeaders()) {
859 if (H.p_type == llvm::ELF::PT_NOTE) {
860 DataExtractor note_data = GetSegmentData(H);
861 if (note_data.GetByteSize()) {
862 lldb_private::ArchSpec arch_spec;
863 RefineModuleDetailsFromNote(note_data, arch_spec, m_uuid);
864 if (m_uuid)
865 return m_uuid;
866 }
867 }
868 }
869
870 // Need to parse the section list to get the UUIDs, so make sure that's been
871 // done.
873 return UUID();
874
875 if (!m_uuid) {
876 using u32le = llvm::support::ulittle32_t;
878 uint32_t core_notes_crc = 0;
879
880 if (!ParseProgramHeaders())
881 return UUID();
882
883 core_notes_crc =
885
886 if (core_notes_crc) {
887 // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it
888 // look different form .gnu_debuglink crc - followed by 4 bytes of note
889 // segments crc.
890 u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)};
891 m_uuid = UUID(data, sizeof(data));
892 }
893 } else {
897 // Use 4 bytes of crc from the .gnu_debuglink section.
898 u32le data(m_gnu_debuglink_crc);
899 m_uuid = UUID(&data, sizeof(data));
900 }
901 }
902 }
903
904 return m_uuid;
905}
906
907std::optional<FileSpec> ObjectFileELF::GetDebugLink() {
908 if (m_gnu_debuglink_file.empty())
909 return std::nullopt;
911}
912
914 size_t num_modules = ParseDependentModules();
915 uint32_t num_specs = 0;
916
917 for (unsigned i = 0; i < num_modules; ++i) {
918 if (files.AppendIfUnique(m_filespec_up->GetFileSpecAtIndex(i)))
919 num_specs++;
920 }
921
922 return num_specs;
923}
924
926 if (!ParseDynamicSymbols())
927 return Address();
928
929 SectionList *section_list = GetSectionList();
930 if (!section_list)
931 return Address();
932
933 for (size_t i = 0; i < m_dynamic_symbols.size(); ++i) {
934 const ELFDynamic &symbol = m_dynamic_symbols[i].symbol;
935
936 if (symbol.d_tag != DT_DEBUG && symbol.d_tag != DT_MIPS_RLD_MAP &&
937 symbol.d_tag != DT_MIPS_RLD_MAP_REL)
938 continue;
939
940 // Compute the offset as the number of previous entries plus the size of
941 // d_tag.
942 const addr_t offset = (i * 2 + 1) * GetAddressByteSize();
943 const addr_t d_file_addr = m_dynamic_base_addr + offset;
944 Address d_addr;
945 if (!d_addr.ResolveAddressUsingFileSections(d_file_addr, GetSectionList()))
946 return Address();
947 if (symbol.d_tag == DT_DEBUG)
948 return d_addr;
949
950 // MIPS executables uses DT_MIPS_RLD_MAP_REL to support PIE. DT_MIPS_RLD_MAP
951 // exists in non-PIE.
952 if ((symbol.d_tag == DT_MIPS_RLD_MAP ||
953 symbol.d_tag == DT_MIPS_RLD_MAP_REL) &&
954 target) {
955 const addr_t d_load_addr = d_addr.GetLoadAddress(target);
956 if (d_load_addr == LLDB_INVALID_ADDRESS)
957 return Address();
958
960 if (symbol.d_tag == DT_MIPS_RLD_MAP) {
961 // DT_MIPS_RLD_MAP tag stores an absolute address of the debug pointer.
962 Address addr;
963 if (target->ReadPointerFromMemory(d_load_addr, error, addr, true))
964 return addr;
965 }
966 if (symbol.d_tag == DT_MIPS_RLD_MAP_REL) {
967 // DT_MIPS_RLD_MAP_REL tag stores the offset to the debug pointer,
968 // relative to the address of the tag.
969 uint64_t rel_offset;
970 rel_offset = target->ReadUnsignedIntegerFromMemory(
971 d_load_addr, GetAddressByteSize(), UINT64_MAX, error, true);
972 if (error.Success() && rel_offset != UINT64_MAX) {
973 Address addr;
974 addr_t debug_ptr_address =
975 d_load_addr - GetAddressByteSize() + rel_offset;
976 addr.SetOffset(debug_ptr_address);
977 return addr;
978 }
979 }
980 }
981 }
982 return Address();
983}
984
986 if (m_entry_point_address.IsValid())
988
989 if (!ParseHeader() || !IsExecutable())
991
992 SectionList *section_list = GetSectionList();
993 addr_t offset = m_header.e_entry;
994
995 if (!section_list)
996 m_entry_point_address.SetOffset(offset);
997 else
998 m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list);
1000}
1001
1004 for (SectionHeaderCollIter I = std::next(m_section_headers.begin());
1005 I != m_section_headers.end(); ++I) {
1006 const ELFSectionHeaderInfo &header = *I;
1007 if (header.sh_flags & SHF_ALLOC)
1008 return Address(GetSectionList()->FindSectionByID(SectionIndex(I)), 0);
1009 }
1010 return LLDB_INVALID_ADDRESS;
1011 }
1012
1013 for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {
1014 const ELFProgramHeader &H = EnumPHdr.value();
1015 if (H.p_type != PT_LOAD)
1016 continue;
1017
1018 return Address(
1019 GetSectionList()->FindSectionByID(SegmentID(EnumPHdr.index())), 0);
1020 }
1021 return LLDB_INVALID_ADDRESS;
1022}
1023
1025 if (m_filespec_up)
1026 return m_filespec_up->GetSize();
1027
1028 m_filespec_up = std::make_unique<FileSpecList>();
1029
1030 if (ParseDynamicSymbols()) {
1031 for (const auto &entry : m_dynamic_symbols) {
1032 if (entry.symbol.d_tag != DT_NEEDED)
1033 continue;
1034 if (!entry.name.empty()) {
1035 FileSpec file_spec(entry.name);
1036 FileSystem::Instance().Resolve(file_spec);
1037 m_filespec_up->Append(file_spec);
1038 }
1039 }
1040 }
1041 return m_filespec_up->GetSize();
1042}
1043
1044// GetProgramHeaderInfo
1046 DataExtractor &object_data,
1047 const ELFHeader &header) {
1048 // We have already parsed the program headers
1049 if (!program_headers.empty())
1050 return program_headers.size();
1051
1052 // If there are no program headers to read we are done.
1053 if (header.e_phnum == 0)
1054 return 0;
1055
1056 program_headers.resize(header.e_phnum);
1057 if (program_headers.size() != header.e_phnum)
1058 return 0;
1059
1060 const size_t ph_size = header.e_phnum * header.e_phentsize;
1061 const elf_off ph_offset = header.e_phoff;
1062 DataExtractor data;
1063 if (data.SetData(object_data, ph_offset, ph_size) != ph_size)
1064 return 0;
1065
1066 uint32_t idx;
1067 lldb::offset_t offset;
1068 for (idx = 0, offset = 0; idx < header.e_phnum; ++idx) {
1069 if (!program_headers[idx].Parse(data, &offset))
1070 break;
1071 }
1072
1073 if (idx < program_headers.size())
1074 program_headers.resize(idx);
1075
1076 return program_headers.size();
1077}
1078
1079// ParseProgramHeaders
1083
1086 lldb_private::ArchSpec &arch_spec,
1087 lldb_private::UUID &uuid) {
1088 Log *log = GetLog(LLDBLog::Modules);
1089 Status error;
1090
1091 lldb::offset_t offset = 0;
1092
1093 while (true) {
1094 // Parse the note header. If this fails, bail out.
1095 const lldb::offset_t note_offset = offset;
1096 ELFNote note = ELFNote();
1097 if (!note.Parse(data, &offset)) {
1098 // We're done.
1099 return error;
1100 }
1101
1102 LLDB_LOGF(log, "ObjectFileELF::%s parsing note name='%s', type=%" PRIu32,
1103 __FUNCTION__, note.n_name.c_str(), note.n_type);
1104
1105 // Process FreeBSD ELF notes.
1106 if ((note.n_name == LLDB_NT_OWNER_FREEBSD) &&
1107 (note.n_type == LLDB_NT_FREEBSD_ABI_TAG) &&
1108 (note.n_descsz == LLDB_NT_FREEBSD_ABI_SIZE)) {
1109 // Pull out the min version info.
1110 uint32_t version_info;
1111 if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1112 error =
1113 Status::FromErrorString("failed to read FreeBSD ABI note payload");
1114 return error;
1115 }
1116
1117 // Convert the version info into a major/minor number.
1118 const uint32_t version_major = version_info / 100000;
1119 const uint32_t version_minor = (version_info / 1000) % 100;
1120
1121 char os_name[32];
1122 snprintf(os_name, sizeof(os_name), "freebsd%" PRIu32 ".%" PRIu32,
1123 version_major, version_minor);
1124
1125 // Set the elf OS version to FreeBSD. Also clear the vendor.
1126 arch_spec.GetTriple().setOSName(os_name);
1127 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1128
1129 LLDB_LOGF(log,
1130 "ObjectFileELF::%s detected FreeBSD %" PRIu32 ".%" PRIu32
1131 ".%" PRIu32,
1132 __FUNCTION__, version_major, version_minor,
1133 static_cast<uint32_t>(version_info % 1000));
1134 }
1135 // Process GNU ELF notes.
1136 else if (note.n_name == LLDB_NT_OWNER_GNU) {
1137 switch (note.n_type) {
1139 if (note.n_descsz == LLDB_NT_GNU_ABI_SIZE) {
1140 // Pull out the min OS version supporting the ABI.
1141 uint32_t version_info[4];
1142 if (data.GetU32(&offset, &version_info[0], note.n_descsz / 4) ==
1143 nullptr) {
1144 error =
1145 Status::FromErrorString("failed to read GNU ABI note payload");
1146 return error;
1147 }
1148
1149 // Set the OS per the OS field.
1150 switch (version_info[0]) {
1152 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1153 arch_spec.GetTriple().setVendor(
1154 llvm::Triple::VendorType::UnknownVendor);
1155 LLDB_LOGF(log,
1156 "ObjectFileELF::%s detected Linux, min version %" PRIu32
1157 ".%" PRIu32 ".%" PRIu32,
1158 __FUNCTION__, version_info[1], version_info[2],
1159 version_info[3]);
1160 // FIXME we have the minimal version number, we could be propagating
1161 // that. version_info[1] = OS Major, version_info[2] = OS Minor,
1162 // version_info[3] = Revision.
1163 break;
1165 arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
1166 arch_spec.GetTriple().setVendor(
1167 llvm::Triple::VendorType::UnknownVendor);
1168 LLDB_LOGF(log,
1169 "ObjectFileELF::%s detected Hurd (unsupported), min "
1170 "version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1171 __FUNCTION__, version_info[1], version_info[2],
1172 version_info[3]);
1173 break;
1175 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Solaris);
1176 arch_spec.GetTriple().setVendor(
1177 llvm::Triple::VendorType::UnknownVendor);
1178 LLDB_LOGF(log,
1179 "ObjectFileELF::%s detected Solaris, min version %" PRIu32
1180 ".%" PRIu32 ".%" PRIu32,
1181 __FUNCTION__, version_info[1], version_info[2],
1182 version_info[3]);
1183 break;
1184 default:
1185 LLDB_LOGF(log,
1186 "ObjectFileELF::%s unrecognized OS in note, id %" PRIu32
1187 ", min version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1188 __FUNCTION__, version_info[0], version_info[1],
1189 version_info[2], version_info[3]);
1190 break;
1191 }
1192 }
1193 break;
1194
1196 // Only bother processing this if we don't already have the uuid set.
1197 if (!uuid.IsValid()) {
1198 // 16 bytes is UUID|MD5, 20 bytes is SHA1. Other linkers may produce a
1199 // build-id of a different length. Accept it as long as it's at least
1200 // 4 bytes as it will be better than our own crc32.
1201 if (note.n_descsz >= 4) {
1202 if (const uint8_t *buf = data.PeekData(offset, note.n_descsz)) {
1203 // Save the build id as the UUID for the module.
1204 uuid = UUID(buf, note.n_descsz);
1205 } else {
1207 "failed to read GNU_BUILD_ID note payload");
1208 return error;
1209 }
1210 }
1211 }
1212 break;
1213 }
1214 if (arch_spec.IsMIPS() &&
1215 arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)
1216 // The note.n_name == LLDB_NT_OWNER_GNU is valid for Linux platform
1217 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1218 }
1219 // Process NetBSD ELF executables and shared libraries
1220 else if ((note.n_name == LLDB_NT_OWNER_NETBSD) &&
1221 (note.n_type == LLDB_NT_NETBSD_IDENT_TAG) &&
1222 (note.n_descsz == LLDB_NT_NETBSD_IDENT_DESCSZ) &&
1223 (note.n_namesz == LLDB_NT_NETBSD_IDENT_NAMESZ)) {
1224 // Pull out the version info.
1225 uint32_t version_info;
1226 if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1227 error =
1228 Status::FromErrorString("failed to read NetBSD ABI note payload");
1229 return error;
1230 }
1231 // Convert the version info into a major/minor/patch number.
1232 // #define __NetBSD_Version__ MMmmrrpp00
1233 //
1234 // M = major version
1235 // m = minor version; a minor number of 99 indicates current.
1236 // r = 0 (since NetBSD 3.0 not used)
1237 // p = patchlevel
1238 const uint32_t version_major = version_info / 100000000;
1239 const uint32_t version_minor = (version_info % 100000000) / 1000000;
1240 const uint32_t version_patch = (version_info % 10000) / 100;
1241 // Set the elf OS version to NetBSD. Also clear the vendor.
1242 arch_spec.GetTriple().setOSName(
1243 llvm::formatv("netbsd{0}.{1}.{2}", version_major, version_minor,
1244 version_patch).str());
1245 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1246 }
1247 // Process NetBSD ELF core(5) notes
1248 else if ((note.n_name == LLDB_NT_OWNER_NETBSDCORE) &&
1249 (note.n_type == LLDB_NT_NETBSD_PROCINFO)) {
1250 // Set the elf OS version to NetBSD. Also clear the vendor.
1251 arch_spec.GetTriple().setOS(llvm::Triple::OSType::NetBSD);
1252 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1253 }
1254 // Process OpenBSD ELF notes.
1255 else if (note.n_name == LLDB_NT_OWNER_OPENBSD) {
1256 // Set the elf OS version to OpenBSD. Also clear the vendor.
1257 arch_spec.GetTriple().setOS(llvm::Triple::OSType::OpenBSD);
1258 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1259 } else if (note.n_name == LLDB_NT_OWNER_ANDROID) {
1260 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1261 arch_spec.GetTriple().setEnvironment(
1262 llvm::Triple::EnvironmentType::Android);
1263 } else if (note.n_name == LLDB_NT_OWNER_LINUX) {
1264 // This is sometimes found in core files and usually contains extended
1265 // register info
1266 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1267 } else if (note.n_name == LLDB_NT_OWNER_CORE) {
1268 // Parse the NT_FILE to look for stuff in paths to shared libraries
1269 // The contents look like this in a 64 bit ELF core file:
1270 //
1271 // count = 0x000000000000000a (10)
1272 // page_size = 0x0000000000001000 (4096)
1273 // Index start end file_ofs path
1274 // ===== ------------------ ------------------ ------------------ -------------------------------------
1275 // [ 0] 0x0000000000401000 0x0000000000000000 /tmp/a.out
1276 // [ 1] 0x0000000000600000 0x0000000000601000 0x0000000000000000 /tmp/a.out
1277 // [ 2] 0x0000000000601000 0x0000000000602000 0x0000000000000001 /tmp/a.out
1278 // [ 3] 0x00007fa79c9ed000 0x00007fa79cba8000 0x0000000000000000 /lib/x86_64-linux-gnu/libc-2.19.so
1279 // [ 4] 0x00007fa79cba8000 0x00007fa79cda7000 0x00000000000001bb /lib/x86_64-linux-gnu/libc-2.19.so
1280 // [ 5] 0x00007fa79cda7000 0x00007fa79cdab000 0x00000000000001ba /lib/x86_64-linux-gnu/libc-2.19.so
1281 // [ 6] 0x00007fa79cdab000 0x00007fa79cdad000 0x00000000000001be /lib/x86_64-linux-gnu/libc-2.19.so
1282 // [ 7] 0x00007fa79cdb2000 0x00007fa79cdd5000 0x0000000000000000 /lib/x86_64-linux-gnu/ld-2.19.so
1283 // [ 8] 0x00007fa79cfd4000 0x00007fa79cfd5000 0x0000000000000022 /lib/x86_64-linux-gnu/ld-2.19.so
1284 // [ 9] 0x00007fa79cfd5000 0x00007fa79cfd6000 0x0000000000000023 /lib/x86_64-linux-gnu/ld-2.19.so
1285 //
1286 // In the 32 bit ELFs the count, page_size, start, end, file_ofs are
1287 // uint32_t.
1288 //
1289 // For reference: see readelf source code (in binutils).
1290 if (note.n_type == NT_FILE) {
1291 uint64_t count = data.GetAddress(&offset);
1292 const char *cstr;
1293 data.GetAddress(&offset); // Skip page size
1294 offset += count * 3 *
1295 data.GetAddressByteSize(); // Skip all start/end/file_ofs
1296 for (size_t i = 0; i < count; ++i) {
1297 cstr = data.GetCStr(&offset);
1298 if (cstr == nullptr) {
1300 "ObjectFileELF::%s trying to read "
1301 "at an offset after the end "
1302 "(GetCStr returned nullptr)",
1303 __FUNCTION__);
1304 return error;
1305 }
1306 llvm::StringRef path(cstr);
1307 if (path.contains("/lib/x86_64-linux-gnu") || path.contains("/lib/i386-linux-gnu")) {
1308 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1309 break;
1310 }
1311 }
1312 if (arch_spec.IsMIPS() &&
1313 arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)
1314 // In case of MIPSR6, the LLDB_NT_OWNER_GNU note is missing for some
1315 // cases (e.g. compile with -nostdlib) Hence set OS to Linux
1316 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1317 }
1318 }
1319
1320 // Calculate the offset of the next note just in case "offset" has been
1321 // used to poke at the contents of the note data
1322 offset = note_offset + note.GetByteSize();
1323 }
1324
1325 return error;
1326}
1327
1329 ArchSpec &arch_spec) {
1330 lldb::offset_t Offset = 0;
1331
1332 uint8_t FormatVersion = data.GetU8(&Offset);
1333 if (FormatVersion != llvm::ELFAttrs::Format_Version)
1334 return;
1335
1336 Offset = Offset + sizeof(uint32_t); // Section Length
1337 llvm::StringRef VendorName = data.GetCStr(&Offset);
1338
1339 if (VendorName != "aeabi")
1340 return;
1341
1342 if (arch_spec.GetTriple().getEnvironment() ==
1343 llvm::Triple::UnknownEnvironment)
1344 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
1345
1346 while (Offset < length) {
1347 uint8_t Tag = data.GetU8(&Offset);
1348 uint32_t Size = data.GetU32(&Offset);
1349
1350 if (Tag != llvm::ARMBuildAttrs::File || Size == 0)
1351 continue;
1352
1353 while (Offset < length) {
1354 uint64_t Tag = data.GetULEB128(&Offset);
1355 switch (Tag) {
1356 default:
1357 if (Tag < 32)
1358 data.GetULEB128(&Offset);
1359 else if (Tag % 2 == 0)
1360 data.GetULEB128(&Offset);
1361 else
1362 data.GetCStr(&Offset);
1363
1364 break;
1365
1366 case llvm::ARMBuildAttrs::CPU_raw_name:
1367 case llvm::ARMBuildAttrs::CPU_name:
1368 data.GetCStr(&Offset);
1369
1370 break;
1371
1372 case llvm::ARMBuildAttrs::ABI_VFP_args: {
1373 uint64_t VFPArgs = data.GetULEB128(&Offset);
1374
1375 if (VFPArgs == llvm::ARMBuildAttrs::BaseAAPCS) {
1376 if (arch_spec.GetTriple().getEnvironment() ==
1377 llvm::Triple::UnknownEnvironment ||
1378 arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABIHF)
1379 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
1380
1382 } else if (VFPArgs == llvm::ARMBuildAttrs::HardFPAAPCS) {
1383 if (arch_spec.GetTriple().getEnvironment() ==
1384 llvm::Triple::UnknownEnvironment ||
1385 arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABI)
1386 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABIHF);
1387
1389 }
1390
1391 break;
1392 }
1393 }
1394 }
1395 }
1396}
1397
1398// GetSectionHeaderInfo
1400 DataExtractor &object_data,
1401 const elf::ELFHeader &header,
1402 lldb_private::UUID &uuid,
1403 std::string &gnu_debuglink_file,
1404 uint32_t &gnu_debuglink_crc,
1405 ArchSpec &arch_spec) {
1406 // Don't reparse the section headers if we already did that.
1407 if (!section_headers.empty())
1408 return section_headers.size();
1409
1410 // Only initialize the arch_spec to okay defaults if they're not already set.
1411 // We'll refine this with note data as we parse the notes.
1412 if (arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) {
1413 llvm::Triple::OSType ostype;
1414 llvm::Triple::OSType spec_ostype;
1415 const uint32_t sub_type = subTypeFromElfHeader(header);
1416 arch_spec.SetArchitecture(eArchTypeELF, header.e_machine, sub_type,
1417 header.e_ident[EI_OSABI]);
1418
1419 // Validate if it is ok to remove GetOsFromOSABI. Note, that now the OS is
1420 // determined based on EI_OSABI flag and the info extracted from ELF notes
1421 // (see RefineModuleDetailsFromNote). However in some cases that still
1422 // might be not enough: for example a shared library might not have any
1423 // notes at all and have EI_OSABI flag set to System V, as result the OS
1424 // will be set to UnknownOS.
1425 GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
1426 spec_ostype = arch_spec.GetTriple().getOS();
1427 assert(spec_ostype == ostype);
1428 UNUSED_IF_ASSERT_DISABLED(spec_ostype);
1429 }
1430
1431 if (arch_spec.GetMachine() == llvm::Triple::mips ||
1432 arch_spec.GetMachine() == llvm::Triple::mipsel ||
1433 arch_spec.GetMachine() == llvm::Triple::mips64 ||
1434 arch_spec.GetMachine() == llvm::Triple::mips64el) {
1435 switch (header.e_flags & llvm::ELF::EF_MIPS_ARCH_ASE) {
1436 case llvm::ELF::EF_MIPS_MICROMIPS:
1438 break;
1439 case llvm::ELF::EF_MIPS_ARCH_ASE_M16:
1441 break;
1442 case llvm::ELF::EF_MIPS_ARCH_ASE_MDMX:
1444 break;
1445 default:
1446 break;
1447 }
1448 }
1449
1450 if (arch_spec.GetMachine() == llvm::Triple::arm ||
1451 arch_spec.GetMachine() == llvm::Triple::thumb) {
1452 if (header.e_flags & llvm::ELF::EF_ARM_SOFT_FLOAT)
1454 else if (header.e_flags & llvm::ELF::EF_ARM_VFP_FLOAT)
1456 }
1457
1458 if (arch_spec.GetMachine() == llvm::Triple::riscv32 ||
1459 arch_spec.GetMachine() == llvm::Triple::riscv64) {
1460 uint32_t flags = arch_spec.GetFlags();
1461
1462 if (header.e_flags & llvm::ELF::EF_RISCV_RVC)
1463 flags |= ArchSpec::eRISCV_rvc;
1464 if (header.e_flags & llvm::ELF::EF_RISCV_RVE)
1465 flags |= ArchSpec::eRISCV_rve;
1466
1467 if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_SINGLE) ==
1468 llvm::ELF::EF_RISCV_FLOAT_ABI_SINGLE)
1470 else if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_DOUBLE) ==
1471 llvm::ELF::EF_RISCV_FLOAT_ABI_DOUBLE)
1473 else if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_QUAD) ==
1474 llvm::ELF::EF_RISCV_FLOAT_ABI_QUAD)
1476
1477 arch_spec.SetFlags(flags);
1478 }
1479
1480 if (arch_spec.GetMachine() == llvm::Triple::loongarch32 ||
1481 arch_spec.GetMachine() == llvm::Triple::loongarch64) {
1482 uint32_t flags = arch_spec.GetFlags();
1483 switch (header.e_flags & llvm::ELF::EF_LOONGARCH_ABI_MODIFIER_MASK) {
1484 case llvm::ELF::EF_LOONGARCH_ABI_SINGLE_FLOAT:
1486 break;
1487 case llvm::ELF::EF_LOONGARCH_ABI_DOUBLE_FLOAT:
1489 break;
1490 case llvm::ELF::EF_LOONGARCH_ABI_SOFT_FLOAT:
1491 break;
1492 }
1493
1494 arch_spec.SetFlags(flags);
1495 }
1496
1497 // If there are no section headers we are done.
1498 if (header.e_shnum == 0)
1499 return 0;
1500
1501 Log *log = GetLog(LLDBLog::Modules);
1502
1503 section_headers.resize(header.e_shnum);
1504 if (section_headers.size() != header.e_shnum)
1505 return 0;
1506
1507 const size_t sh_size = header.e_shnum * header.e_shentsize;
1508 const elf_off sh_offset = header.e_shoff;
1509 DataExtractor sh_data;
1510 if (sh_data.SetData(object_data, sh_offset, sh_size) != sh_size)
1511 return 0;
1512
1513 uint32_t idx;
1514 lldb::offset_t offset;
1515 for (idx = 0, offset = 0; idx < header.e_shnum; ++idx) {
1516 if (!section_headers[idx].Parse(sh_data, &offset))
1517 break;
1518 }
1519 if (idx < section_headers.size())
1520 section_headers.resize(idx);
1521
1522 const unsigned strtab_idx = header.e_shstrndx;
1523 if (strtab_idx && strtab_idx < section_headers.size()) {
1524 const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];
1525 const size_t byte_size = sheader.sh_size;
1526 const Elf64_Off offset = sheader.sh_offset;
1527 lldb_private::DataExtractor shstr_data;
1528
1529 if (shstr_data.SetData(object_data, offset, byte_size) == byte_size) {
1530 for (SectionHeaderCollIter I = section_headers.begin();
1531 I != section_headers.end(); ++I) {
1532 static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");
1533 const ELFSectionHeaderInfo &sheader = *I;
1534 const uint64_t section_size =
1535 sheader.sh_type == SHT_NOBITS ? 0 : sheader.sh_size;
1536 ConstString name(shstr_data.PeekCStr(I->sh_name));
1537
1538 I->section_name = name;
1539
1540 if (arch_spec.IsMIPS()) {
1541 uint32_t arch_flags = arch_spec.GetFlags();
1542 DataExtractor data;
1543 if (sheader.sh_type == SHT_MIPS_ABIFLAGS) {
1544
1545 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1546 section_size) == section_size)) {
1547 // MIPS ASE Mask is at offset 12 in MIPS.abiflags section
1548 lldb::offset_t offset = 12; // MIPS ABI Flags Version: 0
1549 arch_flags |= data.GetU32(&offset);
1550
1551 // The floating point ABI is at offset 7
1552 offset = 7;
1553 switch (data.GetU8(&offset)) {
1554 case llvm::Mips::Val_GNU_MIPS_ABI_FP_ANY:
1556 break;
1557 case llvm::Mips::Val_GNU_MIPS_ABI_FP_DOUBLE:
1559 break;
1560 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SINGLE:
1562 break;
1563 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SOFT:
1565 break;
1566 case llvm::Mips::Val_GNU_MIPS_ABI_FP_OLD_64:
1568 break;
1569 case llvm::Mips::Val_GNU_MIPS_ABI_FP_XX:
1571 break;
1572 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64:
1574 break;
1575 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64A:
1577 break;
1578 }
1579 }
1580 }
1581 // Settings appropriate ArchSpec ABI Flags
1582 switch (header.e_flags & llvm::ELF::EF_MIPS_ABI) {
1583 case llvm::ELF::EF_MIPS_ABI_O32:
1585 break;
1586 case EF_MIPS_ABI_O64:
1588 break;
1589 case EF_MIPS_ABI_EABI32:
1591 break;
1592 case EF_MIPS_ABI_EABI64:
1594 break;
1595 default:
1596 // ABI Mask doesn't cover N32 and N64 ABI.
1597 if (header.e_ident[EI_CLASS] == llvm::ELF::ELFCLASS64)
1599 else if (header.e_flags & llvm::ELF::EF_MIPS_ABI2)
1601 break;
1602 }
1603 arch_spec.SetFlags(arch_flags);
1604 }
1605
1606 if (arch_spec.GetMachine() == llvm::Triple::arm ||
1607 arch_spec.GetMachine() == llvm::Triple::thumb) {
1608 DataExtractor data;
1609
1610 if (sheader.sh_type == SHT_ARM_ATTRIBUTES && section_size != 0 &&
1611 data.SetData(object_data, sheader.sh_offset, section_size) == section_size)
1612 ParseARMAttributes(data, section_size, arch_spec);
1613 }
1614
1615 if (name == g_sect_name_gnu_debuglink) {
1616 DataExtractor data;
1617 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1618 section_size) == section_size)) {
1619 lldb::offset_t gnu_debuglink_offset = 0;
1620 gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);
1621 gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
1622 data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
1623 }
1624 }
1625
1626 // Process ELF note section entries.
1627 bool is_note_header = (sheader.sh_type == SHT_NOTE);
1628
1629 // The section header ".note.android.ident" is stored as a
1630 // PROGBITS type header but it is actually a note header.
1631 static ConstString g_sect_name_android_ident(".note.android.ident");
1632 if (!is_note_header && name == g_sect_name_android_ident)
1633 is_note_header = true;
1634
1635 if (is_note_header) {
1636 // Allow notes to refine module info.
1637 DataExtractor data;
1638 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1639 section_size) == section_size)) {
1640 Status error = RefineModuleDetailsFromNote(data, arch_spec, uuid);
1641 if (error.Fail()) {
1642 LLDB_LOGF(log, "ObjectFileELF::%s ELF note processing failed: %s",
1643 __FUNCTION__, error.AsCString());
1644 }
1645 }
1646 }
1647 }
1648
1649 // Make any unknown triple components to be unspecified unknowns.
1650 if (arch_spec.GetTriple().getVendor() == llvm::Triple::UnknownVendor)
1651 arch_spec.GetTriple().setVendorName(llvm::StringRef());
1652 if (arch_spec.GetTriple().getOS() == llvm::Triple::UnknownOS)
1653 arch_spec.GetTriple().setOSName(llvm::StringRef());
1654
1655 return section_headers.size();
1656 }
1657 }
1658
1659 section_headers.clear();
1660 return 0;
1661}
1662
1663llvm::StringRef
1664ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const {
1665 size_t pos = symbol_name.find('@');
1666 return symbol_name.substr(0, pos);
1667}
1668
1669// ParseSectionHeaders
1675
1678 if (!ParseSectionHeaders())
1679 return nullptr;
1680
1681 if (id < m_section_headers.size())
1682 return &m_section_headers[id];
1683
1684 return nullptr;
1685}
1686
1688 if (!name || !name[0] || !ParseSectionHeaders())
1689 return 0;
1690 for (size_t i = 1; i < m_section_headers.size(); ++i)
1691 if (m_section_headers[i].section_name == ConstString(name))
1692 return i;
1693 return 0;
1694}
1695
1696static SectionType GetSectionTypeFromName(llvm::StringRef Name) {
1697 if (Name.consume_front(".debug_"))
1699
1700 return llvm::StringSwitch<SectionType>(Name)
1701 .Case(".ARM.exidx", eSectionTypeARMexidx)
1702 .Case(".ARM.extab", eSectionTypeARMextab)
1703 .Case(".ctf", eSectionTypeDebug)
1704 .Cases({".data", ".tdata"}, eSectionTypeData)
1705 .Case(".eh_frame", eSectionTypeEHFrame)
1706 .Case(".gnu_debugaltlink", eSectionTypeDWARFGNUDebugAltLink)
1707 .Case(".gosymtab", eSectionTypeGoSymtab)
1708 .Case(".text", eSectionTypeCode)
1709 .Case(".lldbsummaries", lldb::eSectionTypeLLDBTypeSummaries)
1710 .Case(".lldbformatters", lldb::eSectionTypeLLDBFormatters)
1711 .Case(".swift_ast", eSectionTypeSwiftModules)
1712 .Default(eSectionTypeOther);
1713}
1714
1716 switch (H.sh_type) {
1717 case SHT_PROGBITS:
1718 if (H.sh_flags & SHF_EXECINSTR)
1719 return eSectionTypeCode;
1720 break;
1721 case SHT_NOBITS:
1722 if (H.sh_flags & SHF_ALLOC)
1723 return eSectionTypeZeroFill;
1724 break;
1725 case SHT_SYMTAB:
1727 case SHT_DYNSYM:
1729 case SHT_RELA:
1730 case SHT_REL:
1732 case SHT_DYNAMIC:
1734 }
1736}
1737
1738static uint32_t GetTargetByteSize(SectionType Type, const ArchSpec &arch) {
1739 switch (Type) {
1740 case eSectionTypeData:
1742 return arch.GetDataByteSize();
1743 case eSectionTypeCode:
1744 return arch.GetCodeByteSize();
1745 default:
1746 return 1;
1747 }
1748}
1749
1750static Permissions GetPermissions(const ELFSectionHeader &H) {
1751 Permissions Perm = Permissions(0);
1752 if (H.sh_flags & SHF_ALLOC)
1753 Perm |= ePermissionsReadable;
1754 if (H.sh_flags & SHF_WRITE)
1755 Perm |= ePermissionsWritable;
1756 if (H.sh_flags & SHF_EXECINSTR)
1757 Perm |= ePermissionsExecutable;
1758 return Perm;
1759}
1760
1761static Permissions GetPermissions(const ELFProgramHeader &H) {
1762 Permissions Perm = Permissions(0);
1763 if (H.p_flags & PF_R)
1764 Perm |= ePermissionsReadable;
1765 if (H.p_flags & PF_W)
1766 Perm |= ePermissionsWritable;
1767 if (H.p_flags & PF_X)
1768 Perm |= ePermissionsExecutable;
1769 return Perm;
1770}
1771
1772namespace {
1773
1775
1776struct SectionAddressInfo {
1777 SectionSP Segment;
1778 VMRange Range;
1779};
1780
1781// (Unlinked) ELF object files usually have 0 for every section address, meaning
1782// we need to compute synthetic addresses in order for "file addresses" from
1783// different sections to not overlap. This class handles that logic.
1784class VMAddressProvider {
1785 using VMMap = llvm::IntervalMap<addr_t, SectionSP, 4,
1786 llvm::IntervalMapHalfOpenInfo<addr_t>>;
1787
1788 ObjectFile::Type ObjectType;
1789 addr_t NextVMAddress = 0;
1790 VMMap::Allocator Alloc;
1791 VMMap Segments{Alloc};
1792 VMMap Sections{Alloc};
1793 lldb_private::Log *Log = GetLog(LLDBLog::Modules);
1794 size_t SegmentCount = 0;
1795 std::string SegmentName;
1796
1797 VMRange GetVMRange(const ELFSectionHeader &H) {
1798 addr_t Address = H.sh_addr;
1799 addr_t Size = H.sh_flags & SHF_ALLOC ? H.sh_size : 0;
1800
1801 // When this is a debug file for relocatable file, the address is all zero
1802 // and thus needs to use accumulate method
1803 if ((ObjectType == ObjectFile::Type::eTypeObjectFile ||
1804 (ObjectType == ObjectFile::Type::eTypeDebugInfo && H.sh_addr == 0)) &&
1805 Segments.empty() && (H.sh_flags & SHF_ALLOC)) {
1806 NextVMAddress =
1807 llvm::alignTo(NextVMAddress, std::max<addr_t>(H.sh_addralign, 1));
1808 Address = NextVMAddress;
1809 NextVMAddress += Size;
1810 }
1811 return VMRange(Address, Size);
1812 }
1813
1814public:
1815 VMAddressProvider(ObjectFile::Type Type, llvm::StringRef SegmentName)
1816 : ObjectType(Type), SegmentName(std::string(SegmentName)) {}
1817
1818 std::string GetNextSegmentName() const {
1819 return llvm::formatv("{0}[{1}]", SegmentName, SegmentCount).str();
1820 }
1821
1822 std::optional<VMRange> GetAddressInfo(const ELFProgramHeader &H) {
1823 if (H.p_memsz == 0) {
1824 LLDB_LOG(Log, "Ignoring zero-sized {0} segment. Corrupt object file?",
1825 SegmentName);
1826 return std::nullopt;
1827 }
1828
1829 if (Segments.overlaps(H.p_vaddr, H.p_vaddr + H.p_memsz)) {
1830 LLDB_LOG(Log, "Ignoring overlapping {0} segment. Corrupt object file?",
1831 SegmentName);
1832 return std::nullopt;
1833 }
1834 return VMRange(H.p_vaddr, H.p_memsz);
1835 }
1836
1837 std::optional<SectionAddressInfo> GetAddressInfo(const ELFSectionHeader &H) {
1838 VMRange Range = GetVMRange(H);
1839 SectionSP Segment;
1840 auto It = Segments.find(Range.GetRangeBase());
1841 if ((H.sh_flags & SHF_ALLOC) && It.valid()) {
1842 addr_t MaxSize;
1843 if (It.start() <= Range.GetRangeBase()) {
1844 MaxSize = It.stop() - Range.GetRangeBase();
1845 Segment = *It;
1846 } else
1847 MaxSize = It.start() - Range.GetRangeBase();
1848 if (Range.GetByteSize() > MaxSize) {
1849 LLDB_LOG(Log, "Shortening section crossing segment boundaries. "
1850 "Corrupt object file?");
1851 Range.SetByteSize(MaxSize);
1852 }
1853 }
1854 if (Range.GetByteSize() > 0 &&
1855 Sections.overlaps(Range.GetRangeBase(), Range.GetRangeEnd())) {
1856 LLDB_LOG(Log, "Ignoring overlapping section. Corrupt object file?");
1857 return std::nullopt;
1858 }
1859 if (Segment)
1860 Range.Slide(-Segment->GetFileAddress());
1861 return SectionAddressInfo{Segment, Range};
1862 }
1863
1864 void AddSegment(const VMRange &Range, SectionSP Seg) {
1865 Segments.insert(Range.GetRangeBase(), Range.GetRangeEnd(), std::move(Seg));
1866 ++SegmentCount;
1867 }
1868
1869 void AddSection(SectionAddressInfo Info, SectionSP Sect) {
1870 if (Info.Range.GetByteSize() == 0)
1871 return;
1872 if (Info.Segment)
1873 Info.Range.Slide(Info.Segment->GetFileAddress());
1874 Sections.insert(Info.Range.GetRangeBase(), Info.Range.GetRangeEnd(),
1875 std::move(Sect));
1876 }
1877};
1878}
1879
1880// We have to do this because ELF doesn't have section IDs, and also
1881// doesn't require section names to be unique. (We use the section index
1882// for section IDs, but that isn't guaranteed to be the same in separate
1883// debug images.)
1884static SectionSP FindMatchingSection(const SectionList &section_list,
1885 SectionSP section) {
1886 SectionSP sect_sp;
1887
1888 addr_t vm_addr = section->GetFileAddress();
1889 ConstString name = section->GetName();
1890 offset_t byte_size = section->GetByteSize();
1891 bool thread_specific = section->IsThreadSpecific();
1892 uint32_t permissions = section->GetPermissions();
1893 uint32_t alignment = section->GetLog2Align();
1894
1895 for (auto sect : section_list) {
1896 if (sect->GetName() == name &&
1897 sect->IsThreadSpecific() == thread_specific &&
1898 sect->GetPermissions() == permissions &&
1899 sect->GetByteSize() == byte_size && sect->GetFileAddress() == vm_addr &&
1900 sect->GetLog2Align() == alignment) {
1901 sect_sp = sect;
1902 break;
1903 } else {
1904 sect_sp = FindMatchingSection(sect->GetChildren(), section);
1905 if (sect_sp)
1906 break;
1907 }
1908 }
1909
1910 return sect_sp;
1911}
1912
1913void ObjectFileELF::CreateSections(SectionList &unified_section_list) {
1914 if (m_sections_up)
1915 return;
1916
1917 m_sections_up = std::make_unique<SectionList>();
1918 VMAddressProvider regular_provider(GetType(), "PT_LOAD");
1919 VMAddressProvider tls_provider(GetType(), "PT_TLS");
1920
1921 for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {
1922 const ELFProgramHeader &PHdr = EnumPHdr.value();
1923 if (PHdr.p_type != PT_LOAD && PHdr.p_type != PT_TLS)
1924 continue;
1925
1926 VMAddressProvider &provider =
1927 PHdr.p_type == PT_TLS ? tls_provider : regular_provider;
1928 auto InfoOr = provider.GetAddressInfo(PHdr);
1929 if (!InfoOr)
1930 continue;
1931
1932 uint32_t Log2Align = llvm::Log2_64(std::max<elf_xword>(PHdr.p_align, 1));
1933 SectionSP Segment = std::make_shared<Section>(
1934 GetModule(), this, SegmentID(EnumPHdr.index()),
1935 ConstString(provider.GetNextSegmentName()), eSectionTypeContainer,
1936 InfoOr->GetRangeBase(), InfoOr->GetByteSize(), PHdr.p_offset,
1937 PHdr.p_filesz, Log2Align, /*flags*/ 0);
1938 Segment->SetPermissions(GetPermissions(PHdr));
1939 Segment->SetIsThreadSpecific(PHdr.p_type == PT_TLS);
1940 m_sections_up->AddSection(Segment);
1941
1942 provider.AddSegment(*InfoOr, std::move(Segment));
1943 }
1944
1946 if (m_section_headers.empty())
1947 return;
1948
1949 for (SectionHeaderCollIter I = std::next(m_section_headers.begin());
1950 I != m_section_headers.end(); ++I) {
1951 const ELFSectionHeaderInfo &header = *I;
1952
1953 ConstString &name = I->section_name;
1954 const uint64_t file_size =
1955 header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
1956
1957 VMAddressProvider &provider =
1958 header.sh_flags & SHF_TLS ? tls_provider : regular_provider;
1959 auto InfoOr = provider.GetAddressInfo(header);
1960 if (!InfoOr)
1961 continue;
1962
1963 SectionType sect_type = GetSectionType(header);
1964
1965 const uint32_t target_bytes_size =
1966 GetTargetByteSize(sect_type, m_arch_spec);
1967
1968 elf::elf_xword log2align =
1969 (header.sh_addralign == 0) ? 0 : llvm::Log2_64(header.sh_addralign);
1970
1971 SectionSP section_sp(new Section(
1972 InfoOr->Segment, GetModule(), // Module to which this section belongs.
1973 this, // ObjectFile to which this section belongs and should
1974 // read section data from.
1975 SectionIndex(I), // Section ID.
1976 name, // Section name.
1977 sect_type, // Section type.
1978 InfoOr->Range.GetRangeBase(), // VM address.
1979 InfoOr->Range.GetByteSize(), // VM size in bytes of this section.
1980 header.sh_offset, // Offset of this section in the file.
1981 file_size, // Size of the section as found in the file.
1982 log2align, // Alignment of the section
1983 header.sh_flags, // Flags for this section.
1984 target_bytes_size)); // Number of host bytes per target byte
1985
1986 section_sp->SetPermissions(GetPermissions(header));
1987 section_sp->SetIsThreadSpecific(header.sh_flags & SHF_TLS);
1988 (InfoOr->Segment ? InfoOr->Segment->GetChildren() : *m_sections_up)
1989 .AddSection(section_sp);
1990 provider.AddSection(std::move(*InfoOr), std::move(section_sp));
1991 }
1992
1993 // Merge the two adding any new sections, and overwriting any existing
1994 // sections that are SHT_NOBITS
1995 unified_section_list =
1996 SectionList::Merge(unified_section_list, *m_sections_up, MergeSections);
1997
1998 // If there's a .gnu_debugdata section, we'll try to read the .symtab that's
1999 // embedded in there and replace the one in the original object file (if any).
2000 // If there's none in the orignal object file, we add it to it.
2001 if (auto gdd_obj_file = GetGnuDebugDataObjectFile()) {
2002 if (auto gdd_objfile_section_list = gdd_obj_file->GetSectionList()) {
2003 if (SectionSP symtab_section_sp =
2004 gdd_objfile_section_list->FindSectionByType(
2006 SectionSP module_section_sp = unified_section_list.FindSectionByType(
2008 if (module_section_sp)
2009 unified_section_list.ReplaceSection(module_section_sp->GetID(),
2010 symtab_section_sp);
2011 else
2012 unified_section_list.AddSection(symtab_section_sp);
2013 }
2014 }
2015 }
2016}
2017
2018std::shared_ptr<ObjectFileELF> ObjectFileELF::GetGnuDebugDataObjectFile() {
2019 if (m_gnu_debug_data_object_file != nullptr)
2021
2022 SectionSP section =
2023 GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata"));
2024 if (!section)
2025 return nullptr;
2026
2028 GetModule()->ReportWarning(
2029 "No LZMA support found for reading .gnu_debugdata section");
2030 return nullptr;
2031 }
2032
2033 // Uncompress the data
2034 DataExtractor data;
2035 section->GetSectionData(data);
2036 llvm::SmallVector<uint8_t, 0> uncompressedData;
2037 auto err = lldb_private::lzma::uncompress(data.GetData(), uncompressedData);
2038 if (err) {
2039 GetModule()->ReportWarning(
2040 "An error occurred while decompression the section {0}: {1}",
2041 section->GetName().AsCString(), llvm::toString(std::move(err)).c_str());
2042 return nullptr;
2043 }
2044
2045 // Construct ObjectFileELF object from decompressed buffer
2046 DataBufferSP gdd_data_buf(
2047 new DataBufferHeap(uncompressedData.data(), uncompressedData.size()));
2049 llvm::StringRef("gnu_debugdata"));
2051 GetModule(), gdd_data_buf, 0, &fspec, 0, gdd_data_buf->GetByteSize()));
2052
2053 // This line is essential; otherwise a breakpoint can be set but not hit.
2055
2056 ArchSpec spec = m_gnu_debug_data_object_file->GetArchitecture();
2057 if (spec && m_gnu_debug_data_object_file->SetModulesArchitecture(spec))
2059
2060 return nullptr;
2061}
2062
2063// Find the arm/aarch64 mapping symbol character in the given symbol name.
2064// Mapping symbols have the form of "$<char>[.<any>]*". Additionally we
2065// recognize cases when the mapping symbol prefixed by an arbitrary string
2066// because if a symbol prefix added to each symbol in the object file with
2067// objcopy then the mapping symbols are also prefixed.
2068static char FindArmAarch64MappingSymbol(const char *symbol_name) {
2069 if (!symbol_name)
2070 return '\0';
2071
2072 const char *dollar_pos = ::strchr(symbol_name, '$');
2073 if (!dollar_pos || dollar_pos[1] == '\0')
2074 return '\0';
2075
2076 if (dollar_pos[2] == '\0' || dollar_pos[2] == '.')
2077 return dollar_pos[1];
2078 return '\0';
2079}
2080
2081static char FindRISCVMappingSymbol(const char *symbol_name) {
2082 if (!symbol_name)
2083 return '\0';
2084
2085 if (strcmp(symbol_name, "$d") == 0) {
2086 return 'd';
2087 }
2088 if (strcmp(symbol_name, "$x") == 0) {
2089 return 'x';
2090 }
2091 return '\0';
2092}
2093
2094#define STO_MIPS_ISA (3 << 6)
2095#define STO_MICROMIPS (2 << 6)
2096#define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS)
2097
2098// private
2099std::pair<unsigned, ObjectFileELF::FileAddressToAddressClassMap>
2101 SectionList *section_list, const size_t num_symbols,
2102 const DataExtractor &symtab_data,
2103 const DataExtractor &strtab_data) {
2104 ELFSymbol symbol;
2105 lldb::offset_t offset = 0;
2106 // The changes these symbols would make to the class map. We will also update
2107 // m_address_class_map but need to tell the caller what changed because the
2108 // caller may be another object file.
2109 FileAddressToAddressClassMap address_class_map;
2110
2111 static ConstString text_section_name(".text");
2112 static ConstString init_section_name(".init");
2113 static ConstString fini_section_name(".fini");
2114 static ConstString ctors_section_name(".ctors");
2115 static ConstString dtors_section_name(".dtors");
2116
2117 static ConstString data_section_name(".data");
2118 static ConstString rodata_section_name(".rodata");
2119 static ConstString rodata1_section_name(".rodata1");
2120 static ConstString data2_section_name(".data1");
2121 static ConstString bss_section_name(".bss");
2122 static ConstString opd_section_name(".opd"); // For ppc64
2123
2124 // On Android the oatdata and the oatexec symbols in the oat and odex files
2125 // covers the full .text section what causes issues with displaying unusable
2126 // symbol name to the user and very slow unwinding speed because the
2127 // instruction emulation based unwind plans try to emulate all instructions
2128 // in these symbols. Don't add these symbols to the symbol list as they have
2129 // no use for the debugger and they are causing a lot of trouble. Filtering
2130 // can't be restricted to Android because this special object file don't
2131 // contain the note section specifying the environment to Android but the
2132 // custom extension and file name makes it highly unlikely that this will
2133 // collide with anything else.
2134 llvm::StringRef file_extension = m_file.GetFileNameExtension();
2135 bool skip_oatdata_oatexec =
2136 file_extension == ".oat" || file_extension == ".odex";
2137
2138 ArchSpec arch = GetArchitecture();
2139 ModuleSP module_sp(GetModule());
2140 SectionList *module_section_list =
2141 module_sp ? module_sp->GetSectionList() : nullptr;
2142
2143 // We might have debug information in a separate object, in which case
2144 // we need to map the sections from that object to the sections in the
2145 // main object during symbol lookup. If we had to compare the sections
2146 // for every single symbol, that would be expensive, so this map is
2147 // used to accelerate the process.
2148 std::unordered_map<lldb::SectionSP, lldb::SectionSP> section_map;
2149
2150 unsigned i;
2151 for (i = 0; i < num_symbols; ++i) {
2152 if (!symbol.Parse(symtab_data, &offset))
2153 break;
2154
2155 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
2156 if (!symbol_name)
2157 symbol_name = "";
2158
2159 // Skip local symbols starting with ".L" because these are compiler
2160 // generated local labels used for internal purposes (e.g. debugging,
2161 // optimization) and are not relevant for symbol resolution or external
2162 // linkage.
2163 if (llvm::StringRef(symbol_name).starts_with(".L"))
2164 continue;
2165 // No need to add non-section symbols that have no names
2166 if (symbol.getType() != STT_SECTION &&
2167 (symbol_name == nullptr || symbol_name[0] == '\0'))
2168 continue;
2169
2170 // Skipping oatdata and oatexec sections if it is requested. See details
2171 // above the definition of skip_oatdata_oatexec for the reasons.
2172 if (skip_oatdata_oatexec && (::strcmp(symbol_name, "oatdata") == 0 ||
2173 ::strcmp(symbol_name, "oatexec") == 0))
2174 continue;
2175
2176 SectionSP symbol_section_sp;
2177 SymbolType symbol_type = eSymbolTypeInvalid;
2178 Elf64_Half shndx = symbol.st_shndx;
2179
2180 switch (shndx) {
2181 case SHN_ABS:
2182 symbol_type = eSymbolTypeAbsolute;
2183 break;
2184 case SHN_UNDEF:
2185 symbol_type = eSymbolTypeUndefined;
2186 break;
2187 default:
2188 symbol_section_sp = section_list->FindSectionByID(shndx);
2189 break;
2190 }
2191
2192 // If a symbol is undefined do not process it further even if it has a STT
2193 // type
2194 if (symbol_type != eSymbolTypeUndefined) {
2195 switch (symbol.getType()) {
2196 default:
2197 case STT_NOTYPE:
2198 // The symbol's type is not specified.
2199 break;
2200
2201 case STT_OBJECT:
2202 // The symbol is associated with a data object, such as a variable, an
2203 // array, etc.
2204 symbol_type = eSymbolTypeData;
2205 break;
2206
2207 case STT_FUNC:
2208 // The symbol is associated with a function or other executable code.
2209 symbol_type = eSymbolTypeCode;
2210 break;
2211
2212 case STT_SECTION:
2213 // The symbol is associated with a section. Symbol table entries of
2214 // this type exist primarily for relocation and normally have STB_LOCAL
2215 // binding.
2216 break;
2217
2218 case STT_FILE:
2219 // Conventionally, the symbol's name gives the name of the source file
2220 // associated with the object file. A file symbol has STB_LOCAL
2221 // binding, its section index is SHN_ABS, and it precedes the other
2222 // STB_LOCAL symbols for the file, if it is present.
2223 symbol_type = eSymbolTypeSourceFile;
2224 break;
2225
2226 case STT_GNU_IFUNC:
2227 // The symbol is associated with an indirect function. The actual
2228 // function will be resolved if it is referenced.
2229 symbol_type = eSymbolTypeResolver;
2230 break;
2231 }
2232 }
2233
2234 if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) {
2235 if (symbol_section_sp) {
2236 ConstString sect_name = symbol_section_sp->GetName();
2237 if (sect_name == text_section_name || sect_name == init_section_name ||
2238 sect_name == fini_section_name || sect_name == ctors_section_name ||
2239 sect_name == dtors_section_name) {
2240 symbol_type = eSymbolTypeCode;
2241 } else if (sect_name == data_section_name ||
2242 sect_name == data2_section_name ||
2243 sect_name == rodata_section_name ||
2244 sect_name == rodata1_section_name ||
2245 sect_name == bss_section_name) {
2246 symbol_type = eSymbolTypeData;
2247 }
2248 }
2249 }
2250
2251 int64_t symbol_value_offset = 0;
2252 uint32_t additional_flags = 0;
2253 if (arch.IsValid()) {
2254 if (arch.GetMachine() == llvm::Triple::arm) {
2255 if (symbol.getBinding() == STB_LOCAL) {
2256 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2257 if (symbol_type == eSymbolTypeCode) {
2258 switch (mapping_symbol) {
2259 case 'a':
2260 // $a[.<any>]* - marks an ARM instruction sequence
2261 address_class_map[symbol.st_value] = AddressClass::eCode;
2262 break;
2263 case 'b':
2264 case 't':
2265 // $b[.<any>]* - marks a THUMB BL instruction sequence
2266 // $t[.<any>]* - marks a THUMB instruction sequence
2267 address_class_map[symbol.st_value] =
2269 break;
2270 case 'd':
2271 // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2272 address_class_map[symbol.st_value] = AddressClass::eData;
2273 break;
2274 }
2275 }
2276 if (mapping_symbol)
2277 continue;
2278 }
2279 } else if (arch.GetMachine() == llvm::Triple::aarch64) {
2280 if (symbol.getBinding() == STB_LOCAL) {
2281 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2282 if (symbol_type == eSymbolTypeCode) {
2283 switch (mapping_symbol) {
2284 case 'x':
2285 // $x[.<any>]* - marks an A64 instruction sequence
2286 address_class_map[symbol.st_value] = AddressClass::eCode;
2287 break;
2288 case 'd':
2289 // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2290 address_class_map[symbol.st_value] = AddressClass::eData;
2291 break;
2292 }
2293 }
2294 if (mapping_symbol)
2295 continue;
2296 }
2297 } else if (arch.GetTriple().isRISCV()) {
2298 if (symbol.getBinding() == STB_LOCAL) {
2299 char mapping_symbol = FindRISCVMappingSymbol(symbol_name);
2300 if (symbol_type == eSymbolTypeCode) {
2301 // Only handle $d and $x mapping symbols.
2302 // Other mapping symbols are ignored as they don't affect address
2303 // classification.
2304 switch (mapping_symbol) {
2305 case 'x':
2306 // $x - marks a RISCV instruction sequence
2307 address_class_map[symbol.st_value] = AddressClass::eCode;
2308 break;
2309 case 'd':
2310 // $d - marks a RISCV data item sequence
2311 address_class_map[symbol.st_value] = AddressClass::eData;
2312 break;
2313 }
2314 }
2315 if (mapping_symbol)
2316 continue;
2317 }
2318 }
2319
2320 if (arch.GetMachine() == llvm::Triple::arm) {
2321 if (symbol_type == eSymbolTypeCode) {
2322 if (symbol.st_value & 1) {
2323 // Subtracting 1 from the address effectively unsets the low order
2324 // bit, which results in the address actually pointing to the
2325 // beginning of the symbol. This delta will be used below in
2326 // conjunction with symbol.st_value to produce the final
2327 // symbol_value that we store in the symtab.
2328 symbol_value_offset = -1;
2329 address_class_map[symbol.st_value ^ 1] =
2331 } else {
2332 // This address is ARM
2333 address_class_map[symbol.st_value] = AddressClass::eCode;
2334 }
2335 }
2336 }
2337
2338 /*
2339 * MIPS:
2340 * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for
2341 * MIPS).
2342 * This allows processor to switch between microMIPS and MIPS without any
2343 * need
2344 * for special mode-control register. However, apart from .debug_line,
2345 * none of
2346 * the ELF/DWARF sections set the ISA bit (for symbol or section). Use
2347 * st_other
2348 * flag to check whether the symbol is microMIPS and then set the address
2349 * class
2350 * accordingly.
2351 */
2352 if (arch.IsMIPS()) {
2353 if (IS_MICROMIPS(symbol.st_other))
2354 address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
2355 else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) {
2356 symbol.st_value = symbol.st_value & (~1ull);
2357 address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
2358 } else {
2359 if (symbol_type == eSymbolTypeCode)
2360 address_class_map[symbol.st_value] = AddressClass::eCode;
2361 else if (symbol_type == eSymbolTypeData)
2362 address_class_map[symbol.st_value] = AddressClass::eData;
2363 else
2364 address_class_map[symbol.st_value] = AddressClass::eUnknown;
2365 }
2366 }
2367 }
2368
2369 // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB
2370 // symbols. See above for more details.
2371 uint64_t symbol_value = symbol.st_value + symbol_value_offset;
2372
2373 if (symbol_section_sp &&
2375 symbol_value -= symbol_section_sp->GetFileAddress();
2376
2377 if (symbol_section_sp && module_section_list &&
2378 module_section_list != section_list) {
2379 auto section_it = section_map.find(symbol_section_sp);
2380 if (section_it == section_map.end()) {
2381 section_it = section_map
2382 .emplace(symbol_section_sp,
2383 FindMatchingSection(*module_section_list,
2384 symbol_section_sp))
2385 .first;
2386 }
2387 if (section_it->second)
2388 symbol_section_sp = section_it->second;
2389 }
2390
2391 bool is_global = symbol.getBinding() == STB_GLOBAL;
2392 uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags;
2393 llvm::StringRef symbol_ref(symbol_name);
2394
2395 // Symbol names may contain @VERSION suffixes. Find those and strip them
2396 // temporarily.
2397 size_t version_pos = symbol_ref.find('@');
2398 bool has_suffix = version_pos != llvm::StringRef::npos;
2399 llvm::StringRef symbol_bare = symbol_ref.substr(0, version_pos);
2400 Mangled mangled(symbol_bare);
2401
2402 // Now append the suffix back to mangled and unmangled names. Only do it if
2403 // the demangling was successful (string is not empty).
2404 if (has_suffix) {
2405 llvm::StringRef suffix = symbol_ref.substr(version_pos);
2406
2407 llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef();
2408 if (!mangled_name.empty())
2409 mangled.SetMangledName(ConstString((mangled_name + suffix).str()));
2410
2411 ConstString demangled = mangled.GetDemangledName();
2412 llvm::StringRef demangled_name = demangled.GetStringRef();
2413 if (!demangled_name.empty())
2414 mangled.SetDemangledName(ConstString((demangled_name + suffix).str()));
2415 }
2416
2417 // In ELF all symbol should have a valid size but it is not true for some
2418 // function symbols coming from hand written assembly. As none of the
2419 // function symbol should have 0 size we try to calculate the size for
2420 // these symbols in the symtab with saying that their original size is not
2421 // valid.
2422 bool symbol_size_valid =
2423 symbol.st_size != 0 || symbol.getType() != STT_FUNC;
2424
2425 bool is_trampoline = false;
2426 if (arch.IsValid() && (arch.GetMachine() == llvm::Triple::aarch64)) {
2427 // On AArch64, trampolines are registered as code.
2428 // If we detect a trampoline (which starts with __AArch64ADRPThunk_ or
2429 // __AArch64AbsLongThunk_) we register the symbol as a trampoline. This
2430 // way we will be able to detect the trampoline when we step in a function
2431 // and step through the trampoline.
2432 if (symbol_type == eSymbolTypeCode) {
2433 llvm::StringRef trampoline_name = mangled.GetName().GetStringRef();
2434 if (trampoline_name.starts_with("__AArch64ADRPThunk_") ||
2435 trampoline_name.starts_with("__AArch64AbsLongThunk_")) {
2436 symbol_type = eSymbolTypeTrampoline;
2437 is_trampoline = true;
2438 }
2439 }
2440 }
2441
2442 Symbol dc_symbol(
2443 i + start_id, // ID is the original symbol table index.
2444 mangled,
2445 symbol_type, // Type of this symbol
2446 is_global, // Is this globally visible?
2447 false, // Is this symbol debug info?
2448 is_trampoline, // Is this symbol a trampoline?
2449 false, // Is this symbol artificial?
2450 AddressRange(symbol_section_sp, // Section in which this symbol is
2451 // defined or null.
2452 symbol_value, // Offset in section or symbol value.
2453 symbol.st_size), // Size in bytes of this symbol.
2454 symbol_size_valid, // Symbol size is valid
2455 has_suffix, // Contains linker annotations?
2456 flags); // Symbol flags.
2457 if (symbol.getBinding() == STB_WEAK)
2458 dc_symbol.SetIsWeak(true);
2459 symtab->AddSymbol(dc_symbol);
2460 }
2461
2462 m_address_class_map.merge(address_class_map);
2463 return {i, address_class_map};
2464}
2465
2466std::pair<unsigned, ObjectFileELF::FileAddressToAddressClassMap>
2468 lldb_private::Section *symtab) {
2469 if (symtab->GetObjectFile() != this) {
2470 // If the symbol table section is owned by a different object file, have it
2471 // do the parsing.
2472 ObjectFileELF *obj_file_elf =
2473 static_cast<ObjectFileELF *>(symtab->GetObjectFile());
2474 auto [num_symbols, address_class_map] =
2475 obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab);
2476
2477 // The other object file returned the changes it made to its address
2478 // class map, make the same changes to ours.
2479 m_address_class_map.merge(address_class_map);
2480
2481 return {num_symbols, address_class_map};
2482 }
2483
2484 // Get section list for this object file.
2485 SectionList *section_list = m_sections_up.get();
2486 if (!section_list)
2487 return {};
2488
2489 user_id_t symtab_id = symtab->GetID();
2490 const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2491 assert(symtab_hdr->sh_type == SHT_SYMTAB ||
2492 symtab_hdr->sh_type == SHT_DYNSYM);
2493
2494 // sh_link: section header index of associated string table.
2495 user_id_t strtab_id = symtab_hdr->sh_link;
2496 Section *strtab = section_list->FindSectionByID(strtab_id).get();
2497
2498 if (symtab && strtab) {
2499 assert(symtab->GetObjectFile() == this);
2500 assert(strtab->GetObjectFile() == this);
2501
2502 DataExtractor symtab_data;
2503 DataExtractor strtab_data;
2504 if (ReadSectionData(symtab, symtab_data) &&
2505 ReadSectionData(strtab, strtab_data)) {
2506 size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
2507
2508 return ParseSymbols(symbol_table, start_id, section_list, num_symbols,
2509 symtab_data, strtab_data);
2510 }
2511 }
2512
2513 return {0, {}};
2514}
2515
2517 if (m_dynamic_symbols.size())
2518 return m_dynamic_symbols.size();
2519
2520 std::optional<DataExtractor> dynamic_data = GetDynamicData();
2521 if (!dynamic_data)
2522 return 0;
2523
2525 lldb::offset_t cursor = 0;
2526 while (e.symbol.Parse(*dynamic_data, &cursor)) {
2527 m_dynamic_symbols.push_back(e);
2528 if (e.symbol.d_tag == DT_NULL)
2529 break;
2530 }
2531 if (std::optional<DataExtractor> dynstr_data = GetDynstrData()) {
2532 for (ELFDynamicWithName &entry : m_dynamic_symbols) {
2533 switch (entry.symbol.d_tag) {
2534 case DT_NEEDED:
2535 case DT_SONAME:
2536 case DT_RPATH:
2537 case DT_RUNPATH:
2538 case DT_AUXILIARY:
2539 case DT_FILTER: {
2540 lldb::offset_t cursor = entry.symbol.d_val;
2541 const char *name = dynstr_data->GetCStr(&cursor);
2542 if (name)
2543 entry.name = std::string(name);
2544 break;
2545 }
2546 default:
2547 break;
2548 }
2549 }
2550 }
2551 return m_dynamic_symbols.size();
2552}
2553
2555 if (!ParseDynamicSymbols())
2556 return nullptr;
2557 for (const auto &entry : m_dynamic_symbols) {
2558 if (entry.symbol.d_tag == tag)
2559 return &entry.symbol;
2560 }
2561 return nullptr;
2562}
2563
2565 // DT_PLTREL
2566 // This member specifies the type of relocation entry to which the
2567 // procedure linkage table refers. The d_val member holds DT_REL or
2568 // DT_RELA, as appropriate. All relocations in a procedure linkage table
2569 // must use the same relocation.
2570 const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
2571
2572 if (symbol)
2573 return symbol->d_val;
2574
2575 return 0;
2576}
2577
2578// Returns the size of the normal plt entries and the offset of the first
2579// normal plt entry. The 0th entry in the plt table is usually a resolution
2580// entry which have different size in some architectures then the rest of the
2581// plt entries.
2582static std::pair<uint64_t, uint64_t>
2584 const ELFSectionHeader *plt_hdr) {
2585 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2586
2587 // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are
2588 // 16 bytes. So round the entsize up by the alignment if addralign is set.
2589 elf_xword plt_entsize =
2590 plt_hdr->sh_addralign
2591 ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign)
2592 : plt_hdr->sh_entsize;
2593
2594 // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly.
2595 // PLT entries relocation code in general requires multiple instruction and
2596 // should be greater than 4 bytes in most cases. Try to guess correct size
2597 // just in case.
2598 if (plt_entsize <= 4) {
2599 // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the
2600 // size of the plt entries based on the number of entries and the size of
2601 // the plt section with the assumption that the size of the 0th entry is at
2602 // least as big as the size of the normal entries and it isn't much bigger
2603 // then that.
2604 if (plt_hdr->sh_addralign)
2605 plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign /
2606 (num_relocations + 1) * plt_hdr->sh_addralign;
2607 else
2608 plt_entsize = plt_hdr->sh_size / (num_relocations + 1);
2609 }
2610
2611 elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize;
2612
2613 return std::make_pair(plt_entsize, plt_offset);
2614}
2615
2616static unsigned ParsePLTRelocations(
2617 Symtab *symbol_table, user_id_t start_id, unsigned rel_type,
2618 const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2619 const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr,
2620 const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data,
2621 DataExtractor &symtab_data, DataExtractor &strtab_data) {
2622 ELFRelocation rel(rel_type);
2623 ELFSymbol symbol;
2624 lldb::offset_t offset = 0;
2625
2626 uint64_t plt_offset, plt_entsize;
2627 std::tie(plt_entsize, plt_offset) =
2628 GetPltEntrySizeAndOffset(rel_hdr, plt_hdr);
2629 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2630
2631 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2632 reloc_info_fn reloc_type;
2633 reloc_info_fn reloc_symbol;
2634
2635 if (hdr->Is32Bit()) {
2636 reloc_type = ELFRelocation::RelocType32;
2637 reloc_symbol = ELFRelocation::RelocSymbol32;
2638 } else {
2639 reloc_type = ELFRelocation::RelocType64;
2640 reloc_symbol = ELFRelocation::RelocSymbol64;
2641 }
2642
2643 unsigned slot_type = hdr->GetRelocationJumpSlotType();
2644 unsigned i;
2645 for (i = 0; i < num_relocations; ++i) {
2646 if (!rel.Parse(rel_data, &offset))
2647 break;
2648
2649 if (reloc_type(rel) != slot_type)
2650 continue;
2651
2652 lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
2653 if (!symbol.Parse(symtab_data, &symbol_offset))
2654 break;
2655
2656 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
2657 uint64_t plt_index = plt_offset + i * plt_entsize;
2658
2659 Symbol jump_symbol(
2660 i + start_id, // Symbol table index
2661 symbol_name, // symbol name.
2662 eSymbolTypeTrampoline, // Type of this symbol
2663 false, // Is this globally visible?
2664 false, // Is this symbol debug info?
2665 true, // Is this symbol a trampoline?
2666 true, // Is this symbol artificial?
2667 plt_section_sp, // Section in which this symbol is defined or null.
2668 plt_index, // Offset in section or symbol value.
2669 plt_entsize, // Size in bytes of this symbol.
2670 true, // Size is valid
2671 false, // Contains linker annotations?
2672 0); // Symbol flags.
2673
2674 symbol_table->AddSymbol(jump_symbol);
2675 }
2676
2677 return i;
2678}
2679
2680unsigned
2682 const ELFSectionHeaderInfo *rel_hdr,
2683 user_id_t rel_id) {
2684 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2685
2686 // The link field points to the associated symbol table.
2687 user_id_t symtab_id = rel_hdr->sh_link;
2688
2689 // If the link field doesn't point to the appropriate symbol name table then
2690 // try to find it by name as some compiler don't fill in the link fields.
2691 if (!symtab_id)
2692 symtab_id = GetSectionIndexByName(".dynsym");
2693
2694 // Get PLT section. We cannot use rel_hdr->sh_info, since current linkers
2695 // point that to the .got.plt or .got section instead of .plt.
2696 user_id_t plt_id = GetSectionIndexByName(".plt");
2697
2698 if (!symtab_id || !plt_id)
2699 return 0;
2700
2701 const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
2702 if (!plt_hdr)
2703 return 0;
2704
2705 const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
2706 if (!sym_hdr)
2707 return 0;
2708
2709 SectionList *section_list = m_sections_up.get();
2710 if (!section_list)
2711 return 0;
2712
2713 Section *rel_section = section_list->FindSectionByID(rel_id).get();
2714 if (!rel_section)
2715 return 0;
2716
2717 SectionSP plt_section_sp(section_list->FindSectionByID(plt_id));
2718 if (!plt_section_sp)
2719 return 0;
2720
2721 Section *symtab = section_list->FindSectionByID(symtab_id).get();
2722 if (!symtab)
2723 return 0;
2724
2725 // sh_link points to associated string table.
2726 Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link).get();
2727 if (!strtab)
2728 return 0;
2729
2730 DataExtractor rel_data;
2731 if (!ReadSectionData(rel_section, rel_data))
2732 return 0;
2733
2734 DataExtractor symtab_data;
2735 if (!ReadSectionData(symtab, symtab_data))
2736 return 0;
2737
2738 DataExtractor strtab_data;
2739 if (!ReadSectionData(strtab, strtab_data))
2740 return 0;
2741
2742 unsigned rel_type = PLTRelocationType();
2743 if (!rel_type)
2744 return 0;
2745
2746 return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header,
2747 rel_hdr, plt_hdr, sym_hdr, plt_section_sp,
2748 rel_data, symtab_data, strtab_data);
2749}
2750
2751static void ApplyELF64ABS64Relocation(Symtab *symtab, ELFRelocation &rel,
2752 DataExtractor &debug_data,
2753 Section *rel_section) {
2754 Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol64(rel));
2755 if (symbol) {
2756 addr_t value = symbol->GetAddressRef().GetFileAddress();
2757 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2758 // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
2759 WritableDataBuffer *data_buffer =
2760 llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
2761 void *const dst = data_buffer->GetBytes() + rel_section->GetFileOffset() +
2762 ELFRelocation::RelocOffset64(rel);
2763 uint64_t val_offset = value + ELFRelocation::RelocAddend64(rel);
2764 memcpy(dst, &val_offset, sizeof(uint64_t));
2765 }
2766}
2767
2768static void ApplyELF64ABS32Relocation(Symtab *symtab, ELFRelocation &rel,
2769 DataExtractor &debug_data,
2770 Section *rel_section, bool is_signed) {
2771 Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol64(rel));
2772 if (symbol) {
2773 addr_t value = symbol->GetAddressRef().GetFileAddress();
2774 value += ELFRelocation::RelocAddend32(rel);
2775 if ((!is_signed && (value > UINT32_MAX)) ||
2776 (is_signed &&
2777 ((int64_t)value > INT32_MAX || (int64_t)value < INT32_MIN))) {
2778 Log *log = GetLog(LLDBLog::Modules);
2779 LLDB_LOGF(log, "Failed to apply debug info relocations");
2780 return;
2781 }
2782 uint32_t truncated_addr = (value & 0xFFFFFFFF);
2783 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2784 // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
2785 WritableDataBuffer *data_buffer =
2786 llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
2787 void *const dst = data_buffer->GetBytes() + rel_section->GetFileOffset() +
2788 ELFRelocation::RelocOffset32(rel);
2789 memcpy(dst, &truncated_addr, sizeof(uint32_t));
2790 }
2791}
2792
2793static void ApplyELF32ABS32RelRelocation(Symtab *symtab, ELFRelocation &rel,
2794 DataExtractor &debug_data,
2795 Section *rel_section) {
2796 Log *log = GetLog(LLDBLog::Modules);
2797 Symbol *symbol = symtab->FindSymbolByID(ELFRelocation::RelocSymbol32(rel));
2798 if (symbol) {
2799 addr_t value = symbol->GetAddressRef().GetFileAddress();
2800 if (value == LLDB_INVALID_ADDRESS) {
2801 const char *name = symbol->GetName().GetCString();
2802 LLDB_LOGF(log, "Debug info symbol invalid: %s", name);
2803 return;
2804 }
2805 assert(llvm::isUInt<32>(value) && "Valid addresses are 32-bit");
2806 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2807 // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
2808 WritableDataBuffer *data_buffer =
2809 llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
2810 uint8_t *dst = data_buffer->GetBytes() + rel_section->GetFileOffset() +
2811 ELFRelocation::RelocOffset32(rel);
2812 // Implicit addend is stored inline as a signed value.
2813 int32_t addend;
2814 memcpy(&addend, dst, sizeof(int32_t));
2815 // The sum must be positive. This extra check prevents UB from overflow in
2816 // the actual range check below.
2817 if (addend < 0 && static_cast<uint32_t>(-addend) > value) {
2818 LLDB_LOGF(log, "Debug info relocation overflow: 0x%" PRIx64,
2819 static_cast<int64_t>(value) + addend);
2820 return;
2821 }
2822 if (!llvm::isUInt<32>(value + addend)) {
2823 LLDB_LOGF(log, "Debug info relocation out of range: 0x%" PRIx64, value);
2824 return;
2825 }
2826 uint32_t addr = value + addend;
2827 memcpy(dst, &addr, sizeof(uint32_t));
2828 }
2829}
2830
2832 Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2833 const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr,
2834 DataExtractor &rel_data, DataExtractor &symtab_data,
2835 DataExtractor &debug_data, Section *rel_section) {
2836 ELFRelocation rel(rel_hdr->sh_type);
2837 lldb::addr_t offset = 0;
2838 const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2839 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2840 reloc_info_fn reloc_type;
2841 reloc_info_fn reloc_symbol;
2842
2843 if (hdr->Is32Bit()) {
2844 reloc_type = ELFRelocation::RelocType32;
2845 reloc_symbol = ELFRelocation::RelocSymbol32;
2846 } else {
2847 reloc_type = ELFRelocation::RelocType64;
2848 reloc_symbol = ELFRelocation::RelocSymbol64;
2849 }
2850
2851 for (unsigned i = 0; i < num_relocations; ++i) {
2852 if (!rel.Parse(rel_data, &offset)) {
2853 GetModule()->ReportError(".rel{0}[{1:d}] failed to parse relocation",
2854 rel_section->GetName().AsCString(), i);
2855 break;
2856 }
2857 Symbol *symbol = nullptr;
2858
2859 if (hdr->Is32Bit()) {
2860 switch (hdr->e_machine) {
2861 case llvm::ELF::EM_ARM:
2862 switch (reloc_type(rel)) {
2863 case R_ARM_ABS32:
2864 ApplyELF32ABS32RelRelocation(symtab, rel, debug_data, rel_section);
2865 break;
2866 case R_ARM_REL32:
2867 GetModule()->ReportError("unsupported AArch32 relocation:"
2868 " .rel{0}[{1}], type {2}",
2869 rel_section->GetName().AsCString(), i,
2870 reloc_type(rel));
2871 break;
2872 default:
2873 assert(false && "unexpected relocation type");
2874 }
2875 break;
2876 case llvm::ELF::EM_386:
2877 switch (reloc_type(rel)) {
2878 case R_386_32:
2879 symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2880 if (symbol) {
2881 addr_t f_offset =
2882 rel_section->GetFileOffset() + ELFRelocation::RelocOffset32(rel);
2883 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2884 // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
2885 WritableDataBuffer *data_buffer =
2886 llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
2887 uint32_t *dst = reinterpret_cast<uint32_t *>(
2888 data_buffer->GetBytes() + f_offset);
2889
2890 addr_t value = symbol->GetAddressRef().GetFileAddress();
2891 if (rel.IsRela()) {
2892 value += ELFRelocation::RelocAddend32(rel);
2893 } else {
2894 value += *dst;
2895 }
2896 *dst = value;
2897 } else {
2898 GetModule()->ReportError(".rel{0}[{1}] unknown symbol id: {2:d}",
2899 rel_section->GetName().AsCString(), i,
2900 reloc_symbol(rel));
2901 }
2902 break;
2903 case R_386_NONE:
2904 case R_386_PC32:
2905 GetModule()->ReportError("unsupported i386 relocation:"
2906 " .rel{0}[{1}], type {2}",
2907 rel_section->GetName().AsCString(), i,
2908 reloc_type(rel));
2909 break;
2910 default:
2911 assert(false && "unexpected relocation type");
2912 break;
2913 }
2914 break;
2915 default:
2916 GetModule()->ReportError("unsupported 32-bit ELF machine arch: {0}", hdr->e_machine);
2917 break;
2918 }
2919 } else {
2920 switch (hdr->e_machine) {
2921 case llvm::ELF::EM_AARCH64:
2922 switch (reloc_type(rel)) {
2923 case R_AARCH64_ABS64:
2924 ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
2925 break;
2926 case R_AARCH64_ABS32:
2927 ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
2928 break;
2929 default:
2930 assert(false && "unexpected relocation type");
2931 }
2932 break;
2933 case llvm::ELF::EM_LOONGARCH:
2934 switch (reloc_type(rel)) {
2935 case R_LARCH_64:
2936 ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
2937 break;
2938 case R_LARCH_32:
2939 ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
2940 break;
2941 default:
2942 assert(false && "unexpected relocation type");
2943 }
2944 break;
2945 case llvm::ELF::EM_X86_64:
2946 switch (reloc_type(rel)) {
2947 case R_X86_64_64:
2948 ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
2949 break;
2950 case R_X86_64_32:
2951 ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section,
2952 false);
2953 break;
2954 case R_X86_64_32S:
2955 ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
2956 break;
2957 case R_X86_64_PC32:
2958 default:
2959 assert(false && "unexpected relocation type");
2960 }
2961 break;
2962 default:
2963 GetModule()->ReportError("unsupported 64-bit ELF machine arch: {0}", hdr->e_machine);
2964 break;
2965 }
2966 }
2967 }
2968
2969 return 0;
2970}
2971
2973 user_id_t rel_id,
2974 lldb_private::Symtab *thetab) {
2975 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2976
2977 // Parse in the section list if needed.
2978 SectionList *section_list = GetSectionList();
2979 if (!section_list)
2980 return 0;
2981
2982 user_id_t symtab_id = rel_hdr->sh_link;
2983 user_id_t debug_id = rel_hdr->sh_info;
2984
2985 const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2986 if (!symtab_hdr)
2987 return 0;
2988
2989 const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id);
2990 if (!debug_hdr)
2991 return 0;
2992
2993 Section *rel = section_list->FindSectionByID(rel_id).get();
2994 if (!rel)
2995 return 0;
2996
2997 Section *symtab = section_list->FindSectionByID(symtab_id).get();
2998 if (!symtab)
2999 return 0;
3000
3001 Section *debug = section_list->FindSectionByID(debug_id).get();
3002 if (!debug)
3003 return 0;
3004
3005 DataExtractor rel_data;
3006 DataExtractor symtab_data;
3007 DataExtractor debug_data;
3008
3009 if (GetData(rel->GetFileOffset(), rel->GetFileSize(), rel_data) &&
3010 GetData(symtab->GetFileOffset(), symtab->GetFileSize(), symtab_data) &&
3011 GetData(debug->GetFileOffset(), debug->GetFileSize(), debug_data)) {
3012 ApplyRelocations(thetab, &m_header, rel_hdr, symtab_hdr, debug_hdr,
3013 rel_data, symtab_data, debug_data, debug);
3014 }
3015
3016 return 0;
3017}
3018
3020 ModuleSP module_sp(GetModule());
3021 if (!module_sp)
3022 return;
3023
3024 Progress progress("Parsing symbol table",
3025 m_file.GetFilename().AsCString("<Unknown>"));
3026 ElapsedTime elapsed(module_sp->GetSymtabParseTime());
3027
3028 // We always want to use the main object file so we (hopefully) only have one
3029 // cached copy of our symtab, dynamic sections, etc.
3030 ObjectFile *module_obj_file = module_sp->GetObjectFile();
3031 if (module_obj_file && module_obj_file != this)
3032 return module_obj_file->ParseSymtab(lldb_symtab);
3033
3034 SectionList *section_list = module_sp->GetSectionList();
3035 if (!section_list)
3036 return;
3037
3038 uint64_t symbol_id = 0;
3039
3040 // Sharable objects and dynamic executables usually have 2 distinct symbol
3041 // tables, one named ".symtab", and the other ".dynsym". The dynsym is a
3042 // smaller version of the symtab that only contains global symbols. The
3043 // information found in the dynsym is therefore also found in the symtab,
3044 // while the reverse is not necessarily true.
3045 Section *symtab =
3046 section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get();
3047 if (symtab) {
3048 auto [num_symbols, address_class_map] =
3049 ParseSymbolTable(&lldb_symtab, symbol_id, symtab);
3050 m_address_class_map.merge(address_class_map);
3051 symbol_id += num_symbols;
3052 }
3053
3054 // The symtab section is non-allocable and can be stripped, while the
3055 // .dynsym section which should always be always be there. To support the
3056 // minidebuginfo case we parse .dynsym when there's a .gnu_debuginfo
3057 // section, nomatter if .symtab was already parsed or not. This is because
3058 // minidebuginfo normally removes the .symtab symbols which have their
3059 // matching .dynsym counterparts.
3060 if (!symtab ||
3061 GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata"))) {
3062 Section *dynsym =
3064 .get();
3065 if (dynsym) {
3066 auto [num_symbols, address_class_map] =
3067 ParseSymbolTable(&lldb_symtab, symbol_id, dynsym);
3068 symbol_id += num_symbols;
3069 m_address_class_map.merge(address_class_map);
3070 } else {
3071 // Try and read the dynamic symbol table from the .dynamic section.
3072 uint32_t dynamic_num_symbols = 0;
3073 std::optional<DataExtractor> symtab_data =
3074 GetDynsymDataFromDynamic(dynamic_num_symbols);
3075 std::optional<DataExtractor> strtab_data = GetDynstrData();
3076 if (symtab_data && strtab_data) {
3077 auto [num_symbols_parsed, address_class_map] = ParseSymbols(
3078 &lldb_symtab, symbol_id, section_list, dynamic_num_symbols,
3079 symtab_data.value(), strtab_data.value());
3080 symbol_id += num_symbols_parsed;
3081 m_address_class_map.merge(address_class_map);
3082 }
3083 }
3084 }
3085
3086 // DT_JMPREL
3087 // If present, this entry's d_ptr member holds the address of
3088 // relocation
3089 // entries associated solely with the procedure linkage table.
3090 // Separating
3091 // these relocation entries lets the dynamic linker ignore them during
3092 // process initialization, if lazy binding is enabled. If this entry is
3093 // present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
3094 // also be present.
3095 const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
3096 if (symbol) {
3097 // Synthesize trampoline symbols to help navigate the PLT.
3098 addr_t addr = symbol->d_ptr;
3099 Section *reloc_section =
3100 section_list->FindSectionContainingFileAddress(addr).get();
3101 if (reloc_section) {
3102 user_id_t reloc_id = reloc_section->GetID();
3103 const ELFSectionHeaderInfo *reloc_header =
3104 GetSectionHeaderByIndex(reloc_id);
3105 if (reloc_header)
3106 ParseTrampolineSymbols(&lldb_symtab, symbol_id, reloc_header, reloc_id);
3107 }
3108 }
3109
3110 if (DWARFCallFrameInfo *eh_frame =
3111 GetModule()->GetUnwindTable().GetEHFrameInfo()) {
3112 ParseUnwindSymbols(&lldb_symtab, eh_frame);
3113 }
3114
3115 // In the event that there's no symbol entry for the entry point we'll
3116 // artificially create one. We delegate to the symtab object the figuring
3117 // out of the proper size, this will usually make it span til the next
3118 // symbol it finds in the section. This means that if there are missing
3119 // symbols the entry point might span beyond its function definition.
3120 // We're fine with this as it doesn't make it worse than not having a
3121 // symbol entry at all.
3122 if (CalculateType() == eTypeExecutable) {
3123 ArchSpec arch = GetArchitecture();
3124 auto entry_point_addr = GetEntryPointAddress();
3125 bool is_valid_entry_point =
3126 entry_point_addr.IsValid() && entry_point_addr.IsSectionOffset();
3127 addr_t entry_point_file_addr = entry_point_addr.GetFileAddress();
3128 if (is_valid_entry_point && !lldb_symtab.FindSymbolContainingFileAddress(
3129 entry_point_file_addr)) {
3130 uint64_t symbol_id = lldb_symtab.GetNumSymbols();
3131 // Don't set the name for any synthetic symbols, the Symbol
3132 // object will generate one if needed when the name is accessed
3133 // via accessors.
3134 SectionSP section_sp = entry_point_addr.GetSection();
3135 Symbol symbol(
3136 /*symID=*/symbol_id,
3137 /*name=*/llvm::StringRef(), // Name will be auto generated.
3138 /*type=*/eSymbolTypeCode,
3139 /*external=*/true,
3140 /*is_debug=*/false,
3141 /*is_trampoline=*/false,
3142 /*is_artificial=*/true,
3143 /*section_sp=*/section_sp,
3144 /*offset=*/0,
3145 /*size=*/0, // FDE can span multiple symbols so don't use its size.
3146 /*size_is_valid=*/false,
3147 /*contains_linker_annotations=*/false,
3148 /*flags=*/0);
3149 // When the entry point is arm thumb we need to explicitly set its
3150 // class address to reflect that. This is important because expression
3151 // evaluation relies on correctly setting a breakpoint at this
3152 // address.
3153 if (arch.GetMachine() == llvm::Triple::arm &&
3154 (entry_point_file_addr & 1)) {
3155 symbol.GetAddressRef().SetOffset(entry_point_addr.GetOffset() ^ 1);
3156 m_address_class_map[entry_point_file_addr ^ 1] =
3158 } else {
3159 m_address_class_map[entry_point_file_addr] = AddressClass::eCode;
3160 }
3161 lldb_symtab.AddSymbol(symbol);
3162 }
3163 }
3164}
3165
3167{
3168 static const char *debug_prefix = ".debug";
3169
3170 // Set relocated bit so we stop getting called, regardless of whether we
3171 // actually relocate.
3172 section->SetIsRelocated(true);
3173
3174 // We only relocate in ELF relocatable files
3176 return;
3177
3178 const char *section_name = section->GetName().GetCString();
3179 // Can't relocate that which can't be named
3180 if (section_name == nullptr)
3181 return;
3182
3183 // We don't relocate non-debug sections at the moment
3184 if (strncmp(section_name, debug_prefix, strlen(debug_prefix)))
3185 return;
3186
3187 // Relocation section names to look for
3188 std::string needle = std::string(".rel") + section_name;
3189 std::string needlea = std::string(".rela") + section_name;
3190
3192 I != m_section_headers.end(); ++I) {
3193 if (I->sh_type == SHT_RELA || I->sh_type == SHT_REL) {
3194 const char *hay_name = I->section_name.GetCString();
3195 if (hay_name == nullptr)
3196 continue;
3197 if (needle == hay_name || needlea == hay_name) {
3198 const ELFSectionHeader &reloc_header = *I;
3199 user_id_t reloc_id = SectionIndex(I);
3200 RelocateDebugSections(&reloc_header, reloc_id, GetSymtab());
3201 break;
3202 }
3203 }
3204 }
3205}
3206
3208 DWARFCallFrameInfo *eh_frame) {
3209 SectionList *section_list = GetSectionList();
3210 if (!section_list)
3211 return;
3212
3213 // First we save the new symbols into a separate list and add them to the
3214 // symbol table after we collected all symbols we want to add. This is
3215 // neccessary because adding a new symbol invalidates the internal index of
3216 // the symtab what causing the next lookup to be slow because it have to
3217 // recalculate the index first.
3218 std::vector<Symbol> new_symbols;
3219
3220 size_t num_symbols = symbol_table->GetNumSymbols();
3221 uint64_t last_symbol_id =
3222 num_symbols ? symbol_table->SymbolAtIndex(num_symbols - 1)->GetID() : 0;
3223 eh_frame->ForEachFDEEntries([&](lldb::addr_t file_addr, uint32_t size,
3224 dw_offset_t) {
3225 Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr);
3226 if (symbol) {
3227 if (!symbol->GetByteSizeIsValid()) {
3228 symbol->SetByteSize(size);
3229 symbol->SetSizeIsSynthesized(true);
3230 }
3231 } else {
3232 SectionSP section_sp =
3233 section_list->FindSectionContainingFileAddress(file_addr);
3234 if (section_sp) {
3235 addr_t offset = file_addr - section_sp->GetFileAddress();
3236 uint64_t symbol_id = ++last_symbol_id;
3237 // Don't set the name for any synthetic symbols, the Symbol
3238 // object will generate one if needed when the name is accessed
3239 // via accessors.
3240 Symbol eh_symbol(
3241 /*symID=*/symbol_id,
3242 /*name=*/llvm::StringRef(), // Name will be auto generated.
3243 /*type=*/eSymbolTypeCode,
3244 /*external=*/true,
3245 /*is_debug=*/false,
3246 /*is_trampoline=*/false,
3247 /*is_artificial=*/true,
3248 /*section_sp=*/section_sp,
3249 /*offset=*/offset,
3250 /*size=*/0, // FDE can span multiple symbols so don't use its size.
3251 /*size_is_valid=*/false,
3252 /*contains_linker_annotations=*/false,
3253 /*flags=*/0);
3254 new_symbols.push_back(eh_symbol);
3255 }
3256 }
3257 return true;
3258 });
3259
3260 for (const Symbol &s : new_symbols)
3261 symbol_table->AddSymbol(s);
3262}
3263
3265 // TODO: determine this for ELF
3266 return false;
3267}
3268
3269//===----------------------------------------------------------------------===//
3270// Dump
3271//
3272// Dump the specifics of the runtime file container (such as any headers
3273// segments, sections, etc).
3275 ModuleSP module_sp(GetModule());
3276 if (!module_sp) {
3277 return;
3278 }
3279
3280 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
3281 s->Printf("%p: ", static_cast<void *>(this));
3282 s->Indent();
3283 s->PutCString("ObjectFileELF");
3284
3285 ArchSpec header_arch = GetArchitecture();
3286
3287 *s << ", file = '" << m_file
3288 << "', arch = " << header_arch.GetArchitectureName();
3290 s->Printf(", addr = %#16.16" PRIx64, m_memory_addr);
3291 s->EOL();
3292
3294 s->EOL();
3296 s->EOL();
3298 s->EOL();
3299 SectionList *section_list = GetSectionList();
3300 if (section_list)
3301 section_list->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
3302 UINT32_MAX);
3303 Symtab *symtab = GetSymtab();
3304 if (symtab)
3305 symtab->Dump(s, nullptr, eSortOrderNone);
3306 s->EOL();
3308 s->EOL();
3309 DumpELFDynamic(s);
3310 s->EOL();
3311 Address image_info_addr = GetImageInfoAddress(nullptr);
3312 if (image_info_addr.IsValid())
3313 s->Printf("image_info_address = %#16.16" PRIx64 "\n",
3314 image_info_addr.GetFileAddress());
3315}
3316
3317// DumpELFHeader
3318//
3319// Dump the ELF header to the specified output stream
3321 s->PutCString("ELF Header\n");
3322 s->Printf("e_ident[EI_MAG0 ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
3323 s->Printf("e_ident[EI_MAG1 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG1],
3324 header.e_ident[EI_MAG1]);
3325 s->Printf("e_ident[EI_MAG2 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG2],
3326 header.e_ident[EI_MAG2]);
3327 s->Printf("e_ident[EI_MAG3 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG3],
3328 header.e_ident[EI_MAG3]);
3329
3330 s->Printf("e_ident[EI_CLASS ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
3331 s->Printf("e_ident[EI_DATA ] = 0x%2.2x ", header.e_ident[EI_DATA]);
3332 DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
3333 s->Printf("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
3334 s->Printf("e_ident[EI_PAD ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
3335
3336 s->Printf("e_type = 0x%4.4x ", header.e_type);
3337 DumpELFHeader_e_type(s, header.e_type);
3338 s->Printf("\ne_machine = 0x%4.4x\n", header.e_machine);
3339 s->Printf("e_version = 0x%8.8x\n", header.e_version);
3340 s->Printf("e_entry = 0x%8.8" PRIx64 "\n", header.e_entry);
3341 s->Printf("e_phoff = 0x%8.8" PRIx64 "\n", header.e_phoff);
3342 s->Printf("e_shoff = 0x%8.8" PRIx64 "\n", header.e_shoff);
3343 s->Printf("e_flags = 0x%8.8x\n", header.e_flags);
3344 s->Printf("e_ehsize = 0x%4.4x\n", header.e_ehsize);
3345 s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
3346 s->Printf("e_phnum = 0x%8.8x\n", header.e_phnum);
3347 s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
3348 s->Printf("e_shnum = 0x%8.8x\n", header.e_shnum);
3349 s->Printf("e_shstrndx = 0x%8.8x\n", header.e_shstrndx);
3350}
3351
3352// DumpELFHeader_e_type
3353//
3354// Dump an token value for the ELF header member e_type
3356 switch (e_type) {
3357 case ET_NONE:
3358 *s << "ET_NONE";
3359 break;
3360 case ET_REL:
3361 *s << "ET_REL";
3362 break;
3363 case ET_EXEC:
3364 *s << "ET_EXEC";
3365 break;
3366 case ET_DYN:
3367 *s << "ET_DYN";
3368 break;
3369 case ET_CORE:
3370 *s << "ET_CORE";
3371 break;
3372 default:
3373 break;
3374 }
3375}
3376
3377// DumpELFHeader_e_ident_EI_DATA
3378//
3379// Dump an token value for the ELF header member e_ident[EI_DATA]
3381 unsigned char ei_data) {
3382 switch (ei_data) {
3383 case ELFDATANONE:
3384 *s << "ELFDATANONE";
3385 break;
3386 case ELFDATA2LSB:
3387 *s << "ELFDATA2LSB - Little Endian";
3388 break;
3389 case ELFDATA2MSB:
3390 *s << "ELFDATA2MSB - Big Endian";
3391 break;
3392 default:
3393 break;
3394 }
3395}
3396
3397// DumpELFProgramHeader
3398//
3399// Dump a single ELF program header to the specified output stream
3401 const ELFProgramHeader &ph) {
3403 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset,
3404 ph.p_vaddr, ph.p_paddr);
3405 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz,
3406 ph.p_flags);
3407
3409 s->Printf(") %8.8" PRIx64, ph.p_align);
3410}
3411
3412// DumpELFProgramHeader_p_type
3413//
3414// Dump an token value for the ELF program header member p_type which describes
3415// the type of the program header
3417 const int kStrWidth = 15;
3418 switch (p_type) {
3419 CASE_AND_STREAM(s, PT_NULL, kStrWidth);
3420 CASE_AND_STREAM(s, PT_LOAD, kStrWidth);
3421 CASE_AND_STREAM(s, PT_DYNAMIC, kStrWidth);
3422 CASE_AND_STREAM(s, PT_INTERP, kStrWidth);
3423 CASE_AND_STREAM(s, PT_NOTE, kStrWidth);
3424 CASE_AND_STREAM(s, PT_SHLIB, kStrWidth);
3425 CASE_AND_STREAM(s, PT_PHDR, kStrWidth);
3426 CASE_AND_STREAM(s, PT_TLS, kStrWidth);
3427 CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
3428 default:
3429 s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
3430 break;
3431 }
3432}
3433
3434// DumpELFProgramHeader_p_flags
3435//
3436// Dump an token value for the ELF program header member p_flags
3438 *s << ((p_flags & PF_X) ? "PF_X" : " ")
3439 << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
3440 << ((p_flags & PF_W) ? "PF_W" : " ")
3441 << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
3442 << ((p_flags & PF_R) ? "PF_R" : " ");
3443}
3444
3445// DumpELFProgramHeaders
3446//
3447// Dump all of the ELF program header to the specified output stream
3449 if (!ParseProgramHeaders())
3450 return;
3451
3452 s->PutCString("Program Headers\n");
3453 s->PutCString("IDX p_type p_offset p_vaddr p_paddr "
3454 "p_filesz p_memsz p_flags p_align\n");
3455 s->PutCString("==== --------------- -------- -------- -------- "
3456 "-------- -------- ------------------------- --------\n");
3457
3458 for (const auto &H : llvm::enumerate(m_program_headers)) {
3459 s->Format("[{0,2}] ", H.index());
3461 s->EOL();
3462 }
3463}
3464
3465// DumpELFSectionHeader
3466//
3467// Dump a single ELF section header to the specified output stream
3469 const ELFSectionHeaderInfo &sh) {
3470 s->Printf("%8.8x ", sh.sh_name);
3472 s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
3474 s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr,
3475 sh.sh_offset, sh.sh_size);
3476 s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
3477 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
3478}
3479
3480// DumpELFSectionHeader_sh_type
3481//
3482// Dump an token value for the ELF section header member sh_type which
3483// describes the type of the section
3485 const int kStrWidth = 12;
3486 switch (sh_type) {
3487 CASE_AND_STREAM(s, SHT_NULL, kStrWidth);
3488 CASE_AND_STREAM(s, SHT_PROGBITS, kStrWidth);
3489 CASE_AND_STREAM(s, SHT_SYMTAB, kStrWidth);
3490 CASE_AND_STREAM(s, SHT_STRTAB, kStrWidth);
3491 CASE_AND_STREAM(s, SHT_RELA, kStrWidth);
3492 CASE_AND_STREAM(s, SHT_HASH, kStrWidth);
3493 CASE_AND_STREAM(s, SHT_DYNAMIC, kStrWidth);
3494 CASE_AND_STREAM(s, SHT_NOTE, kStrWidth);
3495 CASE_AND_STREAM(s, SHT_NOBITS, kStrWidth);
3496 CASE_AND_STREAM(s, SHT_REL, kStrWidth);
3497 CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth);
3498 CASE_AND_STREAM(s, SHT_DYNSYM, kStrWidth);
3499 CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth);
3500 CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth);
3501 CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth);
3502 CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth);
3503 default:
3504 s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
3505 break;
3506 }
3507}
3508
3509// DumpELFSectionHeader_sh_flags
3510//
3511// Dump an token value for the ELF section header member sh_flags
3513 elf_xword sh_flags) {
3514 *s << ((sh_flags & SHF_WRITE) ? "WRITE" : " ")
3515 << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
3516 << ((sh_flags & SHF_ALLOC) ? "ALLOC" : " ")
3517 << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
3518 << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : " ");
3519}
3520
3521// DumpELFSectionHeaders
3522//
3523// Dump all of the ELF section header to the specified output stream
3525 if (!ParseSectionHeaders())
3526 return;
3527
3528 s->PutCString("Section Headers\n");
3529 s->PutCString("IDX name type flags "
3530 "addr offset size link info addralgn "
3531 "entsize Name\n");
3532 s->PutCString("==== -------- ------------ -------------------------------- "
3533 "-------- -------- -------- -------- -------- -------- "
3534 "-------- ====================\n");
3535
3536 uint32_t idx = 0;
3538 I != m_section_headers.end(); ++I, ++idx) {
3539 s->Printf("[%2u] ", idx);
3541 const char *section_name = I->section_name.AsCString("");
3542 if (section_name)
3543 *s << ' ' << section_name << "\n";
3544 }
3545}
3546
3548 size_t num_modules = ParseDependentModules();
3549
3550 if (num_modules > 0) {
3551 s->PutCString("Dependent Modules:\n");
3552 for (unsigned i = 0; i < num_modules; ++i) {
3553 const FileSpec &spec = m_filespec_up->GetFileSpecAtIndex(i);
3554 s->Printf(" %s\n", spec.GetFilename().GetCString());
3555 }
3556 }
3557}
3558
3559std::string static getDynamicTagAsString(uint16_t Arch, uint64_t Type) {
3560#define DYNAMIC_STRINGIFY_ENUM(tag, value) \
3561 case value: \
3562 return #tag;
3563
3564#define DYNAMIC_TAG(n, v)
3565 switch (Arch) {
3566 case llvm::ELF::EM_AARCH64:
3567 switch (Type) {
3568#define AARCH64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3569#include "llvm/BinaryFormat/DynamicTags.def"
3570#undef AARCH64_DYNAMIC_TAG
3571 }
3572 break;
3573
3574 case llvm::ELF::EM_HEXAGON:
3575 switch (Type) {
3576#define HEXAGON_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3577#include "llvm/BinaryFormat/DynamicTags.def"
3578#undef HEXAGON_DYNAMIC_TAG
3579 }
3580 break;
3581
3582 case llvm::ELF::EM_MIPS:
3583 switch (Type) {
3584#define MIPS_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3585#include "llvm/BinaryFormat/DynamicTags.def"
3586#undef MIPS_DYNAMIC_TAG
3587 }
3588 break;
3589
3590 case llvm::ELF::EM_PPC:
3591 switch (Type) {
3592#define PPC_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3593#include "llvm/BinaryFormat/DynamicTags.def"
3594#undef PPC_DYNAMIC_TAG
3595 }
3596 break;
3597
3598 case llvm::ELF::EM_PPC64:
3599 switch (Type) {
3600#define PPC64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3601#include "llvm/BinaryFormat/DynamicTags.def"
3602#undef PPC64_DYNAMIC_TAG
3603 }
3604 break;
3605
3606 case llvm::ELF::EM_RISCV:
3607 switch (Type) {
3608#define RISCV_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3609#include "llvm/BinaryFormat/DynamicTags.def"
3610#undef RISCV_DYNAMIC_TAG
3611 }
3612 break;
3613 }
3614#undef DYNAMIC_TAG
3615 switch (Type) {
3616// Now handle all dynamic tags except the architecture specific ones
3617#define AARCH64_DYNAMIC_TAG(name, value)
3618#define MIPS_DYNAMIC_TAG(name, value)
3619#define HEXAGON_DYNAMIC_TAG(name, value)
3620#define PPC_DYNAMIC_TAG(name, value)
3621#define PPC64_DYNAMIC_TAG(name, value)
3622#define RISCV_DYNAMIC_TAG(name, value)
3623// Also ignore marker tags such as DT_HIOS (maps to DT_VERNEEDNUM), etc.
3624#define DYNAMIC_TAG_MARKER(name, value)
3625#define DYNAMIC_TAG(name, value) \
3626 case value: \
3627 return #name;
3628#include "llvm/BinaryFormat/DynamicTags.def"
3629#undef DYNAMIC_TAG
3630#undef AARCH64_DYNAMIC_TAG
3631#undef MIPS_DYNAMIC_TAG
3632#undef HEXAGON_DYNAMIC_TAG
3633#undef PPC_DYNAMIC_TAG
3634#undef PPC64_DYNAMIC_TAG
3635#undef RISCV_DYNAMIC_TAG
3636#undef DYNAMIC_TAG_MARKER
3637#undef DYNAMIC_STRINGIFY_ENUM
3638 default:
3639 return "<unknown:>0x" + llvm::utohexstr(Type, true);
3640 }
3641}
3642
3645 if (m_dynamic_symbols.empty())
3646 return;
3647
3648 s->PutCString(".dynamic:\n");
3649 s->PutCString("IDX d_tag d_val/d_ptr\n");
3650 s->PutCString("==== ---------------- ------------------\n");
3651 uint32_t idx = 0;
3652 for (const auto &entry : m_dynamic_symbols) {
3653 s->Printf("[%2u] ", idx++);
3654 s->Printf(
3655 "%-16s 0x%16.16" PRIx64,
3656 getDynamicTagAsString(m_header.e_machine, entry.symbol.d_tag).c_str(),
3657 entry.symbol.d_ptr);
3658 if (!entry.name.empty())
3659 s->Printf(" \"%s\"", entry.name.c_str());
3660 s->EOL();
3661 }
3662}
3663
3665 if (!ParseHeader())
3666 return ArchSpec();
3667
3668 if (m_section_headers.empty()) {
3669 // Allow elf notes to be parsed which may affect the detected architecture.
3671 }
3672
3673 if (CalculateType() == eTypeCoreFile &&
3674 !m_arch_spec.TripleOSWasSpecified()) {
3675 // Core files don't have section headers yet they have PT_NOTE program
3676 // headers that might shed more light on the architecture
3677 for (const elf::ELFProgramHeader &H : ProgramHeaders()) {
3678 if (H.p_type != PT_NOTE || H.p_offset == 0 || H.p_filesz == 0)
3679 continue;
3680 DataExtractor data;
3681 if (data.SetData(m_data, H.p_offset, H.p_filesz) == H.p_filesz) {
3682 UUID uuid;
3684 }
3685 }
3686 }
3687 return m_arch_spec;
3688}
3689
3691 switch (m_header.e_type) {
3692 case llvm::ELF::ET_NONE:
3693 // 0 - No file type
3694 return eTypeUnknown;
3695
3696 case llvm::ELF::ET_REL:
3697 // 1 - Relocatable file
3698 return eTypeObjectFile;
3699
3700 case llvm::ELF::ET_EXEC:
3701 // 2 - Executable file
3702 return eTypeExecutable;
3703
3704 case llvm::ELF::ET_DYN:
3705 // 3 - Shared object file
3706 return eTypeSharedLibrary;
3707
3708 case ET_CORE:
3709 // 4 - Core file
3710 return eTypeCoreFile;
3711
3712 default:
3713 break;
3714 }
3715 return eTypeUnknown;
3716}
3717
3719 switch (m_header.e_type) {
3720 case llvm::ELF::ET_NONE:
3721 // 0 - No file type
3722 return eStrataUnknown;
3723
3724 case llvm::ELF::ET_REL:
3725 // 1 - Relocatable file
3726 return eStrataUnknown;
3727
3728 case llvm::ELF::ET_EXEC:
3729 // 2 - Executable file
3730 {
3731 SectionList *section_list = GetSectionList();
3732 if (section_list) {
3733 static ConstString loader_section_name(".interp");
3734 SectionSP loader_section =
3735 section_list->FindSectionByName(loader_section_name);
3736 if (loader_section) {
3737 char buffer[256];
3738 size_t read_size =
3739 ReadSectionData(loader_section.get(), 0, buffer, sizeof(buffer));
3740
3741 // We compare the content of .interp section
3742 // It will contains \0 when counting read_size, so the size needs to
3743 // decrease by one
3744 llvm::StringRef loader_name(buffer, read_size - 1);
3745 llvm::StringRef freebsd_kernel_loader_name("/red/herring");
3746 if (loader_name == freebsd_kernel_loader_name)
3747 return eStrataKernel;
3748 }
3749 }
3750 return eStrataUser;
3751 }
3752
3753 case llvm::ELF::ET_DYN:
3754 // 3 - Shared object file
3755 // TODO: is there any way to detect that an shared library is a kernel
3756 // related executable by inspecting the program headers, section headers,
3757 // symbols, or any other flag bits???
3758 return eStrataUnknown;
3759
3760 case ET_CORE:
3761 // 4 - Core file
3762 // TODO: is there any way to detect that an core file is a kernel
3763 // related executable by inspecting the program headers, section headers,
3764 // symbols, or any other flag bits???
3765 return eStrataUnknown;
3766
3767 default:
3768 break;
3769 }
3770 return eStrataUnknown;
3771}
3772
3774 lldb::offset_t section_offset, void *dst,
3775 size_t dst_len) {
3776 // If some other objectfile owns this data, pass this to them.
3777 if (section->GetObjectFile() != this)
3778 return section->GetObjectFile()->ReadSectionData(section, section_offset,
3779 dst, dst_len);
3780
3781 if (!section->Test(SHF_COMPRESSED))
3782 return ObjectFile::ReadSectionData(section, section_offset, dst, dst_len);
3783
3784 // For compressed sections we need to read to full data to be able to
3785 // decompress.
3786 DataExtractor data;
3787 ReadSectionData(section, data);
3788 return data.CopyData(section_offset, dst_len, dst);
3789}
3790
3792 DataExtractor &section_data) {
3793 // If some other objectfile owns this data, pass this to them.
3794 if (section->GetObjectFile() != this)
3795 return section->GetObjectFile()->ReadSectionData(section, section_data);
3796
3797 size_t result = ObjectFile::ReadSectionData(section, section_data);
3798 if (result == 0 || !(section->Get() & llvm::ELF::SHF_COMPRESSED))
3799 return result;
3800
3801 auto Decompressor = llvm::object::Decompressor::create(
3802 section->GetName().GetStringRef(),
3803 {reinterpret_cast<const char *>(section_data.GetDataStart()),
3804 size_t(section_data.GetByteSize())},
3806 if (!Decompressor) {
3807 GetModule()->ReportWarning(
3808 "Unable to initialize decompressor for section '{0}': {1}",
3809 section->GetName().GetCString(),
3810 llvm::toString(Decompressor.takeError()).c_str());
3811 section_data.Clear();
3812 return 0;
3813 }
3814
3815 auto buffer_sp =
3816 std::make_shared<DataBufferHeap>(Decompressor->getDecompressedSize(), 0);
3817 if (auto error = Decompressor->decompress(
3818 {buffer_sp->GetBytes(), size_t(buffer_sp->GetByteSize())})) {
3819 GetModule()->ReportWarning("Decompression of section '{0}' failed: {1}",
3820 section->GetName().GetCString(),
3821 llvm::toString(std::move(error)).c_str());
3822 section_data.Clear();
3823 return 0;
3824 }
3825
3826 section_data.SetData(buffer_sp);
3827 return buffer_sp->GetByteSize();
3828}
3829
3830llvm::ArrayRef<ELFProgramHeader> ObjectFileELF::ProgramHeaders() {
3832 return m_program_headers;
3833}
3834
3836 // Try and read the program header from our cached m_data which can come from
3837 // the file on disk being mmap'ed or from the initial part of the ELF file we
3838 // read from memory and cached.
3840 if (data.GetByteSize() == H.p_filesz)
3841 return data;
3842 if (IsInMemory()) {
3843 // We have a ELF file in process memory, read the program header data from
3844 // the process.
3845 if (ProcessSP process_sp = m_process_wp.lock()) {
3846 const lldb::offset_t base_file_addr = GetBaseAddress().GetFileAddress();
3847 const addr_t load_bias = m_memory_addr - base_file_addr;
3848 const addr_t data_addr = H.p_vaddr + load_bias;
3849 if (DataBufferSP data_sp = ReadMemory(process_sp, data_addr, H.p_memsz))
3850 return DataExtractor(data_sp, GetByteOrder(), GetAddressByteSize());
3851 }
3852 }
3853 return DataExtractor();
3854}
3855
3857 for (const ELFProgramHeader &H : ProgramHeaders()) {
3858 if (H.p_paddr != 0)
3859 return true;
3860 }
3861 return false;
3862}
3863
3864std::vector<ObjectFile::LoadableData>
3866 // Create a list of loadable data from loadable segments, using physical
3867 // addresses if they aren't all null
3868 std::vector<LoadableData> loadables;
3869 bool should_use_paddr = AnySegmentHasPhysicalAddress();
3870 for (const ELFProgramHeader &H : ProgramHeaders()) {
3871 LoadableData loadable;
3872 if (H.p_type != llvm::ELF::PT_LOAD)
3873 continue;
3874 loadable.Dest = should_use_paddr ? H.p_paddr : H.p_vaddr;
3875 if (loadable.Dest == LLDB_INVALID_ADDRESS)
3876 continue;
3877 if (H.p_filesz == 0)
3878 continue;
3879 auto segment_data = GetSegmentData(H);
3880 loadable.Contents = llvm::ArrayRef<uint8_t>(segment_data.GetDataStart(),
3881 segment_data.GetByteSize());
3882 loadables.push_back(loadable);
3883 }
3884 return loadables;
3885}
3886
3889 uint64_t Offset) {
3891 Offset);
3892}
3893
3894std::optional<DataExtractor>
3896 uint64_t offset) {
3897 // ELFDynamic values contain a "d_ptr" member that will be a load address if
3898 // we have an ELF file read from memory, or it will be a file address if it
3899 // was read from a ELF file. This function will correctly fetch data pointed
3900 // to by the ELFDynamic::d_ptr, or return std::nullopt if the data isn't
3901 // available.
3902 const lldb::addr_t d_ptr_addr = dyn->d_ptr + offset;
3903 if (ProcessSP process_sp = m_process_wp.lock()) {
3904 if (DataBufferSP data_sp = ReadMemory(process_sp, d_ptr_addr, length))
3905 return DataExtractor(data_sp, GetByteOrder(), GetAddressByteSize());
3906 } else {
3907 // We have an ELF file with no section headers or we didn't find the
3908 // .dynamic section. Try and find the .dynstr section.
3909 Address addr;
3910 if (!addr.ResolveAddressUsingFileSections(d_ptr_addr, GetSectionList()))
3911 return std::nullopt;
3912 DataExtractor data;
3913 addr.GetSection()->GetSectionData(data);
3914 return DataExtractor(data, d_ptr_addr - addr.GetSection()->GetFileAddress(),
3915 length);
3916 }
3917 return std::nullopt;
3918}
3919
3920std::optional<DataExtractor> ObjectFileELF::GetDynstrData() {
3921 if (SectionList *section_list = GetSectionList()) {
3922 // Find the SHT_DYNAMIC section.
3923 if (Section *dynamic =
3924 section_list
3925 ->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
3926 .get()) {
3927 assert(dynamic->GetObjectFile() == this);
3928 if (const ELFSectionHeaderInfo *header =
3929 GetSectionHeaderByIndex(dynamic->GetID())) {
3930 // sh_link: section header index of string table used by entries in
3931 // the section.
3932 if (Section *dynstr =
3933 section_list->FindSectionByID(header->sh_link).get()) {
3934 DataExtractor data;
3935 if (ReadSectionData(dynstr, data))
3936 return data;
3937 }
3938 }
3939 }
3940 }
3941
3942 // Every ELF file which represents an executable or shared library has
3943 // mandatory .dynamic entries. Two of these values are DT_STRTAB and DT_STRSZ
3944 // and represent the dynamic symbol tables's string table. These are needed
3945 // by the dynamic loader and we can read them from a process' address space.
3946 //
3947 // When loading and ELF file from memory, only the program headers are
3948 // guaranteed end up being mapped into memory, and we can find these values in
3949 // the PT_DYNAMIC segment.
3950 const ELFDynamic *strtab = FindDynamicSymbol(DT_STRTAB);
3951 const ELFDynamic *strsz = FindDynamicSymbol(DT_STRSZ);
3952 if (strtab == nullptr || strsz == nullptr)
3953 return std::nullopt;
3954
3955 return ReadDataFromDynamic(strtab, strsz->d_val, /*offset=*/0);
3956}
3957
3958std::optional<lldb_private::DataExtractor> ObjectFileELF::GetDynamicData() {
3959 DataExtractor data;
3960 // The PT_DYNAMIC program header describes where the .dynamic section is and
3961 // doesn't require parsing section headers. The PT_DYNAMIC is required by
3962 // executables and shared libraries so it will always be available.
3963 for (const ELFProgramHeader &H : ProgramHeaders()) {
3964 if (H.p_type == llvm::ELF::PT_DYNAMIC) {
3965 data = GetSegmentData(H);
3966 if (data.GetByteSize() > 0) {
3967 m_dynamic_base_addr = H.p_vaddr;
3968 return data;
3969 }
3970 }
3971 }
3972 // Fall back to using section headers.
3973 if (SectionList *section_list = GetSectionList()) {
3974 // Find the SHT_DYNAMIC section.
3975 if (Section *dynamic =
3976 section_list
3977 ->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
3978 .get()) {
3979 assert(dynamic->GetObjectFile() == this);
3980 if (ReadSectionData(dynamic, data)) {
3981 m_dynamic_base_addr = dynamic->GetFileAddress();
3982 return data;
3983 }
3984 }
3985 }
3986 return std::nullopt;
3987}
3988
3990 const ELFDynamic *hash = FindDynamicSymbol(DT_HASH);
3991 if (hash == nullptr)
3992 return std::nullopt;
3993
3994 // The DT_HASH header looks like this:
3995 struct DtHashHeader {
3996 uint32_t nbucket;
3997 uint32_t nchain;
3998 };
3999 if (auto data = ReadDataFromDynamic(hash, 8)) {
4000 // We don't need the number of buckets value "nbucket", we just need the
4001 // "nchain" value which contains the number of symbols.
4002 offset_t offset = offsetof(DtHashHeader, nchain);
4003 return data->GetU32(&offset);
4004 }
4005
4006 return std::nullopt;
4007}
4008
4010 const ELFDynamic *gnu_hash = FindDynamicSymbol(DT_GNU_HASH);
4011 if (gnu_hash == nullptr)
4012 return std::nullopt;
4013
4014 // Create a DT_GNU_HASH header
4015 // https://flapenguin.me/elf-dt-gnu-hash
4016 struct DtGnuHashHeader {
4017 uint32_t nbuckets = 0;
4018 uint32_t symoffset = 0;
4019 uint32_t bloom_size = 0;
4020 uint32_t bloom_shift = 0;
4021 };
4022 uint32_t num_symbols = 0;
4023 // Read enogh data for the DT_GNU_HASH header so we can extract the values.
4024 if (auto data = ReadDataFromDynamic(gnu_hash, sizeof(DtGnuHashHeader))) {
4025 offset_t offset = 0;
4026 DtGnuHashHeader header;
4027 header.nbuckets = data->GetU32(&offset);
4028 header.symoffset = data->GetU32(&offset);
4029 header.bloom_size = data->GetU32(&offset);
4030 header.bloom_shift = data->GetU32(&offset);
4031 const size_t addr_size = GetAddressByteSize();
4032 const addr_t buckets_offset =
4033 sizeof(DtGnuHashHeader) + addr_size * header.bloom_size;
4034 std::vector<uint32_t> buckets;
4035 if (auto bucket_data = ReadDataFromDynamic(gnu_hash, header.nbuckets * 4,
4036 buckets_offset)) {
4037 offset = 0;
4038 for (uint32_t i = 0; i < header.nbuckets; ++i)
4039 buckets.push_back(bucket_data->GetU32(&offset));
4040 // Locate the chain that handles the largest index bucket.
4041 uint32_t last_symbol = 0;
4042 for (uint32_t bucket_value : buckets)
4043 last_symbol = std::max(bucket_value, last_symbol);
4044 if (last_symbol < header.symoffset) {
4045 num_symbols = header.symoffset;
4046 } else {
4047 // Walk the bucket's chain to add the chain length to the total.
4048 const addr_t chains_base_offset = buckets_offset + header.nbuckets * 4;
4049 for (;;) {
4050 if (auto chain_entry_data = ReadDataFromDynamic(
4051 gnu_hash, 4,
4052 chains_base_offset + (last_symbol - header.symoffset) * 4)) {
4053 offset = 0;
4054 uint32_t chain_entry = chain_entry_data->GetU32(&offset);
4055 ++last_symbol;
4056 // If the low bit is set, this entry is the end of the chain.
4057 if (chain_entry & 1)
4058 break;
4059 } else {
4060 break;
4061 }
4062 }
4063 num_symbols = last_symbol;
4064 }
4065 }
4066 }
4067 if (num_symbols > 0)
4068 return num_symbols;
4069
4070 return std::nullopt;
4071}
4072
4073std::optional<DataExtractor>
4075 // Every ELF file which represents an executable or shared library has
4076 // mandatory .dynamic entries. The DT_SYMTAB value contains a pointer to the
4077 // symbol table, and DT_SYMENT contains the size of a symbol table entry.
4078 // We then can use either the DT_HASH or DT_GNU_HASH to find the number of
4079 // symbols in the symbol table as the symbol count is not stored in the
4080 // .dynamic section as a key/value pair.
4081 //
4082 // When loading and ELF file from memory, only the program headers end up
4083 // being mapped into memory, and we can find these values in the PT_DYNAMIC
4084 // segment.
4085 num_symbols = 0;
4086 // Get the process in case this is an in memory ELF file.
4087 ProcessSP process_sp(m_process_wp.lock());
4088 const ELFDynamic *symtab = FindDynamicSymbol(DT_SYMTAB);
4089 const ELFDynamic *syment = FindDynamicSymbol(DT_SYMENT);
4090 // DT_SYMTAB and DT_SYMENT are mandatory.
4091 if (symtab == nullptr || syment == nullptr)
4092 return std::nullopt;
4093
4094 if (std::optional<uint32_t> syms = GetNumSymbolsFromDynamicHash())
4095 num_symbols = *syms;
4096 else if (std::optional<uint32_t> syms = GetNumSymbolsFromDynamicGnuHash())
4097 num_symbols = *syms;
4098 else
4099 return std::nullopt;
4100 if (num_symbols == 0)
4101 return std::nullopt;
4102 return ReadDataFromDynamic(symtab, syment->d_val * num_symbols);
4103}
static llvm::raw_ostream & error(Stream &strm)
static llvm::raw_ostream & note(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:369
#define LLDB_LOGF(log,...)
Definition Log.h:376
static void ApplyELF64ABS32Relocation(Symtab *symtab, ELFRelocation &rel, DataExtractor &debug_data, Section *rel_section, bool is_signed)
static const elf_word LLDB_NT_NETBSD_IDENT_DESCSZ
static const char *const LLDB_NT_OWNER_NETBSDCORE
static const elf_word LLDB_NT_FREEBSD_ABI_TAG
static std::string getDynamicTagAsString(uint16_t Arch, uint64_t Type)
static uint32_t riscvVariantFromElfFlags(const elf::ELFHeader &header)
static const elf_word LLDB_NT_GNU_ABI_OS_LINUX
static uint32_t ppc64VariantFromElfFlags(const elf::ELFHeader &header)
static bool GetOsFromOSABI(unsigned char osabi_byte, llvm::Triple::OSType &ostype)
#define _MAKE_OSABI_CASE(x)
static uint32_t subTypeFromElfHeader(const elf::ELFHeader &header)
static uint32_t calc_crc32(uint32_t init, const DataExtractor &data)
static char FindArmAarch64MappingSymbol(const char *symbol_name)
static const char *const LLDB_NT_OWNER_CORE
static const elf_word LLDB_NT_NETBSD_IDENT_TAG
static const elf_word LLDB_NT_GNU_ABI_OS_SOLARIS
static std::pair< uint64_t, uint64_t > GetPltEntrySizeAndOffset(const ELFSectionHeader *rel_hdr, const ELFSectionHeader *plt_hdr)
static SectionType GetSectionTypeFromName(llvm::StringRef Name)
static const elf_word LLDB_NT_FREEBSD_ABI_SIZE
static const elf_word LLDB_NT_GNU_ABI_TAG
static char FindRISCVMappingSymbol(const char *symbol_name)
static SectionSP FindMatchingSection(const SectionList &section_list, SectionSP section)
static const char *const LLDB_NT_OWNER_GNU
static const elf_word LLDB_NT_NETBSD_PROCINFO
#define CASE_AND_STREAM(s, def, width)
static user_id_t SegmentID(size_t PHdrIndex)
static void ApplyELF32ABS32RelRelocation(Symtab *symtab, ELFRelocation &rel, DataExtractor &debug_data, Section *rel_section)
static const elf_word LLDB_NT_GNU_ABI_SIZE
static uint32_t GetTargetByteSize(SectionType Type, const ArchSpec &arch)
static const char *const LLDB_NT_OWNER_OPENBSD
static const char *const LLDB_NT_OWNER_FREEBSD
static const char *const LLDB_NT_OWNER_LINUX
static const char * OSABIAsCString(unsigned char osabi_byte)
static Permissions GetPermissions(const ELFSectionHeader &H)
static const char *const LLDB_NT_OWNER_ANDROID
#define IS_MICROMIPS(ST_OTHER)
static const elf_word LLDB_NT_NETBSD_IDENT_NAMESZ
static uint32_t loongarchVariantFromElfFlags(const elf::ELFHeader &header)
static const elf_word LLDB_NT_GNU_ABI_OS_HURD
static uint32_t mipsVariantFromElfFlags(const elf::ELFHeader &header)
static const char *const LLDB_NT_OWNER_NETBSD
static unsigned ParsePLTRelocations(Symtab *symbol_table, user_id_t start_id, unsigned rel_type, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr, const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr, const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data, DataExtractor &symtab_data, DataExtractor &strtab_data)
static void ApplyELF64ABS64Relocation(Symtab *symtab, ELFRelocation &rel, DataExtractor &debug_data, Section *rel_section)
static const elf_word LLDB_NT_GNU_BUILD_ID_TAG
#define LLDB_PLUGIN_DEFINE(PluginName)
static double elapsed(const StatsTimepoint &start, const StatsTimepoint &end)
#define LLDB_SCOPED_TIMERF(...)
Definition Timer.h:86
Generic COFF object file reader.
static size_t GetSectionHeaderInfo(SectionHeaderColl &section_headers, lldb_private::DataExtractor &object_data, const elf::ELFHeader &header, lldb_private::UUID &uuid, std::string &gnu_debuglink_file, uint32_t &gnu_debuglink_crc, lldb_private::ArchSpec &arch_spec)
Parses the elf section headers and returns the uuid, debug link name, crc, archspec.
std::vector< elf::ELFProgramHeader > ProgramHeaderColl
static void DumpELFHeader(lldb_private::Stream *s, const elf::ELFHeader &header)
unsigned ParseTrampolineSymbols(lldb_private::Symtab *symbol_table, lldb::user_id_t start_id, const ELFSectionHeaderInfo *rela_hdr, lldb::user_id_t section_id)
Scans the relocation entries and adds a set of artificial symbols to the given symbol table for each ...
lldb_private::ArchSpec m_arch_spec
The architecture detected from parsing elf file contents.
static void DumpELFSectionHeader_sh_type(lldb_private::Stream *s, elf::elf_word sh_type)
std::shared_ptr< ObjectFileELF > m_gnu_debug_data_object_file
Object file parsed from .gnu_debugdata section (.
SectionHeaderColl::iterator SectionHeaderCollIter
uint32_t m_gnu_debuglink_crc
unsigned RelocateDebugSections(const elf::ELFSectionHeader *rel_hdr, lldb::user_id_t rel_id, lldb_private::Symtab *thetab)
Relocates debug sections.
bool AnySegmentHasPhysicalAddress()
static void Initialize()
static void DumpELFProgramHeader(lldb_private::Stream *s, const elf::ELFProgramHeader &ph)
lldb_private::Address m_entry_point_address
Cached value of the entry point for this module.
size_t ReadSectionData(lldb_private::Section *section, lldb::offset_t section_offset, void *dst, size_t dst_len) override
llvm::StringRef StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const override
static void ParseARMAttributes(lldb_private::DataExtractor &data, uint64_t length, lldb_private::ArchSpec &arch_spec)
lldb_private::DataExtractor GetSegmentData(const elf::ELFProgramHeader &H)
void RelocateSection(lldb_private::Section *section) override
Perform relocations on the section if necessary.
FileAddressToAddressClassMap m_address_class_map
The address class for each symbol in the elf file.
static llvm::StringRef GetPluginDescriptionStatic()
static const uint32_t g_core_uuid_magic
static size_t GetModuleSpecifications(const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp, lldb::offset_t data_offset, lldb::offset_t file_offset, lldb::offset_t length, lldb_private::ModuleSpecList &specs)
bool IsExecutable() const override
Tells whether this object file is capable of being the main executable for a process.
void DumpDependentModules(lldb_private::Stream *s)
ELF dependent module dump routine.
static void DumpELFHeader_e_type(lldb_private::Stream *s, elf::elf_half e_type)
static size_t GetProgramHeaderInfo(ProgramHeaderColl &program_headers, lldb_private::DataExtractor &object_data, const elf::ELFHeader &header)
static bool MagicBytesMatch(lldb::DataBufferSP &data_sp, lldb::addr_t offset, lldb::addr_t length)
std::optional< lldb_private::DataExtractor > GetDynsymDataFromDynamic(uint32_t &num_symbols)
Get the bytes that represent the dynamic symbol table from the .dynamic section from process memory.
DynamicSymbolColl m_dynamic_symbols
Collection of symbols from the dynamic table.
static void DumpELFSectionHeader(lldb_private::Stream *s, const ELFSectionHeaderInfo &sh)
std::vector< ELFSectionHeaderInfo > SectionHeaderColl
static void DumpELFHeader_e_ident_EI_DATA(lldb_private::Stream *s, unsigned char ei_data)
lldb_private::ArchSpec GetArchitecture() override
Get the ArchSpec for this object file.
std::optional< lldb_private::FileSpec > GetDebugLink()
Return the contents of the .gnu_debuglink section, if the object file contains it.
lldb_private::AddressClass GetAddressClass(lldb::addr_t file_addr) override
Get the address type given a file address in an object file.
static void DumpELFSectionHeader_sh_flags(lldb_private::Stream *s, elf::elf_xword sh_flags)
lldb_private::UUID GetUUID() override
Gets the UUID for this object file.
std::optional< uint32_t > GetNumSymbolsFromDynamicGnuHash()
Get the number of symbols from the DT_GNU_HASH dynamic entry.
std::optional< lldb_private::DataExtractor > ReadDataFromDynamic(const elf::ELFDynamic *dyn, uint64_t length, uint64_t offset=0)
Read the bytes pointed to by the dyn dynamic entry.
ObjectFileELF(const lldb::ModuleSP &module_sp, lldb::DataBufferSP data_sp, lldb::offset_t data_offset, const lldb_private::FileSpec *file, lldb::offset_t offset, lldb::offset_t length)
static void DumpELFProgramHeader_p_type(lldb_private::Stream *s, elf::elf_word p_type)
static lldb_private::Status RefineModuleDetailsFromNote(lldb_private::DataExtractor &data, lldb_private::ArchSpec &arch_spec, lldb_private::UUID &uuid)
size_t SectionIndex(const SectionHeaderCollIter &I)
Returns the index of the given section header.
static void DumpELFProgramHeader_p_flags(lldb_private::Stream *s, elf::elf_word p_flags)
static llvm::StringRef GetPluginNameStatic()
size_t ParseDependentModules()
Scans the dynamic section and locates all dependent modules (shared libraries) populating m_filespec_...
void DumpELFSectionHeaders(lldb_private::Stream *s)
std::shared_ptr< ObjectFileELF > GetGnuDebugDataObjectFile()
Takes the .gnu_debugdata and returns the decompressed object file that is stored within that section.
static lldb::WritableDataBufferSP MapFileDataWritable(const lldb_private::FileSpec &file, uint64_t Size, uint64_t Offset)
void Dump(lldb_private::Stream *s) override
Dump a description of this object to a Stream.
static uint32_t CalculateELFNotesSegmentsCRC32(const ProgramHeaderColl &program_headers, lldb_private::DataExtractor &data)
lldb_private::UUID m_uuid
ELF build ID.
void DumpELFProgramHeaders(lldb_private::Stream *s)
std::pair< unsigned, FileAddressToAddressClassMap > ParseSymbolTable(lldb_private::Symtab *symbol_table, lldb::user_id_t start_id, lldb_private::Section *symtab)
Populates the symbol table with all non-dynamic linker symbols.
size_t ParseDynamicSymbols()
Parses the dynamic symbol table and populates m_dynamic_symbols.
static lldb_private::ObjectFile * CreateInstance(const lldb::ModuleSP &module_sp, lldb::DataBufferSP data_sp, lldb::offset_t data_offset, const lldb_private::FileSpec *file, lldb::offset_t file_offset, lldb::offset_t length)
std::optional< lldb_private::DataExtractor > GetDynamicData()
Get the bytes that represent the .dynamic section.
ObjectFile::Type CalculateType() override
The object file should be able to calculate its type by looking at its file header and possibly the s...
lldb::SectionType GetSectionType(const ELFSectionHeaderInfo &H) const
bool SetLoadAddress(lldb_private::Target &target, lldb::addr_t value, bool value_is_offset) override
Sets the load address for an entire module, assuming a rigid slide of sections, if possible in the im...
std::unique_ptr< lldb_private::FileSpecList > m_filespec_up
List of file specifications corresponding to the modules (shared libraries) on which this object file...
std::optional< uint32_t > GetNumSymbolsFromDynamicHash()
Get the number of symbols from the DT_HASH dynamic entry.
bool ParseProgramHeaders()
Parses all section headers present in this object file and populates m_program_headers.
std::vector< LoadableData > GetLoadableData(lldb_private::Target &target) override
Loads this objfile to memory.
const ELFSectionHeaderInfo * GetSectionHeaderByIndex(lldb::user_id_t id)
Returns the section header with the given id or NULL.
void CreateSections(lldb_private::SectionList &unified_section_list) override
lldb::user_id_t GetSectionIndexByName(const char *name)
Utility method for looking up a section given its name.
uint32_t GetAddressByteSize() const override
Gets the address size in bytes for the current object file.
SectionHeaderColl::const_iterator SectionHeaderCollConstIter
ProgramHeaderColl m_program_headers
Collection of program headers.
void DumpELFDynamic(lldb_private::Stream *s)
ELF dump the .dynamic section.
unsigned ApplyRelocations(lldb_private::Symtab *symtab, const elf::ELFHeader *hdr, const elf::ELFSectionHeader *rel_hdr, const elf::ELFSectionHeader *symtab_hdr, const elf::ELFSectionHeader *debug_hdr, lldb_private::DataExtractor &rel_data, lldb_private::DataExtractor &symtab_data, lldb_private::DataExtractor &debug_data, lldb_private::Section *rel_section)
lldb::ByteOrder GetByteOrder() const override
Gets whether endian swapping should occur when extracting data from this object file.
bool ParseHeader() override
Attempts to parse the object header.
static void Terminate()
elf::ELFHeader m_header
ELF file header.
std::string m_gnu_debuglink_file
ELF .gnu_debuglink file and crc data if available.
void ParseUnwindSymbols(lldb_private::Symtab *symbol_table, lldb_private::DWARFCallFrameInfo *eh_frame)
std::pair< unsigned, FileAddressToAddressClassMap > ParseSymbols(lldb_private::Symtab *symbol_table, lldb::user_id_t start_id, lldb_private::SectionList *section_list, const size_t num_symbols, const lldb_private::DataExtractor &symtab_data, const lldb_private::DataExtractor &strtab_data)
Helper routine for ParseSymbolTable().
SectionHeaderColl m_section_headers
Collection of section headers.
lldb_private::Address GetEntryPointAddress() override
Returns the address of the Entry Point in this object file - if the object file doesn't have an entry...
static char ID
ObjectFile::Strata CalculateStrata() override
The object file should be able to calculate the strata of the object file.
void ParseSymtab(lldb_private::Symtab &symtab) override
Parse the symbol table into the provides symbol table object.
unsigned PLTRelocationType()
static lldb_private::ObjectFile * CreateMemoryInstance(const lldb::ModuleSP &module_sp, lldb::WritableDataBufferSP data_sp, const lldb::ProcessSP &process_sp, lldb::addr_t header_addr)
lldb::addr_t m_dynamic_base_addr
The file address of the .dynamic section.
uint32_t GetDependentModules(lldb_private::FileSpecList &files) override
Extract the dependent modules from an object file.
size_t ParseSectionHeaders()
Parses all section headers present in this object file and populates m_section_headers.
lldb_private::Address GetBaseAddress() override
Returns base address of this object file.
bool IsStripped() override
Detect if this object file has been stripped of local symbols.
const elf::ELFDynamic * FindDynamicSymbol(unsigned tag)
std::map< lldb::addr_t, lldb_private::AddressClass > FileAddressToAddressClassMap
An ordered map of file address to address class.
llvm::ArrayRef< elf::ELFProgramHeader > ProgramHeaders()
std::optional< lldb_private::DataExtractor > GetDynstrData()
Get the bytes that represent the dynamic string table data.
lldb_private::Address GetImageInfoAddress(lldb_private::Target *target) override
Similar to Process::GetImageInfoAddress().
A section + offset based address range class.
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:301
bool ResolveAddressUsingFileSections(lldb::addr_t addr, const SectionList *sections)
Resolve a file virtual address using a section list.
Definition Address.cpp:249
lldb::SectionSP GetSection() const
Get const accessor for the section.
Definition Address.h:432
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:281
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
bool SetOffset(lldb::addr_t offset)
Set accessor for the offset.
Definition Address.h:441
An architecture specification class.
Definition ArchSpec.h:31
uint32_t GetCodeByteSize() const
Architecture code byte width accessor.
Definition ArchSpec.cpp:675
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:366
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:468
void SetFlags(uint32_t flags)
Definition ArchSpec.h:541
bool SetArchitecture(ArchitectureType arch_type, uint32_t cpu, uint32_t sub, uint32_t os=0)
Change the architecture object type, CPU type and OS type.
Definition ArchSpec.cpp:845
@ eLoongArch_abi_single_float
soft float
Definition ArchSpec.h:112
@ eLoongArch_abi_double_float
single precision floating point, +f
Definition ArchSpec.h:114
bool IsMIPS() const
if MIPS architecture return true.
Definition ArchSpec.cpp:555
uint32_t GetDataByteSize() const
Architecture data byte width accessor.
Definition ArchSpec.cpp:673
uint32_t GetFlags() const
Definition ArchSpec.h:539
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:677
@ eRISCV_float_abi_double
single precision floating point, +f
Definition ArchSpec.h:97
@ eRISCV_float_abi_quad
double precision floating point, +d
Definition ArchSpec.h:98
@ eRISCV_float_abi_single
soft float
Definition ArchSpec.h:96
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:548
A uniqued constant string class.
Definition ConstString.h:40
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const char * GetCString() const
Get the string value as a C string.
void ForEachFDEEntries(const std::function< bool(lldb::addr_t, uint32_t, dw_offset_t)> &callback)
A subclass of DataBuffer that stores a data buffer on the heap.
An data extractor class.
uint64_t GetULEB128(lldb::offset_t *offset_ptr) const
Extract a unsigned LEB128 value from *offset_ptr.
const char * GetCStr(lldb::offset_t *offset_ptr) const
Extract a C string from *offset_ptr.
const uint8_t * PeekData(lldb::offset_t offset, lldb::offset_t length) const
Peek at a bytes at offset.
const void * GetData(lldb::offset_t *offset_ptr, lldb::offset_t length) const
Extract length bytes from *offset_ptr.
void Clear()
Clears the object state.
lldb::offset_t CopyData(lldb::offset_t offset, lldb::offset_t length, void *dst) const
Copy length bytes from *offset, without swapping bytes.
lldb::DataBufferSP & GetSharedDataBuffer()
uint32_t GetU32(lldb::offset_t *offset_ptr) const
Extract a uint32_t value from *offset_ptr.
uint64_t GetByteSize() const
Get the number of bytes contained in this object.
uint64_t GetAddress(lldb::offset_t *offset_ptr) const
Extract an address from *offset_ptr.
const uint8_t * GetDataStart() const
Get the data start pointer.
lldb::offset_t SetData(const void *bytes, lldb::offset_t length, lldb::ByteOrder byte_order)
Set data with a buffer that is caller owned.
uint32_t GetAddressByteSize() const
Get the current address size.
lldb::ByteOrder GetByteOrder() const
Get the current byte order value.
uint8_t GetU8(lldb::offset_t *offset_ptr) const
Extract a uint8_t value from *offset_ptr.
const char * PeekCStr(lldb::offset_t offset) const
Peek at a C string at offset.
size_t ExtractBytes(lldb::offset_t offset, lldb::offset_t length, lldb::ByteOrder dst_byte_order, void *dst) const
Extract an arbitrary number of bytes in the specified byte order.
A class that measures elapsed time in an exception safe way.
Definition Statistics.h:76
A file collection class.
bool AppendIfUnique(const FileSpec &file)
Append a FileSpec object if unique.
A file utility class.
Definition FileSpec.h:57
FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const
Definition FileSpec.cpp:425
const ConstString & GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:251
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
void Resolve(llvm::SmallVectorImpl< char > &path)
Resolve path to make it canonical.
std::shared_ptr< WritableDataBuffer > CreateWritableDataBuffer(const llvm::Twine &path, uint64_t size=0, uint64_t offset=0)
static FileSystem & Instance()
ValueType Get() const
Get accessor for all flags.
Definition Flags.h:40
bool Test(ValueType bit) const
Test a single flag bit.
Definition Flags.h:96
A class that handles mangled names.
Definition Mangled.h:34
void SetDemangledName(ConstString name)
Definition Mangled.h:138
ConstString GetMangledName() const
Mangled name get accessor.
Definition Mangled.h:152
ConstString GetDemangledName() const
Demangled name get accessor.
Definition Mangled.cpp:284
void SetMangledName(ConstString name)
Definition Mangled.h:143
ConstString GetName(NamePreference preference=ePreferDemangled) const
Best name get accessor.
Definition Mangled.cpp:369
lldb::ModuleSP GetModule() const
Get const accessor for the module pointer.
void Append(const ModuleSpec &spec)
Definition ModuleSpec.h:326
void SetObjectSize(uint64_t object_size)
Definition ModuleSpec.h:117
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:91
void SetObjectOffset(uint64_t object_offset)
Definition ModuleSpec.h:111
DataExtractor m_data
The data for this object file so things can be parsed lazily.
Definition ObjectFile.h:790
std::unique_ptr< lldb_private::SectionList > m_sections_up
Definition ObjectFile.h:794
static lldb::DataBufferSP MapFileData(const FileSpec &file, uint64_t Size, uint64_t Offset)
ObjectFile(const lldb::ModuleSP &module_sp, const FileSpec *file_spec_ptr, lldb::offset_t file_offset, lldb::offset_t length, lldb::DataBufferSP data_sp, lldb::offset_t data_offset)
Construct with a parent module, offset, and header data.
const lldb::addr_t m_memory_addr
Set if the object file only exists in memory.
Definition ObjectFile.h:793
static lldb::SectionType GetDWARFSectionTypeFromName(llvm::StringRef name)
Parses the section type from a section name for DWARF sections.
virtual void ParseSymtab(Symtab &symtab)=0
Parse the symbol table into the provides symbol table object.
virtual AddressClass GetAddressClass(lldb::addr_t file_addr)
Get the address type given a file address in an object file.
Symtab * GetSymtab(bool can_create=true)
Gets the symbol table for the currently selected architecture (and object for archives).
static lldb::WritableDataBufferSP ReadMemory(const lldb::ProcessSP &process_sp, lldb::addr_t addr, size_t byte_size)
size_t GetData(lldb::offset_t offset, size_t length, DataExtractor &data) const
@ eTypeExecutable
A normal executable.
Definition ObjectFile.h:54
@ eTypeDebugInfo
An object file that contains only debug information.
Definition ObjectFile.h:56
@ eTypeObjectFile
An intermediate object file.
Definition ObjectFile.h:60
@ eTypeCoreFile
A core file that has a checkpoint of a program's execution state.
Definition ObjectFile.h:52
@ eTypeSharedLibrary
A shared library that can be used during execution.
Definition ObjectFile.h:62
virtual FileSpec & GetFileSpec()
Get accessor to the object file specification.
Definition ObjectFile.h:281
virtual SectionList * GetSectionList(bool update_module_section_list=true)
Gets the section list for the currently selected architecture (and object for archives).
bool IsInMemory() const
Returns true if the object file exists only in memory.
Definition ObjectFile.h:709
lldb::ProcessWP m_process_wp
Definition ObjectFile.h:791
virtual size_t ReadSectionData(Section *section, lldb::offset_t section_offset, void *dst, size_t dst_len)
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
A Progress indicator helper class.
Definition Progress.h:60
lldb::SectionSP FindSectionByName(ConstString section_dstr) const
Definition Section.cpp:564
static SectionList Merge(SectionList &lhs, SectionList &rhs, MergeCallback filter)
Definition Section.cpp:692
lldb::SectionSP FindSectionByID(lldb::user_id_t sect_id) const
Definition Section.cpp:586
lldb::SectionSP FindSectionContainingFileAddress(lldb::addr_t addr, uint32_t depth=UINT32_MAX) const
Definition Section.cpp:623
size_t GetSize() const
Definition Section.h:77
size_t AddSection(const lldb::SectionSP &section_sp)
Definition Section.cpp:488
bool ReplaceSection(lldb::user_id_t sect_id, const lldb::SectionSP &section_sp, uint32_t depth=UINT32_MAX)
Definition Section.cpp:528
lldb::SectionSP FindSectionByType(lldb::SectionType sect_type, bool check_children, size_t start_idx=0) const
Definition Section.cpp:604
void Dump(llvm::raw_ostream &s, unsigned indent, Target *target, bool show_header, uint32_t depth) const
Definition Section.cpp:650
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition Section.cpp:557
ConstString GetName() const
Definition Section.h:213
void SetIsRelocated(bool b)
Definition Section.h:280
lldb::offset_t GetFileOffset() const
Definition Section.h:183
ObjectFile * GetObjectFile()
Definition Section.h:233
lldb::offset_t GetFileSize() const
Definition Section.h:189
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Definition Stream.h:364
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:406
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:157
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:65
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:155
unsigned GetIndentLevel() const
Get the current indentation level.
Definition Stream.cpp:187
uint32_t GetID() const
Definition Symbol.h:137
void SetSizeIsSynthesized(bool b)
Definition Symbol.h:191
bool GetByteSizeIsValid() const
Definition Symbol.h:209
Address & GetAddressRef()
Definition Symbol.h:73
void SetIsWeak(bool b)
Definition Symbol.h:207
ConstString GetName() const
Definition Symbol.cpp:511
void SetByteSize(lldb::addr_t size)
Definition Symbol.h:213
Symbol * FindSymbolByID(lldb::user_id_t uid) const
Definition Symtab.cpp:219
Symbol * SymbolAtIndex(size_t idx)
Definition Symtab.cpp:228
Symbol * FindSymbolAtFileAddress(lldb::addr_t file_addr)
Definition Symtab.cpp:1022
Symbol * FindSymbolContainingFileAddress(lldb::addr_t file_addr)
Definition Symtab.cpp:1037
uint32_t AddSymbol(const Symbol &symbol)
Definition Symtab.cpp:64
void Dump(Stream *s, Target *target, SortOrder sort_type, Mangled::NamePreference name_preference=Mangled::ePreferDemangled)
Definition Symtab.cpp:87
ObjectFile * GetObjectFile() const
Definition Symtab.h:137
size_t GetNumSymbols() const
Definition Symtab.cpp:77
bool ReadPointerFromMemory(const Address &addr, Status &error, Address &pointer_addr, bool force_live_memory=false)
Definition Target.cpp:2316
uint64_t ReadUnsignedIntegerFromMemory(const Address &addr, size_t integer_byte_size, uint64_t fail_value, Status &error, bool force_live_memory=false)
Definition Target.cpp:2305
bool SetSectionLoadAddress(const lldb::SectionSP &section, lldb::addr_t load_addr, bool warn_multiple=false)
Definition Target.cpp:3329
Represents UUID's of various sizes.
Definition UUID.h:27
bool IsValid() const
Definition UUID.h:69
lldb::addr_t GetByteSize() const
Definition VMRange.h:59
void SetByteSize(lldb::addr_t byte_size)
Definition VMRange.h:61
uint8_t * GetBytes()
Get a pointer to the data.
Definition DataBuffer.h:108
uint64_t dw_offset_t
Definition dwarf.h:24
#define INT32_MAX
#define UINT64_MAX
#define LLDB_INVALID_CPUTYPE
#define UNUSED_IF_ASSERT_DISABLED(x)
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
uint64_t elf_addr
Definition ELFHeader.h:41
uint64_t elf_off
Definition ELFHeader.h:42
uint32_t elf_word
Definition ELFHeader.h:44
uint64_t elf_xword
Definition ELFHeader.h:47
uint16_t elf_half
Definition ELFHeader.h:43
int64_t elf_sxword
Definition ELFHeader.h:48
bool isAvailable()
Definition LZMA.cpp:22
llvm::Error uncompress(llvm::ArrayRef< uint8_t > InputBuffer, llvm::SmallVectorImpl< uint8_t > &Uncompressed)
Definition LZMA.cpp:28
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:332
uint64_t offset_t
Definition lldb-types.h:85
std::shared_ptr< lldb_private::Process > ProcessSP
SymbolType
Symbol types.
@ eSymbolTypeUndefined
@ eSymbolTypeTrampoline
@ eSymbolTypeResolver
@ eSymbolTypeSourceFile
@ eSymbolTypeAbsolute
ByteOrder
Byte ordering definitions.
uint64_t user_id_t
Definition lldb-types.h:82
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
std::shared_ptr< lldb_private::Section > SectionSP
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
@ eSectionTypeELFDynamicSymbols
Elf SHT_DYNSYM section.
@ eSectionTypeZeroFill
@ eSectionTypeARMextab
@ eSectionTypeContainer
The section contains child sections.
@ eSectionTypeELFDynamicLinkInfo
Elf SHT_DYNAMIC section.
@ eSectionTypeAbsoluteAddress
Dummy section for symbols with absolute address.
@ eSectionTypeELFRelocationEntries
Elf SHT_REL or SHT_REL section.
@ eSectionTypeLLDBFormatters
@ eSectionTypeEHFrame
@ eSectionTypeLLDBTypeSummaries
@ eSectionTypeGoSymtab
@ eSectionTypeARMexidx
@ eSectionTypeSwiftModules
@ eSectionTypeDWARFGNUDebugAltLink
@ eSectionTypeELFSymbolTable
Elf SHT_SYMTAB section.
std::shared_ptr< lldb_private::Module > ModuleSP
bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)
Parse an ELFNote entry from the given DataExtractor starting at position offset.
std::string n_name
elf::elf_word n_namesz
lldb_private::ConstString section_name
Represents an entry in an ELF dynamic table.
Definition ELFHeader.h:276
elf_addr d_ptr
Pointer value of the table entry.
Definition ELFHeader.h:280
elf_xword d_val
Integer value of the table entry.
Definition ELFHeader.h:279
bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)
Parse an ELFDynamic entry from the given DataExtractor starting at position offset.
elf_sxword d_tag
Type of dynamic table entry.
Definition ELFHeader.h:277
Generic representation of an ELF file header.
Definition ELFHeader.h:56
elf_word e_shnum
Number of section header entries.
Definition ELFHeader.h:76
bool HasHeaderExtension() const
Check if there should be header extension in section header #0.
Definition ELFHeader.cpp:81
elf_off e_phoff
File offset of program header table.
Definition ELFHeader.h:59
bool Is64Bit() const
Returns true if this is a 64 bit ELF file header.
Definition ELFHeader.h:93
static unsigned AddressSizeInBytes(const uint8_t *magic)
Examines at most EI_NIDENT bytes starting from the given address and determines the address size of t...
elf_half e_phentsize
Size of a program header table entry.
Definition ELFHeader.h:66
bool Is32Bit() const
Returns true if this is a 32 bit ELF file header.
Definition ELFHeader.h:85
static bool MagicBytesMatch(const uint8_t *magic)
Examines at most EI_NIDENT bytes starting from the given pointer and determines if the magic ELF iden...
elf_off e_shoff
File offset of section header table.
Definition ELFHeader.h:60
elf_half e_ehsize
Byte size of the ELF header.
Definition ELFHeader.h:65
bool Parse(lldb_private::DataExtractor &data, lldb::offset_t *offset)
Parse an ELFHeader entry starting at position offset and update the data extractor with the address s...
unsigned GetRelocationJumpSlotType() const
The jump slot relocation type of this ELF.
elf_word e_phnum
Number of program header entries.
Definition ELFHeader.h:75
elf_word e_version
Version of object file (always 1).
Definition ELFHeader.h:62
unsigned char e_ident[llvm::ELF::EI_NIDENT]
ELF file identification.
Definition ELFHeader.h:57
elf_half e_machine
Target architecture.
Definition ELFHeader.h:64
elf_addr e_entry
Virtual address program entry point.
Definition ELFHeader.h:58
elf_word e_shstrndx
String table section index.
Definition ELFHeader.h:77
elf_half e_shentsize
Size of a section header table entry.
Definition ELFHeader.h:68
elf_half e_type
Object file type.
Definition ELFHeader.h:63
elf_word e_flags
Processor specific flags.
Definition ELFHeader.h:61
Generic representation of an ELF program header.
Definition ELFHeader.h:192
elf_xword p_align
Segment alignment constraint.
Definition ELFHeader.h:200
elf_addr p_paddr
Physical address (for non-VM systems).
Definition ELFHeader.h:197
elf_word p_flags
Segment attributes.
Definition ELFHeader.h:194
elf_xword p_filesz
Byte size of the segment in file.
Definition ELFHeader.h:198
elf_off p_offset
Start of segment from beginning of file.
Definition ELFHeader.h:195
elf_addr p_vaddr
Virtual address of segment in memory.
Definition ELFHeader.h:196
elf_xword p_memsz
Byte size of the segment in memory.
Definition ELFHeader.h:199
elf_word p_type
Type of program segment.
Definition ELFHeader.h:193
static unsigned RelocSymbol64(const ELFRel &rel)
Returns the symbol index when the given entry represents a 64-bit relocation.
Definition ELFHeader.h:341
static unsigned RelocType64(const ELFRel &rel)
Returns the type when the given entry represents a 64-bit relocation.
Definition ELFHeader.h:331
static unsigned RelocType32(const ELFRel &rel)
Returns the type when the given entry represents a 32-bit relocation.
Definition ELFHeader.h:328
static unsigned RelocSymbol32(const ELFRel &rel)
Returns the symbol index when the given entry represents a 32-bit relocation.
Definition ELFHeader.h:337
static unsigned RelocSymbol64(const ELFRela &rela)
Returns the symbol index when the given entry represents a 64-bit relocation.
Definition ELFHeader.h:387
static unsigned RelocType64(const ELFRela &rela)
Returns the type when the given entry represents a 64-bit relocation.
Definition ELFHeader.h:375
static unsigned RelocType32(const ELFRela &rela)
Returns the type when the given entry represents a 32-bit relocation.
Definition ELFHeader.h:370
static unsigned RelocSymbol32(const ELFRela &rela)
Returns the symbol index when the given entry represents a 32-bit relocation.
Definition ELFHeader.h:381
Generic representation of an ELF section header.
Definition ELFHeader.h:159
elf_word sh_link
Index of associated section.
Definition ELFHeader.h:166
elf_word sh_info
Extra section info (overloaded).
Definition ELFHeader.h:167
elf_xword sh_size
Number of bytes occupied in the file.
Definition ELFHeader.h:165
elf_xword sh_flags
Section attributes.
Definition ELFHeader.h:162
elf_word sh_name
Section name string index.
Definition ELFHeader.h:160
elf_off sh_offset
Start of section from beginning of file.
Definition ELFHeader.h:164
elf_word sh_type
Section type.
Definition ELFHeader.h:161
elf_xword sh_addralign
Power of two alignment constraint.
Definition ELFHeader.h:168
elf_xword sh_entsize
Byte size of each section entry.
Definition ELFHeader.h:169
elf_addr sh_addr
Virtual address of the section in memory.
Definition ELFHeader.h:163
Represents a symbol within an ELF symbol table.
Definition ELFHeader.h:224
unsigned char getType() const
Returns the type attribute of the st_info member.
Definition ELFHeader.h:238
elf_half st_shndx
Section to which this symbol applies.
Definition ELFHeader.h:230
unsigned char st_info
Symbol type and binding attributes.
Definition ELFHeader.h:228
unsigned char getBinding() const
Returns the binding attribute of the st_info member.
Definition ELFHeader.h:235
bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)
Parse an ELFSymbol entry from the given DataExtractor starting at position offset.
elf_addr st_value
Absolute or relocatable address.
Definition ELFHeader.h:225
elf_word st_name
Symbol name string index.
Definition ELFHeader.h:227
elf_xword st_size
Size of the symbol or zero.
Definition ELFHeader.h:226
unsigned char st_other
Reserved for future use.
Definition ELFHeader.h:229
llvm::ArrayRef< uint8_t > Contents
Definition ObjectFile.h:97
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47