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"
25#include "lldb/Target/Process.h"
27#include "lldb/Target/Target.h"
33#include "lldb/Utility/Log.h"
35#include "lldb/Utility/Status.h"
36#include "lldb/Utility/Stream.h"
38#include "lldb/Utility/Timer.h"
39#include "llvm/ADT/IntervalMap.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/BinaryFormat/ELF.h"
43#include "llvm/Object/Decompressor.h"
44#include "llvm/Support/ARMBuildAttributes.h"
45#include "llvm/Support/CRC.h"
46#include "llvm/Support/Compression.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 null-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 null 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 null 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 constexpr llvm::StringLiteral g_sect_name_gnu_debuglink(
1752 ".gnu_debuglink");
1753 const ELFSectionHeaderInfo &sheader = *I;
1754 const uint64_t section_size =
1755 sheader.sh_type == SHT_NOBITS ? 0 : sheader.sh_size;
1756 llvm::StringRef name = shstr_data.PeekCStr(I->sh_name).value_or("");
1757 I->section_name = name.str();
1758
1759 if (arch_spec.IsMIPS()) {
1760 uint32_t arch_flags = arch_spec.GetFlags();
1761 DataExtractor data;
1762 if (sheader.sh_type == SHT_MIPS_ABIFLAGS) {
1763
1764 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1765 section_size) == section_size)) {
1766 // MIPS ASE Mask is at offset 12 in MIPS.abiflags section
1767 lldb::offset_t offset = 12; // MIPS ABI Flags Version: 0
1768 arch_flags |= data.GetU32(&offset);
1769
1770 // The floating point ABI is at offset 7
1771 offset = 7;
1772 switch (data.GetU8(&offset)) {
1773 case llvm::Mips::Val_GNU_MIPS_ABI_FP_ANY:
1775 break;
1776 case llvm::Mips::Val_GNU_MIPS_ABI_FP_DOUBLE:
1778 break;
1779 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SINGLE:
1781 break;
1782 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SOFT:
1784 break;
1785 case llvm::Mips::Val_GNU_MIPS_ABI_FP_OLD_64:
1787 break;
1788 case llvm::Mips::Val_GNU_MIPS_ABI_FP_XX:
1790 break;
1791 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64:
1793 break;
1794 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64A:
1796 break;
1797 }
1798 }
1799 }
1800 // Settings appropriate ArchSpec ABI Flags
1801 switch (header.e_flags & llvm::ELF::EF_MIPS_ABI) {
1802 case llvm::ELF::EF_MIPS_ABI_O32:
1804 break;
1805 case EF_MIPS_ABI_O64:
1807 break;
1808 case EF_MIPS_ABI_EABI32:
1810 break;
1811 case EF_MIPS_ABI_EABI64:
1813 break;
1814 default:
1815 // ABI Mask doesn't cover N32 and N64 ABI.
1816 if (header.e_ident[EI_CLASS] == llvm::ELF::ELFCLASS64)
1818 else if (header.e_flags & llvm::ELF::EF_MIPS_ABI2)
1820 break;
1821 }
1822 arch_spec.SetFlags(arch_flags);
1823 }
1824
1825 if (arch_spec.GetMachine() == llvm::Triple::arm ||
1826 arch_spec.GetMachine() == llvm::Triple::thumb) {
1827 DataExtractor data;
1828
1829 if (sheader.sh_type == SHT_ARM_ATTRIBUTES && section_size != 0 &&
1830 data.SetData(object_data, sheader.sh_offset, section_size) == section_size)
1831 ParseARMAttributes(data, section_size, arch_spec);
1832 }
1833
1834 if (arch_spec.GetTriple().isRISCV()) {
1835 DataExtractor data;
1836 if (sheader.sh_type == llvm::ELF::SHT_RISCV_ATTRIBUTES &&
1837 section_size != 0 &&
1838 data.SetData(object_data, sheader.sh_offset, section_size) ==
1839 section_size)
1840 ParseRISCVAttributes(data, section_size, arch_spec);
1841 }
1842
1843 if (name == g_sect_name_gnu_debuglink) {
1844 DataExtractor data;
1845 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1846 section_size) == section_size)) {
1847 lldb::offset_t gnu_debuglink_offset = 0;
1848 if (const char *file = data.GetCStr(&gnu_debuglink_offset)) {
1849 gnu_debuglink_file = file;
1850 gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
1851 data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
1852 }
1853 }
1854 }
1855
1856 // Process ELF note section entries.
1857 bool is_note_header = (sheader.sh_type == SHT_NOTE);
1858
1859 // The section header ".note.android.ident" is stored as a
1860 // PROGBITS type header but it is actually a note header.
1861 static constexpr llvm::StringLiteral g_sect_name_android_ident(
1862 ".note.android.ident");
1863 if (!is_note_header && name == g_sect_name_android_ident)
1864 is_note_header = true;
1865
1866 if (is_note_header) {
1867 // Allow notes to refine module info.
1868 DataExtractor data;
1869 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1870 section_size) == section_size)) {
1871 Status error = RefineModuleDetailsFromNote(data, arch_spec, uuid);
1872 if (error.Fail()) {
1873 LLDB_LOGF(log, "ObjectFileELF::%s ELF note processing failed: %s",
1874 __FUNCTION__, error.AsCString());
1875 }
1876 }
1877 }
1878 }
1879
1880 // Make any unknown triple components to be unspecified unknowns.
1881 if (arch_spec.GetTriple().getVendor() == llvm::Triple::UnknownVendor)
1882 arch_spec.GetTriple().setVendorName(llvm::StringRef());
1883 if (arch_spec.GetTriple().getOS() == llvm::Triple::UnknownOS)
1884 arch_spec.GetTriple().setOSName(llvm::StringRef());
1885
1886 return section_headers.size();
1887 }
1888 }
1889
1890 section_headers.clear();
1891 return 0;
1892}
1893
1894llvm::StringRef
1895ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const {
1896 size_t pos = symbol_name.find('@');
1897 return symbol_name.substr(0, pos);
1898}
1899
1900// ParseSectionHeaders
1906
1909 if (!ParseSectionHeaders())
1910 return nullptr;
1911
1912 if (id < m_section_headers.size())
1913 return &m_section_headers[id];
1914
1915 return nullptr;
1916}
1917
1919 if (name.empty() || !ParseSectionHeaders())
1920 return 0;
1921 for (size_t i = 1; i < m_section_headers.size(); ++i)
1922 if (m_section_headers[i].section_name == name)
1923 return i;
1924 return 0;
1925}
1926
1927static SectionType GetSectionTypeFromName(llvm::StringRef Name) {
1928 if (Name.consume_front(".debug_"))
1930
1931 return llvm::StringSwitch<SectionType>(Name)
1932 .Case(".ARM.exidx", eSectionTypeARMexidx)
1933 .Case(".ARM.extab", eSectionTypeARMextab)
1934 .Case(".ctf", eSectionTypeDebug)
1935 .Cases({".data", ".tdata"}, eSectionTypeData)
1936 .Case(".eh_frame", eSectionTypeEHFrame)
1937 .Case(".gnu_debugaltlink", eSectionTypeDWARFGNUDebugAltLink)
1938 .Case(".gosymtab", eSectionTypeGoSymtab)
1939 .Case(".text", eSectionTypeCode)
1940 .Case(".lldbsummaries", lldb::eSectionTypeLLDBTypeSummaries)
1941 .Case(".lldbformatters", lldb::eSectionTypeLLDBFormatters)
1942 .Case(".swift_ast", eSectionTypeSwiftModules)
1943 .Default(eSectionTypeOther);
1944}
1945
1947 switch (H.sh_type) {
1948 case SHT_PROGBITS:
1949 if (H.sh_flags & SHF_EXECINSTR)
1950 return eSectionTypeCode;
1951 break;
1952 case SHT_NOBITS:
1953 if (H.sh_flags & SHF_ALLOC)
1954 return eSectionTypeZeroFill;
1955 break;
1956 case SHT_SYMTAB:
1958 case SHT_DYNSYM:
1960 case SHT_RELA:
1961 case SHT_REL:
1963 case SHT_DYNAMIC:
1965 }
1967}
1968
1969static Permissions GetPermissions(const ELFSectionHeader &H) {
1970 Permissions Perm = Permissions(0);
1971 if (H.sh_flags & SHF_ALLOC)
1972 Perm |= ePermissionsReadable;
1973 if (H.sh_flags & SHF_WRITE)
1974 Perm |= ePermissionsWritable;
1975 if (H.sh_flags & SHF_EXECINSTR)
1976 Perm |= ePermissionsExecutable;
1977 return Perm;
1978}
1979
1980static Permissions GetPermissions(const ELFProgramHeader &H) {
1981 Permissions Perm = Permissions(0);
1982 if (H.p_flags & PF_R)
1983 Perm |= ePermissionsReadable;
1984 if (H.p_flags & PF_W)
1985 Perm |= ePermissionsWritable;
1986 if (H.p_flags & PF_X)
1987 Perm |= ePermissionsExecutable;
1988 return Perm;
1989}
1990
1991namespace {
1992
1994
1995struct SectionAddressInfo {
1996 SectionSP Segment;
1997 VMRange Range;
1998};
1999
2000// (Unlinked) ELF object files usually have 0 for every section address, meaning
2001// we need to compute synthetic addresses in order for "file addresses" from
2002// different sections to not overlap. This class handles that logic.
2003class VMAddressProvider {
2004 using VMMap = llvm::IntervalMap<addr_t, SectionSP, 4,
2005 llvm::IntervalMapHalfOpenInfo<addr_t>>;
2006
2007 ObjectFile::Type ObjectType;
2008 addr_t NextVMAddress = 0;
2009 VMMap::Allocator Alloc;
2010 VMMap Segments{Alloc};
2011 VMMap Sections{Alloc};
2012 lldb_private::Log *Log = GetLog(LLDBLog::Modules);
2013 size_t SegmentCount = 0;
2014 std::string SegmentName;
2015
2016 VMRange GetVMRange(const ELFSectionHeader &H) {
2017 addr_t Address = H.sh_addr;
2018 addr_t Size = H.sh_flags & SHF_ALLOC ? H.sh_size : 0;
2019
2020 // When this is a debug file for relocatable file, the address is all zero
2021 // and thus needs to use accumulate method
2022 if ((ObjectType == ObjectFile::Type::eTypeObjectFile ||
2023 (ObjectType == ObjectFile::Type::eTypeDebugInfo && H.sh_addr == 0)) &&
2024 Segments.empty() && (H.sh_flags & SHF_ALLOC)) {
2025 NextVMAddress =
2026 llvm::alignTo(NextVMAddress, std::max<addr_t>(H.sh_addralign, 1));
2027 Address = NextVMAddress;
2028 NextVMAddress += Size;
2029 }
2030 return VMRange(Address, Size);
2031 }
2032
2033public:
2034 VMAddressProvider(ObjectFile::Type Type, llvm::StringRef SegmentName)
2035 : ObjectType(Type), SegmentName(std::string(SegmentName)) {}
2036
2037 std::string GetNextSegmentName() const {
2038 return llvm::formatv("{0}[{1}]", SegmentName, SegmentCount).str();
2039 }
2040
2041 std::optional<VMRange> GetAddressInfo(const ELFProgramHeader &H) {
2042 if (H.p_memsz == 0) {
2043 LLDB_LOG(Log, "Ignoring zero-sized {0} segment. Corrupt object file?",
2044 SegmentName);
2045 return std::nullopt;
2046 }
2047
2048 if (Segments.overlaps(H.p_vaddr, H.p_vaddr + H.p_memsz)) {
2049 LLDB_LOG(Log, "Ignoring overlapping {0} segment. Corrupt object file?",
2050 SegmentName);
2051 return std::nullopt;
2052 }
2053 return VMRange(H.p_vaddr, H.p_memsz);
2054 }
2055
2056 std::optional<SectionAddressInfo> GetAddressInfo(const ELFSectionHeader &H) {
2057 VMRange Range = GetVMRange(H);
2058 SectionSP Segment;
2059 auto It = Segments.find(Range.GetRangeBase());
2060 if ((H.sh_flags & SHF_ALLOC) && It.valid()) {
2061 addr_t MaxSize;
2062 if (It.start() <= Range.GetRangeBase()) {
2063 MaxSize = It.stop() - Range.GetRangeBase();
2064 Segment = *It;
2065 } else
2066 MaxSize = It.start() - Range.GetRangeBase();
2067 if (Range.GetByteSize() > MaxSize) {
2068 LLDB_LOG(Log, "Shortening section crossing segment boundaries. "
2069 "Corrupt object file?");
2070 Range.SetByteSize(MaxSize);
2071 }
2072 }
2073 if (Range.GetByteSize() > 0 &&
2074 Sections.overlaps(Range.GetRangeBase(), Range.GetRangeEnd())) {
2075 LLDB_LOG(Log, "Ignoring overlapping section. Corrupt object file?");
2076 return std::nullopt;
2077 }
2078 if (Segment)
2079 Range.Slide(-Segment->GetFileAddress());
2080 return SectionAddressInfo{Segment, Range};
2081 }
2082
2083 void AddSegment(const VMRange &Range, SectionSP Seg) {
2084 Segments.insert(Range.GetRangeBase(), Range.GetRangeEnd(), std::move(Seg));
2085 ++SegmentCount;
2086 }
2087
2088 void AddSection(SectionAddressInfo Info, SectionSP Sect) {
2089 if (Info.Range.GetByteSize() == 0)
2090 return;
2091 if (Info.Segment)
2092 Info.Range.Slide(Info.Segment->GetFileAddress());
2093 Sections.insert(Info.Range.GetRangeBase(), Info.Range.GetRangeEnd(),
2094 std::move(Sect));
2095 }
2096};
2097}
2098
2099// We have to do this because ELF doesn't have section IDs, and also
2100// doesn't require section names to be unique. (We use the section index
2101// for section IDs, but that isn't guaranteed to be the same in separate
2102// debug images.)
2103static SectionSP FindMatchingSection(const SectionList &section_list,
2104 SectionSP section) {
2105 SectionSP sect_sp;
2106
2107 addr_t vm_addr = section->GetFileAddress();
2108 llvm::StringRef name = section->GetName();
2109 offset_t byte_size = section->GetByteSize();
2110 bool thread_specific = section->IsThreadSpecific();
2111 uint32_t permissions = section->GetPermissions();
2112 uint32_t alignment = section->GetLog2Align();
2113
2114 for (auto sect : section_list) {
2115 if (sect->GetName() == name &&
2116 sect->IsThreadSpecific() == thread_specific &&
2117 sect->GetPermissions() == permissions &&
2118 sect->GetByteSize() == byte_size && sect->GetFileAddress() == vm_addr &&
2119 sect->GetLog2Align() == alignment) {
2120 sect_sp = sect;
2121 break;
2122 } else {
2123 sect_sp = FindMatchingSection(sect->GetChildren(), section);
2124 if (sect_sp)
2125 break;
2126 }
2127 }
2128
2129 return sect_sp;
2130}
2131
2132void ObjectFileELF::CreateSections(SectionList &unified_section_list) {
2133 if (m_sections_up)
2134 return;
2135
2136 m_sections_up = std::make_unique<SectionList>();
2137 VMAddressProvider regular_provider(GetType(), "PT_LOAD");
2138 VMAddressProvider tls_provider(GetType(), "PT_TLS");
2139
2140 for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {
2141 const ELFProgramHeader &PHdr = EnumPHdr.value();
2142 if (PHdr.p_type != PT_LOAD && PHdr.p_type != PT_TLS)
2143 continue;
2144
2145 VMAddressProvider &provider =
2146 PHdr.p_type == PT_TLS ? tls_provider : regular_provider;
2147 auto InfoOr = provider.GetAddressInfo(PHdr);
2148 if (!InfoOr)
2149 continue;
2150
2151 uint32_t Log2Align = llvm::Log2_64(std::max<elf_xword>(PHdr.p_align, 1));
2152 SectionSP Segment = std::make_shared<Section>(
2153 GetModule(), this, SegmentID(EnumPHdr.index()),
2154 provider.GetNextSegmentName(), eSectionTypeContainer,
2155 InfoOr->GetRangeBase(), InfoOr->GetByteSize(), PHdr.p_offset,
2156 PHdr.p_filesz, Log2Align, /*flags*/ 0);
2157 Segment->SetPermissions(GetPermissions(PHdr));
2158 Segment->SetIsThreadSpecific(PHdr.p_type == PT_TLS);
2159 m_sections_up->AddSection(Segment);
2160
2161 provider.AddSegment(*InfoOr, std::move(Segment));
2162 }
2163
2165 if (m_section_headers.empty())
2166 return;
2167
2168 for (SectionHeaderCollIter I = std::next(m_section_headers.begin());
2169 I != m_section_headers.end(); ++I) {
2170 const ELFSectionHeaderInfo &header = *I;
2171
2172 const std::string &name = I->section_name;
2173 const uint64_t file_size =
2174 header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
2175
2176 VMAddressProvider &provider =
2177 header.sh_flags & SHF_TLS ? tls_provider : regular_provider;
2178 auto InfoOr = provider.GetAddressInfo(header);
2179 if (!InfoOr)
2180 continue;
2181
2182 SectionType sect_type = GetSectionType(header);
2183
2184 elf::elf_xword log2align =
2185 (header.sh_addralign == 0) ? 0 : llvm::Log2_64(header.sh_addralign);
2186
2187 SectionSP section_sp = std::make_shared<Section>(
2188 InfoOr->Segment, GetModule(), // Module to which this section belongs.
2189 this, // ObjectFile to which this section belongs and should
2190 // read section data from.
2191 SectionIndex(I), // Section ID.
2192 name, // Section name.
2193 sect_type, // Section type.
2194 InfoOr->Range.GetRangeBase(), // VM address.
2195 InfoOr->Range.GetByteSize(), // VM size in bytes of this section.
2196 header.sh_offset, // Offset of this section in the file.
2197 file_size, // Size of the section as found in the file.
2198 log2align, // Alignment of the section
2199 header.sh_flags); // Flags for this section.
2200
2201 section_sp->SetPermissions(GetPermissions(header));
2202 section_sp->SetIsThreadSpecific(header.sh_flags & SHF_TLS);
2203 (InfoOr->Segment ? InfoOr->Segment->GetChildren() : *m_sections_up)
2204 .AddSection(section_sp);
2205 provider.AddSection(std::move(*InfoOr), std::move(section_sp));
2206 }
2207
2208 // Merge the two adding any new sections, and overwriting any existing
2209 // sections that are SHT_NOBITS
2210 unified_section_list =
2211 SectionList::Merge(unified_section_list, *m_sections_up, MergeSections);
2212
2213 // If there's a .gnu_debugdata section, we'll try to read the .symtab that's
2214 // embedded in there and replace the one in the original object file (if any).
2215 // If there's none in the orignal object file, we add it to it.
2216 if (auto gdd_obj_file = GetGnuDebugDataObjectFile()) {
2217 if (auto gdd_objfile_section_list = gdd_obj_file->GetSectionList()) {
2218 if (SectionSP symtab_section_sp =
2219 gdd_objfile_section_list->FindSectionByType(
2221 SectionSP module_section_sp = unified_section_list.FindSectionByType(
2223 if (module_section_sp)
2224 unified_section_list.ReplaceSection(module_section_sp,
2225 symtab_section_sp);
2226 else
2227 unified_section_list.AddSection(symtab_section_sp);
2228 }
2229 }
2230 }
2231}
2232
2233std::shared_ptr<ObjectFileELF> ObjectFileELF::GetGnuDebugDataObjectFile() {
2234 if (m_gnu_debug_data_object_file != nullptr)
2236
2237 SectionSP section = GetSectionList()->FindSectionByName(".gnu_debugdata");
2238 if (!section)
2239 return nullptr;
2240
2241 if (!llvm::compression::xz::isAvailable()) {
2242 GetModule()->ReportWarning(
2243 "no LZMA support found for reading .gnu_debugdata section");
2244 return nullptr;
2245 }
2246
2247 // Uncompress the data
2248 DataExtractor data;
2249 section->GetSectionData(data);
2250 llvm::SmallVector<uint8_t, 0> uncompressedData;
2251 auto err =
2252 llvm::compression::xz::decompress(data.GetData(), uncompressedData);
2253 if (err) {
2254 GetModule()->ReportWarning(
2255 "an error occurred while decompressing the section {0}: {1}",
2256 section->GetName(), llvm::toString(std::move(err)).c_str());
2257 return nullptr;
2258 }
2259
2260 // Construct ObjectFileELF object from decompressed buffer
2261 DataBufferSP gdd_data_buf(
2262 new DataBufferHeap(uncompressedData.data(), uncompressedData.size()));
2263 DataExtractorSP extractor_sp = std::make_shared<DataExtractor>(gdd_data_buf);
2265 llvm::StringRef("gnu_debugdata"));
2267 GetModule(), extractor_sp, 0, &fspec, 0, gdd_data_buf->GetByteSize()));
2268
2269 // This line is essential; otherwise a breakpoint can be set but not hit.
2271
2272 ArchSpec spec = m_gnu_debug_data_object_file->GetArchitecture();
2273 if (spec && m_gnu_debug_data_object_file->SetModulesArchitecture(spec))
2275
2276 return nullptr;
2277}
2278
2279// Find the arm/aarch64 mapping symbol character in the given symbol name.
2280// Mapping symbols have the form of "$<char>[.<any>]*". Additionally we
2281// recognize cases when the mapping symbol prefixed by an arbitrary string
2282// because if a symbol prefix added to each symbol in the object file with
2283// objcopy then the mapping symbols are also prefixed.
2284static char FindArmAarch64MappingSymbol(llvm::StringRef symbol_name) {
2285 size_t dollar_pos = symbol_name.find('$');
2286 if (dollar_pos == llvm::StringRef::npos)
2287 return '\0';
2288
2289 llvm::StringRef mapping = symbol_name.drop_front(dollar_pos + 1);
2290 if (mapping.empty())
2291 return '\0';
2292
2293 if (mapping.size() == 1 || mapping[1] == '.')
2294 return mapping[0];
2295 return '\0';
2296}
2297
2298static char FindRISCVMappingSymbol(llvm::StringRef symbol_name) {
2299 if (symbol_name == "$d")
2300 return 'd';
2301 if (symbol_name == "$x")
2302 return 'x';
2303 return '\0';
2304}
2305
2306#define STO_MIPS_ISA (3 << 6)
2307#define STO_MICROMIPS (2 << 6)
2308#define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS)
2309
2310// private
2311std::pair<unsigned, ObjectFileELF::FileAddressToAddressClassMap>
2313 SectionList *section_list, const size_t num_symbols,
2314 const DataExtractor &symtab_data,
2315 const DataExtractor &strtab_data) {
2316 ELFSymbol symbol;
2317 lldb::offset_t offset = 0;
2318 // The changes these symbols would make to the class map. We will also update
2319 // m_address_class_map but need to tell the caller what changed because the
2320 // caller may be another object file.
2321 FileAddressToAddressClassMap address_class_map;
2322
2323 static constexpr llvm::StringLiteral text_section_name(".text");
2324 static constexpr llvm::StringLiteral init_section_name(".init");
2325 static constexpr llvm::StringLiteral fini_section_name(".fini");
2326 static constexpr llvm::StringLiteral ctors_section_name(".ctors");
2327 static constexpr llvm::StringLiteral dtors_section_name(".dtors");
2328
2329 static constexpr llvm::StringLiteral data_section_name(".data");
2330 static constexpr llvm::StringLiteral rodata_section_name(".rodata");
2331 static constexpr llvm::StringLiteral rodata1_section_name(".rodata1");
2332 static constexpr llvm::StringLiteral data2_section_name(".data1");
2333 static constexpr llvm::StringLiteral bss_section_name(".bss");
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 // A missing or unterminated name reads as empty.
2367 llvm::StringRef symbol_name =
2368 strtab_data.PeekCStr(symbol.st_name).value_or("");
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 (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 && symbol_name.ends_with("$plt"))
2383 continue;
2384
2385 // No need to add non-section symbols that have no names
2386 if (symbol.getType() != STT_SECTION && symbol_name.empty())
2387 continue;
2388
2389 // Skipping oatdata and oatexec sections if it is requested. See details
2390 // above the definition of skip_oatdata_oatexec for the reasons.
2391 if (skip_oatdata_oatexec &&
2392 (symbol_name == "oatdata" || symbol_name == "oatexec"))
2393 continue;
2394
2395 SectionSP symbol_section_sp;
2396 SymbolType symbol_type = eSymbolTypeInvalid;
2397 Elf64_Half shndx = symbol.st_shndx;
2398
2399 switch (shndx) {
2400 case SHN_ABS:
2401 symbol_type = eSymbolTypeAbsolute;
2402 break;
2403 case SHN_UNDEF:
2404 symbol_type = eSymbolTypeUndefined;
2405 break;
2406 default:
2407 symbol_section_sp = section_list->FindSectionByID(shndx);
2408 break;
2409 }
2410
2411 // If a symbol is undefined do not process it further even if it has a STT
2412 // type
2413 if (symbol_type != eSymbolTypeUndefined) {
2414 switch (symbol.getType()) {
2415 default:
2416 case STT_NOTYPE:
2417 // The symbol's type is not specified.
2418 break;
2419
2420 case STT_OBJECT:
2421 // The symbol is associated with a data object, such as a variable, an
2422 // array, etc.
2423 symbol_type = eSymbolTypeData;
2424 break;
2425
2426 case STT_FUNC:
2427 // The symbol is associated with a function or other executable code.
2428 symbol_type = eSymbolTypeCode;
2429 break;
2430
2431 case STT_SECTION:
2432 // The symbol is associated with a section. Symbol table entries of
2433 // this type exist primarily for relocation and normally have STB_LOCAL
2434 // binding.
2435 break;
2436
2437 case STT_FILE:
2438 // Conventionally, the symbol's name gives the name of the source file
2439 // associated with the object file. A file symbol has STB_LOCAL
2440 // binding, its section index is SHN_ABS, and it precedes the other
2441 // STB_LOCAL symbols for the file, if it is present.
2442 symbol_type = eSymbolTypeSourceFile;
2443 break;
2444
2445 case STT_GNU_IFUNC:
2446 // The symbol is associated with an indirect function. The actual
2447 // function will be resolved if it is referenced.
2448 symbol_type = eSymbolTypeResolver;
2449 break;
2450
2451 case STT_TLS:
2452 // The symbol is associated with a thread-local data object, such as
2453 // a thread-local variable.
2454 symbol_type = eSymbolTypeData;
2455 break;
2456 }
2457 }
2458
2459 if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) {
2460 if (symbol_section_sp) {
2461 llvm::StringRef sect_name = symbol_section_sp->GetName();
2462 if (sect_name == text_section_name || sect_name == init_section_name ||
2463 sect_name == fini_section_name || sect_name == ctors_section_name ||
2464 sect_name == dtors_section_name) {
2465 symbol_type = eSymbolTypeCode;
2466 } else if (sect_name == data_section_name ||
2467 sect_name == data2_section_name ||
2468 sect_name == rodata_section_name ||
2469 sect_name == rodata1_section_name ||
2470 sect_name == bss_section_name) {
2471 symbol_type = eSymbolTypeData;
2472 } else if (symbol_section_sp->Get() & SHF_ALLOC)
2473 // Check for symbols from custom sections (e.g. added by linker
2474 // scripts) with SHF_ALLOC (i.e. occupies memory during process
2475 // execution) in their flags.
2476 symbol_type = eSymbolTypeData;
2477 }
2478 }
2479
2480 int64_t symbol_value_offset = 0;
2481 uint32_t additional_flags = 0;
2482 if (arch.IsValid()) {
2483 if (arch.GetMachine() == llvm::Triple::arm) {
2484 if (symbol.getBinding() == STB_LOCAL) {
2485 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2486 if (symbol_type == eSymbolTypeCode) {
2487 switch (mapping_symbol) {
2488 case 'a':
2489 // $a[.<any>]* - marks an ARM instruction sequence
2490 address_class_map[symbol.st_value] = AddressClass::eCode;
2491 break;
2492 case 'b':
2493 case 't':
2494 // $b[.<any>]* - marks a THUMB BL instruction sequence
2495 // $t[.<any>]* - marks a THUMB instruction sequence
2496 address_class_map[symbol.st_value] =
2498 break;
2499 case 'd':
2500 // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2501 address_class_map[symbol.st_value] = AddressClass::eData;
2502 break;
2503 }
2504 }
2505 if (mapping_symbol)
2506 continue;
2507 }
2508 } else if (arch.GetMachine() == llvm::Triple::aarch64) {
2509 if (symbol.getBinding() == STB_LOCAL) {
2510 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2511 if (symbol_type == eSymbolTypeCode) {
2512 switch (mapping_symbol) {
2513 case 'x':
2514 // $x[.<any>]* - marks an A64 instruction sequence
2515 address_class_map[symbol.st_value] = AddressClass::eCode;
2516 break;
2517 case 'd':
2518 // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2519 address_class_map[symbol.st_value] = AddressClass::eData;
2520 break;
2521 }
2522 }
2523 if (mapping_symbol)
2524 continue;
2525 }
2526 } else if (arch.GetTriple().isRISCV()) {
2527 if (symbol.getBinding() == STB_LOCAL) {
2528 char mapping_symbol = FindRISCVMappingSymbol(symbol_name);
2529 if (symbol_type == eSymbolTypeCode) {
2530 // Only handle $d and $x mapping symbols.
2531 // Other mapping symbols are ignored as they don't affect address
2532 // classification.
2533 switch (mapping_symbol) {
2534 case 'x':
2535 // $x - marks a RISCV instruction sequence
2536 address_class_map[symbol.st_value] = AddressClass::eCode;
2537 break;
2538 case 'd':
2539 // $d - marks a RISCV data item sequence
2540 address_class_map[symbol.st_value] = AddressClass::eData;
2541 break;
2542 }
2543 }
2544 if (mapping_symbol)
2545 continue;
2546 }
2547 }
2548
2549 if (arch.GetMachine() == llvm::Triple::arm) {
2550 if (symbol_type == eSymbolTypeCode) {
2551 if (symbol.st_value & 1) {
2552 // Subtracting 1 from the address effectively unsets the low order
2553 // bit, which results in the address actually pointing to the
2554 // beginning of the symbol. This delta will be used below in
2555 // conjunction with symbol.st_value to produce the final
2556 // symbol_value that we store in the symtab.
2557 symbol_value_offset = -1;
2558 address_class_map[symbol.st_value ^ 1] =
2560 } else {
2561 // This address is ARM
2562 address_class_map[symbol.st_value] = AddressClass::eCode;
2563 }
2564 }
2565 }
2566
2567 /*
2568 * MIPS:
2569 * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for
2570 * MIPS).
2571 * This allows processor to switch between microMIPS and MIPS without any
2572 * need
2573 * for special mode-control register. However, apart from .debug_line,
2574 * none of
2575 * the ELF/DWARF sections set the ISA bit (for symbol or section). Use
2576 * st_other
2577 * flag to check whether the symbol is microMIPS and then set the address
2578 * class
2579 * accordingly.
2580 */
2581 if (arch.IsMIPS()) {
2582 if (IS_MICROMIPS(symbol.st_other))
2583 address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
2584 else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) {
2585 symbol.st_value = symbol.st_value & (~1ull);
2586 address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
2587 } else {
2588 if (symbol_type == eSymbolTypeCode)
2589 address_class_map[symbol.st_value] = AddressClass::eCode;
2590 else if (symbol_type == eSymbolTypeData)
2591 address_class_map[symbol.st_value] = AddressClass::eData;
2592 else
2593 address_class_map[symbol.st_value] = AddressClass::eUnknown;
2594 }
2595 }
2596 }
2597
2598 // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB
2599 // symbols. See above for more details.
2600 uint64_t symbol_value = symbol.st_value + symbol_value_offset;
2601
2602 if (symbol_section_sp &&
2604 symbol_value -= symbol_section_sp->GetFileAddress();
2605
2606 if (symbol_section_sp && module_section_list &&
2607 module_section_list != section_list) {
2608 auto section_it = section_map.find(symbol_section_sp);
2609 if (section_it == section_map.end()) {
2610 section_it = section_map
2611 .emplace(symbol_section_sp,
2612 FindMatchingSection(*module_section_list,
2613 symbol_section_sp))
2614 .first;
2615 }
2616 if (section_it->second)
2617 symbol_section_sp = section_it->second;
2618 }
2619
2620 bool is_global = symbol.getBinding() == STB_GLOBAL;
2621 uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags;
2622
2623 // Symbol names may contain @VERSION suffixes. Find those and strip them
2624 // temporarily.
2625 size_t version_pos = symbol_name.find('@');
2626 bool has_suffix = version_pos != llvm::StringRef::npos;
2627 llvm::StringRef symbol_bare = symbol_name.substr(0, version_pos);
2628 Mangled mangled(symbol_bare);
2629
2630 // Now append the suffix back to mangled and unmangled names. Only do it if
2631 // the demangling was successful (string is not empty).
2632 if (has_suffix) {
2633 llvm::StringRef suffix = symbol_name.substr(version_pos);
2634
2635 llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef();
2636 if (!mangled_name.empty())
2637 mangled.SetMangledName(ConstString((mangled_name + suffix).str()));
2638
2639 ConstString demangled = mangled.GetDemangledName();
2640 llvm::StringRef demangled_name = demangled.GetStringRef();
2641 if (!demangled_name.empty())
2642 mangled.SetDemangledName(ConstString((demangled_name + suffix).str()));
2643 }
2644
2645 // In ELF all symbol should have a valid size but it is not true for some
2646 // function symbols coming from hand written assembly. As none of the
2647 // function symbol should have 0 size we try to calculate the size for
2648 // these symbols in the symtab with saying that their original size is not
2649 // valid.
2650 bool symbol_size_valid =
2651 symbol.st_size != 0 || symbol.getType() != STT_FUNC;
2652
2653 bool is_trampoline = false;
2654 if (arch.IsValid() && (arch.GetMachine() == llvm::Triple::aarch64)) {
2655 // On AArch64, trampolines are registered as code.
2656 // If we detect a trampoline (which starts with __AArch64ADRPThunk_ or
2657 // __AArch64AbsLongThunk_) we register the symbol as a trampoline. This
2658 // way we will be able to detect the trampoline when we step in a function
2659 // and step through the trampoline.
2660 if (symbol_type == eSymbolTypeCode) {
2661 llvm::StringRef trampoline_name = mangled.GetName().GetStringRef();
2662 if (trampoline_name.starts_with("__AArch64ADRPThunk_") ||
2663 trampoline_name.starts_with("__AArch64AbsLongThunk_")) {
2664 symbol_type = eSymbolTypeTrampoline;
2665 is_trampoline = true;
2666 }
2667 }
2668 }
2669
2670 Symbol dc_symbol(
2671 i + start_id, // ID is the original symbol table index.
2672 mangled,
2673 symbol_type, // Type of this symbol
2674 is_global, // Is this globally visible?
2675 false, // Is this symbol debug info?
2676 is_trampoline, // Is this symbol a trampoline?
2677 false, // Is this symbol artificial?
2678 AddressRange(symbol_section_sp, // Section in which this symbol is
2679 // defined or null.
2680 symbol_value, // Offset in section or symbol value.
2681 symbol.st_size), // Size in bytes of this symbol.
2682 symbol_size_valid, // Symbol size is valid
2683 has_suffix, // Contains linker annotations?
2684 flags); // Symbol flags.
2685 if (symbol.getBinding() == STB_WEAK)
2686 dc_symbol.SetIsWeak(true);
2687 symtab->AddSymbol(dc_symbol);
2688 }
2689
2690 m_address_class_map.merge(address_class_map);
2691 return {i, address_class_map};
2692}
2693
2694std::pair<unsigned, ObjectFileELF::FileAddressToAddressClassMap>
2696 lldb_private::Section *symtab) {
2697 if (symtab->GetObjectFile() != this) {
2698 // If the symbol table section is owned by a different object file, have it
2699 // do the parsing.
2700 ObjectFileELF *obj_file_elf =
2701 static_cast<ObjectFileELF *>(symtab->GetObjectFile());
2702 auto [num_symbols, address_class_map] =
2703 obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab);
2704
2705 // The other object file returned the changes it made to its address
2706 // class map, make the same changes to ours.
2707 m_address_class_map.merge(address_class_map);
2708
2709 return {num_symbols, address_class_map};
2710 }
2711
2712 // Get section list for this object file.
2713 SectionList *section_list = m_sections_up.get();
2714 if (!section_list)
2715 return {};
2716
2717 user_id_t symtab_id = symtab->GetID();
2718 const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2719 assert(symtab_hdr->sh_type == SHT_SYMTAB ||
2720 symtab_hdr->sh_type == SHT_DYNSYM);
2721
2722 // sh_link: section header index of associated string table.
2723 user_id_t strtab_id = symtab_hdr->sh_link;
2724 Section *strtab = section_list->FindSectionByID(strtab_id).get();
2725
2726 if (symtab && strtab) {
2727 assert(symtab->GetObjectFile() == this);
2728 assert(strtab->GetObjectFile() == this);
2729
2730 DataExtractor symtab_data;
2731 DataExtractor strtab_data;
2732 if (ReadSectionData(symtab, symtab_data) &&
2733 ReadSectionData(strtab, strtab_data)) {
2734 size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
2735
2736 return ParseSymbols(symbol_table, start_id, section_list, num_symbols,
2737 symtab_data, strtab_data);
2738 }
2739 }
2740
2741 return {0, {}};
2742}
2743
2745 if (m_dynamic_symbols.size())
2746 return m_dynamic_symbols.size();
2747
2748 std::optional<DataExtractor> dynamic_data = GetDynamicData();
2749 if (!dynamic_data)
2750 return 0;
2751
2753 lldb::offset_t cursor = 0;
2754 while (e.symbol.Parse(*dynamic_data, &cursor)) {
2755 m_dynamic_symbols.push_back(e);
2756 if (e.symbol.d_tag == DT_NULL)
2757 break;
2758 }
2759 if (std::optional<DataExtractor> dynstr_data = GetDynstrData()) {
2760 for (ELFDynamicWithName &entry : m_dynamic_symbols) {
2761 switch (entry.symbol.d_tag) {
2762 case DT_NEEDED:
2763 case DT_SONAME:
2764 case DT_RPATH:
2765 case DT_RUNPATH:
2766 case DT_AUXILIARY:
2767 case DT_FILTER: {
2768 lldb::offset_t cursor = entry.symbol.d_val;
2769 const char *name = dynstr_data->GetCStr(&cursor);
2770 if (name)
2771 entry.name = std::string(name);
2772 break;
2773 }
2774 default:
2775 break;
2776 }
2777 }
2778 }
2779 return m_dynamic_symbols.size();
2780}
2781
2783 if (!ParseDynamicSymbols())
2784 return nullptr;
2785 for (const auto &entry : m_dynamic_symbols) {
2786 if (entry.symbol.d_tag == tag)
2787 return &entry.symbol;
2788 }
2789 return nullptr;
2790}
2791
2793 // DT_PLTREL
2794 // This member specifies the type of relocation entry to which the
2795 // procedure linkage table refers. The d_val member holds DT_REL or
2796 // DT_RELA, as appropriate. All relocations in a procedure linkage table
2797 // must use the same relocation.
2798 const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
2799
2800 if (symbol)
2801 return symbol->d_val;
2802
2803 return 0;
2804}
2805
2806// Returns the size of the normal plt entries and the offset of the first
2807// normal plt entry. The 0th entry in the plt table is usually a resolution
2808// entry which have different size in some architectures then the rest of the
2809// plt entries.
2810static std::pair<uint64_t, uint64_t>
2812 const ELFSectionHeader *plt_hdr) {
2813 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2814
2815 // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are
2816 // 16 bytes. So round the entsize up by the alignment if addralign is set.
2817 elf_xword plt_entsize =
2818 plt_hdr->sh_addralign
2819 ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign)
2820 : plt_hdr->sh_entsize;
2821
2822 // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly.
2823 // PLT entries relocation code in general requires multiple instruction and
2824 // should be greater than 4 bytes in most cases. Try to guess correct size
2825 // just in case.
2826 if (plt_entsize <= 4) {
2827 // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the
2828 // size of the plt entries based on the number of entries and the size of
2829 // the plt section with the assumption that the size of the 0th entry is at
2830 // least as big as the size of the normal entries and it isn't much bigger
2831 // then that.
2832 if (plt_hdr->sh_addralign)
2833 plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign /
2834 (num_relocations + 1) * plt_hdr->sh_addralign;
2835 else
2836 plt_entsize = plt_hdr->sh_size / (num_relocations + 1);
2837 }
2838
2839 elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize;
2840
2841 return std::make_pair(plt_entsize, plt_offset);
2842}
2843
2844static unsigned ParsePLTRelocations(
2845 Symtab *symbol_table, user_id_t start_id, unsigned rel_type,
2846 const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2847 const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr,
2848 const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data,
2849 DataExtractor &symtab_data, DataExtractor &strtab_data) {
2850 ELFRelocation rel(rel_type);
2851 ELFSymbol symbol;
2852 lldb::offset_t offset = 0;
2853
2854 uint64_t plt_offset, plt_entsize;
2855 std::tie(plt_entsize, plt_offset) =
2856 GetPltEntrySizeAndOffset(rel_hdr, plt_hdr);
2857 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2858
2859 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2860 reloc_info_fn reloc_type;
2861 reloc_info_fn reloc_symbol;
2862
2863 if (hdr->Is32Bit()) {
2864 reloc_type = ELFRelocation::RelocType32;
2865 reloc_symbol = ELFRelocation::RelocSymbol32;
2866 } else {
2867 reloc_type = ELFRelocation::RelocType64;
2868 reloc_symbol = ELFRelocation::RelocSymbol64;
2869 }
2870
2871 unsigned slot_type = hdr->GetRelocationJumpSlotType();
2872 unsigned i;
2873 for (i = 0; i < num_relocations; ++i) {
2874 if (!rel.Parse(rel_data, &offset))
2875 break;
2876
2877 if (reloc_type(rel) != slot_type)
2878 continue;
2879
2880 lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
2881 if (!symbol.Parse(symtab_data, &symbol_offset))
2882 break;
2883
2884 llvm::StringRef symbol_name =
2885 strtab_data.PeekCStr(symbol.st_name).value_or("");
2886 uint64_t plt_index = plt_offset + i * plt_entsize;
2887
2888 Symbol jump_symbol(
2889 i + start_id, // Symbol table index
2890 symbol_name, // symbol name.
2891 eSymbolTypeTrampoline, // Type of this symbol
2892 false, // Is this globally visible?
2893 false, // Is this symbol debug info?
2894 true, // Is this symbol a trampoline?
2895 true, // Is this symbol artificial?
2896 plt_section_sp, // Section in which this symbol is defined or null.
2897 plt_index, // Offset in section or symbol value.
2898 plt_entsize, // Size in bytes of this symbol.
2899 true, // Size is valid
2900 false, // Contains linker annotations?
2901 0); // Symbol flags.
2902
2903 symbol_table->AddSymbol(jump_symbol);
2904 }
2905
2906 return i;
2907}
2908
2909unsigned
2911 const ELFSectionHeaderInfo *rel_hdr,
2912 user_id_t rel_id) {
2913 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2914
2915 // The link field points to the associated symbol table.
2916 user_id_t symtab_id = rel_hdr->sh_link;
2917
2918 // If the link field doesn't point to the appropriate symbol name table then
2919 // try to find it by name as some compiler don't fill in the link fields.
2920 if (!symtab_id)
2921 symtab_id = GetSectionIndexByName(".dynsym");
2922
2923 // Get PLT section. We cannot use rel_hdr->sh_info, since current linkers
2924 // point that to the .got.plt or .got section instead of .plt.
2925 user_id_t plt_id = GetSectionIndexByName(".plt");
2926
2927 if (!symtab_id || !plt_id)
2928 return 0;
2929
2930 const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
2931 if (!plt_hdr)
2932 return 0;
2933
2934 const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
2935 if (!sym_hdr)
2936 return 0;
2937
2938 SectionList *section_list = m_sections_up.get();
2939 if (!section_list)
2940 return 0;
2941
2942 Section *rel_section = section_list->FindSectionByID(rel_id).get();
2943 if (!rel_section)
2944 return 0;
2945
2946 SectionSP plt_section_sp(section_list->FindSectionByID(plt_id));
2947 if (!plt_section_sp)
2948 return 0;
2949
2950 Section *symtab = section_list->FindSectionByID(symtab_id).get();
2951 if (!symtab)
2952 return 0;
2953
2954 // sh_link points to associated string table.
2955 Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link).get();
2956 if (!strtab)
2957 return 0;
2958
2959 DataExtractor rel_data;
2960 if (!ReadSectionData(rel_section, rel_data))
2961 return 0;
2962
2963 DataExtractor symtab_data;
2964 if (!ReadSectionData(symtab, symtab_data))
2965 return 0;
2966
2967 DataExtractor strtab_data;
2968 if (!ReadSectionData(strtab, strtab_data))
2969 return 0;
2970
2971 unsigned rel_type = PLTRelocationType();
2972 if (!rel_type)
2973 return 0;
2974
2975 return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header,
2976 rel_hdr, plt_hdr, sym_hdr, plt_section_sp,
2977 rel_data, symtab_data, strtab_data);
2978}
2979
2980/// Returns the \p size bytes at \p offset in \p debug_data for a relocation to
2981/// patch, or reports an error and returns null if they overrun the section.
2982static uint8_t *GetRelocationTarget(DataExtractor &debug_data,
2983 Section *rel_section, uint64_t offset,
2984 size_t size) {
2985 if (!debug_data.ValidOffsetForDataOfSize(offset, size)) {
2986 rel_section->GetModule()->ReportError("relocation outside of section {0}",
2987 rel_section->GetName());
2988 return nullptr;
2989 }
2990 DataBufferSP data_buffer_sp = debug_data.GetSharedDataBuffer();
2991 // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
2992 WritableDataBuffer *data_buffer =
2993 llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
2994 return data_buffer->GetBytes() + debug_data.GetSharedDataOffset() + offset;
2995}
2996
2997static void ApplyELF64ABS64Relocation(Symtab *symtab, ELFRelocation &rel,
2998 DataExtractor &debug_data,
2999 Section *rel_section) {
3000 const Symbol *symbol =
3001 symtab->FindSymbolByID(ELFRelocation::RelocSymbol64(rel));
3002 if (symbol) {
3003 addr_t value = symbol->GetAddressRef().GetFileAddress();
3004 uint8_t *dst = GetRelocationTarget(debug_data, rel_section,
3005 ELFRelocation::RelocOffset64(rel),
3006 sizeof(uint64_t));
3007 if (!dst)
3008 return;
3009 uint64_t val_offset = value + ELFRelocation::RelocAddend64(rel);
3010 memcpy(dst, &val_offset, sizeof(uint64_t));
3011 }
3012}
3013
3014static void ApplyELF64ABS32Relocation(Symtab *symtab, ELFRelocation &rel,
3015 DataExtractor &debug_data,
3016 Section *rel_section, bool is_signed) {
3017 const Symbol *symbol =
3018 symtab->FindSymbolByID(ELFRelocation::RelocSymbol64(rel));
3019 if (symbol) {
3020 addr_t value = symbol->GetAddressRef().GetFileAddress();
3021 value += ELFRelocation::RelocAddend32(rel);
3022 if ((!is_signed && (value > UINT32_MAX)) ||
3023 (is_signed &&
3024 ((int64_t)value > INT32_MAX || (int64_t)value < INT32_MIN))) {
3025 Log *log = GetLog(LLDBLog::Modules);
3026 LLDB_LOGF(log, "Failed to apply debug info relocations");
3027 return;
3028 }
3029 uint32_t truncated_addr = (value & 0xFFFFFFFF);
3030 uint8_t *dst = GetRelocationTarget(debug_data, rel_section,
3031 ELFRelocation::RelocOffset32(rel),
3032 sizeof(uint32_t));
3033 if (!dst)
3034 return;
3035 memcpy(dst, &truncated_addr, sizeof(uint32_t));
3036 }
3037}
3038
3039static void ApplyELF32ABS32RelRelocation(Symtab *symtab, ELFRelocation &rel,
3040 DataExtractor &debug_data,
3041 Section *rel_section) {
3042 Log *log = GetLog(LLDBLog::Modules);
3043 const Symbol *symbol =
3044 symtab->FindSymbolByID(ELFRelocation::RelocSymbol32(rel));
3045 if (symbol) {
3046 addr_t value = symbol->GetAddressRef().GetFileAddress();
3047 if (value == LLDB_INVALID_ADDRESS) {
3048 const char *name = symbol->GetName().GetCString();
3049 LLDB_LOGF(log, "Debug info symbol invalid: %s", name);
3050 return;
3051 }
3052 assert(llvm::isUInt<32>(value) && "Valid addresses are 32-bit");
3053 uint8_t *dst = GetRelocationTarget(debug_data, rel_section,
3054 ELFRelocation::RelocOffset32(rel),
3055 sizeof(uint32_t));
3056 if (!dst)
3057 return;
3058 // Implicit addend is stored inline as a signed value.
3059 int32_t addend;
3060 memcpy(&addend, dst, sizeof(int32_t));
3061 // The sum must be positive. This extra check prevents UB from overflow in
3062 // the actual range check below.
3063 if (addend < 0 && static_cast<uint32_t>(-addend) > value) {
3064 LLDB_LOGF(log, "Debug info relocation overflow: 0x%" PRIx64,
3065 static_cast<int64_t>(value) + addend);
3066 return;
3067 }
3068 if (!llvm::isUInt<32>(value + addend)) {
3069 LLDB_LOGF(log, "Debug info relocation out of range: 0x%" PRIx64, value);
3070 return;
3071 }
3072 uint32_t addr = value + addend;
3073 memcpy(dst, &addr, sizeof(uint32_t));
3074 }
3075}
3076
3078 Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
3079 const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr,
3080 DataExtractor &rel_data, DataExtractor &symtab_data,
3081 DataExtractor &debug_data, Section *rel_section) {
3082 ELFRelocation rel(rel_hdr->sh_type);
3083 lldb::addr_t offset = 0;
3084 const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
3085 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
3086 reloc_info_fn reloc_type;
3087 reloc_info_fn reloc_symbol;
3088
3089 if (hdr->Is32Bit()) {
3090 reloc_type = ELFRelocation::RelocType32;
3091 reloc_symbol = ELFRelocation::RelocSymbol32;
3092 } else {
3093 reloc_type = ELFRelocation::RelocType64;
3094 reloc_symbol = ELFRelocation::RelocSymbol64;
3095 }
3096
3097 for (unsigned i = 0; i < num_relocations; ++i) {
3098 if (!rel.Parse(rel_data, &offset)) {
3099 GetModule()->ReportError(".rel{0}[{1:d}] failed to parse relocation",
3100 rel_section->GetName(), i);
3101 break;
3102 }
3103 const Symbol *symbol = nullptr;
3104
3105 if (hdr->Is32Bit()) {
3106 switch (hdr->e_machine) {
3107 case llvm::ELF::EM_ARM:
3108 switch (reloc_type(rel)) {
3109 case R_ARM_ABS32:
3110 ApplyELF32ABS32RelRelocation(symtab, rel, debug_data, rel_section);
3111 break;
3112 case R_ARM_REL32:
3113 GetModule()->ReportError("unsupported AArch32 relocation:"
3114 " .rel{0}[{1}], type {2}",
3115 rel_section->GetName(), i, reloc_type(rel));
3116 break;
3117 default:
3118 assert(false && "unexpected relocation type");
3119 }
3120 break;
3121 case llvm::ELF::EM_386:
3122 switch (reloc_type(rel)) {
3123 case R_386_32:
3124 symbol = symtab->FindSymbolByID(reloc_symbol(rel));
3125 if (symbol) {
3126 uint32_t *dst = reinterpret_cast<uint32_t *>(GetRelocationTarget(
3127 debug_data, rel_section, ELFRelocation::RelocOffset32(rel),
3128 sizeof(uint32_t)));
3129 if (!dst)
3130 break;
3131
3132 addr_t value = symbol->GetAddressRef().GetFileAddress();
3133 if (rel.IsRela()) {
3134 value += ELFRelocation::RelocAddend32(rel);
3135 } else {
3136 value += *dst;
3137 }
3138 *dst = value;
3139 } else {
3140 GetModule()->ReportError(".rel{0}[{1}] unknown symbol id: {2:d}",
3141 rel_section->GetName(), i,
3142 reloc_symbol(rel));
3143 }
3144 break;
3145 case R_386_NONE:
3146 case R_386_PC32:
3147 GetModule()->ReportError("unsupported i386 relocation:"
3148 " .rel{0}[{1}], type {2}",
3149 rel_section->GetName(), i, reloc_type(rel));
3150 break;
3151 default:
3152 assert(false && "unexpected relocation type");
3153 break;
3154 }
3155 break;
3156 default:
3157 GetModule()->ReportError("unsupported 32-bit ELF machine arch: {0}", hdr->e_machine);
3158 break;
3159 }
3160 } else {
3161 switch (hdr->e_machine) {
3162 case llvm::ELF::EM_AARCH64:
3163 switch (reloc_type(rel)) {
3164 case R_AARCH64_ABS64:
3165 ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
3166 break;
3167 case R_AARCH64_ABS32:
3168 ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
3169 break;
3170 default:
3171 assert(false && "unexpected relocation type");
3172 }
3173 break;
3174 case llvm::ELF::EM_LOONGARCH:
3175 switch (reloc_type(rel)) {
3176 case R_LARCH_64:
3177 ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
3178 break;
3179 case R_LARCH_32:
3180 ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
3181 break;
3182 default:
3183 assert(false && "unexpected relocation type");
3184 }
3185 break;
3186 case llvm::ELF::EM_X86_64:
3187 switch (reloc_type(rel)) {
3188 case R_X86_64_64:
3189 ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
3190 break;
3191 case R_X86_64_32:
3192 ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section,
3193 false);
3194 break;
3195 case R_X86_64_32S:
3196 ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
3197 break;
3198 case R_X86_64_PC32:
3199 default:
3200 assert(false && "unexpected relocation type");
3201 }
3202 break;
3203 default:
3204 GetModule()->ReportError("unsupported 64-bit ELF machine arch: {0}", hdr->e_machine);
3205 break;
3206 }
3207 }
3208 }
3209
3210 return 0;
3211}
3212
3214 user_id_t rel_id,
3215 lldb_private::Symtab *thetab) {
3216 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
3217
3218 // Parse in the section list if needed.
3219 SectionList *section_list = GetSectionList();
3220 if (!section_list)
3221 return 0;
3222
3223 user_id_t symtab_id = rel_hdr->sh_link;
3224 user_id_t debug_id = rel_hdr->sh_info;
3225
3226 const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
3227 if (!symtab_hdr)
3228 return 0;
3229
3230 const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id);
3231 if (!debug_hdr)
3232 return 0;
3233
3234 Section *rel = section_list->FindSectionByID(rel_id).get();
3235 if (!rel)
3236 return 0;
3237
3238 Section *symtab = section_list->FindSectionByID(symtab_id).get();
3239 if (!symtab)
3240 return 0;
3241
3242 Section *debug = section_list->FindSectionByID(debug_id).get();
3243 if (!debug)
3244 return 0;
3245
3246 DataExtractorSP rel_data_sp = std::make_shared<DataExtractor>();
3247 DataExtractorSP symtab_data_sp = std::make_shared<DataExtractor>();
3248 DataExtractorSP debug_data_sp = std::make_shared<DataExtractor>();
3249
3250 if (GetData(rel->GetFileOffset(), rel->GetFileSize(), rel_data_sp) &&
3251 GetData(symtab->GetFileOffset(), symtab->GetFileSize(), symtab_data_sp) &&
3252 GetData(debug->GetFileOffset(), debug->GetFileSize(), debug_data_sp)) {
3253 ApplyRelocations(thetab, &m_header, rel_hdr, symtab_hdr, debug_hdr,
3254 *rel_data_sp, *symtab_data_sp, *debug_data_sp, debug);
3255 }
3256
3257 return 0;
3258}
3259
3261 ModuleSP module_sp(GetModule());
3262 if (!module_sp)
3263 return;
3264
3265 Progress progress("Parsing symbol table",
3266 m_file.GetFilename().nonEmptyOr("<Unknown>").str());
3267 ElapsedTime elapsed(module_sp->GetSymtabParseTime());
3268
3269 // We always want to use the main object file so we (hopefully) only have one
3270 // cached copy of our symtab, dynamic sections, etc.
3271 ObjectFile *module_obj_file = module_sp->GetObjectFile();
3272 if (module_obj_file && module_obj_file != this)
3273 return module_obj_file->ParseSymtab(lldb_symtab);
3274
3275 SectionList *section_list = module_sp->GetSectionList();
3276 if (!section_list)
3277 return;
3278
3279 uint64_t symbol_id = 0;
3280
3281 // Sharable objects and dynamic executables usually have 2 distinct symbol
3282 // tables, one named ".symtab", and the other ".dynsym". The dynsym is a
3283 // smaller version of the symtab that only contains global symbols. The
3284 // information found in the dynsym is therefore also found in the symtab,
3285 // while the reverse is not necessarily true.
3286 Section *symtab =
3287 section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get();
3288 if (symtab) {
3289 auto [num_symbols, address_class_map] =
3290 ParseSymbolTable(&lldb_symtab, symbol_id, symtab);
3291 m_address_class_map.merge(address_class_map);
3292 symbol_id += num_symbols;
3293 }
3294
3295 // The symtab section is non-allocable and can be stripped, while the
3296 // .dynsym section which should always be always be there. To support the
3297 // minidebuginfo case we parse .dynsym when there's a .gnu_debuginfo
3298 // section, nomatter if .symtab was already parsed or not. This is because
3299 // minidebuginfo normally removes the .symtab symbols which have their
3300 // matching .dynsym counterparts.
3301 if (!symtab || GetSectionList()->FindSectionByName(".gnu_debugdata")) {
3302 Section *dynsym =
3304 .get();
3305 if (dynsym) {
3306 auto [num_symbols, address_class_map] =
3307 ParseSymbolTable(&lldb_symtab, symbol_id, dynsym);
3308 symbol_id += num_symbols;
3309 m_address_class_map.merge(address_class_map);
3310 } else {
3311 // Try and read the dynamic symbol table from the .dynamic section.
3312 uint32_t dynamic_num_symbols = 0;
3313 std::optional<DataExtractor> symtab_data =
3314 GetDynsymDataFromDynamic(dynamic_num_symbols);
3315 std::optional<DataExtractor> strtab_data = GetDynstrData();
3316 if (symtab_data && strtab_data) {
3317 auto [num_symbols_parsed, address_class_map] = ParseSymbols(
3318 &lldb_symtab, symbol_id, section_list, dynamic_num_symbols,
3319 symtab_data.value(), strtab_data.value());
3320 symbol_id += num_symbols_parsed;
3321 m_address_class_map.merge(address_class_map);
3322 }
3323 }
3324 }
3325
3326 // DT_JMPREL
3327 // If present, this entry's d_ptr member holds the address of
3328 // relocation
3329 // entries associated solely with the procedure linkage table.
3330 // Separating
3331 // these relocation entries lets the dynamic linker ignore them during
3332 // process initialization, if lazy binding is enabled. If this entry is
3333 // present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
3334 // also be present.
3335 const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
3336 if (symbol) {
3337 // Synthesize trampoline symbols to help navigate the PLT.
3338 addr_t addr = symbol->d_ptr;
3339 Section *reloc_section =
3340 section_list->FindSectionContainingFileAddress(addr).get();
3341 if (reloc_section) {
3342 user_id_t reloc_id = reloc_section->GetID();
3343 const ELFSectionHeaderInfo *reloc_header =
3344 GetSectionHeaderByIndex(reloc_id);
3345 if (reloc_header)
3346 ParseTrampolineSymbols(&lldb_symtab, symbol_id, reloc_header, reloc_id);
3347 }
3348 }
3349
3350 if (DWARFCallFrameInfo *eh_frame =
3351 GetModule()->GetUnwindTable().GetEHFrameInfo()) {
3352 ParseUnwindSymbols(&lldb_symtab, eh_frame);
3353 }
3354
3355 // In the event that there's no symbol entry for the entry point we'll
3356 // artificially create one. We delegate to the symtab object the figuring
3357 // out of the proper size, this will usually make it span til the next
3358 // symbol it finds in the section. This means that if there are missing
3359 // symbols the entry point might span beyond its function definition.
3360 // We're fine with this as it doesn't make it worse than not having a
3361 // symbol entry at all.
3362 if (CalculateType() == eTypeExecutable) {
3363 ArchSpec arch = GetArchitecture();
3364 auto entry_point_addr = GetEntryPointAddress();
3365 bool is_valid_entry_point =
3366 entry_point_addr.IsValid() && entry_point_addr.IsSectionOffset();
3367 addr_t entry_point_file_addr = entry_point_addr.GetFileAddress();
3368 if (is_valid_entry_point && !lldb_symtab.FindSymbolContainingFileAddress(
3369 entry_point_file_addr)) {
3370 uint64_t symbol_id = lldb_symtab.GetNumSymbols();
3371 // Don't set the name for any synthetic symbols, the Symbol
3372 // object will generate one if needed when the name is accessed
3373 // via accessors.
3374 SectionSP section_sp = entry_point_addr.GetSection();
3375 Symbol symbol(
3376 /*symID=*/symbol_id,
3377 /*name=*/llvm::StringRef(), // Name will be auto generated.
3378 /*type=*/eSymbolTypeCode,
3379 /*external=*/true,
3380 /*is_debug=*/false,
3381 /*is_trampoline=*/false,
3382 /*is_artificial=*/true,
3383 /*section_sp=*/section_sp,
3384 /*offset=*/entry_point_addr.GetOffset(),
3385 /*size=*/0, // FDE can span multiple symbols so don't use its size.
3386 /*size_is_valid=*/false,
3387 /*contains_linker_annotations=*/false,
3388 /*flags=*/0);
3389 // When the entry point is arm thumb we need to explicitly set its
3390 // class address to reflect that. This is important because expression
3391 // evaluation relies on correctly setting a breakpoint at this
3392 // address.
3393 if (arch.GetMachine() == llvm::Triple::arm &&
3394 (entry_point_file_addr & 1)) {
3395 symbol.GetAddressRef().Slide(-1);
3396 m_address_class_map[entry_point_file_addr - 1] =
3398 } else {
3399 m_address_class_map[entry_point_file_addr] = AddressClass::eCode;
3400 }
3401 lldb_symtab.AddSymbol(symbol);
3402 }
3403 }
3404}
3405
3407{
3408 static llvm::StringRef debug_prefix(".debug");
3409
3410 // Set relocated bit so we stop getting called, regardless of whether we
3411 // actually relocate.
3412 section->SetIsRelocated(true);
3413
3414 // We only relocate in ELF relocatable files
3416 return;
3417
3418 llvm::StringRef section_name = section->GetName();
3419 // Can't relocate that which can't be named
3420 if (section_name.empty())
3421 return;
3422
3423 // We don't relocate non-debug sections at the moment
3424 if (!section_name.starts_with(debug_prefix))
3425 return;
3426
3427 // Relocation section names to look for
3428 std::string needle = std::string(".rel") + section_name.str();
3429 std::string needlea = std::string(".rela") + section_name.str();
3430
3432 I != m_section_headers.end(); ++I) {
3433 if (I->sh_type == SHT_RELA || I->sh_type == SHT_REL) {
3434 llvm::StringRef hay_name(I->section_name);
3435 if (hay_name.empty())
3436 continue;
3437 if (needle == hay_name || needlea == hay_name) {
3438 const ELFSectionHeader &reloc_header = *I;
3439 user_id_t reloc_id = SectionIndex(I);
3440 RelocateDebugSections(&reloc_header, reloc_id, GetSymtab());
3441 break;
3442 }
3443 }
3444 }
3445}
3446
3448 DWARFCallFrameInfo *eh_frame) {
3449 SectionList *section_list = GetSectionList();
3450 if (!section_list)
3451 return;
3452
3453 // First we save the new symbols into a separate list and add them to the
3454 // symbol table after we collected all symbols we want to add. This is
3455 // neccessary because adding a new symbol invalidates the internal index of
3456 // the symtab what causing the next lookup to be slow because it have to
3457 // recalculate the index first.
3458 std::vector<Symbol> new_symbols;
3459
3460 size_t num_symbols = symbol_table->GetNumSymbols();
3461 uint64_t last_symbol_id =
3462 num_symbols ? symbol_table->SymbolAtIndex(num_symbols - 1)->GetID() : 0;
3463 eh_frame->ForEachFDEEntries([&](lldb::addr_t file_addr, uint32_t size,
3464 dw_offset_t) {
3465 Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr);
3466 if (symbol) {
3467 if (!symbol->GetByteSizeIsValid()) {
3468 symbol->SetByteSize(size);
3469 symbol->SetSizeIsSynthesized(true);
3470 }
3471 } else {
3472 SectionSP section_sp =
3473 section_list->FindSectionContainingFileAddress(file_addr);
3474 if (section_sp) {
3475 addr_t offset = file_addr - section_sp->GetFileAddress();
3476 uint64_t symbol_id = ++last_symbol_id;
3477 // Don't set the name for any synthetic symbols, the Symbol
3478 // object will generate one if needed when the name is accessed
3479 // via accessors.
3480 Symbol eh_symbol(
3481 /*symID=*/symbol_id,
3482 /*name=*/llvm::StringRef(), // Name will be auto generated.
3483 /*type=*/eSymbolTypeCode,
3484 /*external=*/true,
3485 /*is_debug=*/false,
3486 /*is_trampoline=*/false,
3487 /*is_artificial=*/true,
3488 /*section_sp=*/section_sp,
3489 /*offset=*/offset,
3490 /*size=*/0, // FDE can span multiple symbols so don't use its size.
3491 /*size_is_valid=*/false,
3492 /*contains_linker_annotations=*/false,
3493 /*flags=*/0);
3494 new_symbols.push_back(eh_symbol);
3495 }
3496 }
3497 return true;
3498 });
3499
3500 for (const Symbol &s : new_symbols)
3501 symbol_table->AddSymbol(s);
3502}
3503
3505 // TODO: determine this for ELF
3506 return false;
3507}
3508
3509//===----------------------------------------------------------------------===//
3510// Dump
3511//
3512// Dump the specifics of the runtime file container (such as any headers
3513// segments, sections, etc).
3515 ModuleSP module_sp(GetModule());
3516 if (!module_sp) {
3517 return;
3518 }
3519
3520 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
3521 s->Printf("%p: ", static_cast<void *>(this));
3522 s->Indent();
3523 s->PutCString("ObjectFileELF");
3524
3525 ArchSpec header_arch = GetArchitecture();
3526
3527 *s << ", file = '" << m_file
3528 << "', arch = " << header_arch.GetArchitectureName();
3530 s->Printf(", addr = %#16.16" PRIx64, m_memory_addr);
3531 s->EOL();
3532
3534 s->EOL();
3536 s->EOL();
3538 s->EOL();
3539 SectionList *section_list = GetSectionList();
3540 if (section_list)
3541 section_list->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
3542 UINT32_MAX);
3543 Symtab *symtab = GetSymtab();
3544 if (symtab)
3545 symtab->Dump(s, nullptr, eSortOrderNone);
3546 s->EOL();
3548 s->EOL();
3549 DumpELFDynamic(s);
3550 s->EOL();
3551 Address image_info_addr = GetImageInfoAddress(nullptr);
3552 if (image_info_addr.IsValid())
3553 s->Printf("image_info_address = %#16.16" PRIx64 "\n",
3554 image_info_addr.GetFileAddress());
3555}
3556
3557// DumpELFHeader
3558//
3559// Dump the ELF header to the specified output stream
3561 s->PutCString("ELF Header\n");
3562 s->Printf("e_ident[EI_MAG0 ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
3563 s->Printf("e_ident[EI_MAG1 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG1],
3564 header.e_ident[EI_MAG1]);
3565 s->Printf("e_ident[EI_MAG2 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG2],
3566 header.e_ident[EI_MAG2]);
3567 s->Printf("e_ident[EI_MAG3 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG3],
3568 header.e_ident[EI_MAG3]);
3569
3570 s->Printf("e_ident[EI_CLASS ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
3571 s->Printf("e_ident[EI_DATA ] = 0x%2.2x ", header.e_ident[EI_DATA]);
3572 DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
3573 s->Printf("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
3574 s->Printf("e_ident[EI_PAD ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
3575
3576 s->Printf("e_type = 0x%4.4x ", header.e_type);
3577 DumpELFHeader_e_type(s, header.e_type);
3578 s->Printf("\ne_machine = 0x%4.4x\n", header.e_machine);
3579 s->Printf("e_version = 0x%8.8x\n", header.e_version);
3580 s->Printf("e_entry = 0x%8.8" PRIx64 "\n", header.e_entry);
3581 s->Printf("e_phoff = 0x%8.8" PRIx64 "\n", header.e_phoff);
3582 s->Printf("e_shoff = 0x%8.8" PRIx64 "\n", header.e_shoff);
3583 s->Printf("e_flags = 0x%8.8x\n", header.e_flags);
3584 s->Printf("e_ehsize = 0x%4.4x\n", header.e_ehsize);
3585 s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
3586 s->Printf("e_phnum = 0x%8.8x\n", header.e_phnum);
3587 s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
3588 s->Printf("e_shnum = 0x%8.8x\n", header.e_shnum);
3589 s->Printf("e_shstrndx = 0x%8.8x\n", header.e_shstrndx);
3590}
3591
3592// DumpELFHeader_e_type
3593//
3594// Dump an token value for the ELF header member e_type
3596 switch (e_type) {
3597 case ET_NONE:
3598 *s << "ET_NONE";
3599 break;
3600 case ET_REL:
3601 *s << "ET_REL";
3602 break;
3603 case ET_EXEC:
3604 *s << "ET_EXEC";
3605 break;
3606 case ET_DYN:
3607 *s << "ET_DYN";
3608 break;
3609 case ET_CORE:
3610 *s << "ET_CORE";
3611 break;
3612 default:
3613 break;
3614 }
3615}
3616
3617// DumpELFHeader_e_ident_EI_DATA
3618//
3619// Dump an token value for the ELF header member e_ident[EI_DATA]
3621 unsigned char ei_data) {
3622 switch (ei_data) {
3623 case ELFDATANONE:
3624 *s << "ELFDATANONE";
3625 break;
3626 case ELFDATA2LSB:
3627 *s << "ELFDATA2LSB - Little Endian";
3628 break;
3629 case ELFDATA2MSB:
3630 *s << "ELFDATA2MSB - Big Endian";
3631 break;
3632 default:
3633 break;
3634 }
3635}
3636
3637// DumpELFProgramHeader
3638//
3639// Dump a single ELF program header to the specified output stream
3641 const ELFProgramHeader &ph) {
3643 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset,
3644 ph.p_vaddr, ph.p_paddr);
3645 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz,
3646 ph.p_flags);
3647
3649 s->Printf(") %8.8" PRIx64, ph.p_align);
3650}
3651
3652// DumpELFProgramHeader_p_type
3653//
3654// Dump an token value for the ELF program header member p_type which describes
3655// the type of the program header
3657 const int kStrWidth = 15;
3658 switch (p_type) {
3659 CASE_AND_STREAM(s, PT_NULL, kStrWidth);
3660 CASE_AND_STREAM(s, PT_LOAD, kStrWidth);
3661 CASE_AND_STREAM(s, PT_DYNAMIC, kStrWidth);
3662 CASE_AND_STREAM(s, PT_INTERP, kStrWidth);
3663 CASE_AND_STREAM(s, PT_NOTE, kStrWidth);
3664 CASE_AND_STREAM(s, PT_SHLIB, kStrWidth);
3665 CASE_AND_STREAM(s, PT_PHDR, kStrWidth);
3666 CASE_AND_STREAM(s, PT_TLS, kStrWidth);
3667 CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
3668 default:
3669 s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
3670 break;
3671 }
3672}
3673
3674// DumpELFProgramHeader_p_flags
3675//
3676// Dump an token value for the ELF program header member p_flags
3678 *s << ((p_flags & PF_X) ? "PF_X" : " ")
3679 << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
3680 << ((p_flags & PF_W) ? "PF_W" : " ")
3681 << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
3682 << ((p_flags & PF_R) ? "PF_R" : " ");
3683}
3684
3685// DumpELFProgramHeaders
3686//
3687// Dump all of the ELF program header to the specified output stream
3689 if (!ParseProgramHeaders())
3690 return;
3691
3692 s->PutCString("Program Headers\n");
3693 s->PutCString("IDX p_type p_offset p_vaddr p_paddr "
3694 "p_filesz p_memsz p_flags p_align\n");
3695 s->PutCString("==== --------------- -------- -------- -------- "
3696 "-------- -------- ------------------------- --------\n");
3697
3698 for (const auto &H : llvm::enumerate(m_program_headers)) {
3699 s->Format("[{0,2}] ", H.index());
3701 s->EOL();
3702 }
3703}
3704
3705// DumpELFSectionHeader
3706//
3707// Dump a single ELF section header to the specified output stream
3709 const ELFSectionHeaderInfo &sh) {
3710 s->Printf("%8.8x ", sh.sh_name);
3712 s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
3714 s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr,
3715 sh.sh_offset, sh.sh_size);
3716 s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
3717 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
3718}
3719
3720// DumpELFSectionHeader_sh_type
3721//
3722// Dump an token value for the ELF section header member sh_type which
3723// describes the type of the section
3725 const int kStrWidth = 12;
3726 switch (sh_type) {
3727 CASE_AND_STREAM(s, SHT_NULL, kStrWidth);
3728 CASE_AND_STREAM(s, SHT_PROGBITS, kStrWidth);
3729 CASE_AND_STREAM(s, SHT_SYMTAB, kStrWidth);
3730 CASE_AND_STREAM(s, SHT_STRTAB, kStrWidth);
3731 CASE_AND_STREAM(s, SHT_RELA, kStrWidth);
3732 CASE_AND_STREAM(s, SHT_HASH, kStrWidth);
3733 CASE_AND_STREAM(s, SHT_DYNAMIC, kStrWidth);
3734 CASE_AND_STREAM(s, SHT_NOTE, kStrWidth);
3735 CASE_AND_STREAM(s, SHT_NOBITS, kStrWidth);
3736 CASE_AND_STREAM(s, SHT_REL, kStrWidth);
3737 CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth);
3738 CASE_AND_STREAM(s, SHT_DYNSYM, kStrWidth);
3739 CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth);
3740 CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth);
3741 CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth);
3742 CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth);
3743 default:
3744 s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
3745 break;
3746 }
3747}
3748
3749// DumpELFSectionHeader_sh_flags
3750//
3751// Dump an token value for the ELF section header member sh_flags
3753 elf_xword sh_flags) {
3754 *s << ((sh_flags & SHF_WRITE) ? "WRITE" : " ")
3755 << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
3756 << ((sh_flags & SHF_ALLOC) ? "ALLOC" : " ")
3757 << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
3758 << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : " ");
3759}
3760
3761// DumpELFSectionHeaders
3762//
3763// Dump all of the ELF section header to the specified output stream
3765 if (!ParseSectionHeaders())
3766 return;
3767
3768 s->PutCString("Section Headers\n");
3769 s->PutCString("IDX name type flags "
3770 "addr offset size link info addralgn "
3771 "entsize Name\n");
3772 s->PutCString("==== -------- ------------ -------------------------------- "
3773 "-------- -------- -------- -------- -------- -------- "
3774 "-------- ====================\n");
3775
3776 uint32_t idx = 0;
3778 I != m_section_headers.end(); ++I, ++idx) {
3779 s->Printf("[%2u] ", idx);
3781 const std::string &section_name = I->section_name;
3782 if (!section_name.empty())
3783 *s << ' ' << section_name << "\n";
3784 }
3785}
3786
3788 size_t num_modules = ParseDependentModules();
3789
3790 if (num_modules > 0) {
3791 s->PutCString("Dependent Modules:\n");
3792 for (unsigned i = 0; i < num_modules; ++i) {
3793 const FileSpec &spec = m_filespec_up->GetFileSpecAtIndex(i);
3794 s->Format(" {0}\n", spec.GetFilename());
3795 }
3796 }
3797}
3798
3799std::string static getDynamicTagAsString(uint16_t Arch, uint64_t Type) {
3800#define DYNAMIC_STRINGIFY_ENUM(tag, value) \
3801 case value: \
3802 return #tag;
3803
3804#define DYNAMIC_TAG(n, v)
3805 switch (Arch) {
3806 case llvm::ELF::EM_AARCH64:
3807 switch (Type) {
3808#define AARCH64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3809#include "llvm/BinaryFormat/DynamicTags.def"
3810#undef AARCH64_DYNAMIC_TAG
3811 }
3812 break;
3813
3814 case llvm::ELF::EM_HEXAGON:
3815 switch (Type) {
3816#define HEXAGON_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3817#include "llvm/BinaryFormat/DynamicTags.def"
3818#undef HEXAGON_DYNAMIC_TAG
3819 }
3820 break;
3821
3822 case llvm::ELF::EM_MIPS:
3823 switch (Type) {
3824#define MIPS_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3825#include "llvm/BinaryFormat/DynamicTags.def"
3826#undef MIPS_DYNAMIC_TAG
3827 }
3828 break;
3829
3830 case llvm::ELF::EM_PPC:
3831 switch (Type) {
3832#define PPC_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3833#include "llvm/BinaryFormat/DynamicTags.def"
3834#undef PPC_DYNAMIC_TAG
3835 }
3836 break;
3837
3838 case llvm::ELF::EM_PPC64:
3839 switch (Type) {
3840#define PPC64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3841#include "llvm/BinaryFormat/DynamicTags.def"
3842#undef PPC64_DYNAMIC_TAG
3843 }
3844 break;
3845
3846 case llvm::ELF::EM_RISCV:
3847 switch (Type) {
3848#define RISCV_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3849#include "llvm/BinaryFormat/DynamicTags.def"
3850#undef RISCV_DYNAMIC_TAG
3851 }
3852 break;
3853
3854 case llvm::ELF::EM_SPARC:
3855 case llvm::ELF::EM_SPARC32PLUS:
3856 case llvm::ELF::EM_SPARCV9:
3857 switch (Type) {
3858#define SPARC_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3859#include "llvm/BinaryFormat/DynamicTags.def"
3860#undef SPARC_DYNAMIC_TAG
3861 }
3862 break;
3863
3864 case llvm::ELF::EM_X86_64:
3865 switch (Type) {
3866#define X86_64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3867#include "llvm/BinaryFormat/DynamicTags.def"
3868#undef X86_64_DYNAMIC_TAG
3869 }
3870 break;
3871 }
3872#undef DYNAMIC_TAG
3873 switch (Type) {
3874// Now handle all dynamic tags except the architecture specific ones
3875#define AARCH64_DYNAMIC_TAG(name, value)
3876#define MIPS_DYNAMIC_TAG(name, value)
3877#define HEXAGON_DYNAMIC_TAG(name, value)
3878#define PPC_DYNAMIC_TAG(name, value)
3879#define PPC64_DYNAMIC_TAG(name, value)
3880#define RISCV_DYNAMIC_TAG(name, value)
3881#define SPARC_DYNAMIC_TAG(name, value)
3882#define X86_64_DYNAMIC_TAG(name, value)
3883// Also ignore marker tags such as DT_HIOS (maps to DT_VERNEEDNUM), etc.
3884#define DYNAMIC_TAG_MARKER(name, value)
3885#define DYNAMIC_TAG(name, value) \
3886 case value: \
3887 return #name;
3888#include "llvm/BinaryFormat/DynamicTags.def"
3889#undef DYNAMIC_TAG
3890#undef AARCH64_DYNAMIC_TAG
3891#undef MIPS_DYNAMIC_TAG
3892#undef HEXAGON_DYNAMIC_TAG
3893#undef PPC_DYNAMIC_TAG
3894#undef PPC64_DYNAMIC_TAG
3895#undef RISCV_DYNAMIC_TAG
3896#undef SPARC_DYNAMIC_TAG
3897#undef X86_64_DYNAMIC_TAG
3898#undef DYNAMIC_TAG_MARKER
3899#undef DYNAMIC_STRINGIFY_ENUM
3900 default:
3901 return "<unknown:>0x" + llvm::utohexstr(Type, true);
3902 }
3903}
3904
3907 if (m_dynamic_symbols.empty())
3908 return;
3909
3910 s->PutCString(".dynamic:\n");
3911 s->PutCString("IDX d_tag d_val/d_ptr\n");
3912 s->PutCString("==== ---------------- ------------------\n");
3913 uint32_t idx = 0;
3914 for (const auto &entry : m_dynamic_symbols) {
3915 s->Printf("[%2u] ", idx++);
3916 s->Printf(
3917 "%-16s 0x%16.16" PRIx64,
3918 getDynamicTagAsString(m_header.e_machine, entry.symbol.d_tag).c_str(),
3919 entry.symbol.d_ptr);
3920 if (!entry.name.empty())
3921 s->Printf(" \"%s\"", entry.name.c_str());
3922 s->EOL();
3923 }
3924}
3925
3927 if (!ParseHeader())
3928 return ArchSpec();
3929
3930 if (m_section_headers.empty()) {
3931 // Allow elf notes to be parsed which may affect the detected architecture.
3933 }
3934
3935 if (CalculateType() == eTypeCoreFile &&
3936 !m_arch_spec.TripleOSWasSpecified()) {
3937 // Core files don't have section headers yet they have PT_NOTE program
3938 // headers that might shed more light on the architecture
3939 for (const elf::ELFProgramHeader &H : ProgramHeaders()) {
3940 if (H.p_type != PT_NOTE || H.p_offset == 0 || H.p_filesz == 0)
3941 continue;
3942 DataExtractor data;
3943 if (data.SetData(*m_data_nsp, H.p_offset, H.p_filesz) == H.p_filesz) {
3944 UUID uuid;
3946 }
3947 }
3948 }
3949 return m_arch_spec;
3950}
3951
3953 switch (m_header.e_type) {
3954 case llvm::ELF::ET_NONE:
3955 // 0 - No file type
3956 return eTypeUnknown;
3957
3958 case llvm::ELF::ET_REL:
3959 // 1 - Relocatable file
3960 return eTypeObjectFile;
3961
3962 case llvm::ELF::ET_EXEC:
3963 // 2 - Executable file
3964 return eTypeExecutable;
3965
3966 case llvm::ELF::ET_DYN:
3967 // 3 - Shared object file
3968 return eTypeSharedLibrary;
3969
3970 case ET_CORE:
3971 // 4 - Core file
3972 return eTypeCoreFile;
3973
3974 default:
3975 break;
3976 }
3977 return eTypeUnknown;
3978}
3979
3981 switch (m_header.e_type) {
3982 case llvm::ELF::ET_NONE:
3983 // 0 - No file type
3984 return eStrataUnknown;
3985
3986 case llvm::ELF::ET_REL:
3987 // 1 - Relocatable file
3988 return eStrataUnknown;
3989
3990 case llvm::ELF::ET_EXEC:
3991 // 2 - Executable file
3992 {
3993 SectionList *section_list = GetSectionList();
3994 if (section_list) {
3995 llvm::StringRef loader_section_name(".interp");
3996 SectionSP loader_section =
3997 section_list->FindSectionByName(loader_section_name);
3998 if (loader_section) {
3999 char buffer[256];
4000 size_t read_size =
4001 ReadSectionData(loader_section.get(), 0, buffer, sizeof(buffer));
4002
4003 // We compare the content of .interp section
4004 // It will contains \0 when counting read_size, so the size needs to
4005 // decrease by one
4006 llvm::StringRef loader_name(buffer, read_size - 1);
4007 llvm::StringRef freebsd_kernel_loader_name("/red/herring");
4008 if (loader_name == freebsd_kernel_loader_name)
4009 return eStrataKernel;
4010 }
4011 }
4012 return eStrataUser;
4013 }
4014
4015 case llvm::ELF::ET_DYN:
4016 // 3 - Shared object file
4017 // TODO: is there any way to detect that an shared library is a kernel
4018 // related executable by inspecting the program headers, section headers,
4019 // symbols, or any other flag bits???
4020 return eStrataUnknown;
4021
4022 case ET_CORE:
4023 // 4 - Core file
4024 // TODO: is there any way to detect that an core file is a kernel
4025 // related executable by inspecting the program headers, section headers,
4026 // symbols, or any other flag bits???
4027 return eStrataUnknown;
4028
4029 default:
4030 break;
4031 }
4032 return eStrataUnknown;
4033}
4034
4036 lldb::offset_t section_offset, void *dst,
4037 size_t dst_len) {
4038 // If some other objectfile owns this data, pass this to them.
4039 if (section->GetObjectFile() != this)
4040 return section->GetObjectFile()->ReadSectionData(section, section_offset,
4041 dst, dst_len);
4042
4043 if (!section->Test(SHF_COMPRESSED))
4044 return ObjectFile::ReadSectionData(section, section_offset, dst, dst_len);
4045
4046 // For compressed sections we need to read to full data to be able to
4047 // decompress.
4048 DataExtractor data;
4049 ReadSectionData(section, data);
4050 return data.CopyData(section_offset, dst_len, dst);
4051}
4052
4054 DataExtractor &section_data) {
4055 // If some other objectfile owns this data, pass this to them.
4056 if (section->GetObjectFile() != this)
4057 return section->GetObjectFile()->ReadSectionData(section, section_data);
4058
4059 size_t result = ObjectFile::ReadSectionData(section, section_data);
4060 if (result == 0 || !(section->Get() & llvm::ELF::SHF_COMPRESSED))
4061 return result;
4062
4063 auto Decompressor = llvm::object::Decompressor::create(
4064 section->GetName(),
4065 {reinterpret_cast<const char *>(section_data.GetDataStart()),
4066 size_t(section_data.GetByteSize())},
4068 if (!Decompressor) {
4069 GetModule()->ReportWarning(
4070 "unable to initialize decompressor for section '{0}': {1}",
4071 section->GetName(), llvm::toString(Decompressor.takeError()).c_str());
4072 section_data.Clear();
4073 return 0;
4074 }
4075
4076 auto buffer_sp =
4077 std::make_shared<DataBufferHeap>(Decompressor->getDecompressedSize(), 0);
4078 if (auto error = Decompressor->decompress(
4079 {buffer_sp->GetBytes(), size_t(buffer_sp->GetByteSize())})) {
4080 GetModule()->ReportWarning("decompression of section '{0}' failed: {1}",
4081 section->GetName(),
4082 llvm::toString(std::move(error)).c_str());
4083 section_data.Clear();
4084 return 0;
4085 }
4086
4087 section_data.SetData(buffer_sp);
4088 return buffer_sp->GetByteSize();
4089}
4090
4091llvm::ArrayRef<ELFProgramHeader> ObjectFileELF::ProgramHeaders() {
4093 return m_program_headers;
4094}
4095
4097 // Try and read the program header from our cached m_data_nsp which can come
4098 // from the file on disk being mmap'ed or from the initial part of the ELF
4099 // file we read from memory and cached.
4101 if (data.GetByteSize() == H.p_filesz)
4102 return data;
4103 if (IsInMemory()) {
4104 // We have a ELF file in process memory, read the program header data from
4105 // the process.
4106 if (ProcessSP process_sp = m_process_wp.lock()) {
4107 const lldb::offset_t base_file_addr = GetBaseAddress().GetFileAddress();
4108 const addr_t load_bias = m_memory_addr - base_file_addr;
4109 const addr_t data_addr = H.p_vaddr + load_bias;
4110 if (DataBufferSP data_sp = ReadMemory(process_sp, data_addr, H.p_memsz))
4111 return DataExtractor(data_sp, GetByteOrder(), GetAddressByteSize());
4112 }
4113 }
4114 return DataExtractor();
4115}
4116
4118 for (const ELFProgramHeader &H : ProgramHeaders()) {
4119 if (H.p_paddr != 0)
4120 return true;
4121 }
4122 return false;
4123}
4124
4125std::vector<ObjectFile::LoadableData>
4127 // Create a list of loadable data from loadable segments, using physical
4128 // addresses if they aren't all null
4129 std::vector<LoadableData> loadables;
4130 bool should_use_paddr = AnySegmentHasPhysicalAddress();
4131 for (const ELFProgramHeader &H : ProgramHeaders()) {
4132 LoadableData loadable;
4133 if (H.p_type != llvm::ELF::PT_LOAD)
4134 continue;
4135 loadable.Dest = should_use_paddr ? H.p_paddr : H.p_vaddr;
4136 if (loadable.Dest == LLDB_INVALID_ADDRESS)
4137 continue;
4138 if (H.p_filesz == 0)
4139 continue;
4140 auto segment_data = GetSegmentData(H);
4141 loadable.Contents = llvm::ArrayRef<uint8_t>(segment_data.GetDataStart(),
4142 segment_data.GetByteSize());
4143 loadables.push_back(loadable);
4144 }
4145 return loadables;
4146}
4147
4150 uint64_t Offset) {
4152 Offset);
4153}
4154
4155std::optional<DataExtractor>
4157 uint64_t offset) {
4158 // ELFDynamic values contain a "d_ptr" member that will be a load address if
4159 // we have an ELF file read from memory, or it will be a file address if it
4160 // was read from a ELF file. This function will correctly fetch data pointed
4161 // to by the ELFDynamic::d_ptr, or return std::nullopt if the data isn't
4162 // available.
4163 const lldb::addr_t d_ptr_addr = dyn->d_ptr + offset;
4164 if (ProcessSP process_sp = m_process_wp.lock()) {
4165 if (DataBufferSP data_sp = ReadMemory(process_sp, d_ptr_addr, length))
4166 return DataExtractor(data_sp, GetByteOrder(), GetAddressByteSize());
4167 } else {
4168 // We have an ELF file with no section headers or we didn't find the
4169 // .dynamic section. Try and find the .dynstr section.
4170 Address addr;
4171 if (!addr.ResolveAddressUsingFileSections(d_ptr_addr, GetSectionList()))
4172 return std::nullopt;
4173 DataExtractor data;
4174 addr.GetSection()->GetSectionData(data);
4175 return DataExtractor(data, d_ptr_addr - addr.GetSection()->GetFileAddress(),
4176 length);
4177 }
4178 return std::nullopt;
4179}
4180
4181std::optional<DataExtractor> ObjectFileELF::GetDynstrData() {
4182 if (SectionList *section_list = GetSectionList()) {
4183 // Find the SHT_DYNAMIC section.
4184 if (Section *dynamic =
4185 section_list
4186 ->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
4187 .get()) {
4188 assert(dynamic->GetObjectFile() == this);
4189 if (const ELFSectionHeaderInfo *header =
4190 GetSectionHeaderByIndex(dynamic->GetID())) {
4191 // sh_link: section header index of string table used by entries in
4192 // the section.
4193 if (Section *dynstr =
4194 section_list->FindSectionByID(header->sh_link).get()) {
4195 DataExtractor data;
4196 if (ReadSectionData(dynstr, data))
4197 return data;
4198 }
4199 }
4200 }
4201 }
4202
4203 // Every ELF file which represents an executable or shared library has
4204 // mandatory .dynamic entries. Two of these values are DT_STRTAB and DT_STRSZ
4205 // and represent the dynamic symbol tables's string table. These are needed
4206 // by the dynamic loader and we can read them from a process' address space.
4207 //
4208 // When loading and ELF file from memory, only the program headers are
4209 // guaranteed end up being mapped into memory, and we can find these values in
4210 // the PT_DYNAMIC segment.
4211 const ELFDynamic *strtab = FindDynamicSymbol(DT_STRTAB);
4212 const ELFDynamic *strsz = FindDynamicSymbol(DT_STRSZ);
4213 if (strtab == nullptr || strsz == nullptr)
4214 return std::nullopt;
4215
4216 return ReadDataFromDynamic(strtab, strsz->d_val, /*offset=*/0);
4217}
4218
4219std::optional<lldb_private::DataExtractor> ObjectFileELF::GetDynamicData() {
4220 DataExtractor data;
4221 // The PT_DYNAMIC program header describes where the .dynamic section is and
4222 // doesn't require parsing section headers. The PT_DYNAMIC is required by
4223 // executables and shared libraries so it will always be available.
4224 for (const ELFProgramHeader &H : ProgramHeaders()) {
4225 if (H.p_type == llvm::ELF::PT_DYNAMIC) {
4226 data = GetSegmentData(H);
4227 if (data.GetByteSize() > 0) {
4228 m_dynamic_base_addr = H.p_vaddr;
4229 return data;
4230 }
4231 }
4232 }
4233 // Fall back to using section headers.
4234 if (SectionList *section_list = GetSectionList()) {
4235 // Find the SHT_DYNAMIC section.
4236 if (Section *dynamic =
4237 section_list
4238 ->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
4239 .get()) {
4240 assert(dynamic->GetObjectFile() == this);
4241 if (ReadSectionData(dynamic, data)) {
4242 m_dynamic_base_addr = dynamic->GetFileAddress();
4243 return data;
4244 }
4245 }
4246 }
4247 return std::nullopt;
4248}
4249
4251 const ELFDynamic *hash = FindDynamicSymbol(DT_HASH);
4252 if (hash == nullptr)
4253 return std::nullopt;
4254
4255 // The DT_HASH header looks like this:
4256 struct DtHashHeader {
4257 uint32_t nbucket;
4258 uint32_t nchain;
4259 };
4260 if (auto data = ReadDataFromDynamic(hash, 8)) {
4261 // We don't need the number of buckets value "nbucket", we just need the
4262 // "nchain" value which contains the number of symbols.
4263 offset_t offset = offsetof(DtHashHeader, nchain);
4264 return data->GetU32(&offset);
4265 }
4266
4267 return std::nullopt;
4268}
4269
4271 const ELFDynamic *gnu_hash = FindDynamicSymbol(DT_GNU_HASH);
4272 if (gnu_hash == nullptr)
4273 return std::nullopt;
4274
4275 // Create a DT_GNU_HASH header
4276 // https://flapenguin.me/elf-dt-gnu-hash
4277 struct DtGnuHashHeader {
4278 uint32_t nbuckets = 0;
4279 uint32_t symoffset = 0;
4280 uint32_t bloom_size = 0;
4281 uint32_t bloom_shift = 0;
4282 };
4283 uint32_t num_symbols = 0;
4284 // Read enogh data for the DT_GNU_HASH header so we can extract the values.
4285 if (auto data = ReadDataFromDynamic(gnu_hash, sizeof(DtGnuHashHeader))) {
4286 offset_t offset = 0;
4287 DtGnuHashHeader header;
4288 header.nbuckets = data->GetU32(&offset);
4289 header.symoffset = data->GetU32(&offset);
4290 header.bloom_size = data->GetU32(&offset);
4291 header.bloom_shift = data->GetU32(&offset);
4292 const size_t addr_size = GetAddressByteSize();
4293 const addr_t buckets_offset =
4294 sizeof(DtGnuHashHeader) + addr_size * header.bloom_size;
4295 std::vector<uint32_t> buckets;
4296 if (auto bucket_data = ReadDataFromDynamic(gnu_hash, header.nbuckets * 4,
4297 buckets_offset)) {
4298 offset = 0;
4299 for (uint32_t i = 0; i < header.nbuckets; ++i)
4300 buckets.push_back(bucket_data->GetU32(&offset));
4301 // Locate the chain that handles the largest index bucket.
4302 uint32_t last_symbol = 0;
4303 for (uint32_t bucket_value : buckets)
4304 last_symbol = std::max(bucket_value, last_symbol);
4305 if (last_symbol < header.symoffset) {
4306 num_symbols = header.symoffset;
4307 } else {
4308 // Walk the bucket's chain to add the chain length to the total.
4309 const addr_t chains_base_offset = buckets_offset + header.nbuckets * 4;
4310 for (;;) {
4311 if (auto chain_entry_data = ReadDataFromDynamic(
4312 gnu_hash, 4,
4313 chains_base_offset + (last_symbol - header.symoffset) * 4)) {
4314 offset = 0;
4315 uint32_t chain_entry = chain_entry_data->GetU32(&offset);
4316 ++last_symbol;
4317 // If the low bit is set, this entry is the end of the chain.
4318 if (chain_entry & 1)
4319 break;
4320 } else {
4321 break;
4322 }
4323 }
4324 num_symbols = last_symbol;
4325 }
4326 }
4327 }
4328 if (num_symbols > 0)
4329 return num_symbols;
4330
4331 return std::nullopt;
4332}
4333
4334std::optional<DataExtractor>
4336 // Every ELF file which represents an executable or shared library has
4337 // mandatory .dynamic entries. The DT_SYMTAB value contains a pointer to the
4338 // symbol table, and DT_SYMENT contains the size of a symbol table entry.
4339 // We then can use either the DT_HASH or DT_GNU_HASH to find the number of
4340 // symbols in the symbol table as the symbol count is not stored in the
4341 // .dynamic section as a key/value pair.
4342 //
4343 // When loading and ELF file from memory, only the program headers end up
4344 // being mapped into memory, and we can find these values in the PT_DYNAMIC
4345 // segment.
4346 num_symbols = 0;
4347 // Get the process in case this is an in memory ELF file.
4348 ProcessSP process_sp(m_process_wp.lock());
4349 const ELFDynamic *symtab = FindDynamicSymbol(DT_SYMTAB);
4350 const ELFDynamic *syment = FindDynamicSymbol(DT_SYMENT);
4351 // DT_SYMTAB and DT_SYMENT are mandatory.
4352 if (symtab == nullptr || syment == nullptr)
4353 return std::nullopt;
4354
4355 if (std::optional<uint32_t> syms = GetNumSymbolsFromDynamicHash())
4356 num_symbols = *syms;
4357 else if (std::optional<uint32_t> syms = GetNumSymbolsFromDynamicGnuHash())
4358 num_symbols = *syms;
4359 else
4360 return std::nullopt;
4361 if (num_symbols == 0)
4362 return std::nullopt;
4363 return ReadDataFromDynamic(symtab, syment->d_val * num_symbols);
4364}
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 char FindRISCVMappingSymbol(llvm::StringRef symbol_name)
static uint32_t subTypeFromElfHeader(const elf::ELFHeader &header)
static uint32_t calc_crc32(uint32_t init, const DataExtractor &data)
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 char FindArmAarch64MappingSymbol(llvm::StringRef symbol_name)
static const elf_word LLDB_NT_FREEBSD_ABI_SIZE
static const elf_word LLDB_NT_GNU_ABI_TAG
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 uint8_t * GetRelocationTarget(DataExtractor &debug_data, Section *rel_section, uint64_t offset, size_t size)
Returns the size bytes at offset in debug_data for a relocation to patch, or reports an error and ret...
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.
size_t GetSharedDataOffset() const
Get the shared data offset.
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.
bool ValidOffsetForDataOfSize(lldb::offset_t offset, lldb::offset_t length) const
Test the availability of length bytes of data from offset.
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.
std::optional< llvm::StringRef > PeekCStr(lldb::offset_t offset) const
Peek at a null-terminated C string at offset.
lldb::DataBufferSP GetSharedDataBuffer() const
uint8_t GetU8(lldb::offset_t *offset_ptr) const
Extract a uint8_t value from *offset_ptr.
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:76
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:274
lldb::offset_t GetFileOffset() const
Definition Section.h:180
llvm::StringRef GetName() const
Definition Section.h:210
ObjectFile * GetObjectFile()
Definition Section.h:230
lldb::offset_t GetFileSize() const
Definition Section.h:186
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:2440
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:2429
bool SetSectionLoadAddress(const lldb::SectionSP &section, lldb::addr_t load_addr, bool warn_multiple=false)
Definition Target.cpp:3516
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
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