Bug Summary

File:src/gnu/usr.bin/clang/liblldbPluginObjectFile/../../../llvm/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp
Warning:line 2209, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ObjectFileELF.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/liblldbPluginObjectFile/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/liblldbPluginObjectFile/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/liblldbPluginObjectFile/../include -I /usr/src/gnu/usr.bin/clang/liblldbPluginObjectFile/obj -I /usr/src/gnu/usr.bin/clang/liblldbPluginObjectFile/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -I /usr/src/gnu/usr.bin/clang/liblldbPluginObjectFile/../../../llvm/lldb/include -I /usr/src/gnu/usr.bin/clang/liblldbPluginObjectFile/../../../llvm/lldb/source -I /usr/src/gnu/usr.bin/clang/liblldbPluginObjectFile/../../../llvm/clang/include -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/liblldbPluginObjectFile/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/liblldbPluginObjectFile/../../../llvm/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp

/usr/src/gnu/usr.bin/clang/liblldbPluginObjectFile/../../../llvm/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp

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

/usr/src/gnu/usr.bin/clang/liblldbPluginObjectFile/../../../llvm/lldb/include/lldb/Utility/ArchSpec.h

1//===-- ArchSpec.h ----------------------------------------------*- C++ -*-===//
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#ifndef LLDB_UTILITY_ARCHSPEC_H
10#define LLDB_UTILITY_ARCHSPEC_H
11
12#include "lldb/Utility/CompletionRequest.h"
13#include "lldb/Utility/ConstString.h"
14#include "lldb/lldb-enumerations.h"
15#include "lldb/lldb-forward.h"
16#include "lldb/lldb-private-enumerations.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/ADT/Triple.h"
19#include "llvm/Support/YAMLTraits.h"
20#include <cstddef>
21#include <cstdint>
22#include <string>
23
24namespace lldb_private {
25
26/// \class ArchSpec ArchSpec.h "lldb/Utility/ArchSpec.h" An architecture
27/// specification class.
28///
29/// A class designed to be created from a cpu type and subtype, a
30/// string representation, or an llvm::Triple. Keeping all of the conversions
31/// of strings to architecture enumeration values confined to this class
32/// allows new architecture support to be added easily.
33class ArchSpec {
34public:
35 enum MIPSSubType {
36 eMIPSSubType_unknown,
37 eMIPSSubType_mips32,
38 eMIPSSubType_mips32r2,
39 eMIPSSubType_mips32r6,
40 eMIPSSubType_mips32el,
41 eMIPSSubType_mips32r2el,
42 eMIPSSubType_mips32r6el,
43 eMIPSSubType_mips64,
44 eMIPSSubType_mips64r2,
45 eMIPSSubType_mips64r6,
46 eMIPSSubType_mips64el,
47 eMIPSSubType_mips64r2el,
48 eMIPSSubType_mips64r6el,
49 };
50
51 // Masks for the ases word of an ABI flags structure.
52 enum MIPSASE {
53 eMIPSAse_dsp = 0x00000001, // DSP ASE
54 eMIPSAse_dspr2 = 0x00000002, // DSP R2 ASE
55 eMIPSAse_eva = 0x00000004, // Enhanced VA Scheme
56 eMIPSAse_mcu = 0x00000008, // MCU (MicroController) ASE
57 eMIPSAse_mdmx = 0x00000010, // MDMX ASE
58 eMIPSAse_mips3d = 0x00000020, // MIPS-3D ASE
59 eMIPSAse_mt = 0x00000040, // MT ASE
60 eMIPSAse_smartmips = 0x00000080, // SmartMIPS ASE
61 eMIPSAse_virt = 0x00000100, // VZ ASE
62 eMIPSAse_msa = 0x00000200, // MSA ASE
63 eMIPSAse_mips16 = 0x00000400, // MIPS16 ASE
64 eMIPSAse_micromips = 0x00000800, // MICROMIPS ASE
65 eMIPSAse_xpa = 0x00001000, // XPA ASE
66 eMIPSAse_mask = 0x00001fff,
67 eMIPSABI_O32 = 0x00002000,
68 eMIPSABI_N32 = 0x00004000,
69 eMIPSABI_N64 = 0x00008000,
70 eMIPSABI_O64 = 0x00020000,
71 eMIPSABI_EABI32 = 0x00040000,
72 eMIPSABI_EABI64 = 0x00080000,
73 eMIPSABI_mask = 0x000ff000
74 };
75
76 // MIPS Floating point ABI Values
77 enum MIPS_ABI_FP {
78 eMIPS_ABI_FP_ANY = 0x00000000,
79 eMIPS_ABI_FP_DOUBLE = 0x00100000, // hard float / -mdouble-float
80 eMIPS_ABI_FP_SINGLE = 0x00200000, // hard float / -msingle-float
81 eMIPS_ABI_FP_SOFT = 0x00300000, // soft float
82 eMIPS_ABI_FP_OLD_64 = 0x00400000, // -mips32r2 -mfp64
83 eMIPS_ABI_FP_XX = 0x00500000, // -mfpxx
84 eMIPS_ABI_FP_64 = 0x00600000, // -mips32r2 -mfp64
85 eMIPS_ABI_FP_64A = 0x00700000, // -mips32r2 -mfp64 -mno-odd-spreg
86 eMIPS_ABI_FP_mask = 0x00700000
87 };
88
89 // ARM specific e_flags
90 enum ARMeflags {
91 eARM_abi_soft_float = 0x00000200,
92 eARM_abi_hard_float = 0x00000400
93 };
94
95 enum RISCVSubType {
96 eRISCVSubType_unknown,
97 eRISCVSubType_riscv32,
98 eRISCVSubType_riscv64,
99 };
100
101 enum Core {
102 eCore_arm_generic,
103 eCore_arm_armv4,
104 eCore_arm_armv4t,
105 eCore_arm_armv5,
106 eCore_arm_armv5e,
107 eCore_arm_armv5t,
108 eCore_arm_armv6,
109 eCore_arm_armv6m,
110 eCore_arm_armv7,
111 eCore_arm_armv7l,
112 eCore_arm_armv7f,
113 eCore_arm_armv7s,
114 eCore_arm_armv7k,
115 eCore_arm_armv7m,
116 eCore_arm_armv7em,
117 eCore_arm_xscale,
118
119 eCore_thumb,
120 eCore_thumbv4t,
121 eCore_thumbv5,
122 eCore_thumbv5e,
123 eCore_thumbv6,
124 eCore_thumbv6m,
125 eCore_thumbv7,
126 eCore_thumbv7s,
127 eCore_thumbv7k,
128 eCore_thumbv7f,
129 eCore_thumbv7m,
130 eCore_thumbv7em,
131 eCore_arm_arm64,
132 eCore_arm_armv8,
133 eCore_arm_armv8l,
134 eCore_arm_arm64e,
135 eCore_arm_arm64_32,
136 eCore_arm_aarch64,
137
138 eCore_mips32,
139 eCore_mips32r2,
140 eCore_mips32r3,
141 eCore_mips32r5,
142 eCore_mips32r6,
143 eCore_mips32el,
144 eCore_mips32r2el,
145 eCore_mips32r3el,
146 eCore_mips32r5el,
147 eCore_mips32r6el,
148 eCore_mips64,
149 eCore_mips64r2,
150 eCore_mips64r3,
151 eCore_mips64r5,
152 eCore_mips64r6,
153 eCore_mips64el,
154 eCore_mips64r2el,
155 eCore_mips64r3el,
156 eCore_mips64r5el,
157 eCore_mips64r6el,
158
159 eCore_ppc_generic,
160 eCore_ppc_ppc601,
161 eCore_ppc_ppc602,
162 eCore_ppc_ppc603,
163 eCore_ppc_ppc603e,
164 eCore_ppc_ppc603ev,
165 eCore_ppc_ppc604,
166 eCore_ppc_ppc604e,
167 eCore_ppc_ppc620,
168 eCore_ppc_ppc750,
169 eCore_ppc_ppc7400,
170 eCore_ppc_ppc7450,
171 eCore_ppc_ppc970,
172
173 eCore_ppc64le_generic,
174 eCore_ppc64_generic,
175 eCore_ppc64_ppc970_64,
176
177 eCore_s390x_generic,
178
179 eCore_sparc_generic,
180
181 eCore_sparc9_generic,
182
183 eCore_x86_32_i386,
184 eCore_x86_32_i486,
185 eCore_x86_32_i486sx,
186 eCore_x86_32_i686,
187
188 eCore_x86_64_x86_64,
189 eCore_x86_64_x86_64h, // Haswell enabled x86_64
190 eCore_x86_64_amd64,
191 eCore_hexagon_generic,
192 eCore_hexagon_hexagonv4,
193 eCore_hexagon_hexagonv5,
194
195 eCore_riscv32,
196 eCore_riscv64,
197
198 eCore_uknownMach32,
199 eCore_uknownMach64,
200
201 eCore_arc, // little endian ARC
202
203 eCore_avr,
204
205 eCore_wasm32,
206
207 kNumCores,
208
209 kCore_invalid,
210 // The following constants are used for wildcard matching only
211 kCore_any,
212 kCore_arm_any,
213 kCore_ppc_any,
214 kCore_ppc64_any,
215 kCore_x86_32_any,
216 kCore_x86_64_any,
217 kCore_hexagon_any,
218
219 kCore_arm_first = eCore_arm_generic,
220 kCore_arm_last = eCore_arm_xscale,
221
222 kCore_thumb_first = eCore_thumb,
223 kCore_thumb_last = eCore_thumbv7em,
224
225 kCore_ppc_first = eCore_ppc_generic,
226 kCore_ppc_last = eCore_ppc_ppc970,
227
228 kCore_ppc64_first = eCore_ppc64_generic,
229 kCore_ppc64_last = eCore_ppc64_ppc970_64,
230
231 kCore_x86_32_first = eCore_x86_32_i386,
232 kCore_x86_32_last = eCore_x86_32_i686,
233
234 kCore_x86_64_first = eCore_x86_64_x86_64,
235 kCore_x86_64_last = eCore_x86_64_x86_64h,
236
237 kCore_hexagon_first = eCore_hexagon_generic,
238 kCore_hexagon_last = eCore_hexagon_hexagonv5,
239
240 kCore_mips32_first = eCore_mips32,
241 kCore_mips32_last = eCore_mips32r6,
242
243 kCore_mips32el_first = eCore_mips32el,
244 kCore_mips32el_last = eCore_mips32r6el,
245
246 kCore_mips64_first = eCore_mips64,
247 kCore_mips64_last = eCore_mips64r6,
248
249 kCore_mips64el_first = eCore_mips64el,
250 kCore_mips64el_last = eCore_mips64r6el,
251
252 kCore_mips_first = eCore_mips32,
253 kCore_mips_last = eCore_mips64r6el
254
255 };
256
257 /// Default constructor.
258 ///
259 /// Default constructor that initializes the object with invalid cpu type
260 /// and subtype values.
261 ArchSpec();
262
263 /// Constructor over triple.
264 ///
265 /// Constructs an ArchSpec with properties consistent with the given Triple.
266 explicit ArchSpec(const llvm::Triple &triple);
267 explicit ArchSpec(const char *triple_cstr);
268 explicit ArchSpec(llvm::StringRef triple_str);
269 /// Constructor over architecture name.
270 ///
271 /// Constructs an ArchSpec with properties consistent with the given object
272 /// type and architecture name.
273 explicit ArchSpec(ArchitectureType arch_type, uint32_t cpu_type,
274 uint32_t cpu_subtype);
275
276 /// Destructor.
277 ~ArchSpec();
278
279 /// Returns true if the OS, vendor and environment fields of the triple are
280 /// unset. The triple is expected to be normalized
281 /// (llvm::Triple::normalize).
282 static bool ContainsOnlyArch(const llvm::Triple &normalized_triple);
283
284 static void ListSupportedArchNames(StringList &list);
285 static void AutoComplete(CompletionRequest &request);
286
287 /// Returns a static string representing the current architecture.
288 ///
289 /// \return A static string corresponding to the current
290 /// architecture.
291 const char *GetArchitectureName() const;
292
293 /// if MIPS architecture return true.
294 ///
295 /// \return a boolean value.
296 bool IsMIPS() const;
297
298 /// Returns a string representing current architecture as a target CPU for
299 /// tools like compiler, disassembler etc.
300 ///
301 /// \return A string representing target CPU for the current
302 /// architecture.
303 std::string GetClangTargetCPU() const;
304
305 /// Return a string representing target application ABI.
306 ///
307 /// \return A string representing target application ABI.
308 std::string GetTargetABI() const;
309
310 /// Clears the object state.
311 ///
312 /// Clears the object state back to a default invalid state.
313 void Clear();
314
315 /// Returns the size in bytes of an address of the current architecture.
316 ///
317 /// \return The byte size of an address of the current architecture.
318 uint32_t GetAddressByteSize() const;
319
320 /// Returns a machine family for the current architecture.
321 ///
322 /// \return An LLVM arch type.
323 llvm::Triple::ArchType GetMachine() const;
324
325 /// Returns the distribution id of the architecture.
326 ///
327 /// This will be something like "ubuntu", "fedora", etc. on Linux.
328 ///
329 /// \return A ConstString ref containing the distribution id,
330 /// potentially empty.
331 ConstString GetDistributionId() const;
332
333 /// Set the distribution id of the architecture.
334 ///
335 /// This will be something like "ubuntu", "fedora", etc. on Linux. This
336 /// should be the same value returned by HostInfo::GetDistributionId ().
337 void SetDistributionId(const char *distribution_id);
338
339 /// Tests if this ArchSpec is valid.
340 ///
341 /// \return True if the current architecture is valid, false
342 /// otherwise.
343 bool IsValid() const {
344 return m_core
17.1
Field 'm_core' is >= eCore_arm_generic
17.1
Field 'm_core' is >= eCore_arm_generic
17.1
Field 'm_core' is >= eCore_arm_generic
>= eCore_arm_generic && m_core < kNumCores
;
18
Assuming field 'm_core' is >= kNumCores
19
Returning zero, which participates in a condition later
345 }
346 explicit operator bool() const { return IsValid(); }
347
348 bool TripleVendorWasSpecified() const {
349 return !m_triple.getVendorName().empty();
350 }
351
352 bool TripleOSWasSpecified() const { return !m_triple.getOSName().empty(); }
353
354 bool TripleEnvironmentWasSpecified() const {
355 return m_triple.hasEnvironment();
356 }
357
358 /// Merges fields from another ArchSpec into this ArchSpec.
359 ///
360 /// This will use the supplied ArchSpec to fill in any fields of the triple
361 /// in this ArchSpec which were unspecified. This can be used to refine a
362 /// generic ArchSpec with a more specific one. For example, if this
363 /// ArchSpec's triple is something like i386-unknown-unknown-unknown, and we
364 /// have a triple which is x64-pc-windows-msvc, then merging that triple
365 /// into this one will result in the triple i386-pc-windows-msvc.
366 ///
367 void MergeFrom(const ArchSpec &other);
368
369 /// Change the architecture object type, CPU type and OS type.
370 ///
371 /// \param[in] arch_type The object type of this ArchSpec.
372 ///
373 /// \param[in] cpu The required CPU type.
374 ///
375 /// \param[in] os The optional OS type
376 /// The default value of 0 was chosen to from the ELF spec value
377 /// ELFOSABI_NONE. ELF is the only one using this parameter. If another
378 /// format uses this parameter and 0 does not work, use a value over
379 /// 255 because in the ELF header this is value is only a byte.
380 ///
381 /// \return True if the object, and CPU were successfully set.
382 ///
383 /// As a side effect, the vendor value is usually set to unknown. The
384 /// exceptions are
385 /// aarch64-apple-ios
386 /// arm-apple-ios
387 /// thumb-apple-ios
388 /// x86-apple-
389 /// x86_64-apple-
390 ///
391 /// As a side effect, the os value is usually set to unknown The exceptions
392 /// are
393 /// *-*-aix
394 /// aarch64-apple-ios
395 /// arm-apple-ios
396 /// thumb-apple-ios
397 /// powerpc-apple-darwin
398 /// *-*-freebsd
399 /// *-*-linux
400 /// *-*-netbsd
401 /// *-*-openbsd
402 /// *-*-solaris
403 bool SetArchitecture(ArchitectureType arch_type, uint32_t cpu, uint32_t sub,
404 uint32_t os = 0);
405
406 /// Returns the byte order for the architecture specification.
407 ///
408 /// \return The endian enumeration for the current endianness of
409 /// the architecture specification
410 lldb::ByteOrder GetByteOrder() const;
411
412 /// Sets this ArchSpec's byte order.
413 ///
414 /// In the common case there is no need to call this method as the byte
415 /// order can almost always be determined by the architecture. However, many
416 /// CPU's are bi-endian (ARM, Alpha, PowerPC, etc) and the default/assumed
417 /// byte order may be incorrect.
418 void SetByteOrder(lldb::ByteOrder byte_order) { m_byte_order = byte_order; }
419
420 uint32_t GetMinimumOpcodeByteSize() const;
421
422 uint32_t GetMaximumOpcodeByteSize() const;
423
424 Core GetCore() const { return m_core; }
425
426 uint32_t GetMachOCPUType() const;
427
428 uint32_t GetMachOCPUSubType() const;
429
430 /// Architecture data byte width accessor
431 ///
432 /// \return the size in 8-bit (host) bytes of a minimum addressable unit
433 /// from the Architecture's data bus
434 uint32_t GetDataByteSize() const;
435
436 /// Architecture code byte width accessor
437 ///
438 /// \return the size in 8-bit (host) bytes of a minimum addressable unit
439 /// from the Architecture's code bus
440 uint32_t GetCodeByteSize() const;
441
442 /// Architecture triple accessor.
443 ///
444 /// \return A triple describing this ArchSpec.
445 llvm::Triple &GetTriple() { return m_triple; }
446
447 /// Architecture triple accessor.
448 ///
449 /// \return A triple describing this ArchSpec.
450 const llvm::Triple &GetTriple() const { return m_triple; }
451
452 void DumpTriple(llvm::raw_ostream &s) const;
453
454 /// Architecture triple setter.
455 ///
456 /// Configures this ArchSpec according to the given triple. If the triple
457 /// has unknown components in all of the vendor, OS, and the optional
458 /// environment field (i.e. "i386-unknown-unknown") then default values are
459 /// taken from the host. Architecture and environment components are used
460 /// to further resolve the CPU type and subtype, endian characteristics,
461 /// etc.
462 ///
463 /// \return A triple describing this ArchSpec.
464 bool SetTriple(const llvm::Triple &triple);
465
466 bool SetTriple(llvm::StringRef triple_str);
467
468 /// Returns the default endianness of the architecture.
469 ///
470 /// \return The endian enumeration for the default endianness of
471 /// the architecture.
472 lldb::ByteOrder GetDefaultEndian() const;
473
474 /// Returns true if 'char' is a signed type by default in the architecture
475 /// false otherwise
476 ///
477 /// \return True if 'char' is a signed type by default on the
478 /// architecture and false otherwise.
479 bool CharIsSignedByDefault() const;
480
481 /// Compare an ArchSpec to another ArchSpec, requiring an exact cpu type
482 /// match between them. e.g. armv7s is not an exact match with armv7 - this
483 /// would return false
484 ///
485 /// \return true if the two ArchSpecs match.
486 bool IsExactMatch(const ArchSpec &rhs) const;
487
488 /// Compare an ArchSpec to another ArchSpec, requiring a compatible cpu type
489 /// match between them. e.g. armv7s is compatible with armv7 - this method
490 /// would return true
491 ///
492 /// \return true if the two ArchSpecs are compatible
493 bool IsCompatibleMatch(const ArchSpec &rhs) const;
494
495 bool IsFullySpecifiedTriple() const;
496
497 void PiecewiseTripleCompare(const ArchSpec &other, bool &arch_different,
498 bool &vendor_different, bool &os_different,
499 bool &os_version_different,
500 bool &env_different) const;
501
502 /// Detect whether this architecture uses thumb code exclusively
503 ///
504 /// Some embedded ARM chips (e.g. the ARM Cortex M0-7 line) can only execute
505 /// the Thumb instructions, never Arm. We should normally pick up
506 /// arm/thumbness from their the processor status bits (cpsr/xpsr) or hints
507 /// on each function - but when doing bare-boards low level debugging
508 /// (especially common with these embedded processors), we may not have
509 /// those things easily accessible.
510 ///
511 /// \return true if this is an arm ArchSpec which can only execute Thumb
512 /// instructions
513 bool IsAlwaysThumbInstructions() const;
514
515 uint32_t GetFlags() const { return m_flags; }
516
517 void SetFlags(uint32_t flags) { m_flags = flags; }
518
519 void SetFlags(const std::string &elf_abi);
520
521protected:
522 bool IsEqualTo(const ArchSpec &rhs, bool exact_match) const;
523 void UpdateCore();
524
525 llvm::Triple m_triple;
526 Core m_core = kCore_invalid;
527 lldb::ByteOrder m_byte_order = lldb::eByteOrderInvalid;
528
529 // Additional arch flags which we cannot get from triple and core For MIPS
530 // these are application specific extensions like micromips, mips16 etc.
531 uint32_t m_flags = 0;
532
533 ConstString m_distribution_id;
534
535 // Called when m_def or m_entry are changed. Fills in all remaining members
536 // with default values.
537 void CoreUpdated(bool update_triple);
538};
539
540/// \fn bool operator< (const ArchSpec& lhs, const ArchSpec& rhs) Less than
541/// operator.
542///
543/// Tests two ArchSpec objects to see if \a lhs is less than \a rhs.
544///
545/// \param[in] lhs The Left Hand Side ArchSpec object to compare. \param[in]
546/// rhs The Left Hand Side ArchSpec object to compare.
547///
548/// \return true if \a lhs is less than \a rhs
549bool operator<(const ArchSpec &lhs, const ArchSpec &rhs);
550bool operator==(const ArchSpec &lhs, const ArchSpec &rhs);
551
552bool ParseMachCPUDashSubtypeTriple(llvm::StringRef triple_str, ArchSpec &arch);
553
554} // namespace lldb_private
555
556namespace llvm {
557namespace yaml {
558template <> struct ScalarTraits<lldb_private::ArchSpec> {
559 static void output(const lldb_private::ArchSpec &, void *, raw_ostream &);
560 static StringRef input(StringRef, void *, lldb_private::ArchSpec &);
561 static QuotingType mustQuote(StringRef S) { return QuotingType::Double; }
562};
563} // namespace yaml
564} // namespace llvm
565
566LLVM_YAML_IS_SEQUENCE_VECTOR(lldb_private::ArchSpec)namespace llvm { namespace yaml { static_assert( !std::is_fundamental
<lldb_private::ArchSpec>::value && !std::is_same
<lldb_private::ArchSpec, std::string>::value &&
!std::is_same<lldb_private::ArchSpec, llvm::StringRef>
::value, "only use LLVM_YAML_IS_SEQUENCE_VECTOR for types you control"
); template <> struct SequenceElementTraits<lldb_private
::ArchSpec> { static const bool flow = false; }; } }
567
568#endif // LLDB_UTILITY_ARCHSPEC_H

