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 if (m_filespec_up)
1057 return m_filespec_up->GetSize();
1058
1059 m_filespec_up = std::make_unique<FileSpecList>();
1060
1061 if (ParseDynamicSymbols()) {
1062 for (const auto &entry : m_dynamic_symbols) {
1063 if (entry.symbol.d_tag != DT_NEEDED)
1064 continue;
1065 if (!entry.name.empty()) {
1066 FileSpec file_spec(entry.name);
1067 FileSystem::Instance().Resolve(file_spec);
1068 m_filespec_up->Append(file_spec);
1069 }
1070 }
1071 }
1072 return m_filespec_up->GetSize();
1073}
1074
1075// GetProgramHeaderInfo
1077 DataExtractor &object_data,
1078 const ELFHeader &header) {
1079 // We have already parsed the program headers
1080 if (!program_headers.empty())
1081 return program_headers.size();
1082
1083 // If there are no program headers to read we are done.
1084 if (header.e_phnum == 0)
1085 return 0;
1086
1087 program_headers.resize(header.e_phnum);
1088 if (program_headers.size() != header.e_phnum)
1089 return 0;
1090
1091 const size_t ph_size = header.e_phnum * header.e_phentsize;
1092 const elf_off ph_offset = header.e_phoff;
1093 DataExtractor data;
1094 if (data.SetData(object_data, ph_offset, ph_size) != ph_size)
1095 return 0;
1096
1097 uint32_t idx;
1098 lldb::offset_t offset;
1099 for (idx = 0, offset = 0; idx < header.e_phnum; ++idx) {
1100 if (!program_headers[idx].Parse(data, &offset))
1101 break;
1102 }
1103
1104 if (idx < program_headers.size())
1105 program_headers.resize(idx);
1106
1107 return program_headers.size();
1108}
1109
1110// ParseProgramHeaders
1114
1117 lldb_private::ArchSpec &arch_spec,
1118 lldb_private::UUID &uuid) {
1119 Log *log = GetLog(LLDBLog::Modules);
1120 Status error;
1121
1122 lldb::offset_t offset = 0;
1123
1124 while (true) {
1125 // Parse the note header. If this fails, bail out.
1126 const lldb::offset_t note_offset = offset;
1127 ELFNote note = ELFNote();
1128 if (!note.Parse(data, &offset)) {
1129 // We're done.
1130 return error;
1131 }
1132
1133 LLDB_LOGF(log, "ObjectFileELF::%s parsing note name='%s', type=%" PRIu32,
1134 __FUNCTION__, note.n_name.c_str(), note.n_type);
1135
1136 // Process FreeBSD ELF notes.
1137 if ((note.n_name == LLDB_NT_OWNER_FREEBSD) &&
1138 (note.n_type == LLDB_NT_FREEBSD_ABI_TAG) &&
1139 (note.n_descsz == LLDB_NT_FREEBSD_ABI_SIZE)) {
1140 // Pull out the min version info.
1141 uint32_t version_info;
1142 if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1143 error =
1144 Status::FromErrorString("failed to read FreeBSD ABI note payload");
1145 return error;
1146 }
1147
1148 // Convert the version info into a major/minor number.
1149 const uint32_t version_major = version_info / 100000;
1150 const uint32_t version_minor = (version_info / 1000) % 100;
1151
1152 char os_name[32];
1153 snprintf(os_name, sizeof(os_name), "freebsd%" PRIu32 ".%" PRIu32,
1154 version_major, version_minor);
1155
1156 // Set the elf OS version to FreeBSD. Also clear the vendor.
1157 arch_spec.GetTriple().setOSName(os_name);
1158 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1159
1160 LLDB_LOGF(log,
1161 "ObjectFileELF::%s detected FreeBSD %" PRIu32 ".%" PRIu32
1162 ".%" PRIu32,
1163 __FUNCTION__, version_major, version_minor,
1164 static_cast<uint32_t>(version_info % 1000));
1165 }
1166 // Process GNU ELF notes.
1167 else if (note.n_name == LLDB_NT_OWNER_GNU) {
1168 switch (note.n_type) {
1170 if (note.n_descsz == LLDB_NT_GNU_ABI_SIZE) {
1171 // Pull out the min OS version supporting the ABI.
1172 uint32_t version_info[4];
1173 if (data.GetU32(&offset, &version_info[0], note.n_descsz / 4) ==
1174 nullptr) {
1175 error =
1176 Status::FromErrorString("failed to read GNU ABI note payload");
1177 return error;
1178 }
1179
1180 // Set the OS per the OS field.
1181 switch (version_info[0]) {
1183 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1184 arch_spec.GetTriple().setVendor(
1185 llvm::Triple::VendorType::UnknownVendor);
1186 LLDB_LOGF(log,
1187 "ObjectFileELF::%s detected Linux, min version %" PRIu32
1188 ".%" PRIu32 ".%" PRIu32,
1189 __FUNCTION__, version_info[1], version_info[2],
1190 version_info[3]);
1191 // FIXME we have the minimal version number, we could be propagating
1192 // that. version_info[1] = OS Major, version_info[2] = OS Minor,
1193 // version_info[3] = Revision.
1194 break;
1196 arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
1197 arch_spec.GetTriple().setVendor(
1198 llvm::Triple::VendorType::UnknownVendor);
1199 LLDB_LOGF(log,
1200 "ObjectFileELF::%s detected Hurd (unsupported), min "
1201 "version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1202 __FUNCTION__, version_info[1], version_info[2],
1203 version_info[3]);
1204 break;
1206 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Solaris);
1207 arch_spec.GetTriple().setVendor(
1208 llvm::Triple::VendorType::UnknownVendor);
1209 LLDB_LOGF(log,
1210 "ObjectFileELF::%s detected Solaris, min version %" PRIu32
1211 ".%" PRIu32 ".%" PRIu32,
1212 __FUNCTION__, version_info[1], version_info[2],
1213 version_info[3]);
1214 break;
1215 default:
1216 LLDB_LOGF(log,
1217 "ObjectFileELF::%s unrecognized OS in note, id %" PRIu32
1218 ", min version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1219 __FUNCTION__, version_info[0], version_info[1],
1220 version_info[2], version_info[3]);
1221 break;
1222 }
1223 }
1224 break;
1225
1227 // Only bother processing this if we don't already have the uuid set.
1228 if (!uuid.IsValid()) {
1229 // 16 bytes is UUID|MD5, 20 bytes is SHA1. Other linkers may produce a
1230 // build-id of a different length. Accept it as long as it's at least
1231 // 4 bytes as it will be better than our own crc32.
1232 if (note.n_descsz >= 4) {
1233 if (const uint8_t *buf = data.PeekData(offset, note.n_descsz)) {
1234 // Save the build id as the UUID for the module.
1235 uuid = UUID(buf, note.n_descsz);
1236 } else {
1238 "failed to read GNU_BUILD_ID note payload");
1239 return error;
1240 }
1241 }
1242 }
1243 break;
1244 }
1245 if (arch_spec.IsMIPS() &&
1246 arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)
1247 // The note.n_name == LLDB_NT_OWNER_GNU is valid for Linux platform
1248 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1249 }
1250 // Process NetBSD ELF executables and shared libraries
1251 else if ((note.n_name == LLDB_NT_OWNER_NETBSD) &&
1252 (note.n_type == LLDB_NT_NETBSD_IDENT_TAG) &&
1253 (note.n_descsz == LLDB_NT_NETBSD_IDENT_DESCSZ) &&
1254 (note.n_namesz == LLDB_NT_NETBSD_IDENT_NAMESZ)) {
1255 // Pull out the version info.
1256 uint32_t version_info;
1257 if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1258 error =
1259 Status::FromErrorString("failed to read NetBSD ABI note payload");
1260 return error;
1261 }
1262 // Convert the version info into a major/minor/patch number.
1263 // #define __NetBSD_Version__ MMmmrrpp00
1264 //
1265 // M = major version
1266 // m = minor version; a minor number of 99 indicates current.
1267 // r = 0 (since NetBSD 3.0 not used)
1268 // p = patchlevel
1269 const uint32_t version_major = version_info / 100000000;
1270 const uint32_t version_minor = (version_info % 100000000) / 1000000;
1271 const uint32_t version_patch = (version_info % 10000) / 100;
1272 // Set the elf OS version to NetBSD. Also clear the vendor.
1273 arch_spec.GetTriple().setOSName(
1274 llvm::formatv("netbsd{0}.{1}.{2}", version_major, version_minor,
1275 version_patch).str());
1276 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1277 }
1278 // Process NetBSD ELF core(5) notes
1279 else if ((note.n_name == LLDB_NT_OWNER_NETBSDCORE) &&
1280 (note.n_type == LLDB_NT_NETBSD_PROCINFO)) {
1281 // Set the elf OS version to NetBSD. Also clear the vendor.
1282 arch_spec.GetTriple().setOS(llvm::Triple::OSType::NetBSD);
1283 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1284 }
1285 // Process OpenBSD ELF notes.
1286 else if (note.n_name == LLDB_NT_OWNER_OPENBSD) {
1287 // Set the elf OS version to OpenBSD. Also clear the vendor.
1288 arch_spec.GetTriple().setOS(llvm::Triple::OSType::OpenBSD);
1289 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1290 } else if (note.n_name == LLDB_NT_OWNER_ANDROID) {
1291 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1292 arch_spec.GetTriple().setEnvironment(
1293 llvm::Triple::EnvironmentType::Android);
1294 } else if (note.n_name == LLDB_NT_OWNER_LINUX) {
1295 // This is sometimes found in core files and usually contains extended
1296 // register info
1297 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1298 } else if (note.n_name == LLDB_NT_OWNER_CORE) {
1299 // Parse the NT_FILE to look for stuff in paths to shared libraries
1300 // The contents look like this in a 64 bit ELF core file:
1301 //
1302 // count = 0x000000000000000a (10)
1303 // page_size = 0x0000000000001000 (4096)
1304 // Index start end file_ofs path
1305 // ===== ------------------ ------------------ ------------------ -------------------------------------
1306 // [ 0] 0x0000000000401000 0x0000000000000000 /tmp/a.out
1307 // [ 1] 0x0000000000600000 0x0000000000601000 0x0000000000000000 /tmp/a.out
1308 // [ 2] 0x0000000000601000 0x0000000000602000 0x0000000000000001 /tmp/a.out
1309 // [ 3] 0x00007fa79c9ed000 0x00007fa79cba8000 0x0000000000000000 /lib/x86_64-linux-gnu/libc-2.19.so
1310 // [ 4] 0x00007fa79cba8000 0x00007fa79cda7000 0x00000000000001bb /lib/x86_64-linux-gnu/libc-2.19.so
1311 // [ 5] 0x00007fa79cda7000 0x00007fa79cdab000 0x00000000000001ba /lib/x86_64-linux-gnu/libc-2.19.so
1312 // [ 6] 0x00007fa79cdab000 0x00007fa79cdad000 0x00000000000001be /lib/x86_64-linux-gnu/libc-2.19.so
1313 // [ 7] 0x00007fa79cdb2000 0x00007fa79cdd5000 0x0000000000000000 /lib/x86_64-linux-gnu/ld-2.19.so
1314 // [ 8] 0x00007fa79cfd4000 0x00007fa79cfd5000 0x0000000000000022 /lib/x86_64-linux-gnu/ld-2.19.so
1315 // [ 9] 0x00007fa79cfd5000 0x00007fa79cfd6000 0x0000000000000023 /lib/x86_64-linux-gnu/ld-2.19.so
1316 //
1317 // In the 32 bit ELFs the count, page_size, start, end, file_ofs are
1318 // uint32_t.
1319 //
1320 // For reference: see readelf source code (in binutils).
1321 if (note.n_type == NT_FILE) {
1322 uint64_t count = data.GetAddress(&offset);
1323 const char *cstr;
1324 data.GetAddress(&offset); // Skip page size
1325 offset += count * 3 *
1326 data.GetAddressByteSize(); // Skip all start/end/file_ofs
1327 for (size_t i = 0; i < count; ++i) {
1328 cstr = data.GetCStr(&offset);
1329 if (cstr == nullptr) {
1331 "ObjectFileELF::%s trying to read "
1332 "at an offset after the end "
1333 "(GetCStr returned nullptr)",
1334 __FUNCTION__);
1335 return error;
1336 }
1337 llvm::StringRef path(cstr);
1338 if (path.contains("/lib/x86_64-linux-gnu") || path.contains("/lib/i386-linux-gnu")) {
1339 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1340 break;
1341 }
1342 }
1343 if (arch_spec.IsMIPS() &&
1344 arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)
1345 // In case of MIPSR6, the LLDB_NT_OWNER_GNU note is missing for some
1346 // cases (e.g. compile with -nostdlib) Hence set OS to Linux
1347 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1348 }
1349 }
1350
1351 // Calculate the offset of the next note just in case "offset" has been
1352 // used to poke at the contents of the note data
1353 offset = note_offset + note.GetByteSize();
1354 }
1355
1356 return error;
1357}
1358
1360 ArchSpec &arch_spec) {
1361 lldb::offset_t Offset = 0;
1362
1363 uint8_t FormatVersion = data.GetU8(&Offset);
1364 if (FormatVersion != llvm::ELFAttrs::Format_Version)
1365 return;
1366
1367 Offset = Offset + sizeof(uint32_t); // Section Length
1368 llvm::StringRef VendorName = data.GetCStr(&Offset);
1369
1370 if (VendorName != "aeabi")
1371 return;
1372
1373 if (arch_spec.GetTriple().getEnvironment() ==
1374 llvm::Triple::UnknownEnvironment)
1375 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
1376
1377 while (Offset < length) {
1378 uint8_t Tag = data.GetU8(&Offset);
1379 uint32_t Size = data.GetU32(&Offset);
1380
1381 if (Tag != llvm::ARMBuildAttrs::File || Size == 0)
1382 continue;
1383
1384 while (Offset < length) {
1385 uint64_t Tag = data.GetULEB128(&Offset);
1386 switch (Tag) {
1387 default:
1388 if (Tag < 32)
1389 data.GetULEB128(&Offset);
1390 else if (Tag % 2 == 0)
1391 data.GetULEB128(&Offset);
1392 else
1393 data.GetCStr(&Offset);
1394
1395 break;
1396
1397 case llvm::ARMBuildAttrs::CPU_raw_name:
1398 case llvm::ARMBuildAttrs::CPU_name:
1399 data.GetCStr(&Offset);
1400
1401 break;
1402
1403 case llvm::ARMBuildAttrs::ABI_VFP_args: {
1404 uint64_t VFPArgs = data.GetULEB128(&Offset);
1405
1406 if (VFPArgs == llvm::ARMBuildAttrs::BaseAAPCS) {
1407 if (arch_spec.GetTriple().getEnvironment() ==
1408 llvm::Triple::UnknownEnvironment ||
1409 arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABIHF)
1410 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
1411
1413 } else if (VFPArgs == llvm::ARMBuildAttrs::HardFPAAPCS) {
1414 if (arch_spec.GetTriple().getEnvironment() ==
1415 llvm::Triple::UnknownEnvironment ||
1416 arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABI)
1417 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABIHF);
1418
1420 }
1421
1422 break;
1423 }
1424 }
1425 }
1426 }
1427}
1428
1429static std::optional<lldb::offset_t>
1431 uint32_t length, llvm::StringRef name) {
1432 uint32_t section_length = 0;
1433 llvm::StringRef section_name;
1434 do {
1435 offset += section_length;
1436 // Sub-section's size and name are included in the total sub-section length.
1437 // Don't shift the offset here, so it will point at the beginning of the
1438 // sub-section and could be used as a return value.
1439 auto tmp_offset = offset;
1440 section_length = data.GetU32(&tmp_offset);
1441 section_name = data.GetCStr(&tmp_offset);
1442 } while (section_name != name && offset + section_length < length);
1443
1444 if (section_name == name)
1445 return offset;
1446
1447 return std::nullopt;
1448}
1449
1450static std::optional<lldb::offset_t>
1452 unsigned tag) {
1453 // Consume a sub-section size and name to shift the offset at the beginning of
1454 // the sub-sub-sections list.
1455 auto parent_section_length = data.GetU32(&offset);
1456 data.GetCStr(&offset);
1457 auto parent_section_end_offset = offset + parent_section_length;
1458
1459 uint32_t section_length = 0;
1460 unsigned section_tag = 0;
1461 do {
1462 offset += section_length;
1463 // Similar to sub-section sub-sub-section's tag and size are included in the
1464 // total sub-sub-section length.
1465 auto tmp_offset = offset;
1466 section_tag = data.GetULEB128(&tmp_offset);
1467 section_length = data.GetU32(&tmp_offset);
1468 } while (section_tag != tag &&
1469 offset + section_length < parent_section_end_offset);
1470
1471 if (section_tag == tag)
1472 return offset;
1473
1474 return std::nullopt;
1475}
1476
1477static std::optional<std::variant<uint64_t, llvm::StringRef>>
1479 unsigned tag) {
1480 // Consume a sub-sub-section tag and size to shift the offset at the beginning
1481 // of the attribute list.
1482 data.GetULEB128(&offset);
1483 auto parent_section_length = data.GetU32(&offset);
1484 auto parent_section_end_offset = offset + parent_section_length;
1485
1486 std::variant<uint64_t, llvm::StringRef> result;
1487 unsigned attribute_tag = 0;
1488 do {
1489 attribute_tag = data.GetULEB128(&offset);
1490 // From the riscv psABI document:
1491 // RISC-V attributes have a string value if the tag number is odd and an
1492 // integer value if the tag number is even.
1493 if (attribute_tag % 2)
1494 result = data.GetCStr(&offset);
1495 else
1496 result = data.GetULEB128(&offset);
1497 } while (attribute_tag != tag && offset < parent_section_end_offset);
1498
1499 if (attribute_tag == tag)
1500 return result;
1501
1502 return std::nullopt;
1503}
1504
1506 uint64_t length, ArchSpec &arch_spec) {
1507 Log *log = GetLog(LLDBLog::Modules);
1508
1509 lldb::offset_t offset = 0;
1510
1511 // According to the riscv psABI, the .riscv.attributes section has the
1512 // following hierarchical structure:
1513 //
1514 // Section:
1515 // .riscv.attributes {
1516 // - (uint8_t) format
1517 // - Sub-Section 1 {
1518 // * (uint32_t) length
1519 // * (c_str) name
1520 // * Sub-Sub-Section 1.1 {
1521 // > (uleb128_t) tag
1522 // > (uint32_t) length
1523 // > (uleb128_t) attribute_tag_1.1.1
1524 // $ (c_str or uleb128_t) value
1525 // > (uleb128_t) attribute_tag_1.1.2
1526 // $ (c_str or uleb128_t) value
1527 // ...
1528 // Other attributes...
1529 // ...
1530 // > (uleb128_t) attribute_tag_1.1.N
1531 // $ (c_str or uleb128_t) value
1532 // }
1533 // * Sub-Sub-Section 1.2 {
1534 // ...
1535 // Sub-Sub-Section structure...
1536 // ...
1537 // }
1538 // ...
1539 // Other sub-sub-sections...
1540 // ...
1541 // }
1542 // - Sub-Section 2 {
1543 // ...
1544 // Sub-Section structure...
1545 // ...
1546 // }
1547 // ...
1548 // Other sub-sections...
1549 // ...
1550 // }
1551
1552 uint8_t format_version = data.GetU8(&offset);
1553 if (format_version != llvm::ELFAttrs::Format_Version)
1554 return;
1555
1556 auto subsection_or_opt =
1557 FindSubSectionOffsetByName(data, offset, length, "riscv");
1558 if (!subsection_or_opt) {
1559 LLDB_LOGF(log,
1560 "ObjectFileELF::%s Ill-formed .riscv.attributes section: "
1561 "mandatory 'riscv' sub-section was not preserved",
1562 __FUNCTION__);
1563 return;
1564 }
1565
1566 auto subsubsection_or_opt = FindSubSubSectionOffsetByTag(
1567 data, *subsection_or_opt, llvm::ELFAttrs::File);
1568 if (!subsubsection_or_opt)
1569 return;
1570
1571 auto value_or_opt = GetAttributeValueByTag(data, *subsubsection_or_opt,
1572 llvm::RISCVAttrs::ARCH);
1573 if (!value_or_opt)
1574 return;
1575
1576 auto normalized_isa_info = llvm::RISCVISAInfo::parseNormalizedArchString(
1577 std::get<llvm::StringRef>(*value_or_opt));
1578 if (llvm::errorToBool(normalized_isa_info.takeError()))
1579 return;
1580
1581 llvm::SubtargetFeatures features;
1582 features.addFeaturesVector((*normalized_isa_info)->toFeatures());
1583 arch_spec.SetSubtargetFeatures(std::move(features));
1584
1585 // Additional verification of the arch string. This is primarily needed to
1586 // warn users if the executable file contains conflicting RISC-V extensions
1587 // that could lead to invalid disassembler output.
1588 auto isa_info = llvm::RISCVISAInfo::parseArchString(
1589 std::get<llvm::StringRef>(*value_or_opt),
1590 /* EnableExperimentalExtension=*/true);
1591 if (auto error = isa_info.takeError()) {
1592 StreamString ss;
1593 ss << "the .riscv.attributes section contains an invalid RISC-V arch "
1594 "string: "
1595 << llvm::toString(std::move(error))
1596 << "\n\tThis could result in misleading disassembler output\n";
1598 }
1599}
1600
1601// GetSectionHeaderInfo
1603 DataExtractor &object_data,
1604 const elf::ELFHeader &header,
1605 lldb_private::UUID &uuid,
1606 std::string &gnu_debuglink_file,
1607 uint32_t &gnu_debuglink_crc,
1608 ArchSpec &arch_spec) {
1609 // Don't reparse the section headers if we already did that.
1610 if (!section_headers.empty())
1611 return section_headers.size();
1612
1613 // Only initialize the arch_spec to okay defaults if they're not already set.
1614 // We'll refine this with note data as we parse the notes.
1615 if (arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) {
1616 llvm::Triple::OSType ostype;
1617 llvm::Triple::OSType spec_ostype;
1618 const uint32_t sub_type = subTypeFromElfHeader(header);
1619 arch_spec.SetArchitecture(eArchTypeELF, header.e_machine, sub_type,
1620 header.e_ident[EI_OSABI]);
1621
1622 // Validate if it is ok to remove GetOsFromOSABI. Note, that now the OS is
1623 // determined based on EI_OSABI flag and the info extracted from ELF notes
1624 // (see RefineModuleDetailsFromNote). However in some cases that still
1625 // might be not enough: for example a shared library might not have any
1626 // notes at all and have EI_OSABI flag set to System V, as result the OS
1627 // will be set to UnknownOS.
1628 GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
1629 spec_ostype = arch_spec.GetTriple().getOS();
1630 assert(spec_ostype == ostype);
1631 UNUSED_IF_ASSERT_DISABLED(spec_ostype);
1632 }
1633
1634 if (arch_spec.GetMachine() == llvm::Triple::mips ||
1635 arch_spec.GetMachine() == llvm::Triple::mipsel ||
1636 arch_spec.GetMachine() == llvm::Triple::mips64 ||
1637 arch_spec.GetMachine() == llvm::Triple::mips64el) {
1638 switch (header.e_flags & llvm::ELF::EF_MIPS_ARCH_ASE) {
1639 case llvm::ELF::EF_MIPS_MICROMIPS:
1641 break;
1642 case llvm::ELF::EF_MIPS_ARCH_ASE_M16:
1644 break;
1645 case llvm::ELF::EF_MIPS_ARCH_ASE_MDMX:
1647 break;
1648 default:
1649 break;
1650 }
1651 }
1652
1653 if (arch_spec.GetMachine() == llvm::Triple::arm ||
1654 arch_spec.GetMachine() == llvm::Triple::thumb) {
1655 if (header.e_flags & llvm::ELF::EF_ARM_SOFT_FLOAT)
1657 else if (header.e_flags & llvm::ELF::EF_ARM_VFP_FLOAT)
1659 }
1660
1661 if (arch_spec.GetMachine() == llvm::Triple::riscv32 ||
1662 arch_spec.GetMachine() == llvm::Triple::riscv64) {
1663 uint32_t flags = arch_spec.GetFlags();
1664
1665 if (header.e_flags & llvm::ELF::EF_RISCV_RVC)
1666 flags |= ArchSpec::eRISCV_rvc;
1667 if (header.e_flags & llvm::ELF::EF_RISCV_RVE)
1668 flags |= ArchSpec::eRISCV_rve;
1669
1670 if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_SINGLE) ==
1671 llvm::ELF::EF_RISCV_FLOAT_ABI_SINGLE)
1673 else if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_DOUBLE) ==
1674 llvm::ELF::EF_RISCV_FLOAT_ABI_DOUBLE)
1676 else if ((header.e_flags & llvm::ELF::EF_RISCV_FLOAT_ABI_QUAD) ==
1677 llvm::ELF::EF_RISCV_FLOAT_ABI_QUAD)
1679
1680 arch_spec.SetFlags(flags);
1681 }
1682
1683 if (arch_spec.GetMachine() == llvm::Triple::loongarch32 ||
1684 arch_spec.GetMachine() == llvm::Triple::loongarch64) {
1685 uint32_t flags = arch_spec.GetFlags();
1686 switch (header.e_flags & llvm::ELF::EF_LOONGARCH_ABI_MODIFIER_MASK) {
1687 case llvm::ELF::EF_LOONGARCH_ABI_SINGLE_FLOAT:
1689 break;
1690 case llvm::ELF::EF_LOONGARCH_ABI_DOUBLE_FLOAT:
1692 break;
1693 case llvm::ELF::EF_LOONGARCH_ABI_SOFT_FLOAT:
1694 break;
1695 }
1696
1697 arch_spec.SetFlags(flags);
1698 }
1699
1700 // If there are no section headers we are done.
1701 if (header.e_shnum == 0)
1702 return 0;
1703
1704 Log *log = GetLog(LLDBLog::Modules);
1705
1706 section_headers.resize(header.e_shnum);
1707 if (section_headers.size() != header.e_shnum)
1708 return 0;
1709
1710 const size_t sh_size = header.e_shnum * header.e_shentsize;
1711 const elf_off sh_offset = header.e_shoff;
1712 DataExtractor sh_data;
1713 if (sh_data.SetData(object_data, sh_offset, sh_size) != sh_size)
1714 return 0;
1715
1716 uint32_t idx;
1717 lldb::offset_t offset;
1718 for (idx = 0, offset = 0; idx < header.e_shnum; ++idx) {
1719 if (!section_headers[idx].Parse(sh_data, &offset))
1720 break;
1721 }
1722 if (idx < section_headers.size())
1723 section_headers.resize(idx);
1724
1725 const unsigned strtab_idx = header.e_shstrndx;
1726 if (strtab_idx && strtab_idx < section_headers.size()) {
1727 const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];
1728 const size_t byte_size = sheader.sh_size;
1729 const Elf64_Off offset = sheader.sh_offset;
1730 lldb_private::DataExtractor shstr_data;
1731
1732 if (shstr_data.SetData(object_data, offset, byte_size) == byte_size) {
1733 for (SectionHeaderCollIter I = section_headers.begin();
1734 I != section_headers.end(); ++I) {
1735 static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");
1736 const ELFSectionHeaderInfo &sheader = *I;
1737 const uint64_t section_size =
1738 sheader.sh_type == SHT_NOBITS ? 0 : sheader.sh_size;
1739 ConstString name(shstr_data.PeekCStr(I->sh_name));
1740
1741 I->section_name = name;
1742
1743 if (arch_spec.IsMIPS()) {
1744 uint32_t arch_flags = arch_spec.GetFlags();
1745 DataExtractor data;
1746 if (sheader.sh_type == SHT_MIPS_ABIFLAGS) {
1747
1748 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1749 section_size) == section_size)) {
1750 // MIPS ASE Mask is at offset 12 in MIPS.abiflags section
1751 lldb::offset_t offset = 12; // MIPS ABI Flags Version: 0
1752 arch_flags |= data.GetU32(&offset);
1753
1754 // The floating point ABI is at offset 7
1755 offset = 7;
1756 switch (data.GetU8(&offset)) {
1757 case llvm::Mips::Val_GNU_MIPS_ABI_FP_ANY:
1759 break;
1760 case llvm::Mips::Val_GNU_MIPS_ABI_FP_DOUBLE:
1762 break;
1763 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SINGLE:
1765 break;
1766 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SOFT:
1768 break;
1769 case llvm::Mips::Val_GNU_MIPS_ABI_FP_OLD_64:
1771 break;
1772 case llvm::Mips::Val_GNU_MIPS_ABI_FP_XX:
1774 break;
1775 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64:
1777 break;
1778 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64A:
1780 break;
1781 }
1782 }
1783 }
1784 // Settings appropriate ArchSpec ABI Flags
1785 switch (header.e_flags & llvm::ELF::EF_MIPS_ABI) {
1786 case llvm::ELF::EF_MIPS_ABI_O32:
1788 break;
1789 case EF_MIPS_ABI_O64:
1791 break;
1792 case EF_MIPS_ABI_EABI32:
1794 break;
1795 case EF_MIPS_ABI_EABI64:
1797 break;
1798 default:
1799 // ABI Mask doesn't cover N32 and N64 ABI.
1800 if (header.e_ident[EI_CLASS] == llvm::ELF::ELFCLASS64)
1802 else if (header.e_flags & llvm::ELF::EF_MIPS_ABI2)
1804 break;
1805 }
1806 arch_spec.SetFlags(arch_flags);
1807 }
1808
1809 if (arch_spec.GetMachine() == llvm::Triple::arm ||
1810 arch_spec.GetMachine() == llvm::Triple::thumb) {
1811 DataExtractor data;
1812
1813 if (sheader.sh_type == SHT_ARM_ATTRIBUTES && section_size != 0 &&
1814 data.SetData(object_data, sheader.sh_offset, section_size) == section_size)
1815 ParseARMAttributes(data, section_size, arch_spec);
1816 }
1817
1818 if (arch_spec.GetTriple().isRISCV()) {
1819 DataExtractor data;
1820 if (sheader.sh_type == llvm::ELF::SHT_RISCV_ATTRIBUTES &&
1821 section_size != 0 &&
1822 data.SetData(object_data, sheader.sh_offset, section_size) ==
1823 section_size)
1824 ParseRISCVAttributes(data, section_size, arch_spec);
1825 }
1826
1827 if (name == g_sect_name_gnu_debuglink) {
1828 DataExtractor data;
1829 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1830 section_size) == section_size)) {
1831 lldb::offset_t gnu_debuglink_offset = 0;
1832 gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);
1833 gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
1834 data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
1835 }
1836 }
1837
1838 // Process ELF note section entries.
1839 bool is_note_header = (sheader.sh_type == SHT_NOTE);
1840
1841 // The section header ".note.android.ident" is stored as a
1842 // PROGBITS type header but it is actually a note header.
1843 static ConstString g_sect_name_android_ident(".note.android.ident");
1844 if (!is_note_header && name == g_sect_name_android_ident)
1845 is_note_header = true;
1846
1847 if (is_note_header) {
1848 // Allow notes to refine module info.
1849 DataExtractor data;
1850 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1851 section_size) == section_size)) {
1852 Status error = RefineModuleDetailsFromNote(data, arch_spec, uuid);
1853 if (error.Fail()) {
1854 LLDB_LOGF(log, "ObjectFileELF::%s ELF note processing failed: %s",
1855 __FUNCTION__, error.AsCString());
1856 }
1857 }
1858 }
1859 }
1860
1861 // Make any unknown triple components to be unspecified unknowns.
1862 if (arch_spec.GetTriple().getVendor() == llvm::Triple::UnknownVendor)
1863 arch_spec.GetTriple().setVendorName(llvm::StringRef());
1864 if (arch_spec.GetTriple().getOS() == llvm::Triple::UnknownOS)
1865 arch_spec.GetTriple().setOSName(llvm::StringRef());
1866
1867 return section_headers.size();
1868 }
1869 }
1870
1871 section_headers.clear();
1872 return 0;
1873}
1874
1875llvm::StringRef
1876ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const {
1877 size_t pos = symbol_name.find('@');
1878 return symbol_name.substr(0, pos);
1879}
1880
1881// ParseSectionHeaders
1887
1890 if (!ParseSectionHeaders())
1891 return nullptr;
1892
1893 if (id < m_section_headers.size())
1894 return &m_section_headers[id];
1895
1896 return nullptr;
1897}
1898
1900 if (!name || !name[0] || !ParseSectionHeaders())
1901 return 0;
1902 for (size_t i = 1; i < m_section_headers.size(); ++i)
1903 if (m_section_headers[i].section_name == ConstString(name))
1904 return i;
1905 return 0;
1906}
1907
1908static SectionType GetSectionTypeFromName(llvm::StringRef Name) {
1909 if (Name.consume_front(".debug_"))
1911
1912 return llvm::StringSwitch<SectionType>(Name)
1913 .Case(".ARM.exidx", eSectionTypeARMexidx)
1914 .Case(".ARM.extab", eSectionTypeARMextab)
1915 .Case(".ctf", eSectionTypeDebug)
1916 .Cases({".data", ".tdata"}, eSectionTypeData)
1917 .Case(".eh_frame", eSectionTypeEHFrame)
1918 .Case(".gnu_debugaltlink", eSectionTypeDWARFGNUDebugAltLink)
1919 .Case(".gosymtab", eSectionTypeGoSymtab)
1920 .Case(".text", eSectionTypeCode)
1921 .Case(".lldbsummaries", lldb::eSectionTypeLLDBTypeSummaries)
1922 .Case(".lldbformatters", lldb::eSectionTypeLLDBFormatters)
1923 .Case(".swift_ast", eSectionTypeSwiftModules)
1924 .Default(eSectionTypeOther);
1925}
1926
1928 switch (H.sh_type) {
1929 case SHT_PROGBITS:
1930 if (H.sh_flags & SHF_EXECINSTR)
1931 return eSectionTypeCode;
1932 break;
1933 case SHT_NOBITS:
1934 if (H.sh_flags & SHF_ALLOC)
1935 return eSectionTypeZeroFill;
1936 break;
1937 case SHT_SYMTAB:
1939 case SHT_DYNSYM:
1941 case SHT_RELA:
1942 case SHT_REL:
1944 case SHT_DYNAMIC:
1946 }
1948}
1949
1950static Permissions GetPermissions(const ELFSectionHeader &H) {
1951 Permissions Perm = Permissions(0);
1952 if (H.sh_flags & SHF_ALLOC)
1953 Perm |= ePermissionsReadable;
1954 if (H.sh_flags & SHF_WRITE)
1955 Perm |= ePermissionsWritable;
1956 if (H.sh_flags & SHF_EXECINSTR)
1957 Perm |= ePermissionsExecutable;
1958 return Perm;
1959}
1960
1961static Permissions GetPermissions(const ELFProgramHeader &H) {
1962 Permissions Perm = Permissions(0);
1963 if (H.p_flags & PF_R)
1964 Perm |= ePermissionsReadable;
1965 if (H.p_flags & PF_W)
1966 Perm |= ePermissionsWritable;
1967 if (H.p_flags & PF_X)
1968 Perm |= ePermissionsExecutable;
1969 return Perm;
1970}
1971
1972namespace {
1973
1975
1976struct SectionAddressInfo {
1977 SectionSP Segment;
1978 VMRange Range;
1979};
1980
1981// (Unlinked) ELF object files usually have 0 for every section address, meaning
1982// we need to compute synthetic addresses in order for "file addresses" from
1983// different sections to not overlap. This class handles that logic.
1984class VMAddressProvider {
1985 using VMMap = llvm::IntervalMap<addr_t, SectionSP, 4,
1986 llvm::IntervalMapHalfOpenInfo<addr_t>>;
1987
1988 ObjectFile::Type ObjectType;
1989 addr_t NextVMAddress = 0;
1990 VMMap::Allocator Alloc;
1991 VMMap Segments{Alloc};
1992 VMMap Sections{Alloc};
1993 lldb_private::Log *Log = GetLog(LLDBLog::Modules);
1994 size_t SegmentCount = 0;
1995 std::string SegmentName;
1996
1997 VMRange GetVMRange(const ELFSectionHeader &H) {
1998 addr_t Address = H.sh_addr;
1999 addr_t Size = H.sh_flags & SHF_ALLOC ? H.sh_size : 0;
2000
2001 // When this is a debug file for relocatable file, the address is all zero
2002 // and thus needs to use accumulate method
2003 if ((ObjectType == ObjectFile::Type::eTypeObjectFile ||
2004 (ObjectType == ObjectFile::Type::eTypeDebugInfo && H.sh_addr == 0)) &&
2005 Segments.empty() && (H.sh_flags & SHF_ALLOC)) {
2006 NextVMAddress =
2007 llvm::alignTo(NextVMAddress, std::max<addr_t>(H.sh_addralign, 1));
2008 Address = NextVMAddress;
2009 NextVMAddress += Size;
2010 }
2011 return VMRange(Address, Size);
2012 }
2013
2014public:
2015 VMAddressProvider(ObjectFile::Type Type, llvm::StringRef SegmentName)
2016 : ObjectType(Type), SegmentName(std::string(SegmentName)) {}
2017
2018 std::string GetNextSegmentName() const {
2019 return llvm::formatv("{0}[{1}]", SegmentName, SegmentCount).str();
2020 }
2021
2022 std::optional<VMRange> GetAddressInfo(const ELFProgramHeader &H) {
2023 if (H.p_memsz == 0) {
2024 LLDB_LOG(Log, "Ignoring zero-sized {0} segment. Corrupt object file?",
2025 SegmentName);
2026 return std::nullopt;
2027 }
2028
2029 if (Segments.overlaps(H.p_vaddr, H.p_vaddr + H.p_memsz)) {
2030 LLDB_LOG(Log, "Ignoring overlapping {0} segment. Corrupt object file?",
2031 SegmentName);
2032 return std::nullopt;
2033 }
2034 return VMRange(H.p_vaddr, H.p_memsz);
2035 }
2036
2037 std::optional<SectionAddressInfo> GetAddressInfo(const ELFSectionHeader &H) {
2038 VMRange Range = GetVMRange(H);
2039 SectionSP Segment;
2040 auto It = Segments.find(Range.GetRangeBase());
2041 if ((H.sh_flags & SHF_ALLOC) && It.valid()) {
2042 addr_t MaxSize;
2043 if (It.start() <= Range.GetRangeBase()) {
2044 MaxSize = It.stop() - Range.GetRangeBase();
2045 Segment = *It;
2046 } else
2047 MaxSize = It.start() - Range.GetRangeBase();
2048 if (Range.GetByteSize() > MaxSize) {
2049 LLDB_LOG(Log, "Shortening section crossing segment boundaries. "
2050 "Corrupt object file?");
2051 Range.SetByteSize(MaxSize);
2052 }
2053 }
2054 if (Range.GetByteSize() > 0 &&
2055 Sections.overlaps(Range.GetRangeBase(), Range.GetRangeEnd())) {
2056 LLDB_LOG(Log, "Ignoring overlapping section. Corrupt object file?");
2057 return std::nullopt;
2058 }
2059 if (Segment)
2060 Range.Slide(-Segment->GetFileAddress());
2061 return SectionAddressInfo{Segment, Range};
2062 }
2063
2064 void AddSegment(const VMRange &Range, SectionSP Seg) {
2065 Segments.insert(Range.GetRangeBase(), Range.GetRangeEnd(), std::move(Seg));
2066 ++SegmentCount;
2067 }
2068
2069 void AddSection(SectionAddressInfo Info, SectionSP Sect) {
2070 if (Info.Range.GetByteSize() == 0)
2071 return;
2072 if (Info.Segment)
2073 Info.Range.Slide(Info.Segment->GetFileAddress());
2074 Sections.insert(Info.Range.GetRangeBase(), Info.Range.GetRangeEnd(),
2075 std::move(Sect));
2076 }
2077};
2078}
2079
2080// We have to do this because ELF doesn't have section IDs, and also
2081// doesn't require section names to be unique. (We use the section index
2082// for section IDs, but that isn't guaranteed to be the same in separate
2083// debug images.)
2084static SectionSP FindMatchingSection(const SectionList &section_list,
2085 SectionSP section) {
2086 SectionSP sect_sp;
2087
2088 addr_t vm_addr = section->GetFileAddress();
2089 ConstString name = section->GetName();
2090 offset_t byte_size = section->GetByteSize();
2091 bool thread_specific = section->IsThreadSpecific();
2092 uint32_t permissions = section->GetPermissions();
2093 uint32_t alignment = section->GetLog2Align();
2094
2095 for (auto sect : section_list) {
2096 if (sect->GetName() == name &&
2097 sect->IsThreadSpecific() == thread_specific &&
2098 sect->GetPermissions() == permissions &&
2099 sect->GetByteSize() == byte_size && sect->GetFileAddress() == vm_addr &&
2100 sect->GetLog2Align() == alignment) {
2101 sect_sp = sect;
2102 break;
2103 } else {
2104 sect_sp = FindMatchingSection(sect->GetChildren(), section);
2105 if (sect_sp)
2106 break;
2107 }
2108 }
2109
2110 return sect_sp;
2111}
2112
2113void ObjectFileELF::CreateSections(SectionList &unified_section_list) {
2114 if (m_sections_up)
2115 return;
2116
2117 m_sections_up = std::make_unique<SectionList>();
2118 VMAddressProvider regular_provider(GetType(), "PT_LOAD");
2119 VMAddressProvider tls_provider(GetType(), "PT_TLS");
2120
2121 for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {
2122 const ELFProgramHeader &PHdr = EnumPHdr.value();
2123 if (PHdr.p_type != PT_LOAD && PHdr.p_type != PT_TLS)
2124 continue;
2125
2126 VMAddressProvider &provider =
2127 PHdr.p_type == PT_TLS ? tls_provider : regular_provider;
2128 auto InfoOr = provider.GetAddressInfo(PHdr);
2129 if (!InfoOr)
2130 continue;
2131
2132 uint32_t Log2Align = llvm::Log2_64(std::max<elf_xword>(PHdr.p_align, 1));
2133 SectionSP Segment = std::make_shared<Section>(
2134 GetModule(), this, SegmentID(EnumPHdr.index()),
2135 ConstString(provider.GetNextSegmentName()), eSectionTypeContainer,
2136 InfoOr->GetRangeBase(), InfoOr->GetByteSize(), PHdr.p_offset,
2137 PHdr.p_filesz, Log2Align, /*flags*/ 0);
2138 Segment->SetPermissions(GetPermissions(PHdr));
2139 Segment->SetIsThreadSpecific(PHdr.p_type == PT_TLS);
2140 m_sections_up->AddSection(Segment);
2141
2142 provider.AddSegment(*InfoOr, std::move(Segment));
2143 }
2144
2146 if (m_section_headers.empty())
2147 return;
2148
2149 for (SectionHeaderCollIter I = std::next(m_section_headers.begin());
2150 I != m_section_headers.end(); ++I) {
2151 const ELFSectionHeaderInfo &header = *I;
2152
2153 ConstString &name = I->section_name;
2154 const uint64_t file_size =
2155 header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
2156
2157 VMAddressProvider &provider =
2158 header.sh_flags & SHF_TLS ? tls_provider : regular_provider;
2159 auto InfoOr = provider.GetAddressInfo(header);
2160 if (!InfoOr)
2161 continue;
2162
2163 SectionType sect_type = GetSectionType(header);
2164
2165 elf::elf_xword log2align =
2166 (header.sh_addralign == 0) ? 0 : llvm::Log2_64(header.sh_addralign);
2167
2168 SectionSP section_sp(new Section(
2169 InfoOr->Segment, GetModule(), // Module to which this section belongs.
2170 this, // ObjectFile to which this section belongs and should
2171 // read section data from.
2172 SectionIndex(I), // Section ID.
2173 name, // Section name.
2174 sect_type, // Section type.
2175 InfoOr->Range.GetRangeBase(), // VM address.
2176 InfoOr->Range.GetByteSize(), // VM size in bytes of this section.
2177 header.sh_offset, // Offset of this section in the file.
2178 file_size, // Size of the section as found in the file.
2179 log2align, // Alignment of the section
2180 header.sh_flags)); // Flags for this section.
2181
2182 section_sp->SetPermissions(GetPermissions(header));
2183 section_sp->SetIsThreadSpecific(header.sh_flags & SHF_TLS);
2184 (InfoOr->Segment ? InfoOr->Segment->GetChildren() : *m_sections_up)
2185 .AddSection(section_sp);
2186 provider.AddSection(std::move(*InfoOr), std::move(section_sp));
2187 }
2188
2189 // Merge the two adding any new sections, and overwriting any existing
2190 // sections that are SHT_NOBITS
2191 unified_section_list =
2192 SectionList::Merge(unified_section_list, *m_sections_up, MergeSections);
2193
2194 // If there's a .gnu_debugdata section, we'll try to read the .symtab that's
2195 // embedded in there and replace the one in the original object file (if any).
2196 // If there's none in the orignal object file, we add it to it.
2197 if (auto gdd_obj_file = GetGnuDebugDataObjectFile()) {
2198 if (auto gdd_objfile_section_list = gdd_obj_file->GetSectionList()) {
2199 if (SectionSP symtab_section_sp =
2200 gdd_objfile_section_list->FindSectionByType(
2202 SectionSP module_section_sp = unified_section_list.FindSectionByType(
2204 if (module_section_sp)
2205 unified_section_list.ReplaceSection(module_section_sp,
2206 symtab_section_sp);
2207 else
2208 unified_section_list.AddSection(symtab_section_sp);
2209 }
2210 }
2211 }
2212}
2213
2214std::shared_ptr<ObjectFileELF> ObjectFileELF::GetGnuDebugDataObjectFile() {
2215 if (m_gnu_debug_data_object_file != nullptr)
2217
2218 SectionSP section = GetSectionList()->FindSectionByName(".gnu_debugdata");
2219 if (!section)
2220 return nullptr;
2221
2223 GetModule()->ReportWarning(
2224 "no LZMA support found for reading .gnu_debugdata section");
2225 return nullptr;
2226 }
2227
2228 // Uncompress the data
2229 DataExtractor data;
2230 section->GetSectionData(data);
2231 llvm::SmallVector<uint8_t, 0> uncompressedData;
2232 auto err = lldb_private::lzma::uncompress(data.GetData(), uncompressedData);
2233 if (err) {
2234 GetModule()->ReportWarning(
2235 "an error occurred while decompressing the section {0}: {1}",
2236 section->GetName(), llvm::toString(std::move(err)).c_str());
2237 return nullptr;
2238 }
2239
2240 // Construct ObjectFileELF object from decompressed buffer
2241 DataBufferSP gdd_data_buf(
2242 new DataBufferHeap(uncompressedData.data(), uncompressedData.size()));
2243 DataExtractorSP extractor_sp = std::make_shared<DataExtractor>(gdd_data_buf);
2245 llvm::StringRef("gnu_debugdata"));
2247 GetModule(), extractor_sp, 0, &fspec, 0, gdd_data_buf->GetByteSize()));
2248
2249 // This line is essential; otherwise a breakpoint can be set but not hit.
2251
2252 ArchSpec spec = m_gnu_debug_data_object_file->GetArchitecture();
2253 if (spec && m_gnu_debug_data_object_file->SetModulesArchitecture(spec))
2255
2256 return nullptr;
2257}
2258
2259// Find the arm/aarch64 mapping symbol character in the given symbol name.
2260// Mapping symbols have the form of "$<char>[.<any>]*". Additionally we
2261// recognize cases when the mapping symbol prefixed by an arbitrary string
2262// because if a symbol prefix added to each symbol in the object file with
2263// objcopy then the mapping symbols are also prefixed.
2264static char FindArmAarch64MappingSymbol(const char *symbol_name) {
2265 if (!symbol_name)
2266 return '\0';
2267
2268 const char *dollar_pos = ::strchr(symbol_name, '$');
2269 if (!dollar_pos || dollar_pos[1] == '\0')
2270 return '\0';
2271
2272 if (dollar_pos[2] == '\0' || dollar_pos[2] == '.')
2273 return dollar_pos[1];
2274 return '\0';
2275}
2276
2277static char FindRISCVMappingSymbol(const char *symbol_name) {
2278 if (!symbol_name)
2279 return '\0';
2280
2281 if (strcmp(symbol_name, "$d") == 0) {
2282 return 'd';
2283 }
2284 if (strcmp(symbol_name, "$x") == 0) {
2285 return 'x';
2286 }
2287 return '\0';
2288}
2289
2290#define STO_MIPS_ISA (3 << 6)
2291#define STO_MICROMIPS (2 << 6)
2292#define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS)
2293
2294// private
2295std::pair<unsigned, ObjectFileELF::FileAddressToAddressClassMap>
2297 SectionList *section_list, const size_t num_symbols,
2298 const DataExtractor &symtab_data,
2299 const DataExtractor &strtab_data) {
2300 ELFSymbol symbol;
2301 lldb::offset_t offset = 0;
2302 // The changes these symbols would make to the class map. We will also update
2303 // m_address_class_map but need to tell the caller what changed because the
2304 // caller may be another object file.
2305 FileAddressToAddressClassMap address_class_map;
2306
2307 static ConstString text_section_name(".text");
2308 static ConstString init_section_name(".init");
2309 static ConstString fini_section_name(".fini");
2310 static ConstString ctors_section_name(".ctors");
2311 static ConstString dtors_section_name(".dtors");
2312
2313 static ConstString data_section_name(".data");
2314 static ConstString rodata_section_name(".rodata");
2315 static ConstString rodata1_section_name(".rodata1");
2316 static ConstString data2_section_name(".data1");
2317 static ConstString bss_section_name(".bss");
2318 static ConstString opd_section_name(".opd"); // For ppc64
2319
2320 // On Android the oatdata and the oatexec symbols in the oat and odex files
2321 // covers the full .text section what causes issues with displaying unusable
2322 // symbol name to the user and very slow unwinding speed because the
2323 // instruction emulation based unwind plans try to emulate all instructions
2324 // in these symbols. Don't add these symbols to the symbol list as they have
2325 // no use for the debugger and they are causing a lot of trouble. Filtering
2326 // can't be restricted to Android because this special object file don't
2327 // contain the note section specifying the environment to Android but the
2328 // custom extension and file name makes it highly unlikely that this will
2329 // collide with anything else.
2330 llvm::StringRef file_extension = m_file.GetFileNameExtension();
2331 bool skip_oatdata_oatexec =
2332 file_extension == ".oat" || file_extension == ".odex";
2333
2334 ArchSpec arch = GetArchitecture();
2335 ModuleSP module_sp(GetModule());
2336 SectionList *module_section_list =
2337 module_sp ? module_sp->GetSectionList() : nullptr;
2338
2339 // We might have debug information in a separate object, in which case
2340 // we need to map the sections from that object to the sections in the
2341 // main object during symbol lookup. If we had to compare the sections
2342 // for every single symbol, that would be expensive, so this map is
2343 // used to accelerate the process.
2344 std::unordered_map<lldb::SectionSP, lldb::SectionSP> section_map;
2345
2346 unsigned i;
2347 for (i = 0; i < num_symbols; ++i) {
2348 if (!symbol.Parse(symtab_data, &offset))
2349 break;
2350
2351 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
2352 if (!symbol_name)
2353 symbol_name = "";
2354
2355 // Skip local symbols starting with ".L" because these are compiler
2356 // generated local labels used for internal purposes (e.g. debugging,
2357 // optimization) and are not relevant for symbol resolution or external
2358 // linkage.
2359 if (llvm::StringRef(symbol_name).starts_with(".L"))
2360 continue;
2361 // No need to add non-section symbols that have no names
2362 if (symbol.getType() != STT_SECTION &&
2363 (symbol_name == nullptr || symbol_name[0] == '\0'))
2364 continue;
2365
2366 // Skipping oatdata and oatexec sections if it is requested. See details
2367 // above the definition of skip_oatdata_oatexec for the reasons.
2368 if (skip_oatdata_oatexec && (::strcmp(symbol_name, "oatdata") == 0 ||
2369 ::strcmp(symbol_name, "oatexec") == 0))
2370 continue;
2371
2372 SectionSP symbol_section_sp;
2373 SymbolType symbol_type = eSymbolTypeInvalid;
2374 Elf64_Half shndx = symbol.st_shndx;
2375
2376 switch (shndx) {
2377 case SHN_ABS:
2378 symbol_type = eSymbolTypeAbsolute;
2379 break;
2380 case SHN_UNDEF:
2381 symbol_type = eSymbolTypeUndefined;
2382 break;
2383 default:
2384 symbol_section_sp = section_list->FindSectionByID(shndx);
2385 break;
2386 }
2387
2388 // If a symbol is undefined do not process it further even if it has a STT
2389 // type
2390 if (symbol_type != eSymbolTypeUndefined) {
2391 switch (symbol.getType()) {
2392 default:
2393 case STT_NOTYPE:
2394 // The symbol's type is not specified.
2395 break;
2396
2397 case STT_OBJECT:
2398 // The symbol is associated with a data object, such as a variable, an
2399 // array, etc.
2400 symbol_type = eSymbolTypeData;
2401 break;
2402
2403 case STT_FUNC:
2404 // The symbol is associated with a function or other executable code.
2405 symbol_type = eSymbolTypeCode;
2406 break;
2407
2408 case STT_SECTION:
2409 // The symbol is associated with a section. Symbol table entries of
2410 // this type exist primarily for relocation and normally have STB_LOCAL
2411 // binding.
2412 break;
2413
2414 case STT_FILE:
2415 // Conventionally, the symbol's name gives the name of the source file
2416 // associated with the object file. A file symbol has STB_LOCAL
2417 // binding, its section index is SHN_ABS, and it precedes the other
2418 // STB_LOCAL symbols for the file, if it is present.
2419 symbol_type = eSymbolTypeSourceFile;
2420 break;
2421
2422 case STT_GNU_IFUNC:
2423 // The symbol is associated with an indirect function. The actual
2424 // function will be resolved if it is referenced.
2425 symbol_type = eSymbolTypeResolver;
2426 break;
2427
2428 case STT_TLS:
2429 // The symbol is associated with a thread-local data object, such as
2430 // a thread-local variable.
2431 symbol_type = eSymbolTypeData;
2432 break;
2433 }
2434 }
2435
2436 if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) {
2437 if (symbol_section_sp) {
2438 ConstString sect_name = symbol_section_sp->GetName();
2439 if (sect_name == text_section_name || sect_name == init_section_name ||
2440 sect_name == fini_section_name || sect_name == ctors_section_name ||
2441 sect_name == dtors_section_name) {
2442 symbol_type = eSymbolTypeCode;
2443 } else if (sect_name == data_section_name ||
2444 sect_name == data2_section_name ||
2445 sect_name == rodata_section_name ||
2446 sect_name == rodata1_section_name ||
2447 sect_name == bss_section_name) {
2448 symbol_type = eSymbolTypeData;
2449 } else if (symbol_section_sp->Get() & SHF_ALLOC)
2450 // Check for symbols from custom sections (e.g. added by linker
2451 // scripts) with SHF_ALLOC (i.e. occupies memory during process
2452 // execution) in their flags.
2453 symbol_type = eSymbolTypeData;
2454 }
2455 }
2456
2457 int64_t symbol_value_offset = 0;
2458 uint32_t additional_flags = 0;
2459 if (arch.IsValid()) {
2460 if (arch.GetMachine() == llvm::Triple::arm) {
2461 if (symbol.getBinding() == STB_LOCAL) {
2462 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2463 if (symbol_type == eSymbolTypeCode) {
2464 switch (mapping_symbol) {
2465 case 'a':
2466 // $a[.<any>]* - marks an ARM instruction sequence
2467 address_class_map[symbol.st_value] = AddressClass::eCode;
2468 break;
2469 case 'b':
2470 case 't':
2471 // $b[.<any>]* - marks a THUMB BL instruction sequence
2472 // $t[.<any>]* - marks a THUMB instruction sequence
2473 address_class_map[symbol.st_value] =
2475 break;
2476 case 'd':
2477 // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2478 address_class_map[symbol.st_value] = AddressClass::eData;
2479 break;
2480 }
2481 }
2482 if (mapping_symbol)
2483 continue;
2484 }
2485 } else if (arch.GetMachine() == llvm::Triple::aarch64) {
2486 if (symbol.getBinding() == STB_LOCAL) {
2487 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2488 if (symbol_type == eSymbolTypeCode) {
2489 switch (mapping_symbol) {
2490 case 'x':
2491 // $x[.<any>]* - marks an A64 instruction sequence
2492 address_class_map[symbol.st_value] = AddressClass::eCode;
2493 break;
2494 case 'd':
2495 // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2496 address_class_map[symbol.st_value] = AddressClass::eData;
2497 break;
2498 }
2499 }
2500 if (mapping_symbol)
2501 continue;
2502 }
2503 } else if (arch.GetTriple().isRISCV()) {
2504 if (symbol.getBinding() == STB_LOCAL) {
2505 char mapping_symbol = FindRISCVMappingSymbol(symbol_name);
2506 if (symbol_type == eSymbolTypeCode) {
2507 // Only handle $d and $x mapping symbols.
2508 // Other mapping symbols are ignored as they don't affect address
2509 // classification.
2510 switch (mapping_symbol) {
2511 case 'x':
2512 // $x - marks a RISCV instruction sequence
2513 address_class_map[symbol.st_value] = AddressClass::eCode;
2514 break;
2515 case 'd':
2516 // $d - marks a RISCV data item sequence
2517 address_class_map[symbol.st_value] = AddressClass::eData;
2518 break;
2519 }
2520 }
2521 if (mapping_symbol)
2522 continue;
2523 }
2524 }
2525
2526 if (arch.GetMachine() == llvm::Triple::arm) {
2527 if (symbol_type == eSymbolTypeCode) {
2528 if (symbol.st_value & 1) {
2529 // Subtracting 1 from the address effectively unsets the low order
2530 // bit, which results in the address actually pointing to the
2531 // beginning of the symbol. This delta will be used below in
2532 // conjunction with symbol.st_value to produce the final
2533 // symbol_value that we store in the symtab.
2534 symbol_value_offset = -1;
2535 address_class_map[symbol.st_value ^ 1] =
2537 } else {
2538 // This address is ARM
2539 address_class_map[symbol.st_value] = AddressClass::eCode;
2540 }
2541 }
2542 }
2543
2544 /*
2545 * MIPS:
2546 * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for
2547 * MIPS).
2548 * This allows processor to switch between microMIPS and MIPS without any
2549 * need
2550 * for special mode-control register. However, apart from .debug_line,
2551 * none of
2552 * the ELF/DWARF sections set the ISA bit (for symbol or section). Use
2553 * st_other
2554 * flag to check whether the symbol is microMIPS and then set the address
2555 * class
2556 * accordingly.
2557 */
2558 if (arch.IsMIPS()) {
2559 if (IS_MICROMIPS(symbol.st_other))
2560 address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
2561 else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) {
2562 symbol.st_value = symbol.st_value & (~1ull);
2563 address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
2564 } else {
2565 if (symbol_type == eSymbolTypeCode)
2566 address_class_map[symbol.st_value] = AddressClass::eCode;
2567 else if (symbol_type == eSymbolTypeData)
2568 address_class_map[symbol.st_value] = AddressClass::eData;
2569 else
2570 address_class_map[symbol.st_value] = AddressClass::eUnknown;
2571 }
2572 }
2573 }
2574
2575 // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB
2576 // symbols. See above for more details.
2577 uint64_t symbol_value = symbol.st_value + symbol_value_offset;
2578
2579 if (symbol_section_sp &&
2581 symbol_value -= symbol_section_sp->GetFileAddress();
2582
2583 if (symbol_section_sp && module_section_list &&
2584 module_section_list != section_list) {
2585 auto section_it = section_map.find(symbol_section_sp);
2586 if (section_it == section_map.end()) {
2587 section_it = section_map
2588 .emplace(symbol_section_sp,
2589 FindMatchingSection(*module_section_list,
2590 symbol_section_sp))
2591 .first;
2592 }
2593 if (section_it->second)
2594 symbol_section_sp = section_it->second;
2595 }
2596
2597 bool is_global = symbol.getBinding() == STB_GLOBAL;
2598 uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags;
2599 llvm::StringRef symbol_ref(symbol_name);
2600
2601 // Symbol names may contain @VERSION suffixes. Find those and strip them
2602 // temporarily.
2603 size_t version_pos = symbol_ref.find('@');
2604 bool has_suffix = version_pos != llvm::StringRef::npos;
2605 llvm::StringRef symbol_bare = symbol_ref.substr(0, version_pos);
2606 Mangled mangled(symbol_bare);
2607
2608 // Now append the suffix back to mangled and unmangled names. Only do it if
2609 // the demangling was successful (string is not empty).
2610 if (has_suffix) {
2611 llvm::StringRef suffix = symbol_ref.substr(version_pos);
2612
2613 llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef();
2614 if (!mangled_name.empty())
2615 mangled.SetMangledName(ConstString((mangled_name + suffix).str()));
2616
2617 ConstString demangled = mangled.GetDemangledName();
2618 llvm::StringRef demangled_name = demangled.GetStringRef();
2619 if (!demangled_name.empty())
2620 mangled.SetDemangledName(ConstString((demangled_name + suffix).str()));
2621 }
2622
2623 // In ELF all symbol should have a valid size but it is not true for some
2624 // function symbols coming from hand written assembly. As none of the
2625 // function symbol should have 0 size we try to calculate the size for
2626 // these symbols in the symtab with saying that their original size is not
2627 // valid.
2628 bool symbol_size_valid =
2629 symbol.st_size != 0 || symbol.getType() != STT_FUNC;
2630
2631 bool is_trampoline = false;
2632 if (arch.IsValid() && (arch.GetMachine() == llvm::Triple::aarch64)) {
2633 // On AArch64, trampolines are registered as code.
2634 // If we detect a trampoline (which starts with __AArch64ADRPThunk_ or
2635 // __AArch64AbsLongThunk_) we register the symbol as a trampoline. This
2636 // way we will be able to detect the trampoline when we step in a function
2637 // and step through the trampoline.
2638 if (symbol_type == eSymbolTypeCode) {
2639 llvm::StringRef trampoline_name = mangled.GetName().GetStringRef();
2640 if (trampoline_name.starts_with("__AArch64ADRPThunk_") ||
2641 trampoline_name.starts_with("__AArch64AbsLongThunk_")) {
2642 symbol_type = eSymbolTypeTrampoline;
2643 is_trampoline = true;
2644 }
2645 }
2646 }
2647
2648 Symbol dc_symbol(
2649 i + start_id, // ID is the original symbol table index.
2650 mangled,
2651 symbol_type, // Type of this symbol
2652 is_global, // Is this globally visible?
2653 false, // Is this symbol debug info?
2654 is_trampoline, // Is this symbol a trampoline?
2655 false, // Is this symbol artificial?
2656 AddressRange(symbol_section_sp, // Section in which this symbol is
2657 // defined or null.
2658 symbol_value, // Offset in section or symbol value.
2659 symbol.st_size), // Size in bytes of this symbol.
2660 symbol_size_valid, // Symbol size is valid
2661 has_suffix, // Contains linker annotations?
2662 flags); // Symbol flags.
2663 if (symbol.getBinding() == STB_WEAK)
2664 dc_symbol.SetIsWeak(true);
2665 symtab->AddSymbol(dc_symbol);
2666 }
2667
2668 m_address_class_map.merge(address_class_map);
2669 return {i, address_class_map};
2670}
2671
2672std::pair<unsigned, ObjectFileELF::FileAddressToAddressClassMap>
2674 lldb_private::Section *symtab) {
2675 if (symtab->GetObjectFile() != this) {
2676 // If the symbol table section is owned by a different object file, have it
2677 // do the parsing.
2678 ObjectFileELF *obj_file_elf =
2679 static_cast<ObjectFileELF *>(symtab->GetObjectFile());
2680 auto [num_symbols, address_class_map] =
2681 obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab);
2682
2683 // The other object file returned the changes it made to its address
2684 // class map, make the same changes to ours.
2685 m_address_class_map.merge(address_class_map);
2686
2687 return {num_symbols, address_class_map};
2688 }
2689
2690 // Get section list for this object file.
2691 SectionList *section_list = m_sections_up.get();
2692 if (!section_list)
2693 return {};
2694
2695 user_id_t symtab_id = symtab->GetID();
2696 const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2697 assert(symtab_hdr->sh_type == SHT_SYMTAB ||
2698 symtab_hdr->sh_type == SHT_DYNSYM);
2699
2700 // sh_link: section header index of associated string table.
2701 user_id_t strtab_id = symtab_hdr->sh_link;
2702 Section *strtab = section_list->FindSectionByID(strtab_id).get();
2703
2704 if (symtab && strtab) {
2705 assert(symtab->GetObjectFile() == this);
2706 assert(strtab->GetObjectFile() == this);
2707
2708 DataExtractor symtab_data;
2709 DataExtractor strtab_data;
2710 if (ReadSectionData(symtab, symtab_data) &&
2711 ReadSectionData(strtab, strtab_data)) {
2712 size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
2713
2714 return ParseSymbols(symbol_table, start_id, section_list, num_symbols,
2715 symtab_data, strtab_data);
2716 }
2717 }
2718
2719 return {0, {}};
2720}
2721
2723 if (m_dynamic_symbols.size())
2724 return m_dynamic_symbols.size();
2725
2726 std::optional<DataExtractor> dynamic_data = GetDynamicData();
2727 if (!dynamic_data)
2728 return 0;
2729
2731 lldb::offset_t cursor = 0;
2732 while (e.symbol.Parse(*dynamic_data, &cursor)) {
2733 m_dynamic_symbols.push_back(e);
2734 if (e.symbol.d_tag == DT_NULL)
2735 break;
2736 }
2737 if (std::optional<DataExtractor> dynstr_data = GetDynstrData()) {
2738 for (ELFDynamicWithName &entry : m_dynamic_symbols) {
2739 switch (entry.symbol.d_tag) {
2740 case DT_NEEDED:
2741 case DT_SONAME:
2742 case DT_RPATH:
2743 case DT_RUNPATH:
2744 case DT_AUXILIARY:
2745 case DT_FILTER: {
2746 lldb::offset_t cursor = entry.symbol.d_val;
2747 const char *name = dynstr_data->GetCStr(&cursor);
2748 if (name)
2749 entry.name = std::string(name);
2750 break;
2751 }
2752 default:
2753 break;
2754 }
2755 }
2756 }
2757 return m_dynamic_symbols.size();
2758}
2759
2761 if (!ParseDynamicSymbols())
2762 return nullptr;
2763 for (const auto &entry : m_dynamic_symbols) {
2764 if (entry.symbol.d_tag == tag)
2765 return &entry.symbol;
2766 }
2767 return nullptr;
2768}
2769
2771 // DT_PLTREL
2772 // This member specifies the type of relocation entry to which the
2773 // procedure linkage table refers. The d_val member holds DT_REL or
2774 // DT_RELA, as appropriate. All relocations in a procedure linkage table
2775 // must use the same relocation.
2776 const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
2777
2778 if (symbol)
2779 return symbol->d_val;
2780
2781 return 0;
2782}
2783
2784// Returns the size of the normal plt entries and the offset of the first
2785// normal plt entry. The 0th entry in the plt table is usually a resolution
2786// entry which have different size in some architectures then the rest of the
2787// plt entries.
2788static std::pair<uint64_t, uint64_t>
2790 const ELFSectionHeader *plt_hdr) {
2791 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2792
2793 // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are
2794 // 16 bytes. So round the entsize up by the alignment if addralign is set.
2795 elf_xword plt_entsize =
2796 plt_hdr->sh_addralign
2797 ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign)
2798 : plt_hdr->sh_entsize;
2799
2800 // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly.
2801 // PLT entries relocation code in general requires multiple instruction and
2802 // should be greater than 4 bytes in most cases. Try to guess correct size
2803 // just in case.
2804 if (plt_entsize <= 4) {
2805 // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the
2806 // size of the plt entries based on the number of entries and the size of
2807 // the plt section with the assumption that the size of the 0th entry is at
2808 // least as big as the size of the normal entries and it isn't much bigger
2809 // then that.
2810 if (plt_hdr->sh_addralign)
2811 plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign /
2812 (num_relocations + 1) * plt_hdr->sh_addralign;
2813 else
2814 plt_entsize = plt_hdr->sh_size / (num_relocations + 1);
2815 }
2816
2817 elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize;
2818
2819 return std::make_pair(plt_entsize, plt_offset);
2820}
2821
2822static unsigned ParsePLTRelocations(
2823 Symtab *symbol_table, user_id_t start_id, unsigned rel_type,
2824 const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2825 const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr,
2826 const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data,
2827 DataExtractor &symtab_data, DataExtractor &strtab_data) {
2828 ELFRelocation rel(rel_type);
2829 ELFSymbol symbol;
2830 lldb::offset_t offset = 0;
2831
2832 uint64_t plt_offset, plt_entsize;
2833 std::tie(plt_entsize, plt_offset) =
2834 GetPltEntrySizeAndOffset(rel_hdr, plt_hdr);
2835 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2836
2837 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2838 reloc_info_fn reloc_type;
2839 reloc_info_fn reloc_symbol;
2840
2841 if (hdr->Is32Bit()) {
2842 reloc_type = ELFRelocation::RelocType32;
2843 reloc_symbol = ELFRelocation::RelocSymbol32;
2844 } else {
2845 reloc_type = ELFRelocation::RelocType64;
2846 reloc_symbol = ELFRelocation::RelocSymbol64;
2847 }
2848
2849 unsigned slot_type = hdr->GetRelocationJumpSlotType();
2850 unsigned i;
2851 for (i = 0; i < num_relocations; ++i) {
2852 if (!rel.Parse(rel_data, &offset))
2853 break;
2854
2855 if (reloc_type(rel) != slot_type)
2856 continue;
2857
2858 lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
2859 if (!symbol.Parse(symtab_data, &symbol_offset))
2860 break;
2861
2862 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
2863 uint64_t plt_index = plt_offset + i * plt_entsize;
2864
2865 Symbol jump_symbol(
2866 i + start_id, // Symbol table index
2867 symbol_name, // symbol name.
2868 eSymbolTypeTrampoline, // Type of this symbol
2869 false, // Is this globally visible?
2870 false, // Is this symbol debug info?
2871 true, // Is this symbol a trampoline?
2872 true, // Is this symbol artificial?
2873 plt_section_sp, // Section in which this symbol is defined or null.
2874 plt_index, // Offset in section or symbol value.
2875 plt_entsize, // Size in bytes of this symbol.
2876 true, // Size is valid
2877 false, // Contains linker annotations?
2878 0); // Symbol flags.
2879
2880 symbol_table->AddSymbol(jump_symbol);
2881 }
2882
2883 return i;
2884}
2885
2886unsigned
2888 const ELFSectionHeaderInfo *rel_hdr,
2889 user_id_t rel_id) {
2890 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2891
2892 // The link field points to the associated symbol table.
2893 user_id_t symtab_id = rel_hdr->sh_link;
2894
2895 // If the link field doesn't point to the appropriate symbol name table then
2896 // try to find it by name as some compiler don't fill in the link fields.
2897 if (!symtab_id)
2898 symtab_id = GetSectionIndexByName(".dynsym");
2899
2900 // Get PLT section. We cannot use rel_hdr->sh_info, since current linkers
2901 // point that to the .got.plt or .got section instead of .plt.
2902 user_id_t plt_id = GetSectionIndexByName(".plt");
2903
2904 if (!symtab_id || !plt_id)
2905 return 0;
2906
2907 const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
2908 if (!plt_hdr)
2909 return 0;
2910
2911 const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
2912 if (!sym_hdr)
2913 return 0;
2914
2915 SectionList *section_list = m_sections_up.get();
2916 if (!section_list)
2917 return 0;
2918
2919 Section *rel_section = section_list->FindSectionByID(rel_id).get();
2920 if (!rel_section)
2921 return 0;
2922
2923 SectionSP plt_section_sp(section_list->FindSectionByID(plt_id));
2924 if (!plt_section_sp)
2925 return 0;
2926
2927 Section *symtab = section_list->FindSectionByID(symtab_id).get();
2928 if (!symtab)
2929 return 0;
2930
2931 // sh_link points to associated string table.
2932 Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link).get();
2933 if (!strtab)
2934 return 0;
2935
2936 DataExtractor rel_data;
2937 if (!ReadSectionData(rel_section, rel_data))
2938 return 0;
2939
2940 DataExtractor symtab_data;
2941 if (!ReadSectionData(symtab, symtab_data))
2942 return 0;
2943
2944 DataExtractor strtab_data;
2945 if (!ReadSectionData(strtab, strtab_data))
2946 return 0;
2947
2948 unsigned rel_type = PLTRelocationType();
2949 if (!rel_type)
2950 return 0;
2951
2952 return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header,
2953 rel_hdr, plt_hdr, sym_hdr, plt_section_sp,
2954 rel_data, symtab_data, strtab_data);
2955}
2956
2957static void ApplyELF64ABS64Relocation(Symtab *symtab, ELFRelocation &rel,
2958 DataExtractor &debug_data,
2959 Section *rel_section) {
2960 const Symbol *symbol =
2961 symtab->FindSymbolByID(ELFRelocation::RelocSymbol64(rel));
2962 if (symbol) {
2963 addr_t value = symbol->GetAddressRef().GetFileAddress();
2964 DataBufferSP data_buffer_sp = debug_data.GetSharedDataBuffer();
2965 // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
2966 WritableDataBuffer *data_buffer =
2967 llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
2968 void *const dst = data_buffer->GetBytes() + rel_section->GetFileOffset() +
2969 ELFRelocation::RelocOffset64(rel);
2970 uint64_t val_offset = value + ELFRelocation::RelocAddend64(rel);
2971 memcpy(dst, &val_offset, sizeof(uint64_t));
2972 }
2973}
2974
2975static void ApplyELF64ABS32Relocation(Symtab *symtab, ELFRelocation &rel,
2976 DataExtractor &debug_data,
2977 Section *rel_section, bool is_signed) {
2978 const Symbol *symbol =
2979 symtab->FindSymbolByID(ELFRelocation::RelocSymbol64(rel));
2980 if (symbol) {
2981 addr_t value = symbol->GetAddressRef().GetFileAddress();
2982 value += ELFRelocation::RelocAddend32(rel);
2983 if ((!is_signed && (value > UINT32_MAX)) ||
2984 (is_signed &&
2985 ((int64_t)value > INT32_MAX || (int64_t)value < INT32_MIN))) {
2986 Log *log = GetLog(LLDBLog::Modules);
2987 LLDB_LOGF(log, "Failed to apply debug info relocations");
2988 return;
2989 }
2990 uint32_t truncated_addr = (value & 0xFFFFFFFF);
2991 DataBufferSP data_buffer_sp = debug_data.GetSharedDataBuffer();
2992 // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
2993 WritableDataBuffer *data_buffer =
2994 llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
2995 void *const dst = data_buffer->GetBytes() + rel_section->GetFileOffset() +
2996 ELFRelocation::RelocOffset32(rel);
2997 memcpy(dst, &truncated_addr, sizeof(uint32_t));
2998 }
2999}
3000
3001static void ApplyELF32ABS32RelRelocation(Symtab *symtab, ELFRelocation &rel,
3002 DataExtractor &debug_data,
3003 Section *rel_section) {
3004 Log *log = GetLog(LLDBLog::Modules);
3005 const Symbol *symbol =
3006 symtab->FindSymbolByID(ELFRelocation::RelocSymbol32(rel));
3007 if (symbol) {
3008 addr_t value = symbol->GetAddressRef().GetFileAddress();
3009 if (value == LLDB_INVALID_ADDRESS) {
3010 const char *name = symbol->GetName().GetCString();
3011 LLDB_LOGF(log, "Debug info symbol invalid: %s", name);
3012 return;
3013 }
3014 assert(llvm::isUInt<32>(value) && "Valid addresses are 32-bit");
3015 DataBufferSP data_buffer_sp = debug_data.GetSharedDataBuffer();
3016 // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
3017 WritableDataBuffer *data_buffer =
3018 llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
3019 uint8_t *dst = data_buffer->GetBytes() + rel_section->GetFileOffset() +
3020 ELFRelocation::RelocOffset32(rel);
3021 // Implicit addend is stored inline as a signed value.
3022 int32_t addend;
3023 memcpy(&addend, dst, sizeof(int32_t));
3024 // The sum must be positive. This extra check prevents UB from overflow in
3025 // the actual range check below.
3026 if (addend < 0 && static_cast<uint32_t>(-addend) > value) {
3027 LLDB_LOGF(log, "Debug info relocation overflow: 0x%" PRIx64,
3028 static_cast<int64_t>(value) + addend);
3029 return;
3030 }
3031 if (!llvm::isUInt<32>(value + addend)) {
3032 LLDB_LOGF(log, "Debug info relocation out of range: 0x%" PRIx64, value);
3033 return;
3034 }
3035 uint32_t addr = value + addend;
3036 memcpy(dst, &addr, sizeof(uint32_t));
3037 }
3038}
3039
3041 Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
3042 const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr,
3043 DataExtractor &rel_data, DataExtractor &symtab_data,
3044 DataExtractor &debug_data, Section *rel_section) {
3045 ELFRelocation rel(rel_hdr->sh_type);
3046 lldb::addr_t offset = 0;
3047 const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
3048 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
3049 reloc_info_fn reloc_type;
3050 reloc_info_fn reloc_symbol;
3051
3052 if (hdr->Is32Bit()) {
3053 reloc_type = ELFRelocation::RelocType32;
3054 reloc_symbol = ELFRelocation::RelocSymbol32;
3055 } else {
3056 reloc_type = ELFRelocation::RelocType64;
3057 reloc_symbol = ELFRelocation::RelocSymbol64;
3058 }
3059
3060 for (unsigned i = 0; i < num_relocations; ++i) {
3061 if (!rel.Parse(rel_data, &offset)) {
3062 GetModule()->ReportError(".rel{0}[{1:d}] failed to parse relocation",
3063 rel_section->GetName(), i);
3064 break;
3065 }
3066 const Symbol *symbol = nullptr;
3067
3068 if (hdr->Is32Bit()) {
3069 switch (hdr->e_machine) {
3070 case llvm::ELF::EM_ARM:
3071 switch (reloc_type(rel)) {
3072 case R_ARM_ABS32:
3073 ApplyELF32ABS32RelRelocation(symtab, rel, debug_data, rel_section);
3074 break;
3075 case R_ARM_REL32:
3076 GetModule()->ReportError("unsupported AArch32 relocation:"
3077 " .rel{0}[{1}], type {2}",
3078 rel_section->GetName(), i, reloc_type(rel));
3079 break;
3080 default:
3081 assert(false && "unexpected relocation type");
3082 }
3083 break;
3084 case llvm::ELF::EM_386:
3085 switch (reloc_type(rel)) {
3086 case R_386_32:
3087 symbol = symtab->FindSymbolByID(reloc_symbol(rel));
3088 if (symbol) {
3089 addr_t f_offset =
3090 rel_section->GetFileOffset() + ELFRelocation::RelocOffset32(rel);
3091 DataBufferSP data_buffer_sp = debug_data.GetSharedDataBuffer();
3092 // ObjectFileELF creates a WritableDataBuffer in CreateInstance.
3093 WritableDataBuffer *data_buffer =
3094 llvm::cast<WritableDataBuffer>(data_buffer_sp.get());
3095 uint32_t *dst = reinterpret_cast<uint32_t *>(
3096 data_buffer->GetBytes() + f_offset);
3097
3098 addr_t value = symbol->GetAddressRef().GetFileAddress();
3099 if (rel.IsRela()) {
3100 value += ELFRelocation::RelocAddend32(rel);
3101 } else {
3102 value += *dst;
3103 }
3104 *dst = value;
3105 } else {
3106 GetModule()->ReportError(".rel{0}[{1}] unknown symbol id: {2:d}",
3107 rel_section->GetName(), i,
3108 reloc_symbol(rel));
3109 }
3110 break;
3111 case R_386_NONE:
3112 case R_386_PC32:
3113 GetModule()->ReportError("unsupported i386 relocation:"
3114 " .rel{0}[{1}], type {2}",
3115 rel_section->GetName(), i, reloc_type(rel));
3116 break;
3117 default:
3118 assert(false && "unexpected relocation type");
3119 break;
3120 }
3121 break;
3122 default:
3123 GetModule()->ReportError("unsupported 32-bit ELF machine arch: {0}", hdr->e_machine);
3124 break;
3125 }
3126 } else {
3127 switch (hdr->e_machine) {
3128 case llvm::ELF::EM_AARCH64:
3129 switch (reloc_type(rel)) {
3130 case R_AARCH64_ABS64:
3131 ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
3132 break;
3133 case R_AARCH64_ABS32:
3134 ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
3135 break;
3136 default:
3137 assert(false && "unexpected relocation type");
3138 }
3139 break;
3140 case llvm::ELF::EM_LOONGARCH:
3141 switch (reloc_type(rel)) {
3142 case R_LARCH_64:
3143 ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
3144 break;
3145 case R_LARCH_32:
3146 ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
3147 break;
3148 default:
3149 assert(false && "unexpected relocation type");
3150 }
3151 break;
3152 case llvm::ELF::EM_X86_64:
3153 switch (reloc_type(rel)) {
3154 case R_X86_64_64:
3155 ApplyELF64ABS64Relocation(symtab, rel, debug_data, rel_section);
3156 break;
3157 case R_X86_64_32:
3158 ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section,
3159 false);
3160 break;
3161 case R_X86_64_32S:
3162 ApplyELF64ABS32Relocation(symtab, rel, debug_data, rel_section, true);
3163 break;
3164 case R_X86_64_PC32:
3165 default:
3166 assert(false && "unexpected relocation type");
3167 }
3168 break;
3169 default:
3170 GetModule()->ReportError("unsupported 64-bit ELF machine arch: {0}", hdr->e_machine);
3171 break;
3172 }
3173 }
3174 }
3175
3176 return 0;
3177}
3178
3180 user_id_t rel_id,
3181 lldb_private::Symtab *thetab) {
3182 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
3183
3184 // Parse in the section list if needed.
3185 SectionList *section_list = GetSectionList();
3186 if (!section_list)
3187 return 0;
3188
3189 user_id_t symtab_id = rel_hdr->sh_link;
3190 user_id_t debug_id = rel_hdr->sh_info;
3191
3192 const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
3193 if (!symtab_hdr)
3194 return 0;
3195
3196 const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id);
3197 if (!debug_hdr)
3198 return 0;
3199
3200 Section *rel = section_list->FindSectionByID(rel_id).get();
3201 if (!rel)
3202 return 0;
3203
3204 Section *symtab = section_list->FindSectionByID(symtab_id).get();
3205 if (!symtab)
3206 return 0;
3207
3208 Section *debug = section_list->FindSectionByID(debug_id).get();
3209 if (!debug)
3210 return 0;
3211
3212 DataExtractorSP rel_data_sp = std::make_shared<DataExtractor>();
3213 DataExtractorSP symtab_data_sp = std::make_shared<DataExtractor>();
3214 DataExtractorSP debug_data_sp = std::make_shared<DataExtractor>();
3215
3216 if (GetData(rel->GetFileOffset(), rel->GetFileSize(), rel_data_sp) &&
3217 GetData(symtab->GetFileOffset(), symtab->GetFileSize(), symtab_data_sp) &&
3218 GetData(debug->GetFileOffset(), debug->GetFileSize(), debug_data_sp)) {
3219 ApplyRelocations(thetab, &m_header, rel_hdr, symtab_hdr, debug_hdr,
3220 *rel_data_sp, *symtab_data_sp, *debug_data_sp, debug);
3221 }
3222
3223 return 0;
3224}
3225
3227 ModuleSP module_sp(GetModule());
3228 if (!module_sp)
3229 return;
3230
3231 Progress progress("Parsing symbol table",
3232 m_file.GetFilename().nonEmptyOr("<Unknown>").str());
3233 ElapsedTime elapsed(module_sp->GetSymtabParseTime());
3234
3235 // We always want to use the main object file so we (hopefully) only have one
3236 // cached copy of our symtab, dynamic sections, etc.
3237 ObjectFile *module_obj_file = module_sp->GetObjectFile();
3238 if (module_obj_file && module_obj_file != this)
3239 return module_obj_file->ParseSymtab(lldb_symtab);
3240
3241 SectionList *section_list = module_sp->GetSectionList();
3242 if (!section_list)
3243 return;
3244
3245 uint64_t symbol_id = 0;
3246
3247 // Sharable objects and dynamic executables usually have 2 distinct symbol
3248 // tables, one named ".symtab", and the other ".dynsym". The dynsym is a
3249 // smaller version of the symtab that only contains global symbols. The
3250 // information found in the dynsym is therefore also found in the symtab,
3251 // while the reverse is not necessarily true.
3252 Section *symtab =
3253 section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get();
3254 if (symtab) {
3255 auto [num_symbols, address_class_map] =
3256 ParseSymbolTable(&lldb_symtab, symbol_id, symtab);
3257 m_address_class_map.merge(address_class_map);
3258 symbol_id += num_symbols;
3259 }
3260
3261 // The symtab section is non-allocable and can be stripped, while the
3262 // .dynsym section which should always be always be there. To support the
3263 // minidebuginfo case we parse .dynsym when there's a .gnu_debuginfo
3264 // section, nomatter if .symtab was already parsed or not. This is because
3265 // minidebuginfo normally removes the .symtab symbols which have their
3266 // matching .dynsym counterparts.
3267 if (!symtab || GetSectionList()->FindSectionByName(".gnu_debugdata")) {
3268 Section *dynsym =
3270 .get();
3271 if (dynsym) {
3272 auto [num_symbols, address_class_map] =
3273 ParseSymbolTable(&lldb_symtab, symbol_id, dynsym);
3274 symbol_id += num_symbols;
3275 m_address_class_map.merge(address_class_map);
3276 } else {
3277 // Try and read the dynamic symbol table from the .dynamic section.
3278 uint32_t dynamic_num_symbols = 0;
3279 std::optional<DataExtractor> symtab_data =
3280 GetDynsymDataFromDynamic(dynamic_num_symbols);
3281 std::optional<DataExtractor> strtab_data = GetDynstrData();
3282 if (symtab_data && strtab_data) {
3283 auto [num_symbols_parsed, address_class_map] = ParseSymbols(
3284 &lldb_symtab, symbol_id, section_list, dynamic_num_symbols,
3285 symtab_data.value(), strtab_data.value());
3286 symbol_id += num_symbols_parsed;
3287 m_address_class_map.merge(address_class_map);
3288 }
3289 }
3290 }
3291
3292 // DT_JMPREL
3293 // If present, this entry's d_ptr member holds the address of
3294 // relocation
3295 // entries associated solely with the procedure linkage table.
3296 // Separating
3297 // these relocation entries lets the dynamic linker ignore them during
3298 // process initialization, if lazy binding is enabled. If this entry is
3299 // present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
3300 // also be present.
3301 const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
3302 if (symbol) {
3303 // Synthesize trampoline symbols to help navigate the PLT.
3304 addr_t addr = symbol->d_ptr;
3305 Section *reloc_section =
3306 section_list->FindSectionContainingFileAddress(addr).get();
3307 if (reloc_section) {
3308 user_id_t reloc_id = reloc_section->GetID();
3309 const ELFSectionHeaderInfo *reloc_header =
3310 GetSectionHeaderByIndex(reloc_id);
3311 if (reloc_header)
3312 ParseTrampolineSymbols(&lldb_symtab, symbol_id, reloc_header, reloc_id);
3313 }
3314 }
3315
3316 if (DWARFCallFrameInfo *eh_frame =
3317 GetModule()->GetUnwindTable().GetEHFrameInfo()) {
3318 ParseUnwindSymbols(&lldb_symtab, eh_frame);
3319 }
3320
3321 // In the event that there's no symbol entry for the entry point we'll
3322 // artificially create one. We delegate to the symtab object the figuring
3323 // out of the proper size, this will usually make it span til the next
3324 // symbol it finds in the section. This means that if there are missing
3325 // symbols the entry point might span beyond its function definition.
3326 // We're fine with this as it doesn't make it worse than not having a
3327 // symbol entry at all.
3328 if (CalculateType() == eTypeExecutable) {
3329 ArchSpec arch = GetArchitecture();
3330 auto entry_point_addr = GetEntryPointAddress();
3331 bool is_valid_entry_point =
3332 entry_point_addr.IsValid() && entry_point_addr.IsSectionOffset();
3333 addr_t entry_point_file_addr = entry_point_addr.GetFileAddress();
3334 if (is_valid_entry_point && !lldb_symtab.FindSymbolContainingFileAddress(
3335 entry_point_file_addr)) {
3336 uint64_t symbol_id = lldb_symtab.GetNumSymbols();
3337 // Don't set the name for any synthetic symbols, the Symbol
3338 // object will generate one if needed when the name is accessed
3339 // via accessors.
3340 SectionSP section_sp = entry_point_addr.GetSection();
3341 Symbol symbol(
3342 /*symID=*/symbol_id,
3343 /*name=*/llvm::StringRef(), // Name will be auto generated.
3344 /*type=*/eSymbolTypeCode,
3345 /*external=*/true,
3346 /*is_debug=*/false,
3347 /*is_trampoline=*/false,
3348 /*is_artificial=*/true,
3349 /*section_sp=*/section_sp,
3350 /*offset=*/entry_point_addr.GetOffset(),
3351 /*size=*/0, // FDE can span multiple symbols so don't use its size.
3352 /*size_is_valid=*/false,
3353 /*contains_linker_annotations=*/false,
3354 /*flags=*/0);
3355 // When the entry point is arm thumb we need to explicitly set its
3356 // class address to reflect that. This is important because expression
3357 // evaluation relies on correctly setting a breakpoint at this
3358 // address.
3359 if (arch.GetMachine() == llvm::Triple::arm &&
3360 (entry_point_file_addr & 1)) {
3361 symbol.GetAddressRef().Slide(-1);
3362 m_address_class_map[entry_point_file_addr - 1] =
3364 } else {
3365 m_address_class_map[entry_point_file_addr] = AddressClass::eCode;
3366 }
3367 lldb_symtab.AddSymbol(symbol);
3368 }
3369 }
3370}
3371
3373{
3374 static const char *debug_prefix = ".debug";
3375
3376 // Set relocated bit so we stop getting called, regardless of whether we
3377 // actually relocate.
3378 section->SetIsRelocated(true);
3379
3380 // We only relocate in ELF relocatable files
3382 return;
3383
3384 const char *section_name = section->GetName().GetCString();
3385 // Can't relocate that which can't be named
3386 if (section_name == nullptr)
3387 return;
3388
3389 // We don't relocate non-debug sections at the moment
3390 if (strncmp(section_name, debug_prefix, strlen(debug_prefix)))
3391 return;
3392
3393 // Relocation section names to look for
3394 std::string needle = std::string(".rel") + section_name;
3395 std::string needlea = std::string(".rela") + section_name;
3396
3398 I != m_section_headers.end(); ++I) {
3399 if (I->sh_type == SHT_RELA || I->sh_type == SHT_REL) {
3400 const char *hay_name = I->section_name.GetCString();
3401 if (hay_name == nullptr)
3402 continue;
3403 if (needle == hay_name || needlea == hay_name) {
3404 const ELFSectionHeader &reloc_header = *I;
3405 user_id_t reloc_id = SectionIndex(I);
3406 RelocateDebugSections(&reloc_header, reloc_id, GetSymtab());
3407 break;
3408 }
3409 }
3410 }
3411}
3412
3414 DWARFCallFrameInfo *eh_frame) {
3415 SectionList *section_list = GetSectionList();
3416 if (!section_list)
3417 return;
3418
3419 // First we save the new symbols into a separate list and add them to the
3420 // symbol table after we collected all symbols we want to add. This is
3421 // neccessary because adding a new symbol invalidates the internal index of
3422 // the symtab what causing the next lookup to be slow because it have to
3423 // recalculate the index first.
3424 std::vector<Symbol> new_symbols;
3425
3426 size_t num_symbols = symbol_table->GetNumSymbols();
3427 uint64_t last_symbol_id =
3428 num_symbols ? symbol_table->SymbolAtIndex(num_symbols - 1)->GetID() : 0;
3429 eh_frame->ForEachFDEEntries([&](lldb::addr_t file_addr, uint32_t size,
3430 dw_offset_t) {
3431 Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr);
3432 if (symbol) {
3433 if (!symbol->GetByteSizeIsValid()) {
3434 symbol->SetByteSize(size);
3435 symbol->SetSizeIsSynthesized(true);
3436 }
3437 } else {
3438 SectionSP section_sp =
3439 section_list->FindSectionContainingFileAddress(file_addr);
3440 if (section_sp) {
3441 addr_t offset = file_addr - section_sp->GetFileAddress();
3442 uint64_t symbol_id = ++last_symbol_id;
3443 // Don't set the name for any synthetic symbols, the Symbol
3444 // object will generate one if needed when the name is accessed
3445 // via accessors.
3446 Symbol eh_symbol(
3447 /*symID=*/symbol_id,
3448 /*name=*/llvm::StringRef(), // Name will be auto generated.
3449 /*type=*/eSymbolTypeCode,
3450 /*external=*/true,
3451 /*is_debug=*/false,
3452 /*is_trampoline=*/false,
3453 /*is_artificial=*/true,
3454 /*section_sp=*/section_sp,
3455 /*offset=*/offset,
3456 /*size=*/0, // FDE can span multiple symbols so don't use its size.
3457 /*size_is_valid=*/false,
3458 /*contains_linker_annotations=*/false,
3459 /*flags=*/0);
3460 new_symbols.push_back(eh_symbol);
3461 }
3462 }
3463 return true;
3464 });
3465
3466 for (const Symbol &s : new_symbols)
3467 symbol_table->AddSymbol(s);
3468}
3469
3471 // TODO: determine this for ELF
3472 return false;
3473}
3474
3475//===----------------------------------------------------------------------===//
3476// Dump
3477//
3478// Dump the specifics of the runtime file container (such as any headers
3479// segments, sections, etc).
3481 ModuleSP module_sp(GetModule());
3482 if (!module_sp) {
3483 return;
3484 }
3485
3486 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
3487 s->Printf("%p: ", static_cast<void *>(this));
3488 s->Indent();
3489 s->PutCString("ObjectFileELF");
3490
3491 ArchSpec header_arch = GetArchitecture();
3492
3493 *s << ", file = '" << m_file
3494 << "', arch = " << header_arch.GetArchitectureName();
3496 s->Printf(", addr = %#16.16" PRIx64, m_memory_addr);
3497 s->EOL();
3498
3500 s->EOL();
3502 s->EOL();
3504 s->EOL();
3505 SectionList *section_list = GetSectionList();
3506 if (section_list)
3507 section_list->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
3508 UINT32_MAX);
3509 Symtab *symtab = GetSymtab();
3510 if (symtab)
3511 symtab->Dump(s, nullptr, eSortOrderNone);
3512 s->EOL();
3514 s->EOL();
3515 DumpELFDynamic(s);
3516 s->EOL();
3517 Address image_info_addr = GetImageInfoAddress(nullptr);
3518 if (image_info_addr.IsValid())
3519 s->Printf("image_info_address = %#16.16" PRIx64 "\n",
3520 image_info_addr.GetFileAddress());
3521}
3522
3523// DumpELFHeader
3524//
3525// Dump the ELF header to the specified output stream
3527 s->PutCString("ELF Header\n");
3528 s->Printf("e_ident[EI_MAG0 ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
3529 s->Printf("e_ident[EI_MAG1 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG1],
3530 header.e_ident[EI_MAG1]);
3531 s->Printf("e_ident[EI_MAG2 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG2],
3532 header.e_ident[EI_MAG2]);
3533 s->Printf("e_ident[EI_MAG3 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG3],
3534 header.e_ident[EI_MAG3]);
3535
3536 s->Printf("e_ident[EI_CLASS ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
3537 s->Printf("e_ident[EI_DATA ] = 0x%2.2x ", header.e_ident[EI_DATA]);
3538 DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
3539 s->Printf("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
3540 s->Printf("e_ident[EI_PAD ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
3541
3542 s->Printf("e_type = 0x%4.4x ", header.e_type);
3543 DumpELFHeader_e_type(s, header.e_type);
3544 s->Printf("\ne_machine = 0x%4.4x\n", header.e_machine);
3545 s->Printf("e_version = 0x%8.8x\n", header.e_version);
3546 s->Printf("e_entry = 0x%8.8" PRIx64 "\n", header.e_entry);
3547 s->Printf("e_phoff = 0x%8.8" PRIx64 "\n", header.e_phoff);
3548 s->Printf("e_shoff = 0x%8.8" PRIx64 "\n", header.e_shoff);
3549 s->Printf("e_flags = 0x%8.8x\n", header.e_flags);
3550 s->Printf("e_ehsize = 0x%4.4x\n", header.e_ehsize);
3551 s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
3552 s->Printf("e_phnum = 0x%8.8x\n", header.e_phnum);
3553 s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
3554 s->Printf("e_shnum = 0x%8.8x\n", header.e_shnum);
3555 s->Printf("e_shstrndx = 0x%8.8x\n", header.e_shstrndx);
3556}
3557
3558// DumpELFHeader_e_type
3559//
3560// Dump an token value for the ELF header member e_type
3562 switch (e_type) {
3563 case ET_NONE:
3564 *s << "ET_NONE";
3565 break;
3566 case ET_REL:
3567 *s << "ET_REL";
3568 break;
3569 case ET_EXEC:
3570 *s << "ET_EXEC";
3571 break;
3572 case ET_DYN:
3573 *s << "ET_DYN";
3574 break;
3575 case ET_CORE:
3576 *s << "ET_CORE";
3577 break;
3578 default:
3579 break;
3580 }
3581}
3582
3583// DumpELFHeader_e_ident_EI_DATA
3584//
3585// Dump an token value for the ELF header member e_ident[EI_DATA]
3587 unsigned char ei_data) {
3588 switch (ei_data) {
3589 case ELFDATANONE:
3590 *s << "ELFDATANONE";
3591 break;
3592 case ELFDATA2LSB:
3593 *s << "ELFDATA2LSB - Little Endian";
3594 break;
3595 case ELFDATA2MSB:
3596 *s << "ELFDATA2MSB - Big Endian";
3597 break;
3598 default:
3599 break;
3600 }
3601}
3602
3603// DumpELFProgramHeader
3604//
3605// Dump a single ELF program header to the specified output stream
3607 const ELFProgramHeader &ph) {
3609 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset,
3610 ph.p_vaddr, ph.p_paddr);
3611 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz,
3612 ph.p_flags);
3613
3615 s->Printf(") %8.8" PRIx64, ph.p_align);
3616}
3617
3618// DumpELFProgramHeader_p_type
3619//
3620// Dump an token value for the ELF program header member p_type which describes
3621// the type of the program header
3623 const int kStrWidth = 15;
3624 switch (p_type) {
3625 CASE_AND_STREAM(s, PT_NULL, kStrWidth);
3626 CASE_AND_STREAM(s, PT_LOAD, kStrWidth);
3627 CASE_AND_STREAM(s, PT_DYNAMIC, kStrWidth);
3628 CASE_AND_STREAM(s, PT_INTERP, kStrWidth);
3629 CASE_AND_STREAM(s, PT_NOTE, kStrWidth);
3630 CASE_AND_STREAM(s, PT_SHLIB, kStrWidth);
3631 CASE_AND_STREAM(s, PT_PHDR, kStrWidth);
3632 CASE_AND_STREAM(s, PT_TLS, kStrWidth);
3633 CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
3634 default:
3635 s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
3636 break;
3637 }
3638}
3639
3640// DumpELFProgramHeader_p_flags
3641//
3642// Dump an token value for the ELF program header member p_flags
3644 *s << ((p_flags & PF_X) ? "PF_X" : " ")
3645 << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
3646 << ((p_flags & PF_W) ? "PF_W" : " ")
3647 << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
3648 << ((p_flags & PF_R) ? "PF_R" : " ");
3649}
3650
3651// DumpELFProgramHeaders
3652//
3653// Dump all of the ELF program header to the specified output stream
3655 if (!ParseProgramHeaders())
3656 return;
3657
3658 s->PutCString("Program Headers\n");
3659 s->PutCString("IDX p_type p_offset p_vaddr p_paddr "
3660 "p_filesz p_memsz p_flags p_align\n");
3661 s->PutCString("==== --------------- -------- -------- -------- "
3662 "-------- -------- ------------------------- --------\n");
3663
3664 for (const auto &H : llvm::enumerate(m_program_headers)) {
3665 s->Format("[{0,2}] ", H.index());
3667 s->EOL();
3668 }
3669}
3670
3671// DumpELFSectionHeader
3672//
3673// Dump a single ELF section header to the specified output stream
3675 const ELFSectionHeaderInfo &sh) {
3676 s->Printf("%8.8x ", sh.sh_name);
3678 s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
3680 s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr,
3681 sh.sh_offset, sh.sh_size);
3682 s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
3683 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
3684}
3685
3686// DumpELFSectionHeader_sh_type
3687//
3688// Dump an token value for the ELF section header member sh_type which
3689// describes the type of the section
3691 const int kStrWidth = 12;
3692 switch (sh_type) {
3693 CASE_AND_STREAM(s, SHT_NULL, kStrWidth);
3694 CASE_AND_STREAM(s, SHT_PROGBITS, kStrWidth);
3695 CASE_AND_STREAM(s, SHT_SYMTAB, kStrWidth);
3696 CASE_AND_STREAM(s, SHT_STRTAB, kStrWidth);
3697 CASE_AND_STREAM(s, SHT_RELA, kStrWidth);
3698 CASE_AND_STREAM(s, SHT_HASH, kStrWidth);
3699 CASE_AND_STREAM(s, SHT_DYNAMIC, kStrWidth);
3700 CASE_AND_STREAM(s, SHT_NOTE, kStrWidth);
3701 CASE_AND_STREAM(s, SHT_NOBITS, kStrWidth);
3702 CASE_AND_STREAM(s, SHT_REL, kStrWidth);
3703 CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth);
3704 CASE_AND_STREAM(s, SHT_DYNSYM, kStrWidth);
3705 CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth);
3706 CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth);
3707 CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth);
3708 CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth);
3709 default:
3710 s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
3711 break;
3712 }
3713}
3714
3715// DumpELFSectionHeader_sh_flags
3716//
3717// Dump an token value for the ELF section header member sh_flags
3719 elf_xword sh_flags) {
3720 *s << ((sh_flags & SHF_WRITE) ? "WRITE" : " ")
3721 << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
3722 << ((sh_flags & SHF_ALLOC) ? "ALLOC" : " ")
3723 << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
3724 << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : " ");
3725}
3726
3727// DumpELFSectionHeaders
3728//
3729// Dump all of the ELF section header to the specified output stream
3731 if (!ParseSectionHeaders())
3732 return;
3733
3734 s->PutCString("Section Headers\n");
3735 s->PutCString("IDX name type flags "
3736 "addr offset size link info addralgn "
3737 "entsize Name\n");
3738 s->PutCString("==== -------- ------------ -------------------------------- "
3739 "-------- -------- -------- -------- -------- -------- "
3740 "-------- ====================\n");
3741
3742 uint32_t idx = 0;
3744 I != m_section_headers.end(); ++I, ++idx) {
3745 s->Printf("[%2u] ", idx);
3747 const char *section_name = I->section_name.AsCString("");
3748 if (section_name)
3749 *s << ' ' << section_name << "\n";
3750 }
3751}
3752
3754 size_t num_modules = ParseDependentModules();
3755
3756 if (num_modules > 0) {
3757 s->PutCString("Dependent Modules:\n");
3758 for (unsigned i = 0; i < num_modules; ++i) {
3759 const FileSpec &spec = m_filespec_up->GetFileSpecAtIndex(i);
3760 s->Format(" {0}\n", spec.GetFilename());
3761 }
3762 }
3763}
3764
3765std::string static getDynamicTagAsString(uint16_t Arch, uint64_t Type) {
3766#define DYNAMIC_STRINGIFY_ENUM(tag, value) \
3767 case value: \
3768 return #tag;
3769
3770#define DYNAMIC_TAG(n, v)
3771 switch (Arch) {
3772 case llvm::ELF::EM_AARCH64:
3773 switch (Type) {
3774#define AARCH64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3775#include "llvm/BinaryFormat/DynamicTags.def"
3776#undef AARCH64_DYNAMIC_TAG
3777 }
3778 break;
3779
3780 case llvm::ELF::EM_HEXAGON:
3781 switch (Type) {
3782#define HEXAGON_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3783#include "llvm/BinaryFormat/DynamicTags.def"
3784#undef HEXAGON_DYNAMIC_TAG
3785 }
3786 break;
3787
3788 case llvm::ELF::EM_MIPS:
3789 switch (Type) {
3790#define MIPS_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3791#include "llvm/BinaryFormat/DynamicTags.def"
3792#undef MIPS_DYNAMIC_TAG
3793 }
3794 break;
3795
3796 case llvm::ELF::EM_PPC:
3797 switch (Type) {
3798#define PPC_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3799#include "llvm/BinaryFormat/DynamicTags.def"
3800#undef PPC_DYNAMIC_TAG
3801 }
3802 break;
3803
3804 case llvm::ELF::EM_PPC64:
3805 switch (Type) {
3806#define PPC64_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3807#include "llvm/BinaryFormat/DynamicTags.def"
3808#undef PPC64_DYNAMIC_TAG
3809 }
3810 break;
3811
3812 case llvm::ELF::EM_RISCV:
3813 switch (Type) {
3814#define RISCV_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3815#include "llvm/BinaryFormat/DynamicTags.def"
3816#undef RISCV_DYNAMIC_TAG
3817 }
3818 break;
3819
3820 case llvm::ELF::EM_SPARC:
3821 case llvm::ELF::EM_SPARC32PLUS:
3822 case llvm::ELF::EM_SPARCV9:
3823 switch (Type) {
3824#define SPARC_DYNAMIC_TAG(name, value) DYNAMIC_STRINGIFY_ENUM(name, value)
3825#include "llvm/BinaryFormat/DynamicTags.def"
3826#undef SPARC_DYNAMIC_TAG
3827 }
3828 break;
3829 }
3830#undef DYNAMIC_TAG
3831 switch (Type) {
3832// Now handle all dynamic tags except the architecture specific ones
3833#define AARCH64_DYNAMIC_TAG(name, value)
3834#define MIPS_DYNAMIC_TAG(name, value)
3835#define HEXAGON_DYNAMIC_TAG(name, value)
3836#define PPC_DYNAMIC_TAG(name, value)
3837#define PPC64_DYNAMIC_TAG(name, value)
3838#define RISCV_DYNAMIC_TAG(name, value)
3839#define SPARC_DYNAMIC_TAG(name, value)
3840// Also ignore marker tags such as DT_HIOS (maps to DT_VERNEEDNUM), etc.
3841#define DYNAMIC_TAG_MARKER(name, value)
3842#define DYNAMIC_TAG(name, value) \
3843 case value: \
3844 return #name;
3845#include "llvm/BinaryFormat/DynamicTags.def"
3846#undef DYNAMIC_TAG
3847#undef AARCH64_DYNAMIC_TAG
3848#undef MIPS_DYNAMIC_TAG
3849#undef HEXAGON_DYNAMIC_TAG
3850#undef PPC_DYNAMIC_TAG
3851#undef PPC64_DYNAMIC_TAG
3852#undef RISCV_DYNAMIC_TAG
3853#undef SPARC_DYNAMIC_TAG
3854#undef DYNAMIC_TAG_MARKER
3855#undef DYNAMIC_STRINGIFY_ENUM
3856 default:
3857 return "<unknown:>0x" + llvm::utohexstr(Type, true);
3858 }
3859}
3860
3863 if (m_dynamic_symbols.empty())
3864 return;
3865
3866 s->PutCString(".dynamic:\n");
3867 s->PutCString("IDX d_tag d_val/d_ptr\n");
3868 s->PutCString("==== ---------------- ------------------\n");
3869 uint32_t idx = 0;
3870 for (const auto &entry : m_dynamic_symbols) {
3871 s->Printf("[%2u] ", idx++);
3872 s->Printf(
3873 "%-16s 0x%16.16" PRIx64,
3874 getDynamicTagAsString(m_header.e_machine, entry.symbol.d_tag).c_str(),
3875 entry.symbol.d_ptr);
3876 if (!entry.name.empty())
3877 s->Printf(" \"%s\"", entry.name.c_str());
3878 s->EOL();
3879 }
3880}
3881
3883 if (!ParseHeader())
3884 return ArchSpec();
3885
3886 if (m_section_headers.empty()) {
3887 // Allow elf notes to be parsed which may affect the detected architecture.
3889 }
3890
3891 if (CalculateType() == eTypeCoreFile &&
3892 !m_arch_spec.TripleOSWasSpecified()) {
3893 // Core files don't have section headers yet they have PT_NOTE program
3894 // headers that might shed more light on the architecture
3895 for (const elf::ELFProgramHeader &H : ProgramHeaders()) {
3896 if (H.p_type != PT_NOTE || H.p_offset == 0 || H.p_filesz == 0)
3897 continue;
3898 DataExtractor data;
3899 if (data.SetData(*m_data_nsp, H.p_offset, H.p_filesz) == H.p_filesz) {
3900 UUID uuid;
3902 }
3903 }
3904 }
3905 return m_arch_spec;
3906}
3907
3909 switch (m_header.e_type) {
3910 case llvm::ELF::ET_NONE:
3911 // 0 - No file type
3912 return eTypeUnknown;
3913
3914 case llvm::ELF::ET_REL:
3915 // 1 - Relocatable file
3916 return eTypeObjectFile;
3917
3918 case llvm::ELF::ET_EXEC:
3919 // 2 - Executable file
3920 return eTypeExecutable;
3921
3922 case llvm::ELF::ET_DYN:
3923 // 3 - Shared object file
3924 return eTypeSharedLibrary;
3925
3926 case ET_CORE:
3927 // 4 - Core file
3928 return eTypeCoreFile;
3929
3930 default:
3931 break;
3932 }
3933 return eTypeUnknown;
3934}
3935
3937 switch (m_header.e_type) {
3938 case llvm::ELF::ET_NONE:
3939 // 0 - No file type
3940 return eStrataUnknown;
3941
3942 case llvm::ELF::ET_REL:
3943 // 1 - Relocatable file
3944 return eStrataUnknown;
3945
3946 case llvm::ELF::ET_EXEC:
3947 // 2 - Executable file
3948 {
3949 SectionList *section_list = GetSectionList();
3950 if (section_list) {
3951 llvm::StringRef loader_section_name(".interp");
3952 SectionSP loader_section =
3953 section_list->FindSectionByName(loader_section_name);
3954 if (loader_section) {
3955 char buffer[256];
3956 size_t read_size =
3957 ReadSectionData(loader_section.get(), 0, buffer, sizeof(buffer));
3958
3959 // We compare the content of .interp section
3960 // It will contains \0 when counting read_size, so the size needs to
3961 // decrease by one
3962 llvm::StringRef loader_name(buffer, read_size - 1);
3963 llvm::StringRef freebsd_kernel_loader_name("/red/herring");
3964 if (loader_name == freebsd_kernel_loader_name)
3965 return eStrataKernel;
3966 }
3967 }
3968 return eStrataUser;
3969 }
3970
3971 case llvm::ELF::ET_DYN:
3972 // 3 - Shared object file
3973 // TODO: is there any way to detect that an shared library is a kernel
3974 // related executable by inspecting the program headers, section headers,
3975 // symbols, or any other flag bits???
3976 return eStrataUnknown;
3977
3978 case ET_CORE:
3979 // 4 - Core file
3980 // TODO: is there any way to detect that an core file is a kernel
3981 // related executable by inspecting the program headers, section headers,
3982 // symbols, or any other flag bits???
3983 return eStrataUnknown;
3984
3985 default:
3986 break;
3987 }
3988 return eStrataUnknown;
3989}
3990
3992 lldb::offset_t section_offset, void *dst,
3993 size_t dst_len) {
3994 // If some other objectfile owns this data, pass this to them.
3995 if (section->GetObjectFile() != this)
3996 return section->GetObjectFile()->ReadSectionData(section, section_offset,
3997 dst, dst_len);
3998
3999 if (!section->Test(SHF_COMPRESSED))
4000 return ObjectFile::ReadSectionData(section, section_offset, dst, dst_len);
4001
4002 // For compressed sections we need to read to full data to be able to
4003 // decompress.
4004 DataExtractor data;
4005 ReadSectionData(section, data);
4006 return data.CopyData(section_offset, dst_len, dst);
4007}
4008
4010 DataExtractor &section_data) {
4011 // If some other objectfile owns this data, pass this to them.
4012 if (section->GetObjectFile() != this)
4013 return section->GetObjectFile()->ReadSectionData(section, section_data);
4014
4015 size_t result = ObjectFile::ReadSectionData(section, section_data);
4016 if (result == 0 || !(section->Get() & llvm::ELF::SHF_COMPRESSED))
4017 return result;
4018
4019 auto Decompressor = llvm::object::Decompressor::create(
4020 section->GetName().GetStringRef(),
4021 {reinterpret_cast<const char *>(section_data.GetDataStart()),
4022 size_t(section_data.GetByteSize())},
4024 if (!Decompressor) {
4025 GetModule()->ReportWarning(
4026 "unable to initialize decompressor for section '{0}': {1}",
4027 section->GetName().GetCString(),
4028 llvm::toString(Decompressor.takeError()).c_str());
4029 section_data.Clear();
4030 return 0;
4031 }
4032
4033 auto buffer_sp =
4034 std::make_shared<DataBufferHeap>(Decompressor->getDecompressedSize(), 0);
4035 if (auto error = Decompressor->decompress(
4036 {buffer_sp->GetBytes(), size_t(buffer_sp->GetByteSize())})) {
4037 GetModule()->ReportWarning("decompression of section '{0}' failed: {1}",
4038 section->GetName().GetCString(),
4039 llvm::toString(std::move(error)).c_str());
4040 section_data.Clear();
4041 return 0;
4042 }
4043
4044 section_data.SetData(buffer_sp);
4045 return buffer_sp->GetByteSize();
4046}
4047
4048llvm::ArrayRef<ELFProgramHeader> ObjectFileELF::ProgramHeaders() {
4050 return m_program_headers;
4051}
4052
4054 // Try and read the program header from our cached m_data_nsp which can come
4055 // from the file on disk being mmap'ed or from the initial part of the ELF
4056 // file we read from memory and cached.
4058 if (data.GetByteSize() == H.p_filesz)
4059 return data;
4060 if (IsInMemory()) {
4061 // We have a ELF file in process memory, read the program header data from
4062 // the process.
4063 if (ProcessSP process_sp = m_process_wp.lock()) {
4064 const lldb::offset_t base_file_addr = GetBaseAddress().GetFileAddress();
4065 const addr_t load_bias = m_memory_addr - base_file_addr;
4066 const addr_t data_addr = H.p_vaddr + load_bias;
4067 if (DataBufferSP data_sp = ReadMemory(process_sp, data_addr, H.p_memsz))
4068 return DataExtractor(data_sp, GetByteOrder(), GetAddressByteSize());
4069 }
4070 }
4071 return DataExtractor();
4072}
4073
4075 for (const ELFProgramHeader &H : ProgramHeaders()) {
4076 if (H.p_paddr != 0)
4077 return true;
4078 }
4079 return false;
4080}
4081
4082std::vector<ObjectFile::LoadableData>
4084 // Create a list of loadable data from loadable segments, using physical
4085 // addresses if they aren't all null
4086 std::vector<LoadableData> loadables;
4087 bool should_use_paddr = AnySegmentHasPhysicalAddress();
4088 for (const ELFProgramHeader &H : ProgramHeaders()) {
4089 LoadableData loadable;
4090 if (H.p_type != llvm::ELF::PT_LOAD)
4091 continue;
4092 loadable.Dest = should_use_paddr ? H.p_paddr : H.p_vaddr;
4093 if (loadable.Dest == LLDB_INVALID_ADDRESS)
4094 continue;
4095 if (H.p_filesz == 0)
4096 continue;
4097 auto segment_data = GetSegmentData(H);
4098 loadable.Contents = llvm::ArrayRef<uint8_t>(segment_data.GetDataStart(),
4099 segment_data.GetByteSize());
4100 loadables.push_back(loadable);
4101 }
4102 return loadables;
4103}
4104
4107 uint64_t Offset) {
4109 Offset);
4110}
4111
4112std::optional<DataExtractor>
4114 uint64_t offset) {
4115 // ELFDynamic values contain a "d_ptr" member that will be a load address if
4116 // we have an ELF file read from memory, or it will be a file address if it
4117 // was read from a ELF file. This function will correctly fetch data pointed
4118 // to by the ELFDynamic::d_ptr, or return std::nullopt if the data isn't
4119 // available.
4120 const lldb::addr_t d_ptr_addr = dyn->d_ptr + offset;
4121 if (ProcessSP process_sp = m_process_wp.lock()) {
4122 if (DataBufferSP data_sp = ReadMemory(process_sp, d_ptr_addr, length))
4123 return DataExtractor(data_sp, GetByteOrder(), GetAddressByteSize());
4124 } else {
4125 // We have an ELF file with no section headers or we didn't find the
4126 // .dynamic section. Try and find the .dynstr section.
4127 Address addr;
4128 if (!addr.ResolveAddressUsingFileSections(d_ptr_addr, GetSectionList()))
4129 return std::nullopt;
4130 DataExtractor data;
4131 addr.GetSection()->GetSectionData(data);
4132 return DataExtractor(data, d_ptr_addr - addr.GetSection()->GetFileAddress(),
4133 length);
4134 }
4135 return std::nullopt;
4136}
4137
4138std::optional<DataExtractor> ObjectFileELF::GetDynstrData() {
4139 if (SectionList *section_list = GetSectionList()) {
4140 // Find the SHT_DYNAMIC section.
4141 if (Section *dynamic =
4142 section_list
4143 ->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
4144 .get()) {
4145 assert(dynamic->GetObjectFile() == this);
4146 if (const ELFSectionHeaderInfo *header =
4147 GetSectionHeaderByIndex(dynamic->GetID())) {
4148 // sh_link: section header index of string table used by entries in
4149 // the section.
4150 if (Section *dynstr =
4151 section_list->FindSectionByID(header->sh_link).get()) {
4152 DataExtractor data;
4153 if (ReadSectionData(dynstr, data))
4154 return data;
4155 }
4156 }
4157 }
4158 }
4159
4160 // Every ELF file which represents an executable or shared library has
4161 // mandatory .dynamic entries. Two of these values are DT_STRTAB and DT_STRSZ
4162 // and represent the dynamic symbol tables's string table. These are needed
4163 // by the dynamic loader and we can read them from a process' address space.
4164 //
4165 // When loading and ELF file from memory, only the program headers are
4166 // guaranteed end up being mapped into memory, and we can find these values in
4167 // the PT_DYNAMIC segment.
4168 const ELFDynamic *strtab = FindDynamicSymbol(DT_STRTAB);
4169 const ELFDynamic *strsz = FindDynamicSymbol(DT_STRSZ);
4170 if (strtab == nullptr || strsz == nullptr)
4171 return std::nullopt;
4172
4173 return ReadDataFromDynamic(strtab, strsz->d_val, /*offset=*/0);
4174}
4175
4176std::optional<lldb_private::DataExtractor> ObjectFileELF::GetDynamicData() {
4177 DataExtractor data;
4178 // The PT_DYNAMIC program header describes where the .dynamic section is and
4179 // doesn't require parsing section headers. The PT_DYNAMIC is required by
4180 // executables and shared libraries so it will always be available.
4181 for (const ELFProgramHeader &H : ProgramHeaders()) {
4182 if (H.p_type == llvm::ELF::PT_DYNAMIC) {
4183 data = GetSegmentData(H);
4184 if (data.GetByteSize() > 0) {
4185 m_dynamic_base_addr = H.p_vaddr;
4186 return data;
4187 }
4188 }
4189 }
4190 // Fall back to using section headers.
4191 if (SectionList *section_list = GetSectionList()) {
4192 // Find the SHT_DYNAMIC section.
4193 if (Section *dynamic =
4194 section_list
4195 ->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
4196 .get()) {
4197 assert(dynamic->GetObjectFile() == this);
4198 if (ReadSectionData(dynamic, data)) {
4199 m_dynamic_base_addr = dynamic->GetFileAddress();
4200 return data;
4201 }
4202 }
4203 }
4204 return std::nullopt;
4205}
4206
4208 const ELFDynamic *hash = FindDynamicSymbol(DT_HASH);
4209 if (hash == nullptr)
4210 return std::nullopt;
4211
4212 // The DT_HASH header looks like this:
4213 struct DtHashHeader {
4214 uint32_t nbucket;
4215 uint32_t nchain;
4216 };
4217 if (auto data = ReadDataFromDynamic(hash, 8)) {
4218 // We don't need the number of buckets value "nbucket", we just need the
4219 // "nchain" value which contains the number of symbols.
4220 offset_t offset = offsetof(DtHashHeader, nchain);
4221 return data->GetU32(&offset);
4222 }
4223
4224 return std::nullopt;
4225}
4226
4228 const ELFDynamic *gnu_hash = FindDynamicSymbol(DT_GNU_HASH);
4229 if (gnu_hash == nullptr)
4230 return std::nullopt;
4231
4232 // Create a DT_GNU_HASH header
4233 // https://flapenguin.me/elf-dt-gnu-hash
4234 struct DtGnuHashHeader {
4235 uint32_t nbuckets = 0;
4236 uint32_t symoffset = 0;
4237 uint32_t bloom_size = 0;
4238 uint32_t bloom_shift = 0;
4239 };
4240 uint32_t num_symbols = 0;
4241 // Read enogh data for the DT_GNU_HASH header so we can extract the values.
4242 if (auto data = ReadDataFromDynamic(gnu_hash, sizeof(DtGnuHashHeader))) {
4243 offset_t offset = 0;
4244 DtGnuHashHeader header;
4245 header.nbuckets = data->GetU32(&offset);
4246 header.symoffset = data->GetU32(&offset);
4247 header.bloom_size = data->GetU32(&offset);
4248 header.bloom_shift = data->GetU32(&offset);
4249 const size_t addr_size = GetAddressByteSize();
4250 const addr_t buckets_offset =
4251 sizeof(DtGnuHashHeader) + addr_size * header.bloom_size;
4252 std::vector<uint32_t> buckets;
4253 if (auto bucket_data = ReadDataFromDynamic(gnu_hash, header.nbuckets * 4,
4254 buckets_offset)) {
4255 offset = 0;
4256 for (uint32_t i = 0; i < header.nbuckets; ++i)
4257 buckets.push_back(bucket_data->GetU32(&offset));
4258 // Locate the chain that handles the largest index bucket.
4259 uint32_t last_symbol = 0;
4260 for (uint32_t bucket_value : buckets)
4261 last_symbol = std::max(bucket_value, last_symbol);
4262 if (last_symbol < header.symoffset) {
4263 num_symbols = header.symoffset;
4264 } else {
4265 // Walk the bucket's chain to add the chain length to the total.
4266 const addr_t chains_base_offset = buckets_offset + header.nbuckets * 4;
4267 for (;;) {
4268 if (auto chain_entry_data = ReadDataFromDynamic(
4269 gnu_hash, 4,
4270 chains_base_offset + (last_symbol - header.symoffset) * 4)) {
4271 offset = 0;
4272 uint32_t chain_entry = chain_entry_data->GetU32(&offset);
4273 ++last_symbol;
4274 // If the low bit is set, this entry is the end of the chain.
4275 if (chain_entry & 1)
4276 break;
4277 } else {
4278 break;
4279 }
4280 }
4281 num_symbols = last_symbol;
4282 }
4283 }
4284 }
4285 if (num_symbols > 0)
4286 return num_symbols;
4287
4288 return std::nullopt;
4289}
4290
4291std::optional<DataExtractor>
4293 // Every ELF file which represents an executable or shared library has
4294 // mandatory .dynamic entries. The DT_SYMTAB value contains a pointer to the
4295 // symbol table, and DT_SYMENT contains the size of a symbol table entry.
4296 // We then can use either the DT_HASH or DT_GNU_HASH to find the number of
4297 // symbols in the symbol table as the symbol count is not stored in the
4298 // .dynamic section as a key/value pair.
4299 //
4300 // When loading and ELF file from memory, only the program headers end up
4301 // being mapped into memory, and we can find these values in the PT_DYNAMIC
4302 // segment.
4303 num_symbols = 0;
4304 // Get the process in case this is an in memory ELF file.
4305 ProcessSP process_sp(m_process_wp.lock());
4306 const ELFDynamic *symtab = FindDynamicSymbol(DT_SYMTAB);
4307 const ELFDynamic *syment = FindDynamicSymbol(DT_SYMENT);
4308 // DT_SYMTAB and DT_SYMENT are mandatory.
4309 if (symtab == nullptr || syment == nullptr)
4310 return std::nullopt;
4311
4312 if (std::optional<uint32_t> syms = GetNumSymbolsFromDynamicHash())
4313 num_symbols = *syms;
4314 else if (std::optional<uint32_t> syms = GetNumSymbolsFromDynamicGnuHash())
4315 num_symbols = *syms;
4316 else
4317 return std::nullopt;
4318 if (num_symbols == 0)
4319 return std::nullopt;
4320 return ReadDataFromDynamic(symtab, syment->d_val * num_symbols);
4321}
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:376
#define LLDB_LOGF(log,...)
Definition Log.h:390
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...
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)
lldb::user_id_t GetSectionIndexByName(const char *name)
Utility method for looking up a section given its name.
ObjectFileELF(const lldb::ModuleSP &module_sp, lldb::DataExtractorSP extractor_sp, lldb::offset_t data_offset, const lldb_private::FileSpec *file, lldb::offset_t offset, lldb::offset_t length)
uint32_t GetAddressByteSize() const override
Gets the address size in bytes for the current object file.
SectionHeaderColl::const_iterator SectionHeaderCollConstIter
ProgramHeaderColl m_program_headers
Collection of program headers.
void DumpELFDynamic(lldb_private::Stream *s)
ELF dump the .dynamic section.
unsigned ApplyRelocations(lldb_private::Symtab *symtab, const elf::ELFHeader *hdr, const elf::ELFSectionHeader *rel_hdr, const elf::ELFSectionHeader *symtab_hdr, const elf::ELFSectionHeader *debug_hdr, lldb_private::DataExtractor &rel_data, lldb_private::DataExtractor &symtab_data, lldb_private::DataExtractor &debug_data, lldb_private::Section *rel_section)
lldb::ByteOrder GetByteOrder() const override
Gets whether endian swapping should occur when extracting data from this object file.
bool ParseHeader() override
Attempts to parse the object header.
static void 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::addr_t m_dynamic_base_addr
The file address of the .dynamic section.
uint32_t GetDependentModules(lldb_private::FileSpecList &files) override
Extract the dependent modules from an object file.
size_t ParseSectionHeaders()
Parses all section headers present in this object file and populates m_section_headers.
lldb_private::Address GetBaseAddress() override
Returns base address of this object file.
bool IsStripped() override
Detect if this object file has been stripped of local symbols.
const elf::ELFDynamic * FindDynamicSymbol(unsigned tag)
std::map< lldb::addr_t, lldb_private::AddressClass > FileAddressToAddressClassMap
An ordered map of file address to address class.
llvm::ArrayRef< elf::ELFProgramHeader > ProgramHeaders()
std::optional< lldb_private::DataExtractor > GetDynstrData()
Get the bytes that represent the dynamic string table data.
lldb_private::Address GetImageInfoAddress(lldb_private::Target *target) override
Similar to Process::GetImageInfoAddress().
A section + offset based address range class.
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:301
bool ResolveAddressUsingFileSections(lldb::addr_t addr, const SectionList *sections)
Resolve a file virtual address using a section list.
Definition Address.cpp:249
lldb::SectionSP GetSection() const
Get const accessor for the section.
Definition Address.h:426
bool Slide(int64_t offset)
Definition Address.h:446
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:281
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
bool SetOffset(lldb::addr_t offset)
Set accessor for the offset.
Definition Address.h:435
An architecture specification class.
Definition ArchSpec.h:32
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:452
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:544
void SetFlags(uint32_t flags)
Definition ArchSpec.h:617
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:747
uint32_t GetFlags() const
Definition ArchSpec.h:615
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:881
@ 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:740
void SetSubtargetFeatures(llvm::SubtargetFeatures &&subtarget_features)
Definition ArchSpec.h:625
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.
bool AppendIfUnique(const FileSpec &file)
Append a FileSpec object if unique.
A file utility class.
Definition FileSpec.h:57
FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const
Definition FileSpec.cpp:423
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:249
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:376
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:779
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:777
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:771
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:685
lldb::ProcessWP m_process_wp
Definition ObjectFile.h:775
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:520
static SectionList Merge(SectionList &lhs, SectionList &rhs, MergeCallback filter)
Definition Section.cpp:687
lldb::SectionSP FindSectionByID(lldb::user_id_t sect_id) const
Definition Section.cpp:581
lldb::SectionSP FindSectionContainingFileAddress(lldb::addr_t addr, uint32_t depth=UINT32_MAX) const
Definition Section.cpp:618
size_t GetSize() const
Definition Section.h:77
lldb::SectionSP FindSectionByName(llvm::StringRef section_name) const
Definition Section.cpp:559
size_t AddSection(const lldb::SectionSP &section_sp)
Definition Section.cpp:480
lldb::SectionSP FindSectionByType(lldb::SectionType sect_type, bool check_children, size_t start_idx=0) const
Definition Section.cpp:599
void Dump(llvm::raw_ostream &s, unsigned indent, Target *target, bool show_header, uint32_t depth) const
Definition Section.cpp:645
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition Section.cpp:552
ConstString GetName() const
Definition Section.h:211
void SetIsRelocated(bool b)
Definition Section.h:275
lldb::offset_t GetFileOffset() const
Definition Section.h:181
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:137
void SetSizeIsSynthesized(bool b)
Definition Symbol.h:191
bool GetByteSizeIsValid() const
Definition Symbol.h:209
Address & GetAddressRef()
Definition Symbol.h:73
void SetIsWeak(bool b)
Definition Symbol.h:207
ConstString GetName() const
Definition Symbol.cpp:511
void SetByteSize(lldb::addr_t size)
Definition Symbol.h:213
Symbol * FindSymbolByID(lldb::user_id_t uid) const
Definition Symtab.cpp: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:2411
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:2400
bool SetSectionLoadAddress(const lldb::SectionSP &section, lldb::addr_t load_addr, bool warn_multiple=false)
Definition Target.cpp:3495
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:339
uint64_t offset_t
Definition lldb-types.h:85
std::shared_ptr< lldb_private::Process > ProcessSP
SymbolType
Symbol types.
@ eSymbolTypeUndefined
@ eSymbolTypeTrampoline
@ eSymbolTypeResolver
@ eSymbolTypeSourceFile
@ eSymbolTypeAbsolute
ByteOrder
Byte ordering definitions.
uint64_t user_id_t
Definition lldb-types.h:82
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
std::shared_ptr< lldb_private::Section > SectionSP
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
@ eSectionTypeELFDynamicSymbols
Elf SHT_DYNSYM section.
@ eSectionTypeZeroFill
@ eSectionTypeARMextab
@ eSectionTypeContainer
The section contains child sections.
@ eSectionTypeELFDynamicLinkInfo
Elf SHT_DYNAMIC section.
@ eSectionTypeAbsoluteAddress
Dummy section for symbols with absolute address.
@ eSectionTypeELFRelocationEntries
Elf SHT_REL or SHT_REL section.
@ eSectionTypeLLDBFormatters
@ eSectionTypeEHFrame
@ eSectionTypeLLDBTypeSummaries
@ eSectionTypeGoSymtab
@ eSectionTypeARMexidx
@ eSectionTypeSwiftModules
@ eSectionTypeDWARFGNUDebugAltLink
@ eSectionTypeELFSymbolTable
Elf SHT_SYMTAB section.
std::shared_ptr< lldb_private::DataExtractor > DataExtractorSP
std::shared_ptr< lldb_private::Module > ModuleSP
bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)
Parse an ELFNote entry from the given DataExtractor starting at position offset.
std::string n_name
elf::elf_word n_namesz
lldb_private::ConstString section_name
Represents an entry in an ELF dynamic table.
Definition ELFHeader.h:276
elf_addr d_ptr
Pointer value of the table entry.
Definition ELFHeader.h:280
elf_xword d_val
Integer value of the table entry.
Definition ELFHeader.h:279
bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)
Parse an ELFDynamic entry from the given DataExtractor starting at position offset.
elf_sxword d_tag
Type of dynamic table entry.
Definition ELFHeader.h:277
Generic representation of an ELF file header.
Definition ELFHeader.h:56
elf_word e_shnum
Number of section header entries.
Definition ELFHeader.h:76
bool HasHeaderExtension() const
Check if there should be header extension in section header #0.
Definition ELFHeader.cpp:81
elf_off e_phoff
File offset of program header table.
Definition ELFHeader.h:59
bool Is64Bit() const
Returns true if this is a 64 bit ELF file header.
Definition ELFHeader.h:93
static unsigned AddressSizeInBytes(const uint8_t *magic)
Examines at most EI_NIDENT bytes starting from the given address and determines the address size of t...
elf_half e_phentsize
Size of a program header table entry.
Definition ELFHeader.h:66
bool Is32Bit() const
Returns true if this is a 32 bit ELF file header.
Definition ELFHeader.h:85
static bool MagicBytesMatch(const uint8_t *magic)
Examines at most EI_NIDENT bytes starting from the given pointer and determines if the magic ELF iden...
elf_off e_shoff
File offset of section header table.
Definition ELFHeader.h:60
elf_half e_ehsize
Byte size of the ELF header.
Definition ELFHeader.h:65
bool Parse(lldb_private::DataExtractor &data, lldb::offset_t *offset)
Parse an ELFHeader entry starting at position offset and update the data extractor with the address s...
unsigned GetRelocationJumpSlotType() const
The jump slot relocation type of this ELF.
elf_word e_phnum
Number of program header entries.
Definition ELFHeader.h:75
elf_word e_version
Version of object file (always 1).
Definition ELFHeader.h:62
unsigned char e_ident[llvm::ELF::EI_NIDENT]
ELF file identification.
Definition ELFHeader.h:57
elf_half e_machine
Target architecture.
Definition ELFHeader.h:64
elf_addr e_entry
Virtual address program entry point.
Definition ELFHeader.h:58
elf_word e_shstrndx
String table section index.
Definition ELFHeader.h:77
elf_half e_shentsize
Size of a section header table entry.
Definition ELFHeader.h:68
elf_half e_type
Object file type.
Definition ELFHeader.h:63
elf_word e_flags
Processor specific flags.
Definition ELFHeader.h:61
Generic representation of an ELF program header.
Definition ELFHeader.h:192
elf_xword p_align
Segment alignment constraint.
Definition ELFHeader.h:200
elf_addr p_paddr
Physical address (for non-VM systems).
Definition ELFHeader.h:197
elf_word p_flags
Segment attributes.
Definition ELFHeader.h:194
elf_xword p_filesz
Byte size of the segment in file.
Definition ELFHeader.h:198
elf_off p_offset
Start of segment from beginning of file.
Definition ELFHeader.h:195
elf_addr p_vaddr
Virtual address of segment in memory.
Definition ELFHeader.h:196
elf_xword p_memsz
Byte size of the segment in memory.
Definition ELFHeader.h:199
elf_word p_type
Type of program segment.
Definition ELFHeader.h:193
static unsigned RelocSymbol64(const ELFRel &rel)
Returns the symbol index when the given entry represents a 64-bit relocation.
Definition ELFHeader.h:341
static unsigned RelocType64(const ELFRel &rel)
Returns the type when the given entry represents a 64-bit relocation.
Definition ELFHeader.h:331
static unsigned RelocType32(const ELFRel &rel)
Returns the type when the given entry represents a 32-bit relocation.
Definition ELFHeader.h:328
static unsigned RelocSymbol32(const ELFRel &rel)
Returns the symbol index when the given entry represents a 32-bit relocation.
Definition ELFHeader.h:337
static unsigned RelocSymbol64(const ELFRela &rela)
Returns the symbol index when the given entry represents a 64-bit relocation.
Definition ELFHeader.h:387
static unsigned RelocType64(const ELFRela &rela)
Returns the type when the given entry represents a 64-bit relocation.
Definition ELFHeader.h:375
static unsigned RelocType32(const ELFRela &rela)
Returns the type when the given entry represents a 32-bit relocation.
Definition ELFHeader.h:370
static unsigned RelocSymbol32(const ELFRela &rela)
Returns the symbol index when the given entry represents a 32-bit relocation.
Definition ELFHeader.h:381
Generic representation of an ELF section header.
Definition ELFHeader.h:159
elf_word sh_link
Index of associated section.
Definition ELFHeader.h:166
elf_word sh_info
Extra section info (overloaded).
Definition ELFHeader.h:167
elf_xword sh_size
Number of bytes occupied in the file.
Definition ELFHeader.h:165
elf_xword sh_flags
Section attributes.
Definition ELFHeader.h:162
elf_word sh_name
Section name string index.
Definition ELFHeader.h:160
elf_off sh_offset
Start of section from beginning of file.
Definition ELFHeader.h:164
elf_word sh_type
Section type.
Definition ELFHeader.h:161
elf_xword sh_addralign
Power of two alignment constraint.
Definition ELFHeader.h:168
elf_xword sh_entsize
Byte size of each section entry.
Definition ELFHeader.h:169
elf_addr sh_addr
Virtual address of the section in memory.
Definition ELFHeader.h:163
Represents a symbol within an ELF symbol table.
Definition ELFHeader.h:224
unsigned char getType() const
Returns the type attribute of the st_info member.
Definition ELFHeader.h:238
elf_half st_shndx
Section to which this symbol applies.
Definition ELFHeader.h:230
unsigned char st_info
Symbol type and binding attributes.
Definition ELFHeader.h:228
unsigned char getBinding() const
Returns the binding attribute of the st_info member.
Definition ELFHeader.h:235
bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)
Parse an ELFSymbol entry from the given DataExtractor starting at position offset.
elf_addr st_value
Absolute or relocatable address.
Definition ELFHeader.h:225
elf_word st_name
Symbol name string index.
Definition ELFHeader.h:227
elf_xword st_size
Size of the symbol or zero.
Definition ELFHeader.h:226
unsigned char st_other
Reserved for future use.
Definition ELFHeader.h:229
llvm::ArrayRef< uint8_t > Contents
Definition ObjectFile.h:98
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47