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