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