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