/usr/include/c++/v1/__memory/shared_ptr.h

1// -*- C++ -*-
2//===----------------------------------------------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP___MEMORY_SHARED_PTR_H
11#define _LIBCPP___MEMORY_SHARED_PTR_H
12
13#include <__availability>
14#include <__config>
15#include <__functional_base>
16#include <__functional/binary_function.h>
17#include <__functional/operations.h>
18#include <__functional/reference_wrapper.h>
19#include <__memory/addressof.h>
20#include <__memory/allocation_guard.h>
21#include <__memory/allocator_traits.h>
22#include <__memory/allocator.h>
23#include <__memory/compressed_pair.h>
24#include <__memory/pointer_traits.h>
25#include <__memory/unique_ptr.h>
26#include <__utility/forward.h>
27#include <cstddef>
28#include <cstdlib> // abort
29#include <iosfwd>
30#include <stdexcept>
31#include <typeinfo>
32#include <type_traits>
33#include <utility>
34#if !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)
35# include <atomic>
36#endif
37
38#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
39# include <__memory/auto_ptr.h>
40#endif
41
42#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
43#pragma GCC system_header
44#endif
45
46_LIBCPP_PUSH_MACROSpush_macro("min") push_macro("max")
47#include <__undef_macros>
48
49_LIBCPP_BEGIN_NAMESPACE_STDnamespace std { inline namespace __1 {
50
51template <class _Alloc>
52class __allocator_destructor
53{
54 typedef _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) allocator_traits<_Alloc> __alloc_traits;
55public:
56 typedef _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) typename __alloc_traits::pointer pointer;
57 typedef _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) typename __alloc_traits::size_type size_type;
58private:
59 _Alloc& __alloc_;
60 size_type __s_;
61public:
62 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
__allocator_destructor(_Alloc& __a, size_type __s)
63 _NOEXCEPTnoexcept
64 : __alloc_(__a), __s_(__s) {}
65 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
66 void operator()(pointer __p) _NOEXCEPTnoexcept
67 {__alloc_traits::deallocate(__alloc_, __p, __s_);}
68};
69
70// NOTE: Relaxed and acq/rel atomics (for increment and decrement respectively)
71// should be sufficient for thread safety.
72// See https://llvm.org/PR22803
73#if defined(__clang__1) && __has_builtin(__atomic_add_fetch)1 \
74 && defined(__ATOMIC_RELAXED0) \
75 && defined(__ATOMIC_ACQ_REL4)
76# define _LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT
77#elif defined(_LIBCPP_COMPILER_GCC)
78# define _LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT
79#endif
80
81template <class _ValueType>
82inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
83_ValueType __libcpp_relaxed_load(_ValueType const* __value) {
84#if !defined(_LIBCPP_HAS_NO_THREADS) && \
85 defined(__ATOMIC_RELAXED0) && \
86 (__has_builtin(__atomic_load_n)1 || defined(_LIBCPP_COMPILER_GCC))
87 return __atomic_load_n(__value, __ATOMIC_RELAXED0);
88#else
89 return *__value;
90#endif
91}
92
93template <class _ValueType>
94inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
95_ValueType __libcpp_acquire_load(_ValueType const* __value) {
96#if !defined(_LIBCPP_HAS_NO_THREADS) && \
97 defined(__ATOMIC_ACQUIRE2) && \
98 (__has_builtin(__atomic_load_n)1 || defined(_LIBCPP_COMPILER_GCC))
99 return __atomic_load_n(__value, __ATOMIC_ACQUIRE2);
100#else
101 return *__value;
102#endif
103}
104
105template <class _Tp>
106inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_Tp
107__libcpp_atomic_refcount_increment(_Tp& __t) _NOEXCEPTnoexcept
108{
109#if defined(_LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT) && !defined(_LIBCPP_HAS_NO_THREADS)
110 return __atomic_add_fetch(&__t, 1, __ATOMIC_RELAXED0);
111#else
112 return __t += 1;
113#endif
114}
115
116template <class _Tp>
117inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_Tp
118__libcpp_atomic_refcount_decrement(_Tp& __t) _NOEXCEPTnoexcept
119{
120#if defined(_LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT) && !defined(_LIBCPP_HAS_NO_THREADS)
121 return __atomic_add_fetch(&__t, -1, __ATOMIC_ACQ_REL4);
122#else
123 return __t -= 1;
124#endif
125}
126
127class _LIBCPP_EXCEPTION_ABI__attribute__ ((__visibility__("default"))) bad_weak_ptr
128 : public std::exception
129{
130public:
131 bad_weak_ptr() _NOEXCEPTnoexcept = default;
132 bad_weak_ptr(const bad_weak_ptr&) _NOEXCEPTnoexcept = default;
133 virtual ~bad_weak_ptr() _NOEXCEPTnoexcept;
134 virtual const char* what() const _NOEXCEPTnoexcept;
135};
136
137_LIBCPP_NORETURN[[noreturn]] inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
138void __throw_bad_weak_ptr()
139{
140#ifndef _LIBCPP_NO_EXCEPTIONS
141 throw bad_weak_ptr();
142#else
143 _VSTDstd::__1::abort();
144#endif
145}
146
147template<class _Tp> class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) weak_ptr;
148
149class _LIBCPP_TYPE_VIS__attribute__ ((__visibility__("default"))) __shared_count
150{
151 __shared_count(const __shared_count&);
152 __shared_count& operator=(const __shared_count&);
153
154protected:
155 long __shared_owners_;
156 virtual ~__shared_count();
157private:
158 virtual void __on_zero_shared() _NOEXCEPTnoexcept = 0;
159
160public:
161 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
162 explicit __shared_count(long __refs = 0) _NOEXCEPTnoexcept
163 : __shared_owners_(__refs) {}
164
165#if defined(_LIBCPP_BUILDING_LIBRARY) && \
166 defined(_LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS)
167 void __add_shared() _NOEXCEPTnoexcept;
168 bool __release_shared() _NOEXCEPTnoexcept;
169#else
170 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
171 void __add_shared() _NOEXCEPTnoexcept {
172 __libcpp_atomic_refcount_increment(__shared_owners_);
173 }
174 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
175 bool __release_shared() _NOEXCEPTnoexcept {
176 if (__libcpp_atomic_refcount_decrement(__shared_owners_) == -1) {
177 __on_zero_shared();
178 return true;
179 }
180 return false;
181 }
182#endif
183 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
184 long use_count() const _NOEXCEPTnoexcept {
185 return __libcpp_relaxed_load(&__shared_owners_) + 1;
186 }
187};
188
189class _LIBCPP_TYPE_VIS__attribute__ ((__visibility__("default"))) __shared_weak_count
190 : private __shared_count
191{
192 long __shared_weak_owners_;
193
194public:
195 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
196 explicit __shared_weak_count(long __refs = 0) _NOEXCEPTnoexcept
197 : __shared_count(__refs),
198 __shared_weak_owners_(__refs) {}
199protected:
200 virtual ~__shared_weak_count();
201
202public:
203#if defined(_LIBCPP_BUILDING_LIBRARY) && \
204 defined(_LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS)
205 void __add_shared() _NOEXCEPTnoexcept;
206 void __add_weak() _NOEXCEPTnoexcept;
207 void __release_shared() _NOEXCEPTnoexcept;
208#else
209 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
210 void __add_shared() _NOEXCEPTnoexcept {
211 __shared_count::__add_shared();
212 }
213 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
214 void __add_weak() _NOEXCEPTnoexcept {
215 __libcpp_atomic_refcount_increment(__shared_weak_owners_);
216 }
217 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
218 void __release_shared() _NOEXCEPTnoexcept {
219 if (__shared_count::__release_shared())
220 __release_weak();
221 }
222#endif
223 void __release_weak() _NOEXCEPTnoexcept;
224 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
225 long use_count() const _NOEXCEPTnoexcept {return __shared_count::use_count();}
226 __shared_weak_count* lock() _NOEXCEPTnoexcept;
227
228 virtual const void* __get_deleter(const type_info&) const _NOEXCEPTnoexcept;
229private:
230 virtual void __on_zero_shared_weak() _NOEXCEPTnoexcept = 0;
231};
232
233template <class _Tp, class _Dp, class _Alloc>
234class __shared_ptr_pointer
235 : public __shared_weak_count
236{
237 __compressed_pair<__compressed_pair<_Tp, _Dp>, _Alloc> __data_;
238public:
239 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
240 __shared_ptr_pointer(_Tp __p, _Dp __d, _Alloc __a)
241 : __data_(__compressed_pair<_Tp, _Dp>(__p, _VSTDstd::__1::move(__d)), _VSTDstd::__1::move(__a)) {}
242
243#ifndef _LIBCPP_NO_RTTI
244 virtual const void* __get_deleter(const type_info&) const _NOEXCEPTnoexcept;
245#endif
246
247private:
248 virtual void __on_zero_shared() _NOEXCEPTnoexcept;
249 virtual void __on_zero_shared_weak() _NOEXCEPTnoexcept;
250};
251
252#ifndef _LIBCPP_NO_RTTI
253
254template <class _Tp, class _Dp, class _Alloc>
255const void*
256__shared_ptr_pointer<_Tp, _Dp, _Alloc>::__get_deleter(const type_info& __t) const _NOEXCEPTnoexcept
257{
258 return __t == typeid(_Dp) ? _VSTDstd::__1::addressof(__data_.first().second()) : nullptr;
259}
260
261#endif // _LIBCPP_NO_RTTI
262
263template <class _Tp, class _Dp, class _Alloc>
264void
265__shared_ptr_pointer<_Tp, _Dp, _Alloc>::__on_zero_shared() _NOEXCEPTnoexcept
266{
267 __data_.first().second()(__data_.first().first());
268 __data_.first().second().~_Dp();
269}
270
271template <class _Tp, class _Dp, class _Alloc>
272void
273__shared_ptr_pointer<_Tp, _Dp, _Alloc>::__on_zero_shared_weak() _NOEXCEPTnoexcept
274{
275 typedef typename __allocator_traits_rebind<_Alloc, __shared_ptr_pointer>::type _Al;
276 typedef allocator_traits<_Al> _ATraits;
277 typedef pointer_traits<typename _ATraits::pointer> _PTraits;
278
279 _Al __a(__data_.second());
280 __data_.second().~_Alloc();
281 __a.deallocate(_PTraits::pointer_to(*this), 1);
282}
283
284template <class _Tp, class _Alloc>
285struct __shared_ptr_emplace
286 : __shared_weak_count
287{
288 template<class ..._Args>
289 _LIBCPP_HIDE_FROM_ABI__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
290 explicit __shared_ptr_emplace(_Alloc __a, _Args&& ...__args)
291 : __storage_(_VSTDstd::__1::move(__a))
292 {
293#if _LIBCPP_STD_VER14 > 17
294 using _TpAlloc = typename __allocator_traits_rebind<_Alloc, _Tp>::type;
295 _TpAlloc __tmp(*__get_alloc());
296 allocator_traits<_TpAlloc>::construct(__tmp, __get_elem(), _VSTDstd::__1::forward<_Args>(__args)...);
297#else
298 ::new ((void*)__get_elem()) _Tp(_VSTDstd::__1::forward<_Args>(__args)...);
299#endif
300 }
301
302 _LIBCPP_HIDE_FROM_ABI__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
303 _Alloc* __get_alloc() _NOEXCEPTnoexcept { return __storage_.__get_alloc(); }
304
305 _LIBCPP_HIDE_FROM_ABI__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
306 _Tp* __get_elem() _NOEXCEPTnoexcept { return __storage_.__get_elem(); }
307
308private:
309 virtual void __on_zero_shared() _NOEXCEPTnoexcept {
310#if _LIBCPP_STD_VER14 > 17
311 using _TpAlloc = typename __allocator_traits_rebind<_Alloc, _Tp>::type;
312 _TpAlloc __tmp(*__get_alloc());
313 allocator_traits<_TpAlloc>::destroy(__tmp, __get_elem());
314#else
315 __get_elem()->~_Tp();
316#endif
317 }
318
319 virtual void __on_zero_shared_weak() _NOEXCEPTnoexcept {
320 using _ControlBlockAlloc = typename __allocator_traits_rebind<_Alloc, __shared_ptr_emplace>::type;
321 using _ControlBlockPointer = typename allocator_traits<_ControlBlockAlloc>::pointer;
322 _ControlBlockAlloc __tmp(*__get_alloc());
323 __storage_.~_Storage();
324 allocator_traits<_ControlBlockAlloc>::deallocate(__tmp,
325 pointer_traits<_ControlBlockPointer>::pointer_to(*this), 1);
326 }
327
328 // This class implements the control block for non-array shared pointers created
329 // through `std::allocate_shared` and `std::make_shared`.
330 //
331 // In previous versions of the library, we used a compressed pair to store
332 // both the _Alloc and the _Tp. This implies using EBO, which is incompatible
333 // with Allocator construction for _Tp. To allow implementing P0674 in C++20,
334 // we now use a properly aligned char buffer while making sure that we maintain
335 // the same layout that we had when we used a compressed pair.
336 using _CompressedPair = __compressed_pair<_Alloc, _Tp>;
337 struct _ALIGNAS_TYPE(_CompressedPair)alignas(_CompressedPair) _Storage {
338 char __blob_[sizeof(_CompressedPair)];
339
340 _LIBCPP_HIDE_FROM_ABI__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
explicit _Storage(_Alloc&& __a) {
341 ::new ((void*)__get_alloc()) _Alloc(_VSTDstd::__1::move(__a));
342 }
343 _LIBCPP_HIDE_FROM_ABI__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
~_Storage() {
344 __get_alloc()->~_Alloc();
345 }
346 _Alloc* __get_alloc() _NOEXCEPTnoexcept {
347 _CompressedPair *__as_pair = reinterpret_cast<_CompressedPair*>(__blob_);
348 typename _CompressedPair::_Base1* __first = _CompressedPair::__get_first_base(__as_pair);
349 _Alloc *__alloc = reinterpret_cast<_Alloc*>(__first);
350 return __alloc;
351 }
352 _LIBCPP_NO_CFI__attribute__((__no_sanitize__("cfi"))) _Tp* __get_elem() _NOEXCEPTnoexcept {
353 _CompressedPair *__as_pair = reinterpret_cast<_CompressedPair*>(__blob_);
354 typename _CompressedPair::_Base2* __second = _CompressedPair::__get_second_base(__as_pair);
355 _Tp *__elem = reinterpret_cast<_Tp*>(__second);
356 return __elem;
357 }
358 };
359
360 static_assert(_LIBCPP_ALIGNOF(_Storage)alignof(_Storage) == _LIBCPP_ALIGNOF(_CompressedPair)alignof(_CompressedPair), "");
361 static_assert(sizeof(_Storage) == sizeof(_CompressedPair), "");
362 _Storage __storage_;
363};
364
365struct __shared_ptr_dummy_rebind_allocator_type;
366template <>
367class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) allocator<__shared_ptr_dummy_rebind_allocator_type>
368{
369public:
370 template <class _Other>
371 struct rebind
372 {
373 typedef allocator<_Other> other;
374 };
375};
376
377template<class _Tp> class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) enable_shared_from_this;
378
379template<class _Tp, class _Up>
380struct __compatible_with
381#if _LIBCPP_STD_VER14 > 14
382 : is_convertible<remove_extent_t<_Tp>*, remove_extent_t<_Up>*> {};
383#else
384 : is_convertible<_Tp*, _Up*> {};
385#endif // _LIBCPP_STD_VER > 14
386
387template <class _Ptr, class = void>
388struct __is_deletable : false_type { };
389template <class _Ptr>
390struct __is_deletable<_Ptr, decltype(delete declval<_Ptr>())> : true_type { };
391
392template <class _Ptr, class = void>
393struct __is_array_deletable : false_type { };
394template <class _Ptr>
395struct __is_array_deletable<_Ptr, decltype(delete[] declval<_Ptr>())> : true_type { };
396
397template <class _Dp, class _Pt,
398 class = decltype(declval<_Dp>()(declval<_Pt>()))>
399static true_type __well_formed_deleter_test(int);
400
401template <class, class>
402static false_type __well_formed_deleter_test(...);
403
404template <class _Dp, class _Pt>
405struct __well_formed_deleter : decltype(__well_formed_deleter_test<_Dp, _Pt>(0)) {};
406
407template<class _Dp, class _Tp, class _Yp>
408struct __shared_ptr_deleter_ctor_reqs
409{
410 static const bool value = __compatible_with<_Tp, _Yp>::value &&
411 is_move_constructible<_Dp>::value &&
412 __well_formed_deleter<_Dp, _Tp*>::value;
413};
414
415#if defined(_LIBCPP_ABI_ENABLE_SHARED_PTR_TRIVIAL_ABI)
416# define _LIBCPP_SHARED_PTR_TRIVIAL_ABI __attribute__((trivial_abi))
417#else
418# define _LIBCPP_SHARED_PTR_TRIVIAL_ABI
419#endif
420
421template<class _Tp>
422class _LIBCPP_SHARED_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) shared_ptr
423{
424public:
425#if _LIBCPP_STD_VER14 > 14
426 typedef weak_ptr<_Tp> weak_type;
427 typedef remove_extent_t<_Tp> element_type;
428#else
429 typedef _Tp element_type;
430#endif
431
432private:
433 element_type* __ptr_;
434 __shared_weak_count* __cntrl_;
435
436 struct __nat {int __for_bool_;};
437public:
438 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
439 _LIBCPP_CONSTEXPRconstexpr shared_ptr() _NOEXCEPTnoexcept;
440 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
441 _LIBCPP_CONSTEXPRconstexpr shared_ptr(nullptr_t) _NOEXCEPTnoexcept;
442
443 template<class _Yp, class = _EnableIf<
444 _And<
445 __compatible_with<_Yp, _Tp>
446 // In C++03 we get errors when trying to do SFINAE with the
447 // delete operator, so we always pretend that it's deletable.
448 // The same happens on GCC.
449#if !defined(_LIBCPP_CXX03_LANG) && !defined(_LIBCPP_COMPILER_GCC)
450 , _If<is_array<_Tp>::value, __is_array_deletable<_Yp*>, __is_deletable<_Yp*> >
451#endif
452 >::value
453 > >
454 explicit shared_ptr(_Yp* __p) : __ptr_(__p) {
455 unique_ptr<_Yp> __hold(__p);
456 typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
457 typedef __shared_ptr_pointer<_Yp*, __shared_ptr_default_delete<_Tp, _Yp>, _AllocT > _CntrlBlk;
458 __cntrl_ = new _CntrlBlk(__p, __shared_ptr_default_delete<_Tp, _Yp>(), _AllocT());
459 __hold.release();
460 __enable_weak_this(__p, __p);
461 }
462
463 template<class _Yp, class _Dp>
464 shared_ptr(_Yp* __p, _Dp __d,
465 typename enable_if<__shared_ptr_deleter_ctor_reqs<_Dp, _Yp, element_type>::value, __nat>::type = __nat());
466 template<class _Yp, class _Dp, class _Alloc>
467 shared_ptr(_Yp* __p, _Dp __d, _Alloc __a,
468 typename enable_if<__shared_ptr_deleter_ctor_reqs<_Dp, _Yp, element_type>::value, __nat>::type = __nat());
469 template <class _Dp> shared_ptr(nullptr_t __p, _Dp __d);
470 template <class _Dp, class _Alloc> shared_ptr(nullptr_t __p, _Dp __d, _Alloc __a);
471 template<class _Yp> _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
shared_ptr(const shared_ptr<_Yp>& __r, element_type* __p) _NOEXCEPTnoexcept;
472 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
473 shared_ptr(const shared_ptr& __r) _NOEXCEPTnoexcept;
474 template<class _Yp>
475 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
476 shared_ptr(const shared_ptr<_Yp>& __r,
477 typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type = __nat())
478 _NOEXCEPTnoexcept;
479 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
480 shared_ptr(shared_ptr&& __r) _NOEXCEPTnoexcept;
481 template<class _Yp> _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
shared_ptr(shared_ptr<_Yp>&& __r,
482 typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type = __nat())
483 _NOEXCEPTnoexcept;
484 template<class _Yp> explicit shared_ptr(const weak_ptr<_Yp>& __r,
485 typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type= __nat());
486#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
487 template<class _Yp>
488 shared_ptr(auto_ptr<_Yp>&& __r,
489 typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type = __nat());
490#endif
491 template <class _Yp, class _Dp>
492 shared_ptr(unique_ptr<_Yp, _Dp>&&,
493 typename enable_if
494 <
495 !is_lvalue_reference<_Dp>::value &&
496 is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
497 __nat
498 >::type = __nat());
499 template <class _Yp, class _Dp>
500 shared_ptr(unique_ptr<_Yp, _Dp>&&,
501 typename enable_if
502 <
503 is_lvalue_reference<_Dp>::value &&
504 is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
505 __nat
506 >::type = __nat());
507
508 ~shared_ptr();
509
510 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
511 shared_ptr& operator=(const shared_ptr& __r) _NOEXCEPTnoexcept;
512 template<class _Yp>
513 typename enable_if
514 <
515 __compatible_with<_Yp, element_type>::value,
516 shared_ptr&
517 >::type
518 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
519 operator=(const shared_ptr<_Yp>& __r) _NOEXCEPTnoexcept;
520 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
521 shared_ptr& operator=(shared_ptr&& __r) _NOEXCEPTnoexcept;
522 template<class _Yp>
523 typename enable_if
524 <
525 __compatible_with<_Yp, element_type>::value,
526 shared_ptr&
527 >::type
528 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
529 operator=(shared_ptr<_Yp>&& __r);
530#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
531 template<class _Yp>
532 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
533 typename enable_if
534 <
535 !is_array<_Yp>::value &&
536 is_convertible<_Yp*, element_type*>::value,
537 shared_ptr
538 >::type&
539 operator=(auto_ptr<_Yp>&& __r);
540#endif
541 template <class _Yp, class _Dp>
542 typename enable_if
543 <
544 is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
545 shared_ptr&
546 >::type
547 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
548 operator=(unique_ptr<_Yp, _Dp>&& __r);
549
550 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
551 void swap(shared_ptr& __r) _NOEXCEPTnoexcept;
552 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
553 void reset() _NOEXCEPTnoexcept;
554 template<class _Yp>
555 typename enable_if
556 <
557 __compatible_with<_Yp, element_type>::value,
558 void
559 >::type
560 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
561 reset(_Yp* __p);
562 template<class _Yp, class _Dp>
563 typename enable_if
564 <
565 __compatible_with<_Yp, element_type>::value,
566 void
567 >::type
568 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
569 reset(_Yp* __p, _Dp __d);
570 template<class _Yp, class _Dp, class _Alloc>
571 typename enable_if
572 <
573 __compatible_with<_Yp, element_type>::value,
574 void
575 >::type
576 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
577 reset(_Yp* __p, _Dp __d, _Alloc __a);
578
579 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
580 element_type* get() const _NOEXCEPTnoexcept {return __ptr_;}
581 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
582 typename add_lvalue_reference<element_type>::type operator*() const _NOEXCEPTnoexcept
583 {return *__ptr_;}
584 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
585 element_type* operator->() const _NOEXCEPTnoexcept
586 {
587 static_assert(!is_array<_Tp>::value,
588 "std::shared_ptr<T>::operator-> is only valid when T is not an array type.");
589 return __ptr_;
590 }
591 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
592 long use_count() const _NOEXCEPTnoexcept {return __cntrl_ ? __cntrl_->use_count() : 0;}
593 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
594 bool unique() const _NOEXCEPTnoexcept {return use_count() == 1;}
595 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
596 explicit operator bool() const _NOEXCEPTnoexcept {return get() != nullptr;}
24
Returning zero, which participates in a condition later
597 template <class _Up>
598 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
599 bool owner_before(shared_ptr<_Up> const& __p) const _NOEXCEPTnoexcept
600 {return __cntrl_ < __p.__cntrl_;}
601 template <class _Up>
602 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
603 bool owner_before(weak_ptr<_Up> const& __p) const _NOEXCEPTnoexcept
604 {return __cntrl_ < __p.__cntrl_;}
605 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
606 bool
607 __owner_equivalent(const shared_ptr& __p) const
608 {return __cntrl_ == __p.__cntrl_;}
609
610#if _LIBCPP_STD_VER14 > 14
611 typename add_lvalue_reference<element_type>::type
612 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
613 operator[](ptrdiff_t __i) const
614 {
615 static_assert(is_array<_Tp>::value,
616 "std::shared_ptr<T>::operator[] is only valid when T is an array type.");
617 return __ptr_[__i];
618 }
619#endif
620
621#ifndef _LIBCPP_NO_RTTI
622 template <class _Dp>
623 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
624 _Dp* __get_deleter() const _NOEXCEPTnoexcept
625 {return static_cast<_Dp*>(__cntrl_
626 ? const_cast<void *>(__cntrl_->__get_deleter(typeid(_Dp)))
627 : nullptr);}
628#endif // _LIBCPP_NO_RTTI
629
630 template<class _Yp, class _CntrlBlk>
631 static shared_ptr<_Tp>
632 __create_with_control_block(_Yp* __p, _CntrlBlk* __cntrl) _NOEXCEPTnoexcept
633 {
634 shared_ptr<_Tp> __r;
635 __r.__ptr_ = __p;
636 __r.__cntrl_ = __cntrl;
637 __r.__enable_weak_this(__r.__ptr_, __r.__ptr_);
638 return __r;
639 }
640
641private:
642 template <class _Yp, bool = is_function<_Yp>::value>
643 struct __shared_ptr_default_allocator
644 {
645 typedef allocator<_Yp> type;
646 };
647
648 template <class _Yp>
649 struct __shared_ptr_default_allocator<_Yp, true>
650 {
651 typedef allocator<__shared_ptr_dummy_rebind_allocator_type> type;
652 };
653
654 template <class _Yp, class _OrigPtr>
655 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
656 typename enable_if<is_convertible<_OrigPtr*,
657 const enable_shared_from_this<_Yp>*
658 >::value,
659 void>::type
660 __enable_weak_this(const enable_shared_from_this<_Yp>* __e,
661 _OrigPtr* __ptr) _NOEXCEPTnoexcept
662 {
663 typedef typename remove_cv<_Yp>::type _RawYp;
664 if (__e && __e->__weak_this_.expired())
665 {
666 __e->__weak_this_ = shared_ptr<_RawYp>(*this,
667 const_cast<_RawYp*>(static_cast<const _Yp*>(__ptr)));
668 }
669 }
670
671 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
void __enable_weak_this(...) _NOEXCEPTnoexcept {}
672
673 template <class, class _Yp>
674 struct __shared_ptr_default_delete
675 : default_delete<_Yp> {};
676
677 template <class _Yp, class _Un, size_t _Sz>
678 struct __shared_ptr_default_delete<_Yp[_Sz], _Un>
679 : default_delete<_Yp[]> {};
680
681 template <class _Yp, class _Un>
682 struct __shared_ptr_default_delete<_Yp[], _Un>
683 : default_delete<_Yp[]> {};
684
685 template <class _Up> friend class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) shared_ptr;
686 template <class _Up> friend class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) weak_ptr;
687};
688
689#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
690template<class _Tp>
691shared_ptr(weak_ptr<_Tp>) -> shared_ptr<_Tp>;
692template<class _Tp, class _Dp>
693shared_ptr(unique_ptr<_Tp, _Dp>) -> shared_ptr<_Tp>;
694#endif
695
696template<class _Tp>
697inline
698_LIBCPP_CONSTEXPRconstexpr
699shared_ptr<_Tp>::shared_ptr() _NOEXCEPTnoexcept
700 : __ptr_(nullptr),
701 __cntrl_(nullptr)
702{
703}
704
705template<class _Tp>
706inline
707_LIBCPP_CONSTEXPRconstexpr
708shared_ptr<_Tp>::shared_ptr(nullptr_t) _NOEXCEPTnoexcept
709 : __ptr_(nullptr),
710 __cntrl_(nullptr)
711{
712}
713
714template<class _Tp>
715template<class _Yp, class _Dp>
716shared_ptr<_Tp>::shared_ptr(_Yp* __p, _Dp __d,
717 typename enable_if<__shared_ptr_deleter_ctor_reqs<_Dp, _Yp, element_type>::value, __nat>::type)
718 : __ptr_(__p)
719{
720#ifndef _LIBCPP_NO_EXCEPTIONS
721 try
722 {
723#endif // _LIBCPP_NO_EXCEPTIONS
724 typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
725 typedef __shared_ptr_pointer<_Yp*, _Dp, _AllocT > _CntrlBlk;
726#ifndef _LIBCPP_CXX03_LANG
727 __cntrl_ = new _CntrlBlk(__p, _VSTDstd::__1::move(__d), _AllocT());
728#else
729 __cntrl_ = new _CntrlBlk(__p, __d, _AllocT());
730#endif // not _LIBCPP_CXX03_LANG
731 __enable_weak_this(__p, __p);
732#ifndef _LIBCPP_NO_EXCEPTIONS
733 }
734 catch (...)
735 {
736 __d(__p);
737 throw;
738 }
739#endif // _LIBCPP_NO_EXCEPTIONS
740}
741
742template<class _Tp>
743template<class _Dp>
744shared_ptr<_Tp>::shared_ptr(nullptr_t __p, _Dp __d)
745 : __ptr_(nullptr)
746{
747#ifndef _LIBCPP_NO_EXCEPTIONS
748 try
749 {
750#endif // _LIBCPP_NO_EXCEPTIONS
751 typedef typename __shared_ptr_default_allocator<_Tp>::type _AllocT;
752 typedef __shared_ptr_pointer<nullptr_t, _Dp, _AllocT > _CntrlBlk;
753#ifndef _LIBCPP_CXX03_LANG
754 __cntrl_ = new _CntrlBlk(__p, _VSTDstd::__1::move(__d), _AllocT());
755#else
756 __cntrl_ = new _CntrlBlk(__p, __d, _AllocT());
757#endif // not _LIBCPP_CXX03_LANG
758#ifndef _LIBCPP_NO_EXCEPTIONS
759 }
760 catch (...)
761 {
762 __d(__p);
763 throw;
764 }
765#endif // _LIBCPP_NO_EXCEPTIONS
766}
767
768template<class _Tp>
769template<class _Yp, class _Dp, class _Alloc>
770shared_ptr<_Tp>::shared_ptr(_Yp* __p, _Dp __d, _Alloc __a,
771 typename enable_if<__shared_ptr_deleter_ctor_reqs<_Dp, _Yp, element_type>::value, __nat>::type)
772 : __ptr_(__p)
773{
774#ifndef _LIBCPP_NO_EXCEPTIONS
775 try
776 {
777#endif // _LIBCPP_NO_EXCEPTIONS
778 typedef __shared_ptr_pointer<_Yp*, _Dp, _Alloc> _CntrlBlk;
779 typedef typename __allocator_traits_rebind<_Alloc, _CntrlBlk>::type _A2;
780 typedef __allocator_destructor<_A2> _D2;
781 _A2 __a2(__a);
782 unique_ptr<_CntrlBlk, _D2> __hold2(__a2.allocate(1), _D2(__a2, 1));
783 ::new ((void*)_VSTDstd::__1::addressof(*__hold2.get()))
784#ifndef _LIBCPP_CXX03_LANG
785 _CntrlBlk(__p, _VSTDstd::__1::move(__d), __a);
786#else
787 _CntrlBlk(__p, __d, __a);
788#endif // not _LIBCPP_CXX03_LANG
789 __cntrl_ = _VSTDstd::__1::addressof(*__hold2.release());
790 __enable_weak_this(__p, __p);
791#ifndef _LIBCPP_NO_EXCEPTIONS
792 }
793 catch (...)
794 {
795 __d(__p);
796 throw;
797 }
798#endif // _LIBCPP_NO_EXCEPTIONS
799}
800
801template<class _Tp>
802template<class _Dp, class _Alloc>
803shared_ptr<_Tp>::shared_ptr(nullptr_t __p, _Dp __d, _Alloc __a)
804 : __ptr_(nullptr)
805{
806#ifndef _LIBCPP_NO_EXCEPTIONS
807 try
808 {
809#endif // _LIBCPP_NO_EXCEPTIONS
810 typedef __shared_ptr_pointer<nullptr_t, _Dp, _Alloc> _CntrlBlk;
811 typedef typename __allocator_traits_rebind<_Alloc, _CntrlBlk>::type _A2;
812 typedef __allocator_destructor<_A2> _D2;
813 _A2 __a2(__a);
814 unique_ptr<_CntrlBlk, _D2> __hold2(__a2.allocate(1), _D2(__a2, 1));
815 ::new ((void*)_VSTDstd::__1::addressof(*__hold2.get()))
816#ifndef _LIBCPP_CXX03_LANG
817 _CntrlBlk(__p, _VSTDstd::__1::move(__d), __a);
818#else
819 _CntrlBlk(__p, __d, __a);
820#endif // not _LIBCPP_CXX03_LANG
821 __cntrl_ = _VSTDstd::__1::addressof(*__hold2.release());
822#ifndef _LIBCPP_NO_EXCEPTIONS
823 }
824 catch (...)
825 {
826 __d(__p);
827 throw;
828 }
829#endif // _LIBCPP_NO_EXCEPTIONS
830}
831
832template<class _Tp>
833template<class _Yp>
834inline
835shared_ptr<_Tp>::shared_ptr(const shared_ptr<_Yp>& __r, element_type *__p) _NOEXCEPTnoexcept
836 : __ptr_(__p),
837 __cntrl_(__r.__cntrl_)
838{
839 if (__cntrl_)
840 __cntrl_->__add_shared();
841}
842
843template<class _Tp>
844inline
845shared_ptr<_Tp>::shared_ptr(const shared_ptr& __r) _NOEXCEPTnoexcept
846 : __ptr_(__r.__ptr_),
847 __cntrl_(__r.__cntrl_)
848{
849 if (__cntrl_)
850 __cntrl_->__add_shared();
851}
852
853template<class _Tp>
854template<class _Yp>
855inline
856shared_ptr<_Tp>::shared_ptr(const shared_ptr<_Yp>& __r,
857 typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type)
858 _NOEXCEPTnoexcept
859 : __ptr_(__r.__ptr_),
860 __cntrl_(__r.__cntrl_)
861{
862 if (__cntrl_)
863 __cntrl_->__add_shared();
864}
865
866template<class _Tp>
867inline
868shared_ptr<_Tp>::shared_ptr(shared_ptr&& __r) _NOEXCEPTnoexcept
869 : __ptr_(__r.__ptr_),
870 __cntrl_(__r.__cntrl_)
871{
872 __r.__ptr_ = nullptr;
873 __r.__cntrl_ = nullptr;
874}
875
876template<class _Tp>
877template<class _Yp>
878inline
879shared_ptr<_Tp>::shared_ptr(shared_ptr<_Yp>&& __r,
880 typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type)
881 _NOEXCEPTnoexcept
882 : __ptr_(__r.__ptr_),
883 __cntrl_(__r.__cntrl_)
884{
885 __r.__ptr_ = nullptr;
886 __r.__cntrl_ = nullptr;
887}
888
889#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
890template<class _Tp>
891template<class _Yp>
892shared_ptr<_Tp>::shared_ptr(auto_ptr<_Yp>&& __r,
893 typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type)
894 : __ptr_(__r.get())
895{
896 typedef __shared_ptr_pointer<_Yp*, default_delete<_Yp>, allocator<_Yp> > _CntrlBlk;
897 __cntrl_ = new _CntrlBlk(__r.get(), default_delete<_Yp>(), allocator<_Yp>());
898 __enable_weak_this(__r.get(), __r.get());
899 __r.release();
900}
901#endif
902
903template<class _Tp>
904template <class _Yp, class _Dp>
905shared_ptr<_Tp>::shared_ptr(unique_ptr<_Yp, _Dp>&& __r,
906 typename enable_if
907 <
908 !is_lvalue_reference<_Dp>::value &&
909 is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
910 __nat
911 >::type)
912 : __ptr_(__r.get())
913{
914#if _LIBCPP_STD_VER14 > 11
915 if (__ptr_ == nullptr)
916 __cntrl_ = nullptr;
917 else
918#endif
919 {
920 typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
921 typedef __shared_ptr_pointer<typename unique_ptr<_Yp, _Dp>::pointer, _Dp, _AllocT > _CntrlBlk;
922 __cntrl_ = new _CntrlBlk(__r.get(), __r.get_deleter(), _AllocT());
923 __enable_weak_this(__r.get(), __r.get());
924 }
925 __r.release();
926}
927
928template<class _Tp>
929template <class _Yp, class _Dp>
930shared_ptr<_Tp>::shared_ptr(unique_ptr<_Yp, _Dp>&& __r,
931 typename enable_if
932 <
933 is_lvalue_reference<_Dp>::value &&
934 is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
935 __nat
936 >::type)
937 : __ptr_(__r.get())
938{
939#if _LIBCPP_STD_VER14 > 11
940 if (__ptr_ == nullptr)
941 __cntrl_ = nullptr;
942 else
943#endif
944 {
945 typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
946 typedef __shared_ptr_pointer<typename unique_ptr<_Yp, _Dp>::pointer,
947 reference_wrapper<typename remove_reference<_Dp>::type>,
948 _AllocT > _CntrlBlk;
949 __cntrl_ = new _CntrlBlk(__r.get(), _VSTDstd::__1::ref(__r.get_deleter()), _AllocT());
950 __enable_weak_this(__r.get(), __r.get());
951 }
952 __r.release();
953}
954
955template<class _Tp>
956shared_ptr<_Tp>::~shared_ptr()
957{
958 if (__cntrl_)
959 __cntrl_->__release_shared();
960}
961
962template<class _Tp>
963inline
964shared_ptr<_Tp>&
965shared_ptr<_Tp>::operator=(const shared_ptr& __r) _NOEXCEPTnoexcept
966{
967 shared_ptr(__r).swap(*this);
968 return *this;
969}
970
971template<class _Tp>
972template<class _Yp>
973inline
974typename enable_if
975<
976 __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
977 shared_ptr<_Tp>&
978>::type
979shared_ptr<_Tp>::operator=(const shared_ptr<_Yp>& __r) _NOEXCEPTnoexcept
980{
981 shared_ptr(__r).swap(*this);
982 return *this;
983}
984
985template<class _Tp>
986inline
987shared_ptr<_Tp>&
988shared_ptr<_Tp>::operator=(shared_ptr&& __r) _NOEXCEPTnoexcept
989{
990 shared_ptr(_VSTDstd::__1::move(__r)).swap(*this);
991 return *this;
992}
993
994template<class _Tp>
995template<class _Yp>
996inline
997typename enable_if
998<
999 __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
1000 shared_ptr<_Tp>&
1001>::type
1002shared_ptr<_Tp>::operator=(shared_ptr<_Yp>&& __r)
1003{
1004 shared_ptr(_VSTDstd::__1::move(__r)).swap(*this);
1005 return *this;
1006}
1007
1008#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
1009template<class _Tp>
1010template<class _Yp>
1011inline
1012typename enable_if
1013<
1014 !is_array<_Yp>::value &&
1015 is_convertible<_Yp*, typename shared_ptr<_Tp>::element_type*>::value,
1016 shared_ptr<_Tp>
1017>::type&
1018shared_ptr<_Tp>::operator=(auto_ptr<_Yp>&& __r)
1019{
1020 shared_ptr(_VSTDstd::__1::move(__r)).swap(*this);
1021 return *this;
1022}
1023#endif
1024
1025template<class _Tp>
1026template <class _Yp, class _Dp>
1027inline
1028typename enable_if
1029<
1030 is_convertible<typename unique_ptr<_Yp, _Dp>::pointer,
1031 typename shared_ptr<_Tp>::element_type*>::value,
1032 shared_ptr<_Tp>&
1033>::type
1034shared_ptr<_Tp>::operator=(unique_ptr<_Yp, _Dp>&& __r)
1035{
1036 shared_ptr(_VSTDstd::__1::move(__r)).swap(*this);
1037 return *this;
1038}
1039
1040template<class _Tp>
1041inline
1042void
1043shared_ptr<_Tp>::swap(shared_ptr& __r) _NOEXCEPTnoexcept
1044{
1045 _VSTDstd::__1::swap(__ptr_, __r.__ptr_);
1046 _VSTDstd::__1::swap(__cntrl_, __r.__cntrl_);
1047}
1048
1049template<class _Tp>
1050inline
1051void
1052shared_ptr<_Tp>::reset() _NOEXCEPTnoexcept
1053{
1054 shared_ptr().swap(*this);
1055}
1056
1057template<class _Tp>
1058template<class _Yp>
1059inline
1060typename enable_if
1061<
1062 __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
1063 void
1064>::type
1065shared_ptr<_Tp>::reset(_Yp* __p)
1066{
1067 shared_ptr(__p).swap(*this);
1068}
1069
1070template<class _Tp>
1071template<class _Yp, class _Dp>
1072inline
1073typename enable_if
1074<
1075 __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
1076 void
1077>::type
1078shared_ptr<_Tp>::reset(_Yp* __p, _Dp __d)
1079{
1080 shared_ptr(__p, __d).swap(*this);
1081}
1082
1083template<class _Tp>
1084template<class _Yp, class _Dp, class _Alloc>
1085inline
1086typename enable_if
1087<
1088 __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
1089 void
1090>::type
1091shared_ptr<_Tp>::reset(_Yp* __p, _Dp __d, _Alloc __a)
1092{
1093 shared_ptr(__p, __d, __a).swap(*this);
1094}
1095
1096//
1097// std::allocate_shared and std::make_shared
1098//
1099template<class _Tp, class _Alloc, class ..._Args, class = _EnableIf<!is_array<_Tp>::value> >
1100_LIBCPP_HIDE_FROM_ABI__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1101shared_ptr<_Tp> allocate_shared(const _Alloc& __a, _Args&& ...__args)
1102{
1103 using _ControlBlock = __shared_ptr_emplace<_Tp, _Alloc>;
1104 using _ControlBlockAllocator = typename __allocator_traits_rebind<_Alloc, _ControlBlock>::type;
1105 __allocation_guard<_ControlBlockAllocator> __guard(__a, 1);
1106 ::new ((void*)_VSTDstd::__1::addressof(*__guard.__get())) _ControlBlock(__a, _VSTDstd::__1::forward<_Args>(__args)...);
1107 auto __control_block = __guard.__release_ptr();
1108 return shared_ptr<_Tp>::__create_with_control_block((*__control_block).__get_elem(), _VSTDstd::__1::addressof(*__control_block));
1109}
1110
1111template<class _Tp, class ..._Args, class = _EnableIf<!is_array<_Tp>::value> >
1112_LIBCPP_HIDE_FROM_ABI__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1113shared_ptr<_Tp> make_shared(_Args&& ...__args)
1114{
1115 return _VSTDstd::__1::allocate_shared<_Tp>(allocator<_Tp>(), _VSTDstd::__1::forward<_Args>(__args)...);
1116}
1117
1118template<class _Tp, class _Up>
1119inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1120bool
1121operator==(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPTnoexcept
1122{
1123 return __x.get() == __y.get();
1124}
1125
1126template<class _Tp, class _Up>
1127inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1128bool
1129operator!=(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPTnoexcept
1130{
1131 return !(__x == __y);
1132}
1133
1134template<class _Tp, class _Up>
1135inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1136bool
1137operator<(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPTnoexcept
1138{
1139#if _LIBCPP_STD_VER14 <= 11
1140 typedef typename common_type<_Tp*, _Up*>::type _Vp;
1141 return less<_Vp>()(__x.get(), __y.get());
1142#else
1143 return less<>()(__x.get(), __y.get());
1144#endif
1145
1146}
1147
1148template<class _Tp, class _Up>
1149inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1150bool
1151operator>(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPTnoexcept
1152{
1153 return __y < __x;
1154}
1155
1156template<class _Tp, class _Up>
1157inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1158bool
1159operator<=(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPTnoexcept
1160{
1161 return !(__y < __x);
1162}
1163
1164template<class _Tp, class _Up>
1165inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1166bool
1167operator>=(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPTnoexcept
1168{
1169 return !(__x < __y);
1170}
1171
1172template<class _Tp>
1173inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1174bool
1175operator==(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPTnoexcept
1176{
1177 return !__x;
23
Calling 'shared_ptr::operator bool'
25
Returning from 'shared_ptr::operator bool'
26
Returning the value 1, which participates in a condition later
1178}
1179
1180template<class _Tp>
1181inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1182bool
1183operator==(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPTnoexcept
1184{
1185 return !__x;
1186}
1187
1188template<class _Tp>
1189inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1190bool
1191operator!=(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPTnoexcept
1192{
1193 return static_cast<bool>(__x);
1194}
1195
1196template<class _Tp>
1197inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1198bool
1199operator!=(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPTnoexcept
1200{
1201 return static_cast<bool>(__x);
1202}
1203
1204template<class _Tp>
1205inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1206bool
1207operator<(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPTnoexcept
1208{
1209 return less<_Tp*>()(__x.get(), nullptr);
1210}
1211
1212template<class _Tp>
1213inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1214bool
1215operator<(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPTnoexcept
1216{
1217 return less<_Tp*>()(nullptr, __x.get());
1218}
1219
1220template<class _Tp>
1221inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1222bool
1223operator>(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPTnoexcept
1224{
1225 return nullptr < __x;
1226}
1227
1228template<class _Tp>
1229inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1230bool
1231operator>(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPTnoexcept
1232{
1233 return __x < nullptr;
1234}
1235
1236template<class _Tp>
1237inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1238bool
1239operator<=(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPTnoexcept
1240{
1241 return !(nullptr < __x);
1242}
1243
1244template<class _Tp>
1245inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1246bool
1247operator<=(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPTnoexcept
1248{
1249 return !(__x < nullptr);
1250}
1251
1252template<class _Tp>
1253inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1254bool
1255operator>=(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPTnoexcept
1256{
1257 return !(__x < nullptr);
1258}
1259
1260template<class _Tp>
1261inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1262bool
1263operator>=(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPTnoexcept
1264{
1265 return !(nullptr < __x);
1266}
1267
1268template<class _Tp>
1269inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1270void
1271swap(shared_ptr<_Tp>& __x, shared_ptr<_Tp>& __y) _NOEXCEPTnoexcept
1272{
1273 __x.swap(__y);
1274}
1275
1276template<class _Tp, class _Up>
1277inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1278shared_ptr<_Tp>
1279static_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPTnoexcept
1280{
1281 return shared_ptr<_Tp>(__r,
1282 static_cast<
1283 typename shared_ptr<_Tp>::element_type*>(__r.get()));
1284}
1285
1286template<class _Tp, class _Up>
1287inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1288shared_ptr<_Tp>
1289dynamic_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPTnoexcept
1290{
1291 typedef typename shared_ptr<_Tp>::element_type _ET;
1292 _ET* __p = dynamic_cast<_ET*>(__r.get());
1293 return __p ? shared_ptr<_Tp>(__r, __p) : shared_ptr<_Tp>();
1294}
1295
1296template<class _Tp, class _Up>
1297shared_ptr<_Tp>
1298const_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPTnoexcept
1299{
1300 typedef typename shared_ptr<_Tp>::element_type _RTp;
1301 return shared_ptr<_Tp>(__r, const_cast<_RTp*>(__r.get()));
1302}
1303
1304template<class _Tp, class _Up>
1305shared_ptr<_Tp>
1306reinterpret_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPTnoexcept
1307{
1308 return shared_ptr<_Tp>(__r,
1309 reinterpret_cast<
1310 typename shared_ptr<_Tp>::element_type*>(__r.get()));
1311}
1312
1313#ifndef _LIBCPP_NO_RTTI
1314
1315template<class _Dp, class _Tp>
1316inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1317_Dp*
1318get_deleter(const shared_ptr<_Tp>& __p) _NOEXCEPTnoexcept
1319{
1320 return __p.template __get_deleter<_Dp>();
1321}
1322
1323#endif // _LIBCPP_NO_RTTI
1324
1325template<class _Tp>
1326class _LIBCPP_SHARED_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) weak_ptr
1327{
1328public:
1329 typedef _Tp element_type;
1330private:
1331 element_type* __ptr_;
1332 __shared_weak_count* __cntrl_;
1333
1334public:
1335 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1336 _LIBCPP_CONSTEXPRconstexpr weak_ptr() _NOEXCEPTnoexcept;
1337 template<class _Yp> _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
weak_ptr(shared_ptr<_Yp> const& __r,
1338 typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type = 0)
1339 _NOEXCEPTnoexcept;
1340 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1341 weak_ptr(weak_ptr const& __r) _NOEXCEPTnoexcept;
1342 template<class _Yp> _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
weak_ptr(weak_ptr<_Yp> const& __r,
1343 typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type = 0)
1344 _NOEXCEPTnoexcept;
1345
1346 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1347 weak_ptr(weak_ptr&& __r) _NOEXCEPTnoexcept;
1348 template<class _Yp> _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
weak_ptr(weak_ptr<_Yp>&& __r,
1349 typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type = 0)
1350 _NOEXCEPTnoexcept;
1351 ~weak_ptr();
1352
1353 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1354 weak_ptr& operator=(weak_ptr const& __r) _NOEXCEPTnoexcept;
1355 template<class _Yp>
1356 typename enable_if
1357 <
1358 is_convertible<_Yp*, element_type*>::value,
1359 weak_ptr&
1360 >::type
1361 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1362 operator=(weak_ptr<_Yp> const& __r) _NOEXCEPTnoexcept;
1363
1364 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1365 weak_ptr& operator=(weak_ptr&& __r) _NOEXCEPTnoexcept;
1366 template<class _Yp>
1367 typename enable_if
1368 <
1369 is_convertible<_Yp*, element_type*>::value,
1370 weak_ptr&
1371 >::type
1372 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1373 operator=(weak_ptr<_Yp>&& __r) _NOEXCEPTnoexcept;
1374
1375 template<class _Yp>
1376 typename enable_if
1377 <
1378 is_convertible<_Yp*, element_type*>::value,
1379 weak_ptr&
1380 >::type
1381 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1382 operator=(shared_ptr<_Yp> const& __r) _NOEXCEPTnoexcept;
1383
1384 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1385 void swap(weak_ptr& __r) _NOEXCEPTnoexcept;
1386 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1387 void reset() _NOEXCEPTnoexcept;
1388
1389 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1390 long use_count() const _NOEXCEPTnoexcept
1391 {return __cntrl_ ? __cntrl_->use_count() : 0;}
1392 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1393 bool expired() const _NOEXCEPTnoexcept
1394 {return __cntrl_ == nullptr || __cntrl_->use_count() == 0;}
1395 shared_ptr<_Tp> lock() const _NOEXCEPTnoexcept;
1396 template<class _Up>
1397 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1398 bool owner_before(const shared_ptr<_Up>& __r) const _NOEXCEPTnoexcept
1399 {return __cntrl_ < __r.__cntrl_;}
1400 template<class _Up>
1401 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1402 bool owner_before(const weak_ptr<_Up>& __r) const _NOEXCEPTnoexcept
1403 {return __cntrl_ < __r.__cntrl_;}
1404
1405 template <class _Up> friend class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) weak_ptr;
1406 template <class _Up> friend class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) shared_ptr;
1407};
1408
1409#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
1410template<class _Tp>
1411weak_ptr(shared_ptr<_Tp>) -> weak_ptr<_Tp>;
1412#endif
1413
1414template<class _Tp>
1415inline
1416_LIBCPP_CONSTEXPRconstexpr
1417weak_ptr<_Tp>::weak_ptr() _NOEXCEPTnoexcept
1418 : __ptr_(nullptr),
1419 __cntrl_(nullptr)
1420{
1421}
1422
1423template<class _Tp>
1424inline
1425weak_ptr<_Tp>::weak_ptr(weak_ptr const& __r) _NOEXCEPTnoexcept
1426 : __ptr_(__r.__ptr_),
1427 __cntrl_(__r.__cntrl_)
1428{
1429 if (__cntrl_)
1430 __cntrl_->__add_weak();
1431}
1432
1433template<class _Tp>
1434template<class _Yp>
1435inline
1436weak_ptr<_Tp>::weak_ptr(shared_ptr<_Yp> const& __r,
1437 typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type)
1438 _NOEXCEPTnoexcept
1439 : __ptr_(__r.__ptr_),
1440 __cntrl_(__r.__cntrl_)
1441{
1442 if (__cntrl_)
1443 __cntrl_->__add_weak();
1444}
1445
1446template<class _Tp>
1447template<class _Yp>
1448inline
1449weak_ptr<_Tp>::weak_ptr(weak_ptr<_Yp> const& __r,
1450 typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type)
1451 _NOEXCEPTnoexcept
1452 : __ptr_(__r.__ptr_),
1453 __cntrl_(__r.__cntrl_)
1454{
1455 if (__cntrl_)
1456 __cntrl_->__add_weak();
1457}
1458
1459template<class _Tp>
1460inline
1461weak_ptr<_Tp>::weak_ptr(weak_ptr&& __r) _NOEXCEPTnoexcept
1462 : __ptr_(__r.__ptr_),
1463 __cntrl_(__r.__cntrl_)
1464{
1465 __r.__ptr_ = nullptr;
1466 __r.__cntrl_ = nullptr;
1467}
1468
1469template<class _Tp>
1470template<class _Yp>
1471inline
1472weak_ptr<_Tp>::weak_ptr(weak_ptr<_Yp>&& __r,
1473 typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type)
1474 _NOEXCEPTnoexcept
1475 : __ptr_(__r.__ptr_),
1476 __cntrl_(__r.__cntrl_)
1477{
1478 __r.__ptr_ = nullptr;
1479 __r.__cntrl_ = nullptr;
1480}
1481
1482template<class _Tp>
1483weak_ptr<_Tp>::~weak_ptr()
1484{
1485 if (__cntrl_)
1486 __cntrl_->__release_weak();
1487}
1488
1489template<class _Tp>
1490inline
1491weak_ptr<_Tp>&
1492weak_ptr<_Tp>::operator=(weak_ptr const& __r) _NOEXCEPTnoexcept
1493{
1494 weak_ptr(__r).swap(*this);
1495 return *this;
1496}
1497
1498template<class _Tp>
1499template<class _Yp>
1500inline
1501typename enable_if
1502<
1503 is_convertible<_Yp*, _Tp*>::value,
1504 weak_ptr<_Tp>&
1505>::type
1506weak_ptr<_Tp>::operator=(weak_ptr<_Yp> const& __r) _NOEXCEPTnoexcept
1507{
1508 weak_ptr(__r).swap(*this);
1509 return *this;
1510}
1511
1512template<class _Tp>
1513inline
1514weak_ptr<_Tp>&
1515weak_ptr<_Tp>::operator=(weak_ptr&& __r) _NOEXCEPTnoexcept
1516{
1517 weak_ptr(_VSTDstd::__1::move(__r)).swap(*this);
1518 return *this;
1519}
1520
1521template<class _Tp>
1522template<class _Yp>
1523inline
1524typename enable_if
1525<
1526 is_convertible<_Yp*, _Tp*>::value,
1527 weak_ptr<_Tp>&
1528>::type
1529weak_ptr<_Tp>::operator=(weak_ptr<_Yp>&& __r) _NOEXCEPTnoexcept
1530{
1531 weak_ptr(_VSTDstd::__1::move(__r)).swap(*this);
1532 return *this;
1533}
1534
1535template<class _Tp>
1536template<class _Yp>
1537inline
1538typename enable_if
1539<
1540 is_convertible<_Yp*, _Tp*>::value,
1541 weak_ptr<_Tp>&
1542>::type
1543weak_ptr<_Tp>::operator=(shared_ptr<_Yp> const& __r) _NOEXCEPTnoexcept
1544{
1545 weak_ptr(__r).swap(*this);
1546 return *this;
1547}
1548
1549template<class _Tp>
1550inline
1551void
1552weak_ptr<_Tp>::swap(weak_ptr& __r) _NOEXCEPTnoexcept
1553{
1554 _VSTDstd::__1::swap(__ptr_, __r.__ptr_);
1555 _VSTDstd::__1::swap(__cntrl_, __r.__cntrl_);
1556}
1557
1558template<class _Tp>
1559inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1560void
1561swap(weak_ptr<_Tp>& __x, weak_ptr<_Tp>& __y) _NOEXCEPTnoexcept
1562{
1563 __x.swap(__y);
1564}
1565
1566template<class _Tp>
1567inline
1568void
1569weak_ptr<_Tp>::reset() _NOEXCEPTnoexcept
1570{
1571 weak_ptr().swap(*this);
1572}
1573
1574template<class _Tp>
1575template<class _Yp>
1576shared_ptr<_Tp>::shared_ptr(const weak_ptr<_Yp>& __r,
1577 typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type)
1578 : __ptr_(__r.__ptr_),
1579 __cntrl_(__r.__cntrl_ ? __r.__cntrl_->lock() : __r.__cntrl_)
1580{
1581 if (__cntrl_ == nullptr)
1582 __throw_bad_weak_ptr();
1583}
1584
1585template<class _Tp>
1586shared_ptr<_Tp>
1587weak_ptr<_Tp>::lock() const _NOEXCEPTnoexcept
1588{
1589 shared_ptr<_Tp> __r;
1590 __r.__cntrl_ = __cntrl_ ? __cntrl_->lock() : __cntrl_;
1591 if (__r.__cntrl_)
1592 __r.__ptr_ = __ptr_;
1593 return __r;
1594}
1595
1596#if _LIBCPP_STD_VER14 > 14
1597template <class _Tp = void> struct owner_less;
1598#else
1599template <class _Tp> struct owner_less;
1600#endif
1601
1602
1603_LIBCPP_SUPPRESS_DEPRECATED_PUSHGCC diagnostic push GCC diagnostic ignored "-Wdeprecated" GCC
diagnostic ignored "-Wdeprecated-declarations"
1604template <class _Tp>
1605struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) owner_less<shared_ptr<_Tp> >
1606#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
1607 : binary_function<shared_ptr<_Tp>, shared_ptr<_Tp>, bool>
1608#endif
1609{
1610_LIBCPP_SUPPRESS_DEPRECATED_POPGCC diagnostic pop
1611#if _LIBCPP_STD_VER14 <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
1612 _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
1613 _LIBCPP_DEPRECATED_IN_CXX17 typedef shared_ptr<_Tp> first_argument_type;
1614 _LIBCPP_DEPRECATED_IN_CXX17 typedef shared_ptr<_Tp> second_argument_type;
1615#endif
1616 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1617 bool operator()(shared_ptr<_Tp> const& __x, shared_ptr<_Tp> const& __y) const _NOEXCEPTnoexcept
1618 {return __x.owner_before(__y);}
1619 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1620 bool operator()(shared_ptr<_Tp> const& __x, weak_ptr<_Tp> const& __y) const _NOEXCEPTnoexcept
1621 {return __x.owner_before(__y);}
1622 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1623 bool operator()( weak_ptr<_Tp> const& __x, shared_ptr<_Tp> const& __y) const _NOEXCEPTnoexcept
1624 {return __x.owner_before(__y);}
1625};
1626
1627_LIBCPP_SUPPRESS_DEPRECATED_PUSHGCC diagnostic push GCC diagnostic ignored "-Wdeprecated" GCC
diagnostic ignored "-Wdeprecated-declarations"
1628template <class _Tp>
1629struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) owner_less<weak_ptr<_Tp> >
1630#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
1631 : binary_function<weak_ptr<_Tp>, weak_ptr<_Tp>, bool>
1632#endif
1633{
1634_LIBCPP_SUPPRESS_DEPRECATED_POPGCC diagnostic pop
1635#if _LIBCPP_STD_VER14 <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
1636 _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
1637 _LIBCPP_DEPRECATED_IN_CXX17 typedef weak_ptr<_Tp> first_argument_type;
1638 _LIBCPP_DEPRECATED_IN_CXX17 typedef weak_ptr<_Tp> second_argument_type;
1639#endif
1640 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1641 bool operator()( weak_ptr<_Tp> const& __x, weak_ptr<_Tp> const& __y) const _NOEXCEPTnoexcept
1642 {return __x.owner_before(__y);}
1643 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1644 bool operator()(shared_ptr<_Tp> const& __x, weak_ptr<_Tp> const& __y) const _NOEXCEPTnoexcept
1645 {return __x.owner_before(__y);}
1646 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1647 bool operator()( weak_ptr<_Tp> const& __x, shared_ptr<_Tp> const& __y) const _NOEXCEPTnoexcept
1648 {return __x.owner_before(__y);}
1649};
1650
1651#if _LIBCPP_STD_VER14 > 14
1652template <>
1653struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) owner_less<void>
1654{
1655 template <class _Tp, class _Up>
1656 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1657 bool operator()( shared_ptr<_Tp> const& __x, shared_ptr<_Up> const& __y) const _NOEXCEPTnoexcept
1658 {return __x.owner_before(__y);}
1659 template <class _Tp, class _Up>
1660 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1661 bool operator()( shared_ptr<_Tp> const& __x, weak_ptr<_Up> const& __y) const _NOEXCEPTnoexcept
1662 {return __x.owner_before(__y);}
1663 template <class _Tp, class _Up>
1664 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1665 bool operator()( weak_ptr<_Tp> const& __x, shared_ptr<_Up> const& __y) const _NOEXCEPTnoexcept
1666 {return __x.owner_before(__y);}
1667 template <class _Tp, class _Up>
1668 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1669 bool operator()( weak_ptr<_Tp> const& __x, weak_ptr<_Up> const& __y) const _NOEXCEPTnoexcept
1670 {return __x.owner_before(__y);}
1671 typedef void is_transparent;
1672};
1673#endif
1674
1675template<class _Tp>
1676class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) enable_shared_from_this
1677{
1678 mutable weak_ptr<_Tp> __weak_this_;
1679protected:
1680 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPRconstexpr
1681 enable_shared_from_this() _NOEXCEPTnoexcept {}
1682 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1683 enable_shared_from_this(enable_shared_from_this const&) _NOEXCEPTnoexcept {}
1684 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1685 enable_shared_from_this& operator=(enable_shared_from_this const&) _NOEXCEPTnoexcept
1686 {return *this;}
1687 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1688 ~enable_shared_from_this() {}
1689public:
1690 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1691 shared_ptr<_Tp> shared_from_this()
1692 {return shared_ptr<_Tp>(__weak_this_);}
1693 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1694 shared_ptr<_Tp const> shared_from_this() const
1695 {return shared_ptr<const _Tp>(__weak_this_);}
1696
1697#if _LIBCPP_STD_VER14 > 14
1698 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1699 weak_ptr<_Tp> weak_from_this() _NOEXCEPTnoexcept
1700 { return __weak_this_; }
1701
1702 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1703 weak_ptr<const _Tp> weak_from_this() const _NOEXCEPTnoexcept
1704 { return __weak_this_; }
1705#endif // _LIBCPP_STD_VER > 14
1706
1707 template <class _Up> friend class shared_ptr;
1708};
1709
1710template <class _Tp> struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) hash;
1711
1712template <class _Tp>
1713struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) hash<shared_ptr<_Tp> >
1714{
1715#if _LIBCPP_STD_VER14 <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
1716 _LIBCPP_DEPRECATED_IN_CXX17 typedef shared_ptr<_Tp> argument_type;
1717 _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
1718#endif
1719
1720 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1721 size_t operator()(const shared_ptr<_Tp>& __ptr) const _NOEXCEPTnoexcept
1722 {
1723 return hash<typename shared_ptr<_Tp>::element_type*>()(__ptr.get());
1724 }
1725};
1726
1727template<class _CharT, class _Traits, class _Yp>
1728inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1729basic_ostream<_CharT, _Traits>&
1730operator<<(basic_ostream<_CharT, _Traits>& __os, shared_ptr<_Yp> const& __p);
1731
1732
1733#if !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)
1734
1735class _LIBCPP_TYPE_VIS__attribute__ ((__visibility__("default"))) __sp_mut
1736{
1737 void* __lx;
1738public:
1739 void lock() _NOEXCEPTnoexcept;
1740 void unlock() _NOEXCEPTnoexcept;
1741
1742private:
1743 _LIBCPP_CONSTEXPRconstexpr __sp_mut(void*) _NOEXCEPTnoexcept;
1744 __sp_mut(const __sp_mut&);
1745 __sp_mut& operator=(const __sp_mut&);
1746
1747 friend _LIBCPP_FUNC_VIS__attribute__ ((__visibility__("default"))) __sp_mut& __get_sp_mut(const void*);
1748};
1749
1750_LIBCPP_FUNC_VIS__attribute__ ((__visibility__("default"))) _LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1751__sp_mut& __get_sp_mut(const void*);
1752
1753template <class _Tp>
1754inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1755bool
1756atomic_is_lock_free(const shared_ptr<_Tp>*)
1757{
1758 return false;
1759}
1760
1761template <class _Tp>
1762_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1763shared_ptr<_Tp>
1764atomic_load(const shared_ptr<_Tp>* __p)
1765{
1766 __sp_mut& __m = __get_sp_mut(__p);
1767 __m.lock();
1768 shared_ptr<_Tp> __q = *__p;
1769 __m.unlock();
1770 return __q;
1771}
1772
1773template <class _Tp>
1774inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1775_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1776shared_ptr<_Tp>
1777atomic_load_explicit(const shared_ptr<_Tp>* __p, memory_order)
1778{
1779 return atomic_load(__p);
1780}
1781
1782template <class _Tp>
1783_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1784void
1785atomic_store(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r)
1786{
1787 __sp_mut& __m = __get_sp_mut(__p);
1788 __m.lock();
1789 __p->swap(__r);
1790 __m.unlock();
1791}
1792
1793template <class _Tp>
1794inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1795_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1796void
1797atomic_store_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r, memory_order)
1798{
1799 atomic_store(__p, __r);
1800}
1801
1802template <class _Tp>
1803_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1804shared_ptr<_Tp>
1805atomic_exchange(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r)
1806{
1807 __sp_mut& __m = __get_sp_mut(__p);
1808 __m.lock();
1809 __p->swap(__r);
1810 __m.unlock();
1811 return __r;
1812}
1813
1814template <class _Tp>
1815inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1816_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1817shared_ptr<_Tp>
1818atomic_exchange_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r, memory_order)
1819{
1820 return atomic_exchange(__p, __r);
1821}
1822
1823template <class _Tp>
1824_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1825bool
1826atomic_compare_exchange_strong(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w)
1827{
1828 shared_ptr<_Tp> __temp;
1829 __sp_mut& __m = __get_sp_mut(__p);
1830 __m.lock();
1831 if (__p->__owner_equivalent(*__v))
1832 {
1833 _VSTDstd::__1::swap(__temp, *__p);
1834 *__p = __w;
1835 __m.unlock();
1836 return true;
1837 }
1838 _VSTDstd::__1::swap(__temp, *__v);
1839 *__v = *__p;
1840 __m.unlock();
1841 return false;
1842}
1843
1844template <class _Tp>
1845inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1846_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1847bool
1848atomic_compare_exchange_weak(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w)
1849{
1850 return atomic_compare_exchange_strong(__p, __v, __w);
1851}
1852
1853template <class _Tp>
1854inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1855_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1856bool
1857atomic_compare_exchange_strong_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v,
1858 shared_ptr<_Tp> __w, memory_order, memory_order)
1859{
1860 return atomic_compare_exchange_strong(__p, __v, __w);
1861}
1862
1863template <class _Tp>
1864inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1865_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1866bool
1867atomic_compare_exchange_weak_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v,
1868 shared_ptr<_Tp> __w, memory_order, memory_order)
1869{
1870 return atomic_compare_exchange_weak(__p, __v, __w);
1871}
1872
1873#endif // !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)
1874
1875_LIBCPP_END_NAMESPACE_STD} }
1876
1877_LIBCPP_POP_MACROSpop_macro("min") pop_macro("max")
1878
1879#endif // _LIBCPP___MEMORY_SHARED_PTR_H