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