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