Bug Summary

File:src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp
Warning:line 1109, column 51
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 DWARFExpression.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/liblldbExpression/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/liblldbExpression/../include -I /usr/src/gnu/usr.bin/clang/liblldbExpression/obj -I /usr/src/gnu/usr.bin/clang/liblldbExpression/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/liblldbExpression/../../../llvm/lldb/include -I /usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source -I /usr/src/gnu/usr.bin/clang/liblldbExpression/../../../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/liblldbExpression/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/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp

/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp

1//===-- DWARFExpression.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 "lldb/Expression/DWARFExpression.h"
10
11#include <cinttypes>
12
13#include <vector>
14
15#include "lldb/Core/Module.h"
16#include "lldb/Core/Value.h"
17#include "lldb/Core/dwarf.h"
18#include "lldb/Utility/DataEncoder.h"
19#include "lldb/Utility/Log.h"
20#include "lldb/Utility/RegisterValue.h"
21#include "lldb/Utility/Scalar.h"
22#include "lldb/Utility/StreamString.h"
23#include "lldb/Utility/VMRange.h"
24
25#include "lldb/Host/Host.h"
26#include "lldb/Utility/Endian.h"
27
28#include "lldb/Symbol/Function.h"
29
30#include "lldb/Target/ABI.h"
31#include "lldb/Target/ExecutionContext.h"
32#include "lldb/Target/Process.h"
33#include "lldb/Target/RegisterContext.h"
34#include "lldb/Target/StackFrame.h"
35#include "lldb/Target/StackID.h"
36#include "lldb/Target/Target.h"
37#include "lldb/Target/Thread.h"
38
39#include "Plugins/SymbolFile/DWARF/DWARFUnit.h"
40
41using namespace lldb;
42using namespace lldb_private;
43
44static lldb::addr_t
45ReadAddressFromDebugAddrSection(const DWARFUnit *dwarf_cu,
46 uint32_t index) {
47 uint32_t index_size = dwarf_cu->GetAddressByteSize();
48 dw_offset_t addr_base = dwarf_cu->GetAddrBase();
49 lldb::offset_t offset = addr_base + index * index_size;
50 const DWARFDataExtractor &data =
51 dwarf_cu->GetSymbolFileDWARF().GetDWARFContext().getOrLoadAddrData();
52 if (data.ValidOffsetForDataOfSize(offset, index_size))
53 return data.GetMaxU64_unchecked(&offset, index_size);
54 return LLDB_INVALID_ADDRESS0xffffffffffffffffULL;
55}
56
57// DWARFExpression constructor
58DWARFExpression::DWARFExpression() : m_module_wp(), m_data() {}
59
60DWARFExpression::DWARFExpression(lldb::ModuleSP module_sp,
61 const DataExtractor &data,
62 const DWARFUnit *dwarf_cu)
63 : m_module_wp(), m_data(data), m_dwarf_cu(dwarf_cu),
64 m_reg_kind(eRegisterKindDWARF) {
65 if (module_sp)
66 m_module_wp = module_sp;
67}
68
69// Destructor
70DWARFExpression::~DWARFExpression() = default;
71
72bool DWARFExpression::IsValid() const { return m_data.GetByteSize() > 0; }
73
74void DWARFExpression::UpdateValue(uint64_t const_value,
75 lldb::offset_t const_value_byte_size,
76 uint8_t addr_byte_size) {
77 if (!const_value_byte_size)
78 return;
79
80 m_data.SetData(
81 DataBufferSP(new DataBufferHeap(&const_value, const_value_byte_size)));
82 m_data.SetByteOrder(endian::InlHostByteOrder());
83 m_data.SetAddressByteSize(addr_byte_size);
84}
85
86void DWARFExpression::DumpLocation(Stream *s, const DataExtractor &data,
87 lldb::DescriptionLevel level,
88 ABI *abi) const {
89 llvm::DWARFExpression(data.GetAsLLVM(), data.GetAddressByteSize())
90 .print(s->AsRawOstream(), llvm::DIDumpOptions(),
91 abi ? &abi->GetMCRegisterInfo() : nullptr, nullptr);
92}
93
94void DWARFExpression::SetLocationListAddresses(addr_t cu_file_addr,
95 addr_t func_file_addr) {
96 m_loclist_addresses = LoclistAddresses{cu_file_addr, func_file_addr};
97}
98
99int DWARFExpression::GetRegisterKind() { return m_reg_kind; }
100
101void DWARFExpression::SetRegisterKind(RegisterKind reg_kind) {
102 m_reg_kind = reg_kind;
103}
104
105bool DWARFExpression::IsLocationList() const {
106 return bool(m_loclist_addresses);
107}
108
109namespace {
110/// Implement enough of the DWARFObject interface in order to be able to call
111/// DWARFLocationTable::dumpLocationList. We don't have access to a real
112/// DWARFObject here because DWARFExpression is used in non-DWARF scenarios too.
113class DummyDWARFObject final: public llvm::DWARFObject {
114public:
115 DummyDWARFObject(bool IsLittleEndian) : IsLittleEndian(IsLittleEndian) {}
116
117 bool isLittleEndian() const override { return IsLittleEndian; }
118
119 llvm::Optional<llvm::RelocAddrEntry> find(const llvm::DWARFSection &Sec,
120 uint64_t Pos) const override {
121 return llvm::None;
122 }
123private:
124 bool IsLittleEndian;
125};
126}
127
128void DWARFExpression::GetDescription(Stream *s, lldb::DescriptionLevel level,
129 addr_t location_list_base_addr,
130 ABI *abi) const {
131 if (IsLocationList()) {
132 // We have a location list
133 lldb::offset_t offset = 0;
134 std::unique_ptr<llvm::DWARFLocationTable> loctable_up =
135 m_dwarf_cu->GetLocationTable(m_data);
136
137 llvm::MCRegisterInfo *MRI = abi ? &abi->GetMCRegisterInfo() : nullptr;
138 llvm::DIDumpOptions DumpOpts;
139 DumpOpts.RecoverableErrorHandler = [&](llvm::Error E) {
140 s->AsRawOstream() << "error: " << toString(std::move(E));
141 };
142 loctable_up->dumpLocationList(
143 &offset, s->AsRawOstream(),
144 llvm::object::SectionedAddress{m_loclist_addresses->cu_file_addr}, MRI,
145 DummyDWARFObject(m_data.GetByteOrder() == eByteOrderLittle), nullptr,
146 DumpOpts, s->GetIndentLevel() + 2);
147 } else {
148 // We have a normal location that contains DW_OP location opcodes
149 DumpLocation(s, m_data, level, abi);
150 }
151}
152
153static bool ReadRegisterValueAsScalar(RegisterContext *reg_ctx,
154 lldb::RegisterKind reg_kind,
155 uint32_t reg_num, Status *error_ptr,
156 Value &value) {
157 if (reg_ctx == nullptr) {
158 if (error_ptr)
159 error_ptr->SetErrorString("No register context in frame.\n");
160 } else {
161 uint32_t native_reg =
162 reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
163 if (native_reg == LLDB_INVALID_REGNUM0xffffffffU) {
164 if (error_ptr)
165 error_ptr->SetErrorStringWithFormat("Unable to convert register "
166 "kind=%u reg_num=%u to a native "
167 "register number.\n",
168 reg_kind, reg_num);
169 } else {
170 const RegisterInfo *reg_info =
171 reg_ctx->GetRegisterInfoAtIndex(native_reg);
172 RegisterValue reg_value;
173 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
174 if (reg_value.GetScalarValue(value.GetScalar())) {
175 value.SetValueType(Value::ValueType::Scalar);
176 value.SetContext(Value::ContextType::RegisterInfo,
177 const_cast<RegisterInfo *>(reg_info));
178 if (error_ptr)
179 error_ptr->Clear();
180 return true;
181 } else {
182 // If we get this error, then we need to implement a value buffer in
183 // the dwarf expression evaluation function...
184 if (error_ptr)
185 error_ptr->SetErrorStringWithFormat(
186 "register %s can't be converted to a scalar value",
187 reg_info->name);
188 }
189 } else {
190 if (error_ptr)
191 error_ptr->SetErrorStringWithFormat("register %s is not available",
192 reg_info->name);
193 }
194 }
195 }
196 return false;
197}
198
199/// Return the length in bytes of the set of operands for \p op. No guarantees
200/// are made on the state of \p data after this call.
201static offset_t GetOpcodeDataSize(const DataExtractor &data,
202 const lldb::offset_t data_offset,
203 const uint8_t op) {
204 lldb::offset_t offset = data_offset;
205 switch (op) {
206 case DW_OP_addr:
207 case DW_OP_call_ref: // 0x9a 1 address sized offset of DIE (DWARF3)
208 return data.GetAddressByteSize();
209
210 // Opcodes with no arguments
211 case DW_OP_deref: // 0x06
212 case DW_OP_dup: // 0x12
213 case DW_OP_drop: // 0x13
214 case DW_OP_over: // 0x14
215 case DW_OP_swap: // 0x16
216 case DW_OP_rot: // 0x17
217 case DW_OP_xderef: // 0x18
218 case DW_OP_abs: // 0x19
219 case DW_OP_and: // 0x1a
220 case DW_OP_div: // 0x1b
221 case DW_OP_minus: // 0x1c
222 case DW_OP_mod: // 0x1d
223 case DW_OP_mul: // 0x1e
224 case DW_OP_neg: // 0x1f
225 case DW_OP_not: // 0x20
226 case DW_OP_or: // 0x21
227 case DW_OP_plus: // 0x22
228 case DW_OP_shl: // 0x24
229 case DW_OP_shr: // 0x25
230 case DW_OP_shra: // 0x26
231 case DW_OP_xor: // 0x27
232 case DW_OP_eq: // 0x29
233 case DW_OP_ge: // 0x2a
234 case DW_OP_gt: // 0x2b
235 case DW_OP_le: // 0x2c
236 case DW_OP_lt: // 0x2d
237 case DW_OP_ne: // 0x2e
238 case DW_OP_lit0: // 0x30
239 case DW_OP_lit1: // 0x31
240 case DW_OP_lit2: // 0x32
241 case DW_OP_lit3: // 0x33
242 case DW_OP_lit4: // 0x34
243 case DW_OP_lit5: // 0x35
244 case DW_OP_lit6: // 0x36
245 case DW_OP_lit7: // 0x37
246 case DW_OP_lit8: // 0x38
247 case DW_OP_lit9: // 0x39
248 case DW_OP_lit10: // 0x3A
249 case DW_OP_lit11: // 0x3B
250 case DW_OP_lit12: // 0x3C
251 case DW_OP_lit13: // 0x3D
252 case DW_OP_lit14: // 0x3E
253 case DW_OP_lit15: // 0x3F
254 case DW_OP_lit16: // 0x40
255 case DW_OP_lit17: // 0x41
256 case DW_OP_lit18: // 0x42
257 case DW_OP_lit19: // 0x43
258 case DW_OP_lit20: // 0x44
259 case DW_OP_lit21: // 0x45
260 case DW_OP_lit22: // 0x46
261 case DW_OP_lit23: // 0x47
262 case DW_OP_lit24: // 0x48
263 case DW_OP_lit25: // 0x49
264 case DW_OP_lit26: // 0x4A
265 case DW_OP_lit27: // 0x4B
266 case DW_OP_lit28: // 0x4C
267 case DW_OP_lit29: // 0x4D
268 case DW_OP_lit30: // 0x4E
269 case DW_OP_lit31: // 0x4f
270 case DW_OP_reg0: // 0x50
271 case DW_OP_reg1: // 0x51
272 case DW_OP_reg2: // 0x52
273 case DW_OP_reg3: // 0x53
274 case DW_OP_reg4: // 0x54
275 case DW_OP_reg5: // 0x55
276 case DW_OP_reg6: // 0x56
277 case DW_OP_reg7: // 0x57
278 case DW_OP_reg8: // 0x58
279 case DW_OP_reg9: // 0x59
280 case DW_OP_reg10: // 0x5A
281 case DW_OP_reg11: // 0x5B
282 case DW_OP_reg12: // 0x5C
283 case DW_OP_reg13: // 0x5D
284 case DW_OP_reg14: // 0x5E
285 case DW_OP_reg15: // 0x5F
286 case DW_OP_reg16: // 0x60
287 case DW_OP_reg17: // 0x61
288 case DW_OP_reg18: // 0x62
289 case DW_OP_reg19: // 0x63
290 case DW_OP_reg20: // 0x64
291 case DW_OP_reg21: // 0x65
292 case DW_OP_reg22: // 0x66
293 case DW_OP_reg23: // 0x67
294 case DW_OP_reg24: // 0x68
295 case DW_OP_reg25: // 0x69
296 case DW_OP_reg26: // 0x6A
297 case DW_OP_reg27: // 0x6B
298 case DW_OP_reg28: // 0x6C
299 case DW_OP_reg29: // 0x6D
300 case DW_OP_reg30: // 0x6E
301 case DW_OP_reg31: // 0x6F
302 case DW_OP_nop: // 0x96
303 case DW_OP_push_object_address: // 0x97 DWARF3
304 case DW_OP_form_tls_address: // 0x9b DWARF3
305 case DW_OP_call_frame_cfa: // 0x9c DWARF3
306 case DW_OP_stack_value: // 0x9f DWARF4
307 case DW_OP_GNU_push_tls_address: // 0xe0 GNU extension
308 return 0;
309
310 // Opcodes with a single 1 byte arguments
311 case DW_OP_const1u: // 0x08 1 1-byte constant
312 case DW_OP_const1s: // 0x09 1 1-byte constant
313 case DW_OP_pick: // 0x15 1 1-byte stack index
314 case DW_OP_deref_size: // 0x94 1 1-byte size of data retrieved
315 case DW_OP_xderef_size: // 0x95 1 1-byte size of data retrieved
316 return 1;
317
318 // Opcodes with a single 2 byte arguments
319 case DW_OP_const2u: // 0x0a 1 2-byte constant
320 case DW_OP_const2s: // 0x0b 1 2-byte constant
321 case DW_OP_skip: // 0x2f 1 signed 2-byte constant
322 case DW_OP_bra: // 0x28 1 signed 2-byte constant
323 case DW_OP_call2: // 0x98 1 2-byte offset of DIE (DWARF3)
324 return 2;
325
326 // Opcodes with a single 4 byte arguments
327 case DW_OP_const4u: // 0x0c 1 4-byte constant
328 case DW_OP_const4s: // 0x0d 1 4-byte constant
329 case DW_OP_call4: // 0x99 1 4-byte offset of DIE (DWARF3)
330 return 4;
331
332 // Opcodes with a single 8 byte arguments
333 case DW_OP_const8u: // 0x0e 1 8-byte constant
334 case DW_OP_const8s: // 0x0f 1 8-byte constant
335 return 8;
336
337 // All opcodes that have a single ULEB (signed or unsigned) argument
338 case DW_OP_addrx: // 0xa1 1 ULEB128 index
339 case DW_OP_constu: // 0x10 1 ULEB128 constant
340 case DW_OP_consts: // 0x11 1 SLEB128 constant
341 case DW_OP_plus_uconst: // 0x23 1 ULEB128 addend
342 case DW_OP_breg0: // 0x70 1 ULEB128 register
343 case DW_OP_breg1: // 0x71 1 ULEB128 register
344 case DW_OP_breg2: // 0x72 1 ULEB128 register
345 case DW_OP_breg3: // 0x73 1 ULEB128 register
346 case DW_OP_breg4: // 0x74 1 ULEB128 register
347 case DW_OP_breg5: // 0x75 1 ULEB128 register
348 case DW_OP_breg6: // 0x76 1 ULEB128 register
349 case DW_OP_breg7: // 0x77 1 ULEB128 register
350 case DW_OP_breg8: // 0x78 1 ULEB128 register
351 case DW_OP_breg9: // 0x79 1 ULEB128 register
352 case DW_OP_breg10: // 0x7a 1 ULEB128 register
353 case DW_OP_breg11: // 0x7b 1 ULEB128 register
354 case DW_OP_breg12: // 0x7c 1 ULEB128 register
355 case DW_OP_breg13: // 0x7d 1 ULEB128 register
356 case DW_OP_breg14: // 0x7e 1 ULEB128 register
357 case DW_OP_breg15: // 0x7f 1 ULEB128 register
358 case DW_OP_breg16: // 0x80 1 ULEB128 register
359 case DW_OP_breg17: // 0x81 1 ULEB128 register
360 case DW_OP_breg18: // 0x82 1 ULEB128 register
361 case DW_OP_breg19: // 0x83 1 ULEB128 register
362 case DW_OP_breg20: // 0x84 1 ULEB128 register
363 case DW_OP_breg21: // 0x85 1 ULEB128 register
364 case DW_OP_breg22: // 0x86 1 ULEB128 register
365 case DW_OP_breg23: // 0x87 1 ULEB128 register
366 case DW_OP_breg24: // 0x88 1 ULEB128 register
367 case DW_OP_breg25: // 0x89 1 ULEB128 register
368 case DW_OP_breg26: // 0x8a 1 ULEB128 register
369 case DW_OP_breg27: // 0x8b 1 ULEB128 register
370 case DW_OP_breg28: // 0x8c 1 ULEB128 register
371 case DW_OP_breg29: // 0x8d 1 ULEB128 register
372 case DW_OP_breg30: // 0x8e 1 ULEB128 register
373 case DW_OP_breg31: // 0x8f 1 ULEB128 register
374 case DW_OP_regx: // 0x90 1 ULEB128 register
375 case DW_OP_fbreg: // 0x91 1 SLEB128 offset
376 case DW_OP_piece: // 0x93 1 ULEB128 size of piece addressed
377 case DW_OP_GNU_addr_index: // 0xfb 1 ULEB128 index
378 case DW_OP_GNU_const_index: // 0xfc 1 ULEB128 index
379 data.Skip_LEB128(&offset);
380 return offset - data_offset;
381
382 // All opcodes that have a 2 ULEB (signed or unsigned) arguments
383 case DW_OP_bregx: // 0x92 2 ULEB128 register followed by SLEB128 offset
384 case DW_OP_bit_piece: // 0x9d ULEB128 bit size, ULEB128 bit offset (DWARF3);
385 data.Skip_LEB128(&offset);
386 data.Skip_LEB128(&offset);
387 return offset - data_offset;
388
389 case DW_OP_implicit_value: // 0x9e ULEB128 size followed by block of that size
390 // (DWARF4)
391 {
392 uint64_t block_len = data.Skip_LEB128(&offset);
393 offset += block_len;
394 return offset - data_offset;
395 }
396
397 case DW_OP_GNU_entry_value:
398 case DW_OP_entry_value: // 0xa3 ULEB128 size + variable-length block
399 {
400 uint64_t subexpr_len = data.GetULEB128(&offset);
401 return (offset - data_offset) + subexpr_len;
402 }
403
404 default:
405 break;
406 }
407 return LLDB_INVALID_OFFSET0xffffffffffffffffULL;
408}
409
410lldb::addr_t DWARFExpression::GetLocation_DW_OP_addr(uint32_t op_addr_idx,
411 bool &error) const {
412 error = false;
413 if (IsLocationList())
414 return LLDB_INVALID_ADDRESS0xffffffffffffffffULL;
415 lldb::offset_t offset = 0;
416 uint32_t curr_op_addr_idx = 0;
417 while (m_data.ValidOffset(offset)) {
418 const uint8_t op = m_data.GetU8(&offset);
419
420 if (op == DW_OP_addr) {
421 const lldb::addr_t op_file_addr = m_data.GetAddress(&offset);
422 if (curr_op_addr_idx == op_addr_idx)
423 return op_file_addr;
424 else
425 ++curr_op_addr_idx;
426 } else if (op == DW_OP_GNU_addr_index || op == DW_OP_addrx) {
427 uint64_t index = m_data.GetULEB128(&offset);
428 if (curr_op_addr_idx == op_addr_idx) {
429 if (!m_dwarf_cu) {
430 error = true;
431 break;
432 }
433
434 return ReadAddressFromDebugAddrSection(m_dwarf_cu, index);
435 } else
436 ++curr_op_addr_idx;
437 } else {
438 const offset_t op_arg_size = GetOpcodeDataSize(m_data, offset, op);
439 if (op_arg_size == LLDB_INVALID_OFFSET0xffffffffffffffffULL) {
440 error = true;
441 break;
442 }
443 offset += op_arg_size;
444 }
445 }
446 return LLDB_INVALID_ADDRESS0xffffffffffffffffULL;
447}
448
449bool DWARFExpression::Update_DW_OP_addr(lldb::addr_t file_addr) {
450 if (IsLocationList())
451 return false;
452 lldb::offset_t offset = 0;
453 while (m_data.ValidOffset(offset)) {
454 const uint8_t op = m_data.GetU8(&offset);
455
456 if (op == DW_OP_addr) {
457 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
458 // We have to make a copy of the data as we don't know if this data is
459 // from a read only memory mapped buffer, so we duplicate all of the data
460 // first, then modify it, and if all goes well, we then replace the data
461 // for this expression
462
463 // So first we copy the data into a heap buffer
464 std::unique_ptr<DataBufferHeap> head_data_up(
465 new DataBufferHeap(m_data.GetDataStart(), m_data.GetByteSize()));
466
467 // Make en encoder so we can write the address into the buffer using the
468 // correct byte order (endianness)
469 DataEncoder encoder(head_data_up->GetBytes(), head_data_up->GetByteSize(),
470 m_data.GetByteOrder(), addr_byte_size);
471
472 // Replace the address in the new buffer
473 if (encoder.PutUnsigned(offset, addr_byte_size, file_addr) == UINT32_MAX0xffffffffU)
474 return false;
475
476 // All went well, so now we can reset the data using a shared pointer to
477 // the heap data so "m_data" will now correctly manage the heap data.
478 m_data.SetData(DataBufferSP(head_data_up.release()));
479 return true;
480 } else {
481 const offset_t op_arg_size = GetOpcodeDataSize(m_data, offset, op);
482 if (op_arg_size == LLDB_INVALID_OFFSET0xffffffffffffffffULL)
483 break;
484 offset += op_arg_size;
485 }
486 }
487 return false;
488}
489
490bool DWARFExpression::ContainsThreadLocalStorage() const {
491 // We are assuming for now that any thread local variable will not have a
492 // location list. This has been true for all thread local variables we have
493 // seen so far produced by any compiler.
494 if (IsLocationList())
495 return false;
496 lldb::offset_t offset = 0;
497 while (m_data.ValidOffset(offset)) {
498 const uint8_t op = m_data.GetU8(&offset);
499
500 if (op == DW_OP_form_tls_address || op == DW_OP_GNU_push_tls_address)
501 return true;
502 const offset_t op_arg_size = GetOpcodeDataSize(m_data, offset, op);
503 if (op_arg_size == LLDB_INVALID_OFFSET0xffffffffffffffffULL)
504 return false;
505 else
506 offset += op_arg_size;
507 }
508 return false;
509}
510bool DWARFExpression::LinkThreadLocalStorage(
511 lldb::ModuleSP new_module_sp,
512 std::function<lldb::addr_t(lldb::addr_t file_addr)> const
513 &link_address_callback) {
514 // We are assuming for now that any thread local variable will not have a
515 // location list. This has been true for all thread local variables we have
516 // seen so far produced by any compiler.
517 if (IsLocationList())
518 return false;
519
520 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
521 // We have to make a copy of the data as we don't know if this data is from a
522 // read only memory mapped buffer, so we duplicate all of the data first,
523 // then modify it, and if all goes well, we then replace the data for this
524 // expression
525
526 // So first we copy the data into a heap buffer
527 std::shared_ptr<DataBufferHeap> heap_data_sp(
528 new DataBufferHeap(m_data.GetDataStart(), m_data.GetByteSize()));
529
530 // Make en encoder so we can write the address into the buffer using the
531 // correct byte order (endianness)
532 DataEncoder encoder(heap_data_sp->GetBytes(), heap_data_sp->GetByteSize(),
533 m_data.GetByteOrder(), addr_byte_size);
534
535 lldb::offset_t offset = 0;
536 lldb::offset_t const_offset = 0;
537 lldb::addr_t const_value = 0;
538 size_t const_byte_size = 0;
539 while (m_data.ValidOffset(offset)) {
540 const uint8_t op = m_data.GetU8(&offset);
541
542 bool decoded_data = false;
543 switch (op) {
544 case DW_OP_const4u:
545 // Remember the const offset in case we later have a
546 // DW_OP_form_tls_address or DW_OP_GNU_push_tls_address
547 const_offset = offset;
548 const_value = m_data.GetU32(&offset);
549 decoded_data = true;
550 const_byte_size = 4;
551 break;
552
553 case DW_OP_const8u:
554 // Remember the const offset in case we later have a
555 // DW_OP_form_tls_address or DW_OP_GNU_push_tls_address
556 const_offset = offset;
557 const_value = m_data.GetU64(&offset);
558 decoded_data = true;
559 const_byte_size = 8;
560 break;
561
562 case DW_OP_form_tls_address:
563 case DW_OP_GNU_push_tls_address:
564 // DW_OP_form_tls_address and DW_OP_GNU_push_tls_address must be preceded
565 // by a file address on the stack. We assume that DW_OP_const4u or
566 // DW_OP_const8u is used for these values, and we check that the last
567 // opcode we got before either of these was DW_OP_const4u or
568 // DW_OP_const8u. If so, then we can link the value accodingly. For
569 // Darwin, the value in the DW_OP_const4u or DW_OP_const8u is the file
570 // address of a structure that contains a function pointer, the pthread
571 // key and the offset into the data pointed to by the pthread key. So we
572 // must link this address and also set the module of this expression to
573 // the new_module_sp so we can resolve the file address correctly
574 if (const_byte_size > 0) {
575 lldb::addr_t linked_file_addr = link_address_callback(const_value);
576 if (linked_file_addr == LLDB_INVALID_ADDRESS0xffffffffffffffffULL)
577 return false;
578 // Replace the address in the new buffer
579 if (encoder.PutUnsigned(const_offset, const_byte_size,
580 linked_file_addr) == UINT32_MAX0xffffffffU)
581 return false;
582 }
583 break;
584
585 default:
586 const_offset = 0;
587 const_value = 0;
588 const_byte_size = 0;
589 break;
590 }
591
592 if (!decoded_data) {
593 const offset_t op_arg_size = GetOpcodeDataSize(m_data, offset, op);
594 if (op_arg_size == LLDB_INVALID_OFFSET0xffffffffffffffffULL)
595 return false;
596 else
597 offset += op_arg_size;
598 }
599 }
600
601 // If we linked the TLS address correctly, update the module so that when the
602 // expression is evaluated it can resolve the file address to a load address
603 // and read the
604 // TLS data
605 m_module_wp = new_module_sp;
606 m_data.SetData(heap_data_sp);
607 return true;
608}
609
610bool DWARFExpression::LocationListContainsAddress(addr_t func_load_addr,
611 lldb::addr_t addr) const {
612 if (func_load_addr == LLDB_INVALID_ADDRESS0xffffffffffffffffULL || addr == LLDB_INVALID_ADDRESS0xffffffffffffffffULL)
613 return false;
614
615 if (!IsLocationList())
616 return false;
617
618 return GetLocationExpression(func_load_addr, addr) != llvm::None;
619}
620
621bool DWARFExpression::DumpLocationForAddress(Stream *s,
622 lldb::DescriptionLevel level,
623 addr_t func_load_addr,
624 addr_t address, ABI *abi) {
625 if (!IsLocationList()) {
626 DumpLocation(s, m_data, level, abi);
627 return true;
628 }
629 if (llvm::Optional<DataExtractor> expr =
630 GetLocationExpression(func_load_addr, address)) {
631 DumpLocation(s, *expr, level, abi);
632 return true;
633 }
634 return false;
635}
636
637static bool Evaluate_DW_OP_entry_value(std::vector<Value> &stack,
638 ExecutionContext *exe_ctx,
639 RegisterContext *reg_ctx,
640 const DataExtractor &opcodes,
641 lldb::offset_t &opcode_offset,
642 Status *error_ptr, Log *log) {
643 // DW_OP_entry_value(sub-expr) describes the location a variable had upon
644 // function entry: this variable location is presumed to be optimized out at
645 // the current PC value. The caller of the function may have call site
646 // information that describes an alternate location for the variable (e.g. a
647 // constant literal, or a spilled stack value) in the parent frame.
648 //
649 // Example (this is pseudo-code & pseudo-DWARF, but hopefully illustrative):
650 //
651 // void child(int &sink, int x) {
652 // ...
653 // /* "x" gets optimized out. */
654 //
655 // /* The location of "x" here is: DW_OP_entry_value($reg2). */
656 // ++sink;
657 // }
658 //
659 // void parent() {
660 // int sink;
661 //
662 // /*
663 // * The callsite information emitted here is:
664 // *
665 // * DW_TAG_call_site
666 // * DW_AT_return_pc ... (for "child(sink, 123);")
667 // * DW_TAG_call_site_parameter (for "sink")
668 // * DW_AT_location ($reg1)
669 // * DW_AT_call_value ($SP - 8)
670 // * DW_TAG_call_site_parameter (for "x")
671 // * DW_AT_location ($reg2)
672 // * DW_AT_call_value ($literal 123)
673 // *
674 // * DW_TAG_call_site
675 // * DW_AT_return_pc ... (for "child(sink, 456);")
676 // * ...
677 // */
678 // child(sink, 123);
679 // child(sink, 456);
680 // }
681 //
682 // When the program stops at "++sink" within `child`, the debugger determines
683 // the call site by analyzing the return address. Once the call site is found,
684 // the debugger determines which parameter is referenced by DW_OP_entry_value
685 // and evaluates the corresponding location for that parameter in `parent`.
686
687 // 1. Find the function which pushed the current frame onto the stack.
688 if ((!exe_ctx || !exe_ctx->HasTargetScope()) || !reg_ctx) {
689 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no exe/reg context")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: no exe/reg context")
; } while (0)
;
690 return false;
691 }
692
693 StackFrame *current_frame = exe_ctx->GetFramePtr();
694 Thread *thread = exe_ctx->GetThreadPtr();
695 if (!current_frame || !thread) {
696 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no current frame/thread")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: no current frame/thread"
); } while (0)
;
697 return false;
698 }
699
700 Target &target = exe_ctx->GetTargetRef();
701 StackFrameSP parent_frame = nullptr;
702 addr_t return_pc = LLDB_INVALID_ADDRESS0xffffffffffffffffULL;
703 uint32_t current_frame_idx = current_frame->GetFrameIndex();
704 uint32_t num_frames = thread->GetStackFrameCount();
705 for (uint32_t parent_frame_idx = current_frame_idx + 1;
706 parent_frame_idx < num_frames; ++parent_frame_idx) {
707 parent_frame = thread->GetStackFrameAtIndex(parent_frame_idx);
708 // Require a valid sequence of frames.
709 if (!parent_frame)
710 break;
711
712 // Record the first valid return address, even if this is an inlined frame,
713 // in order to look up the associated call edge in the first non-inlined
714 // parent frame.
715 if (return_pc == LLDB_INVALID_ADDRESS0xffffffffffffffffULL) {
716 return_pc = parent_frame->GetFrameCodeAddress().GetLoadAddress(&target);
717 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: immediate ancestor with pc = {0:x}"
, return_pc); } while (0)
718 "Evaluate_DW_OP_entry_value: immediate ancestor with pc = {0:x}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: immediate ancestor with pc = {0:x}"
, return_pc); } while (0)
719 return_pc)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: immediate ancestor with pc = {0:x}"
, return_pc); } while (0)
;
720 }
721
722 // If we've found an inlined frame, skip it (these have no call site
723 // parameters).
724 if (parent_frame->IsInlined())
725 continue;
726
727 // We've found the first non-inlined parent frame.
728 break;
729 }
730 if (!parent_frame || !parent_frame->GetRegisterContext()) {
731 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no parent frame with reg ctx")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: no parent frame with reg ctx"
); } while (0)
;
732 return false;
733 }
734
735 Function *parent_func =
736 parent_frame->GetSymbolContext(eSymbolContextFunction).function;
737 if (!parent_func) {
738 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no parent function")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: no parent function")
; } while (0)
;
739 return false;
740 }
741
742 // 2. Find the call edge in the parent function responsible for creating the
743 // current activation.
744 Function *current_func =
745 current_frame->GetSymbolContext(eSymbolContextFunction).function;
746 if (!current_func) {
747 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no current function")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: no current function"
); } while (0)
;
748 return false;
749 }
750
751 CallEdge *call_edge = nullptr;
752 ModuleList &modlist = target.GetImages();
753 ExecutionContext parent_exe_ctx = *exe_ctx;
754 parent_exe_ctx.SetFrameSP(parent_frame);
755 if (!parent_frame->IsArtificial()) {
756 // If the parent frame is not artificial, the current activation may be
757 // produced by an ambiguous tail call. In this case, refuse to proceed.
758 call_edge = parent_func->GetCallEdgeForReturnAddress(return_pc, target);
759 if (!call_edge) {
760 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: no call edge for retn-pc = {0:x} "
"in parent frame {1}", return_pc, parent_func->GetName())
; } while (0)
761 "Evaluate_DW_OP_entry_value: no call edge for retn-pc = {0:x} "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: no call edge for retn-pc = {0:x} "
"in parent frame {1}", return_pc, parent_func->GetName())
; } while (0)
762 "in parent frame {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: no call edge for retn-pc = {0:x} "
"in parent frame {1}", return_pc, parent_func->GetName())
; } while (0)
763 return_pc, parent_func->GetName())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: no call edge for retn-pc = {0:x} "
"in parent frame {1}", return_pc, parent_func->GetName())
; } while (0)
;
764 return false;
765 }
766 Function *callee_func = call_edge->GetCallee(modlist, parent_exe_ctx);
767 if (callee_func != current_func) {
768 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: ambiguous call sequence, "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: ambiguous call sequence, "
"can't find real parent frame"); } while (0)
769 "can't find real parent frame")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: ambiguous call sequence, "
"can't find real parent frame"); } while (0)
;
770 return false;
771 }
772 } else {
773 // The StackFrameList solver machinery has deduced that an unambiguous tail
774 // call sequence that produced the current activation. The first edge in
775 // the parent that points to the current function must be valid.
776 for (auto &edge : parent_func->GetTailCallingEdges()) {
777 if (edge->GetCallee(modlist, parent_exe_ctx) == current_func) {
778 call_edge = edge.get();
779 break;
780 }
781 }
782 }
783 if (!call_edge) {
784 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no unambiguous edge from parent "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: no unambiguous edge from parent "
"to current function"); } while (0)
785 "to current function")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: no unambiguous edge from parent "
"to current function"); } while (0)
;
786 return false;
787 }
788
789 // 3. Attempt to locate the DW_OP_entry_value expression in the set of
790 // available call site parameters. If found, evaluate the corresponding
791 // parameter in the context of the parent frame.
792 const uint32_t subexpr_len = opcodes.GetULEB128(&opcode_offset);
793 const void *subexpr_data = opcodes.GetData(&opcode_offset, subexpr_len);
794 if (!subexpr_data) {
795 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: subexpr could not be read")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: subexpr could not be read"
); } while (0)
;
796 return false;
797 }
798
799 const CallSiteParameter *matched_param = nullptr;
800 for (const CallSiteParameter &param : call_edge->GetCallSiteParameters()) {
801 DataExtractor param_subexpr_extractor;
802 if (!param.LocationInCallee.GetExpressionData(param_subexpr_extractor))
803 continue;
804 lldb::offset_t param_subexpr_offset = 0;
805 const void *param_subexpr_data =
806 param_subexpr_extractor.GetData(&param_subexpr_offset, subexpr_len);
807 if (!param_subexpr_data ||
808 param_subexpr_extractor.BytesLeft(param_subexpr_offset) != 0)
809 continue;
810
811 // At this point, the DW_OP_entry_value sub-expression and the callee-side
812 // expression in the call site parameter are known to have the same length.
813 // Check whether they are equal.
814 //
815 // Note that an equality check is sufficient: the contents of the
816 // DW_OP_entry_value subexpression are only used to identify the right call
817 // site parameter in the parent, and do not require any special handling.
818 if (memcmp(subexpr_data, param_subexpr_data, subexpr_len) == 0) {
819 matched_param = &param;
820 break;
821 }
822 }
823 if (!matched_param) {
824 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: no matching call site param found"
); } while (0)
825 "Evaluate_DW_OP_entry_value: no matching call site param found")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: no matching call site param found"
); } while (0)
;
826 return false;
827 }
828
829 // TODO: Add support for DW_OP_push_object_address within a DW_OP_entry_value
830 // subexpresion whenever llvm does.
831 Value result;
832 const DWARFExpression &param_expr = matched_param->LocationInCaller;
833 if (!param_expr.Evaluate(&parent_exe_ctx,
834 parent_frame->GetRegisterContext().get(),
835 /*loclist_base_addr=*/LLDB_INVALID_ADDRESS0xffffffffffffffffULL,
836 /*initial_value_ptr=*/nullptr,
837 /*object_address_ptr=*/nullptr, result, error_ptr)) {
838 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: call site param evaluation failed"
); } while (0)
839 "Evaluate_DW_OP_entry_value: call site param evaluation failed")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_entry_value: call site param evaluation failed"
); } while (0)
;
840 return false;
841 }
842
843 stack.push_back(result);
844 return true;
845}
846
847bool DWARFExpression::Evaluate(ExecutionContextScope *exe_scope,
848 lldb::addr_t loclist_base_load_addr,
849 const Value *initial_value_ptr,
850 const Value *object_address_ptr, Value &result,
851 Status *error_ptr) const {
852 ExecutionContext exe_ctx(exe_scope);
853 return Evaluate(&exe_ctx, nullptr, loclist_base_load_addr, initial_value_ptr,
854 object_address_ptr, result, error_ptr);
855}
856
857bool DWARFExpression::Evaluate(ExecutionContext *exe_ctx,
858 RegisterContext *reg_ctx,
859 lldb::addr_t func_load_addr,
860 const Value *initial_value_ptr,
861 const Value *object_address_ptr, Value &result,
862 Status *error_ptr) const {
863 ModuleSP module_sp = m_module_wp.lock();
864
865 if (IsLocationList()) {
866 addr_t pc;
867 StackFrame *frame = nullptr;
868 if (reg_ctx)
869 pc = reg_ctx->GetPC();
870 else {
871 frame = exe_ctx->GetFramePtr();
872 if (!frame)
873 return false;
874 RegisterContextSP reg_ctx_sp = frame->GetRegisterContext();
875 if (!reg_ctx_sp)
876 return false;
877 pc = reg_ctx_sp->GetPC();
878 }
879
880 if (func_load_addr != LLDB_INVALID_ADDRESS0xffffffffffffffffULL) {
881 if (pc == LLDB_INVALID_ADDRESS0xffffffffffffffffULL) {
882 if (error_ptr)
883 error_ptr->SetErrorString("Invalid PC in frame.");
884 return false;
885 }
886
887 if (llvm::Optional<DataExtractor> expr =
888 GetLocationExpression(func_load_addr, pc)) {
889 return DWARFExpression::Evaluate(
890 exe_ctx, reg_ctx, module_sp, *expr, m_dwarf_cu, m_reg_kind,
891 initial_value_ptr, object_address_ptr, result, error_ptr);
892 }
893 }
894 if (error_ptr)
895 error_ptr->SetErrorString("variable not available");
896 return false;
897 }
898
899 // Not a location list, just a single expression.
900 return DWARFExpression::Evaluate(exe_ctx, reg_ctx, module_sp, m_data,
901 m_dwarf_cu, m_reg_kind, initial_value_ptr,
902 object_address_ptr, result, error_ptr);
903}
904
905namespace {
906/// The location description kinds described by the DWARF v5
907/// specification. Composite locations are handled out-of-band and
908/// thus aren't part of the enum.
909enum LocationDescriptionKind {
910 Empty,
911 Memory,
912 Register,
913 Implicit
914 /* Composite*/
915};
916/// Adjust value's ValueType according to the kind of location description.
917void UpdateValueTypeFromLocationDescription(Log *log, const DWARFUnit *dwarf_cu,
918 LocationDescriptionKind kind,
919 Value *value = nullptr) {
920 // Note that this function is conflating DWARF expressions with
921 // DWARF location descriptions. Perhaps it would be better to define
922 // a wrapper for DWARFExpresssion::Eval() that deals with DWARF
923 // location descriptions (which consist of one or more DWARF
924 // expressions). But doing this would mean we'd also need factor the
925 // handling of DW_OP_(bit_)piece out of this function.
926 if (dwarf_cu && dwarf_cu->GetVersion() >= 4) {
927 const char *log_msg = "DWARF location description kind: %s";
928 switch (kind) {
929 case Empty:
930 LLDB_LOGF(log, log_msg, "Empty")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf(log_msg, "Empty"); } while (0)
;
931 break;
932 case Memory:
933 LLDB_LOGF(log, log_msg, "Memory")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf(log_msg, "Memory"); } while (0)
;
934 if (value->GetValueType() == Value::ValueType::Scalar)
935 value->SetValueType(Value::ValueType::LoadAddress);
936 break;
937 case Register:
938 LLDB_LOGF(log, log_msg, "Register")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf(log_msg, "Register"); } while (0)
;
939 value->SetValueType(Value::ValueType::Scalar);
940 break;
941 case Implicit:
942 LLDB_LOGF(log, log_msg, "Implicit")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf(log_msg, "Implicit"); } while (0)
;
943 if (value->GetValueType() == Value::ValueType::LoadAddress)
944 value->SetValueType(Value::ValueType::Scalar);
945 break;
946 }
947 }
948}
949} // namespace
950
951bool DWARFExpression::Evaluate(
952 ExecutionContext *exe_ctx, RegisterContext *reg_ctx,
953 lldb::ModuleSP module_sp, const DataExtractor &opcodes,
954 const DWARFUnit *dwarf_cu, const lldb::RegisterKind reg_kind,
955 const Value *initial_value_ptr, const Value *object_address_ptr,
956 Value &result, Status *error_ptr) {
957
958 if (opcodes.GetByteSize() == 0) {
1
Assuming the condition is false
2
Taking false branch
959 if (error_ptr)
960 error_ptr->SetErrorString(
961 "no location, value may have been optimized out");
962 return false;
963 }
964 std::vector<Value> stack;
965
966 Process *process = nullptr;
967 StackFrame *frame = nullptr;
968
969 if (exe_ctx) {
3
Assuming 'exe_ctx' is null
4
Taking false branch
970 process = exe_ctx->GetProcessPtr();
971 frame = exe_ctx->GetFramePtr();
972 }
973 if (reg_ctx == nullptr && frame)
5
Assuming the condition is false
974 reg_ctx = frame->GetRegisterContext().get();
975
976 if (initial_value_ptr)
6
Assuming 'initial_value_ptr' is null
7
Taking false branch
977 stack.push_back(*initial_value_ptr);
978
979 lldb::offset_t offset = 0;
980 Value tmp;
981 uint32_t reg_num;
982
983 /// Insertion point for evaluating multi-piece expression.
984 uint64_t op_piece_offset = 0;
985 Value pieces; // Used for DW_OP_piece
986
987 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS(1u << 8)));
988 // A generic type is "an integral type that has the size of an address and an
989 // unspecified signedness". For now, just use the signedness of the operand.
990 // TODO: Implement a real typed stack, and store the genericness of the value
991 // there.
992 auto to_generic = [&](auto v) {
993 bool is_signed = std::is_signed<decltype(v)>::value;
994 return Scalar(llvm::APSInt(
995 llvm::APInt(8 * opcodes.GetAddressByteSize(), v, is_signed),
996 !is_signed));
997 };
998
999 // The default kind is a memory location. This is updated by any
1000 // operation that changes this, such as DW_OP_stack_value, and reset
1001 // by composition operations like DW_OP_piece.
1002 LocationDescriptionKind dwarf4_location_description_kind = Memory;
1003
1004 while (opcodes.ValidOffset(offset)) {
8
Calling 'DataExtractor::ValidOffset'
10
Returning from 'DataExtractor::ValidOffset'
11
Loop condition is true. Entering loop body
1005 const lldb::offset_t op_offset = offset;
1006 const uint8_t op = opcodes.GetU8(&offset);
1007
1008 if (log && log->GetVerbose()) {
12
Assuming 'log' is null
1009 size_t count = stack.size();
1010 LLDB_LOGF(log, "Stack before operation has %" PRIu64 " values:",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Stack before operation has %" "llu"
" values:", (uint64_t)count); } while (0)
1011 (uint64_t)count)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Stack before operation has %" "llu"
" values:", (uint64_t)count); } while (0)
;
1012 for (size_t i = 0; i < count; ++i) {
1013 StreamString new_value;
1014 new_value.Printf("[%" PRIu64"llu" "]", (uint64_t)i);
1015 stack[i].Dump(&new_value);
1016 LLDB_LOGF(log, " %s", new_value.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf(" %s", new_value.GetData()); } while
(0)
;
1017 }
1018 LLDB_LOGF(log, "0x%8.8" PRIx64 ": %s", op_offset,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("0x%8.8" "llx" ": %s", op_offset, DW_OP_value_to_name
(op)); } while (0)
1019 DW_OP_value_to_name(op))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("0x%8.8" "llx" ": %s", op_offset, DW_OP_value_to_name
(op)); } while (0)
;
1020 }
1021
1022 switch (op) {
13
Control jumps to 'case DW_OP_deref:' at line 1078
1023 // The DW_OP_addr operation has a single operand that encodes a machine
1024 // address and whose size is the size of an address on the target machine.
1025 case DW_OP_addr:
1026 stack.push_back(Scalar(opcodes.GetAddress(&offset)));
1027 stack.back().SetValueType(Value::ValueType::FileAddress);
1028 // Convert the file address to a load address, so subsequent
1029 // DWARF operators can operate on it.
1030 if (frame)
1031 stack.back().ConvertToLoadAddress(module_sp.get(),
1032 frame->CalculateTarget().get());
1033 break;
1034
1035 // The DW_OP_addr_sect_offset4 is used for any location expressions in
1036 // shared libraries that have a location like:
1037 // DW_OP_addr(0x1000)
1038 // If this address resides in a shared library, then this virtual address
1039 // won't make sense when it is evaluated in the context of a running
1040 // process where shared libraries have been slid. To account for this, this
1041 // new address type where we can store the section pointer and a 4 byte
1042 // offset.
1043 // case DW_OP_addr_sect_offset4:
1044 // {
1045 // result_type = eResultTypeFileAddress;
1046 // lldb::Section *sect = (lldb::Section
1047 // *)opcodes.GetMaxU64(&offset, sizeof(void *));
1048 // lldb::addr_t sect_offset = opcodes.GetU32(&offset);
1049 //
1050 // Address so_addr (sect, sect_offset);
1051 // lldb::addr_t load_addr = so_addr.GetLoadAddress();
1052 // if (load_addr != LLDB_INVALID_ADDRESS)
1053 // {
1054 // // We successfully resolve a file address to a load
1055 // // address.
1056 // stack.push_back(load_addr);
1057 // break;
1058 // }
1059 // else
1060 // {
1061 // // We were able
1062 // if (error_ptr)
1063 // error_ptr->SetErrorStringWithFormat ("Section %s in
1064 // %s is not currently loaded.\n",
1065 // sect->GetName().AsCString(),
1066 // sect->GetModule()->GetFileSpec().GetFilename().AsCString());
1067 // return false;
1068 // }
1069 // }
1070 // break;
1071
1072 // OPCODE: DW_OP_deref
1073 // OPERANDS: none
1074 // DESCRIPTION: Pops the top stack entry and treats it as an address.
1075 // The value retrieved from that address is pushed. The size of the data
1076 // retrieved from the dereferenced address is the size of an address on the
1077 // target machine.
1078 case DW_OP_deref: {
1079 if (stack.empty()) {
14
Assuming the condition is false
15
Taking false branch
1080 if (error_ptr)
1081 error_ptr->SetErrorString("Expression stack empty for DW_OP_deref.");
1082 return false;
1083 }
1084 Value::ValueType value_type = stack.back().GetValueType();
1085 switch (value_type) {
16
Control jumps to 'case FileAddress:' at line 1093
1086 case Value::ValueType::HostAddress: {
1087 void *src = (void *)stack.back().GetScalar().ULongLong();
1088 intptr_t ptr;
1089 ::memcpy(&ptr, src, sizeof(void *));
1090 stack.back().GetScalar() = ptr;
1091 stack.back().ClearContext();
1092 } break;
1093 case Value::ValueType::FileAddress: {
1094 auto file_addr = stack.back().GetScalar().ULongLong(
1095 LLDB_INVALID_ADDRESS0xffffffffffffffffULL);
1096 if (!module_sp) {
17
Calling 'shared_ptr::operator bool'
20
Returning from 'shared_ptr::operator bool'
21
Taking false branch
1097 if (error_ptr)
1098 error_ptr->SetErrorString(
1099 "need module to resolve file address for DW_OP_deref");
1100 return false;
1101 }
1102 Address so_addr;
1103 if (!module_sp->ResolveFileAddress(file_addr, so_addr)) {
22
Assuming the condition is false
23
Taking false branch
1104 if (error_ptr)
1105 error_ptr->SetErrorString(
1106 "failed to resolve file address in module");
1107 return false;
1108 }
1109 addr_t load_Addr = so_addr.GetLoadAddress(exe_ctx->GetTargetPtr());
24
Called C++ object pointer is null
1110 if (load_Addr == LLDB_INVALID_ADDRESS0xffffffffffffffffULL) {
1111 if (error_ptr)
1112 error_ptr->SetErrorString("failed to resolve load address");
1113 return false;
1114 }
1115 stack.back().GetScalar() = load_Addr;
1116 // Fall through to load address promotion code below.
1117 } LLVM_FALLTHROUGH[[gnu::fallthrough]];
1118 case Value::ValueType::Scalar:
1119 // Promote Scalar to LoadAddress and fall through.
1120 stack.back().SetValueType(Value::ValueType::LoadAddress);
1121 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1122 case Value::ValueType::LoadAddress:
1123 if (exe_ctx) {
1124 if (process) {
1125 lldb::addr_t pointer_addr =
1126 stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS0xffffffffffffffffULL);
1127 Status error;
1128 lldb::addr_t pointer_value =
1129 process->ReadPointerFromMemory(pointer_addr, error);
1130 if (pointer_value != LLDB_INVALID_ADDRESS0xffffffffffffffffULL) {
1131 if (ABISP abi_sp = process->GetABI())
1132 pointer_value = abi_sp->FixCodeAddress(pointer_value);
1133 stack.back().GetScalar() = pointer_value;
1134 stack.back().ClearContext();
1135 } else {
1136 if (error_ptr)
1137 error_ptr->SetErrorStringWithFormat(
1138 "Failed to dereference pointer from 0x%" PRIx64"llx"
1139 " for DW_OP_deref: %s\n",
1140 pointer_addr, error.AsCString());
1141 return false;
1142 }
1143 } else {
1144 if (error_ptr)
1145 error_ptr->SetErrorString("NULL process for DW_OP_deref.\n");
1146 return false;
1147 }
1148 } else {
1149 if (error_ptr)
1150 error_ptr->SetErrorString(
1151 "NULL execution context for DW_OP_deref.\n");
1152 return false;
1153 }
1154 break;
1155
1156 case Value::ValueType::Invalid:
1157 if (error_ptr)
1158 error_ptr->SetErrorString("Invalid value type for DW_OP_deref.\n");
1159 return false;
1160 }
1161
1162 } break;
1163
1164 // OPCODE: DW_OP_deref_size
1165 // OPERANDS: 1
1166 // 1 - uint8_t that specifies the size of the data to dereference.
1167 // DESCRIPTION: Behaves like the DW_OP_deref operation: it pops the top
1168 // stack entry and treats it as an address. The value retrieved from that
1169 // address is pushed. In the DW_OP_deref_size operation, however, the size
1170 // in bytes of the data retrieved from the dereferenced address is
1171 // specified by the single operand. This operand is a 1-byte unsigned
1172 // integral constant whose value may not be larger than the size of an
1173 // address on the target machine. The data retrieved is zero extended to
1174 // the size of an address on the target machine before being pushed on the
1175 // expression stack.
1176 case DW_OP_deref_size: {
1177 if (stack.empty()) {
1178 if (error_ptr)
1179 error_ptr->SetErrorString(
1180 "Expression stack empty for DW_OP_deref_size.");
1181 return false;
1182 }
1183 uint8_t size = opcodes.GetU8(&offset);
1184 Value::ValueType value_type = stack.back().GetValueType();
1185 switch (value_type) {
1186 case Value::ValueType::HostAddress: {
1187 void *src = (void *)stack.back().GetScalar().ULongLong();
1188 intptr_t ptr;
1189 ::memcpy(&ptr, src, sizeof(void *));
1190 // I can't decide whether the size operand should apply to the bytes in
1191 // their
1192 // lldb-host endianness or the target endianness.. I doubt this'll ever
1193 // come up but I'll opt for assuming big endian regardless.
1194 switch (size) {
1195 case 1:
1196 ptr = ptr & 0xff;
1197 break;
1198 case 2:
1199 ptr = ptr & 0xffff;
1200 break;
1201 case 3:
1202 ptr = ptr & 0xffffff;
1203 break;
1204 case 4:
1205 ptr = ptr & 0xffffffff;
1206 break;
1207 // the casts are added to work around the case where intptr_t is a 32
1208 // bit quantity;
1209 // presumably we won't hit the 5..7 cases if (void*) is 32-bits in this
1210 // program.
1211 case 5:
1212 ptr = (intptr_t)ptr & 0xffffffffffULL;
1213 break;
1214 case 6:
1215 ptr = (intptr_t)ptr & 0xffffffffffffULL;
1216 break;
1217 case 7:
1218 ptr = (intptr_t)ptr & 0xffffffffffffffULL;
1219 break;
1220 default:
1221 break;
1222 }
1223 stack.back().GetScalar() = ptr;
1224 stack.back().ClearContext();
1225 } break;
1226 case Value::ValueType::Scalar:
1227 case Value::ValueType::LoadAddress:
1228 if (exe_ctx) {
1229 if (process) {
1230 lldb::addr_t pointer_addr =
1231 stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS0xffffffffffffffffULL);
1232 uint8_t addr_bytes[sizeof(lldb::addr_t)];
1233 Status error;
1234 if (process->ReadMemory(pointer_addr, &addr_bytes, size, error) ==
1235 size) {
1236 DataExtractor addr_data(addr_bytes, sizeof(addr_bytes),
1237 process->GetByteOrder(), size);
1238 lldb::offset_t addr_data_offset = 0;
1239 switch (size) {
1240 case 1:
1241 stack.back().GetScalar() = addr_data.GetU8(&addr_data_offset);
1242 break;
1243 case 2:
1244 stack.back().GetScalar() = addr_data.GetU16(&addr_data_offset);
1245 break;
1246 case 4:
1247 stack.back().GetScalar() = addr_data.GetU32(&addr_data_offset);
1248 break;
1249 case 8:
1250 stack.back().GetScalar() = addr_data.GetU64(&addr_data_offset);
1251 break;
1252 default:
1253 stack.back().GetScalar() =
1254 addr_data.GetAddress(&addr_data_offset);
1255 }
1256 stack.back().ClearContext();
1257 } else {
1258 if (error_ptr)
1259 error_ptr->SetErrorStringWithFormat(
1260 "Failed to dereference pointer from 0x%" PRIx64"llx"
1261 " for DW_OP_deref: %s\n",
1262 pointer_addr, error.AsCString());
1263 return false;
1264 }
1265 } else {
1266 if (error_ptr)
1267 error_ptr->SetErrorString("NULL process for DW_OP_deref_size.\n");
1268 return false;
1269 }
1270 } else {
1271 if (error_ptr)
1272 error_ptr->SetErrorString(
1273 "NULL execution context for DW_OP_deref_size.\n");
1274 return false;
1275 }
1276 break;
1277
1278 case Value::ValueType::FileAddress:
1279 case Value::ValueType::Invalid:
1280 if (error_ptr)
1281 error_ptr->SetErrorString("Invalid value for DW_OP_deref_size.\n");
1282 return false;
1283 }
1284
1285 } break;
1286
1287 // OPCODE: DW_OP_xderef_size
1288 // OPERANDS: 1
1289 // 1 - uint8_t that specifies the size of the data to dereference.
1290 // DESCRIPTION: Behaves like the DW_OP_xderef operation: the entry at
1291 // the top of the stack is treated as an address. The second stack entry is
1292 // treated as an "address space identifier" for those architectures that
1293 // support multiple address spaces. The top two stack elements are popped,
1294 // a data item is retrieved through an implementation-defined address
1295 // calculation and pushed as the new stack top. In the DW_OP_xderef_size
1296 // operation, however, the size in bytes of the data retrieved from the
1297 // dereferenced address is specified by the single operand. This operand is
1298 // a 1-byte unsigned integral constant whose value may not be larger than
1299 // the size of an address on the target machine. The data retrieved is zero
1300 // extended to the size of an address on the target machine before being
1301 // pushed on the expression stack.
1302 case DW_OP_xderef_size:
1303 if (error_ptr)
1304 error_ptr->SetErrorString("Unimplemented opcode: DW_OP_xderef_size.");
1305 return false;
1306 // OPCODE: DW_OP_xderef
1307 // OPERANDS: none
1308 // DESCRIPTION: Provides an extended dereference mechanism. The entry at
1309 // the top of the stack is treated as an address. The second stack entry is
1310 // treated as an "address space identifier" for those architectures that
1311 // support multiple address spaces. The top two stack elements are popped,
1312 // a data item is retrieved through an implementation-defined address
1313 // calculation and pushed as the new stack top. The size of the data
1314 // retrieved from the dereferenced address is the size of an address on the
1315 // target machine.
1316 case DW_OP_xderef:
1317 if (error_ptr)
1318 error_ptr->SetErrorString("Unimplemented opcode: DW_OP_xderef.");
1319 return false;
1320
1321 // All DW_OP_constXXX opcodes have a single operand as noted below:
1322 //
1323 // Opcode Operand 1
1324 // DW_OP_const1u 1-byte unsigned integer constant
1325 // DW_OP_const1s 1-byte signed integer constant
1326 // DW_OP_const2u 2-byte unsigned integer constant
1327 // DW_OP_const2s 2-byte signed integer constant
1328 // DW_OP_const4u 4-byte unsigned integer constant
1329 // DW_OP_const4s 4-byte signed integer constant
1330 // DW_OP_const8u 8-byte unsigned integer constant
1331 // DW_OP_const8s 8-byte signed integer constant
1332 // DW_OP_constu unsigned LEB128 integer constant
1333 // DW_OP_consts signed LEB128 integer constant
1334 case DW_OP_const1u:
1335 stack.push_back(to_generic(opcodes.GetU8(&offset)));
1336 break;
1337 case DW_OP_const1s:
1338 stack.push_back(to_generic((int8_t)opcodes.GetU8(&offset)));
1339 break;
1340 case DW_OP_const2u:
1341 stack.push_back(to_generic(opcodes.GetU16(&offset)));
1342 break;
1343 case DW_OP_const2s:
1344 stack.push_back(to_generic((int16_t)opcodes.GetU16(&offset)));
1345 break;
1346 case DW_OP_const4u:
1347 stack.push_back(to_generic(opcodes.GetU32(&offset)));
1348 break;
1349 case DW_OP_const4s:
1350 stack.push_back(to_generic((int32_t)opcodes.GetU32(&offset)));
1351 break;
1352 case DW_OP_const8u:
1353 stack.push_back(to_generic(opcodes.GetU64(&offset)));
1354 break;
1355 case DW_OP_const8s:
1356 stack.push_back(to_generic((int64_t)opcodes.GetU64(&offset)));
1357 break;
1358 // These should also use to_generic, but we can't do that due to a
1359 // producer-side bug in llvm. See llvm.org/pr48087.
1360 case DW_OP_constu:
1361 stack.push_back(Scalar(opcodes.GetULEB128(&offset)));
1362 break;
1363 case DW_OP_consts:
1364 stack.push_back(Scalar(opcodes.GetSLEB128(&offset)));
1365 break;
1366
1367 // OPCODE: DW_OP_dup
1368 // OPERANDS: none
1369 // DESCRIPTION: duplicates the value at the top of the stack
1370 case DW_OP_dup:
1371 if (stack.empty()) {
1372 if (error_ptr)
1373 error_ptr->SetErrorString("Expression stack empty for DW_OP_dup.");
1374 return false;
1375 } else
1376 stack.push_back(stack.back());
1377 break;
1378
1379 // OPCODE: DW_OP_drop
1380 // OPERANDS: none
1381 // DESCRIPTION: pops the value at the top of the stack
1382 case DW_OP_drop:
1383 if (stack.empty()) {
1384 if (error_ptr)
1385 error_ptr->SetErrorString("Expression stack empty for DW_OP_drop.");
1386 return false;
1387 } else
1388 stack.pop_back();
1389 break;
1390
1391 // OPCODE: DW_OP_over
1392 // OPERANDS: none
1393 // DESCRIPTION: Duplicates the entry currently second in the stack at
1394 // the top of the stack.
1395 case DW_OP_over:
1396 if (stack.size() < 2) {
1397 if (error_ptr)
1398 error_ptr->SetErrorString(
1399 "Expression stack needs at least 2 items for DW_OP_over.");
1400 return false;
1401 } else
1402 stack.push_back(stack[stack.size() - 2]);
1403 break;
1404
1405 // OPCODE: DW_OP_pick
1406 // OPERANDS: uint8_t index into the current stack
1407 // DESCRIPTION: The stack entry with the specified index (0 through 255,
1408 // inclusive) is pushed on the stack
1409 case DW_OP_pick: {
1410 uint8_t pick_idx = opcodes.GetU8(&offset);
1411 if (pick_idx < stack.size())
1412 stack.push_back(stack[stack.size() - 1 - pick_idx]);
1413 else {
1414 if (error_ptr)
1415 error_ptr->SetErrorStringWithFormat(
1416 "Index %u out of range for DW_OP_pick.\n", pick_idx);
1417 return false;
1418 }
1419 } break;
1420
1421 // OPCODE: DW_OP_swap
1422 // OPERANDS: none
1423 // DESCRIPTION: swaps the top two stack entries. The entry at the top
1424 // of the stack becomes the second stack entry, and the second entry
1425 // becomes the top of the stack
1426 case DW_OP_swap:
1427 if (stack.size() < 2) {
1428 if (error_ptr)
1429 error_ptr->SetErrorString(
1430 "Expression stack needs at least 2 items for DW_OP_swap.");
1431 return false;
1432 } else {
1433 tmp = stack.back();
1434 stack.back() = stack[stack.size() - 2];
1435 stack[stack.size() - 2] = tmp;
1436 }
1437 break;
1438
1439 // OPCODE: DW_OP_rot
1440 // OPERANDS: none
1441 // DESCRIPTION: Rotates the first three stack entries. The entry at
1442 // the top of the stack becomes the third stack entry, the second entry
1443 // becomes the top of the stack, and the third entry becomes the second
1444 // entry.
1445 case DW_OP_rot:
1446 if (stack.size() < 3) {
1447 if (error_ptr)
1448 error_ptr->SetErrorString(
1449 "Expression stack needs at least 3 items for DW_OP_rot.");
1450 return false;
1451 } else {
1452 size_t last_idx = stack.size() - 1;
1453 Value old_top = stack[last_idx];
1454 stack[last_idx] = stack[last_idx - 1];
1455 stack[last_idx - 1] = stack[last_idx - 2];
1456 stack[last_idx - 2] = old_top;
1457 }
1458 break;
1459
1460 // OPCODE: DW_OP_abs
1461 // OPERANDS: none
1462 // DESCRIPTION: pops the top stack entry, interprets it as a signed
1463 // value and pushes its absolute value. If the absolute value can not be
1464 // represented, the result is undefined.
1465 case DW_OP_abs:
1466 if (stack.empty()) {
1467 if (error_ptr)
1468 error_ptr->SetErrorString(
1469 "Expression stack needs at least 1 item for DW_OP_abs.");
1470 return false;
1471 } else if (!stack.back().ResolveValue(exe_ctx).AbsoluteValue()) {
1472 if (error_ptr)
1473 error_ptr->SetErrorString(
1474 "Failed to take the absolute value of the first stack item.");
1475 return false;
1476 }
1477 break;
1478
1479 // OPCODE: DW_OP_and
1480 // OPERANDS: none
1481 // DESCRIPTION: pops the top two stack values, performs a bitwise and
1482 // operation on the two, and pushes the result.
1483 case DW_OP_and:
1484 if (stack.size() < 2) {
1485 if (error_ptr)
1486 error_ptr->SetErrorString(
1487 "Expression stack needs at least 2 items for DW_OP_and.");
1488 return false;
1489 } else {
1490 tmp = stack.back();
1491 stack.pop_back();
1492 stack.back().ResolveValue(exe_ctx) =
1493 stack.back().ResolveValue(exe_ctx) & tmp.ResolveValue(exe_ctx);
1494 }
1495 break;
1496
1497 // OPCODE: DW_OP_div
1498 // OPERANDS: none
1499 // DESCRIPTION: pops the top two stack values, divides the former second
1500 // entry by the former top of the stack using signed division, and pushes
1501 // the result.
1502 case DW_OP_div:
1503 if (stack.size() < 2) {
1504 if (error_ptr)
1505 error_ptr->SetErrorString(
1506 "Expression stack needs at least 2 items for DW_OP_div.");
1507 return false;
1508 } else {
1509 tmp = stack.back();
1510 if (tmp.ResolveValue(exe_ctx).IsZero()) {
1511 if (error_ptr)
1512 error_ptr->SetErrorString("Divide by zero.");
1513 return false;
1514 } else {
1515 stack.pop_back();
1516 stack.back() =
1517 stack.back().ResolveValue(exe_ctx) / tmp.ResolveValue(exe_ctx);
1518 if (!stack.back().ResolveValue(exe_ctx).IsValid()) {
1519 if (error_ptr)
1520 error_ptr->SetErrorString("Divide failed.");
1521 return false;
1522 }
1523 }
1524 }
1525 break;
1526
1527 // OPCODE: DW_OP_minus
1528 // OPERANDS: none
1529 // DESCRIPTION: pops the top two stack values, subtracts the former top
1530 // of the stack from the former second entry, and pushes the result.
1531 case DW_OP_minus:
1532 if (stack.size() < 2) {
1533 if (error_ptr)
1534 error_ptr->SetErrorString(
1535 "Expression stack needs at least 2 items for DW_OP_minus.");
1536 return false;
1537 } else {
1538 tmp = stack.back();
1539 stack.pop_back();
1540 stack.back().ResolveValue(exe_ctx) =
1541 stack.back().ResolveValue(exe_ctx) - tmp.ResolveValue(exe_ctx);
1542 }
1543 break;
1544
1545 // OPCODE: DW_OP_mod
1546 // OPERANDS: none
1547 // DESCRIPTION: pops the top two stack values and pushes the result of
1548 // the calculation: former second stack entry modulo the former top of the
1549 // stack.
1550 case DW_OP_mod:
1551 if (stack.size() < 2) {
1552 if (error_ptr)
1553 error_ptr->SetErrorString(
1554 "Expression stack needs at least 2 items for DW_OP_mod.");
1555 return false;
1556 } else {
1557 tmp = stack.back();
1558 stack.pop_back();
1559 stack.back().ResolveValue(exe_ctx) =
1560 stack.back().ResolveValue(exe_ctx) % tmp.ResolveValue(exe_ctx);
1561 }
1562 break;
1563
1564 // OPCODE: DW_OP_mul
1565 // OPERANDS: none
1566 // DESCRIPTION: pops the top two stack entries, multiplies them
1567 // together, and pushes the result.
1568 case DW_OP_mul:
1569 if (stack.size() < 2) {
1570 if (error_ptr)
1571 error_ptr->SetErrorString(
1572 "Expression stack needs at least 2 items for DW_OP_mul.");
1573 return false;
1574 } else {
1575 tmp = stack.back();
1576 stack.pop_back();
1577 stack.back().ResolveValue(exe_ctx) =
1578 stack.back().ResolveValue(exe_ctx) * tmp.ResolveValue(exe_ctx);
1579 }
1580 break;
1581
1582 // OPCODE: DW_OP_neg
1583 // OPERANDS: none
1584 // DESCRIPTION: pops the top stack entry, and pushes its negation.
1585 case DW_OP_neg:
1586 if (stack.empty()) {
1587 if (error_ptr)
1588 error_ptr->SetErrorString(
1589 "Expression stack needs at least 1 item for DW_OP_neg.");
1590 return false;
1591 } else {
1592 if (!stack.back().ResolveValue(exe_ctx).UnaryNegate()) {
1593 if (error_ptr)
1594 error_ptr->SetErrorString("Unary negate failed.");
1595 return false;
1596 }
1597 }
1598 break;
1599
1600 // OPCODE: DW_OP_not
1601 // OPERANDS: none
1602 // DESCRIPTION: pops the top stack entry, and pushes its bitwise
1603 // complement
1604 case DW_OP_not:
1605 if (stack.empty()) {
1606 if (error_ptr)
1607 error_ptr->SetErrorString(
1608 "Expression stack needs at least 1 item for DW_OP_not.");
1609 return false;
1610 } else {
1611 if (!stack.back().ResolveValue(exe_ctx).OnesComplement()) {
1612 if (error_ptr)
1613 error_ptr->SetErrorString("Logical NOT failed.");
1614 return false;
1615 }
1616 }
1617 break;
1618
1619 // OPCODE: DW_OP_or
1620 // OPERANDS: none
1621 // DESCRIPTION: pops the top two stack entries, performs a bitwise or
1622 // operation on the two, and pushes the result.
1623 case DW_OP_or:
1624 if (stack.size() < 2) {
1625 if (error_ptr)
1626 error_ptr->SetErrorString(
1627 "Expression stack needs at least 2 items for DW_OP_or.");
1628 return false;
1629 } else {
1630 tmp = stack.back();
1631 stack.pop_back();
1632 stack.back().ResolveValue(exe_ctx) =
1633 stack.back().ResolveValue(exe_ctx) | tmp.ResolveValue(exe_ctx);
1634 }
1635 break;
1636
1637 // OPCODE: DW_OP_plus
1638 // OPERANDS: none
1639 // DESCRIPTION: pops the top two stack entries, adds them together, and
1640 // pushes the result.
1641 case DW_OP_plus:
1642 if (stack.size() < 2) {
1643 if (error_ptr)
1644 error_ptr->SetErrorString(
1645 "Expression stack needs at least 2 items for DW_OP_plus.");
1646 return false;
1647 } else {
1648 tmp = stack.back();
1649 stack.pop_back();
1650 stack.back().GetScalar() += tmp.GetScalar();
1651 }
1652 break;
1653
1654 // OPCODE: DW_OP_plus_uconst
1655 // OPERANDS: none
1656 // DESCRIPTION: pops the top stack entry, adds it to the unsigned LEB128
1657 // constant operand and pushes the result.
1658 case DW_OP_plus_uconst:
1659 if (stack.empty()) {
1660 if (error_ptr)
1661 error_ptr->SetErrorString(
1662 "Expression stack needs at least 1 item for DW_OP_plus_uconst.");
1663 return false;
1664 } else {
1665 const uint64_t uconst_value = opcodes.GetULEB128(&offset);
1666 // Implicit conversion from a UINT to a Scalar...
1667 stack.back().GetScalar() += uconst_value;
1668 if (!stack.back().GetScalar().IsValid()) {
1669 if (error_ptr)
1670 error_ptr->SetErrorString("DW_OP_plus_uconst failed.");
1671 return false;
1672 }
1673 }
1674 break;
1675
1676 // OPCODE: DW_OP_shl
1677 // OPERANDS: none
1678 // DESCRIPTION: pops the top two stack entries, shifts the former
1679 // second entry left by the number of bits specified by the former top of
1680 // the stack, and pushes the result.
1681 case DW_OP_shl:
1682 if (stack.size() < 2) {
1683 if (error_ptr)
1684 error_ptr->SetErrorString(
1685 "Expression stack needs at least 2 items for DW_OP_shl.");
1686 return false;
1687 } else {
1688 tmp = stack.back();
1689 stack.pop_back();
1690 stack.back().ResolveValue(exe_ctx) <<= tmp.ResolveValue(exe_ctx);
1691 }
1692 break;
1693
1694 // OPCODE: DW_OP_shr
1695 // OPERANDS: none
1696 // DESCRIPTION: pops the top two stack entries, shifts the former second
1697 // entry right logically (filling with zero bits) by the number of bits
1698 // specified by the former top of the stack, and pushes the result.
1699 case DW_OP_shr:
1700 if (stack.size() < 2) {
1701 if (error_ptr)
1702 error_ptr->SetErrorString(
1703 "Expression stack needs at least 2 items for DW_OP_shr.");
1704 return false;
1705 } else {
1706 tmp = stack.back();
1707 stack.pop_back();
1708 if (!stack.back().ResolveValue(exe_ctx).ShiftRightLogical(
1709 tmp.ResolveValue(exe_ctx))) {
1710 if (error_ptr)
1711 error_ptr->SetErrorString("DW_OP_shr failed.");
1712 return false;
1713 }
1714 }
1715 break;
1716
1717 // OPCODE: DW_OP_shra
1718 // OPERANDS: none
1719 // DESCRIPTION: pops the top two stack entries, shifts the former second
1720 // entry right arithmetically (divide the magnitude by 2, keep the same
1721 // sign for the result) by the number of bits specified by the former top
1722 // of the stack, and pushes the result.
1723 case DW_OP_shra:
1724 if (stack.size() < 2) {
1725 if (error_ptr)
1726 error_ptr->SetErrorString(
1727 "Expression stack needs at least 2 items for DW_OP_shra.");
1728 return false;
1729 } else {
1730 tmp = stack.back();
1731 stack.pop_back();
1732 stack.back().ResolveValue(exe_ctx) >>= tmp.ResolveValue(exe_ctx);
1733 }
1734 break;
1735
1736 // OPCODE: DW_OP_xor
1737 // OPERANDS: none
1738 // DESCRIPTION: pops the top two stack entries, performs the bitwise
1739 // exclusive-or operation on the two, and pushes the result.
1740 case DW_OP_xor:
1741 if (stack.size() < 2) {
1742 if (error_ptr)
1743 error_ptr->SetErrorString(
1744 "Expression stack needs at least 2 items for DW_OP_xor.");
1745 return false;
1746 } else {
1747 tmp = stack.back();
1748 stack.pop_back();
1749 stack.back().ResolveValue(exe_ctx) =
1750 stack.back().ResolveValue(exe_ctx) ^ tmp.ResolveValue(exe_ctx);
1751 }
1752 break;
1753
1754 // OPCODE: DW_OP_skip
1755 // OPERANDS: int16_t
1756 // DESCRIPTION: An unconditional branch. Its single operand is a 2-byte
1757 // signed integer constant. The 2-byte constant is the number of bytes of
1758 // the DWARF expression to skip forward or backward from the current
1759 // operation, beginning after the 2-byte constant.
1760 case DW_OP_skip: {
1761 int16_t skip_offset = (int16_t)opcodes.GetU16(&offset);
1762 lldb::offset_t new_offset = offset + skip_offset;
1763 if (opcodes.ValidOffset(new_offset))
1764 offset = new_offset;
1765 else {
1766 if (error_ptr)
1767 error_ptr->SetErrorString("Invalid opcode offset in DW_OP_skip.");
1768 return false;
1769 }
1770 } break;
1771
1772 // OPCODE: DW_OP_bra
1773 // OPERANDS: int16_t
1774 // DESCRIPTION: A conditional branch. Its single operand is a 2-byte
1775 // signed integer constant. This operation pops the top of stack. If the
1776 // value popped is not the constant 0, the 2-byte constant operand is the
1777 // number of bytes of the DWARF expression to skip forward or backward from
1778 // the current operation, beginning after the 2-byte constant.
1779 case DW_OP_bra:
1780 if (stack.empty()) {
1781 if (error_ptr)
1782 error_ptr->SetErrorString(
1783 "Expression stack needs at least 1 item for DW_OP_bra.");
1784 return false;
1785 } else {
1786 tmp = stack.back();
1787 stack.pop_back();
1788 int16_t bra_offset = (int16_t)opcodes.GetU16(&offset);
1789 Scalar zero(0);
1790 if (tmp.ResolveValue(exe_ctx) != zero) {
1791 lldb::offset_t new_offset = offset + bra_offset;
1792 if (opcodes.ValidOffset(new_offset))
1793 offset = new_offset;
1794 else {
1795 if (error_ptr)
1796 error_ptr->SetErrorString("Invalid opcode offset in DW_OP_bra.");
1797 return false;
1798 }
1799 }
1800 }
1801 break;
1802
1803 // OPCODE: DW_OP_eq
1804 // OPERANDS: none
1805 // DESCRIPTION: pops the top two stack values, compares using the
1806 // equals (==) operator.
1807 // STACK RESULT: push the constant value 1 onto the stack if the result
1808 // of the operation is true or the constant value 0 if the result of the
1809 // operation is false.
1810 case DW_OP_eq:
1811 if (stack.size() < 2) {
1812 if (error_ptr)
1813 error_ptr->SetErrorString(
1814 "Expression stack needs at least 2 items for DW_OP_eq.");
1815 return false;
1816 } else {
1817 tmp = stack.back();
1818 stack.pop_back();
1819 stack.back().ResolveValue(exe_ctx) =
1820 stack.back().ResolveValue(exe_ctx) == tmp.ResolveValue(exe_ctx);
1821 }
1822 break;
1823
1824 // OPCODE: DW_OP_ge
1825 // OPERANDS: none
1826 // DESCRIPTION: pops the top two stack values, compares using the
1827 // greater than or equal to (>=) operator.
1828 // STACK RESULT: push the constant value 1 onto the stack if the result
1829 // of the operation is true or the constant value 0 if the result of the
1830 // operation is false.
1831 case DW_OP_ge:
1832 if (stack.size() < 2) {
1833 if (error_ptr)
1834 error_ptr->SetErrorString(
1835 "Expression stack needs at least 2 items for DW_OP_ge.");
1836 return false;
1837 } else {
1838 tmp = stack.back();
1839 stack.pop_back();
1840 stack.back().ResolveValue(exe_ctx) =
1841 stack.back().ResolveValue(exe_ctx) >= tmp.ResolveValue(exe_ctx);
1842 }
1843 break;
1844
1845 // OPCODE: DW_OP_gt
1846 // OPERANDS: none
1847 // DESCRIPTION: pops the top two stack values, compares using the
1848 // greater than (>) operator.
1849 // STACK RESULT: push the constant value 1 onto the stack if the result
1850 // of the operation is true or the constant value 0 if the result of the
1851 // operation is false.
1852 case DW_OP_gt:
1853 if (stack.size() < 2) {
1854 if (error_ptr)
1855 error_ptr->SetErrorString(
1856 "Expression stack needs at least 2 items for DW_OP_gt.");
1857 return false;
1858 } else {
1859 tmp = stack.back();
1860 stack.pop_back();
1861 stack.back().ResolveValue(exe_ctx) =
1862 stack.back().ResolveValue(exe_ctx) > tmp.ResolveValue(exe_ctx);
1863 }
1864 break;
1865
1866 // OPCODE: DW_OP_le
1867 // OPERANDS: none
1868 // DESCRIPTION: pops the top two stack values, compares using the
1869 // less than or equal to (<=) operator.
1870 // STACK RESULT: push the constant value 1 onto the stack if the result
1871 // of the operation is true or the constant value 0 if the result of the
1872 // operation is false.
1873 case DW_OP_le:
1874 if (stack.size() < 2) {
1875 if (error_ptr)
1876 error_ptr->SetErrorString(
1877 "Expression stack needs at least 2 items for DW_OP_le.");
1878 return false;
1879 } else {
1880 tmp = stack.back();
1881 stack.pop_back();
1882 stack.back().ResolveValue(exe_ctx) =
1883 stack.back().ResolveValue(exe_ctx) <= tmp.ResolveValue(exe_ctx);
1884 }
1885 break;
1886
1887 // OPCODE: DW_OP_lt
1888 // OPERANDS: none
1889 // DESCRIPTION: pops the top two stack values, compares using the
1890 // less than (<) operator.
1891 // STACK RESULT: push the constant value 1 onto the stack if the result
1892 // of the operation is true or the constant value 0 if the result of the
1893 // operation is false.
1894 case DW_OP_lt:
1895 if (stack.size() < 2) {
1896 if (error_ptr)
1897 error_ptr->SetErrorString(
1898 "Expression stack needs at least 2 items for DW_OP_lt.");
1899 return false;
1900 } else {
1901 tmp = stack.back();
1902 stack.pop_back();
1903 stack.back().ResolveValue(exe_ctx) =
1904 stack.back().ResolveValue(exe_ctx) < tmp.ResolveValue(exe_ctx);
1905 }
1906 break;
1907
1908 // OPCODE: DW_OP_ne
1909 // OPERANDS: none
1910 // DESCRIPTION: pops the top two stack values, compares using the
1911 // not equal (!=) operator.
1912 // STACK RESULT: push the constant value 1 onto the stack if the result
1913 // of the operation is true or the constant value 0 if the result of the
1914 // operation is false.
1915 case DW_OP_ne:
1916 if (stack.size() < 2) {
1917 if (error_ptr)
1918 error_ptr->SetErrorString(
1919 "Expression stack needs at least 2 items for DW_OP_ne.");
1920 return false;
1921 } else {
1922 tmp = stack.back();
1923 stack.pop_back();
1924 stack.back().ResolveValue(exe_ctx) =
1925 stack.back().ResolveValue(exe_ctx) != tmp.ResolveValue(exe_ctx);
1926 }
1927 break;
1928
1929 // OPCODE: DW_OP_litn
1930 // OPERANDS: none
1931 // DESCRIPTION: encode the unsigned literal values from 0 through 31.
1932 // STACK RESULT: push the unsigned literal constant value onto the top
1933 // of the stack.
1934 case DW_OP_lit0:
1935 case DW_OP_lit1:
1936 case DW_OP_lit2:
1937 case DW_OP_lit3:
1938 case DW_OP_lit4:
1939 case DW_OP_lit5:
1940 case DW_OP_lit6:
1941 case DW_OP_lit7:
1942 case DW_OP_lit8:
1943 case DW_OP_lit9:
1944 case DW_OP_lit10:
1945 case DW_OP_lit11:
1946 case DW_OP_lit12:
1947 case DW_OP_lit13:
1948 case DW_OP_lit14:
1949 case DW_OP_lit15:
1950 case DW_OP_lit16:
1951 case DW_OP_lit17:
1952 case DW_OP_lit18:
1953 case DW_OP_lit19:
1954 case DW_OP_lit20:
1955 case DW_OP_lit21:
1956 case DW_OP_lit22:
1957 case DW_OP_lit23:
1958 case DW_OP_lit24:
1959 case DW_OP_lit25:
1960 case DW_OP_lit26:
1961 case DW_OP_lit27:
1962 case DW_OP_lit28:
1963 case DW_OP_lit29:
1964 case DW_OP_lit30:
1965 case DW_OP_lit31:
1966 stack.push_back(to_generic(op - DW_OP_lit0));
1967 break;
1968
1969 // OPCODE: DW_OP_regN
1970 // OPERANDS: none
1971 // DESCRIPTION: Push the value in register n on the top of the stack.
1972 case DW_OP_reg0:
1973 case DW_OP_reg1:
1974 case DW_OP_reg2:
1975 case DW_OP_reg3:
1976 case DW_OP_reg4:
1977 case DW_OP_reg5:
1978 case DW_OP_reg6:
1979 case DW_OP_reg7:
1980 case DW_OP_reg8:
1981 case DW_OP_reg9:
1982 case DW_OP_reg10:
1983 case DW_OP_reg11:
1984 case DW_OP_reg12:
1985 case DW_OP_reg13:
1986 case DW_OP_reg14:
1987 case DW_OP_reg15:
1988 case DW_OP_reg16:
1989 case DW_OP_reg17:
1990 case DW_OP_reg18:
1991 case DW_OP_reg19:
1992 case DW_OP_reg20:
1993 case DW_OP_reg21:
1994 case DW_OP_reg22:
1995 case DW_OP_reg23:
1996 case DW_OP_reg24:
1997 case DW_OP_reg25:
1998 case DW_OP_reg26:
1999 case DW_OP_reg27:
2000 case DW_OP_reg28:
2001 case DW_OP_reg29:
2002 case DW_OP_reg30:
2003 case DW_OP_reg31: {
2004 dwarf4_location_description_kind = Register;
2005 reg_num = op - DW_OP_reg0;
2006
2007 if (ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, error_ptr, tmp))
2008 stack.push_back(tmp);
2009 else
2010 return false;
2011 } break;
2012 // OPCODE: DW_OP_regx
2013 // OPERANDS:
2014 // ULEB128 literal operand that encodes the register.
2015 // DESCRIPTION: Push the value in register on the top of the stack.
2016 case DW_OP_regx: {
2017 dwarf4_location_description_kind = Register;
2018 reg_num = opcodes.GetULEB128(&offset);
2019 if (ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, error_ptr, tmp))
2020 stack.push_back(tmp);
2021 else
2022 return false;
2023 } break;
2024
2025 // OPCODE: DW_OP_bregN
2026 // OPERANDS:
2027 // SLEB128 offset from register N
2028 // DESCRIPTION: Value is in memory at the address specified by register
2029 // N plus an offset.
2030 case DW_OP_breg0:
2031 case DW_OP_breg1:
2032 case DW_OP_breg2:
2033 case DW_OP_breg3:
2034 case DW_OP_breg4:
2035 case DW_OP_breg5:
2036 case DW_OP_breg6:
2037 case DW_OP_breg7:
2038 case DW_OP_breg8:
2039 case DW_OP_breg9:
2040 case DW_OP_breg10:
2041 case DW_OP_breg11:
2042 case DW_OP_breg12:
2043 case DW_OP_breg13:
2044 case DW_OP_breg14:
2045 case DW_OP_breg15:
2046 case DW_OP_breg16:
2047 case DW_OP_breg17:
2048 case DW_OP_breg18:
2049 case DW_OP_breg19:
2050 case DW_OP_breg20:
2051 case DW_OP_breg21:
2052 case DW_OP_breg22:
2053 case DW_OP_breg23:
2054 case DW_OP_breg24:
2055 case DW_OP_breg25:
2056 case DW_OP_breg26:
2057 case DW_OP_breg27:
2058 case DW_OP_breg28:
2059 case DW_OP_breg29:
2060 case DW_OP_breg30:
2061 case DW_OP_breg31: {
2062 reg_num = op - DW_OP_breg0;
2063
2064 if (ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, error_ptr,
2065 tmp)) {
2066 int64_t breg_offset = opcodes.GetSLEB128(&offset);
2067 tmp.ResolveValue(exe_ctx) += (uint64_t)breg_offset;
2068 tmp.ClearContext();
2069 stack.push_back(tmp);
2070 stack.back().SetValueType(Value::ValueType::LoadAddress);
2071 } else
2072 return false;
2073 } break;
2074 // OPCODE: DW_OP_bregx
2075 // OPERANDS: 2
2076 // ULEB128 literal operand that encodes the register.
2077 // SLEB128 offset from register N
2078 // DESCRIPTION: Value is in memory at the address specified by register
2079 // N plus an offset.
2080 case DW_OP_bregx: {
2081 reg_num = opcodes.GetULEB128(&offset);
2082
2083 if (ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, error_ptr,
2084 tmp)) {
2085 int64_t breg_offset = opcodes.GetSLEB128(&offset);
2086 tmp.ResolveValue(exe_ctx) += (uint64_t)breg_offset;
2087 tmp.ClearContext();
2088 stack.push_back(tmp);
2089 stack.back().SetValueType(Value::ValueType::LoadAddress);
2090 } else
2091 return false;
2092 } break;
2093
2094 case DW_OP_fbreg:
2095 if (exe_ctx) {
2096 if (frame) {
2097 Scalar value;
2098 if (frame->GetFrameBaseValue(value, error_ptr)) {
2099 int64_t fbreg_offset = opcodes.GetSLEB128(&offset);
2100 value += fbreg_offset;
2101 stack.push_back(value);
2102 stack.back().SetValueType(Value::ValueType::LoadAddress);
2103 } else
2104 return false;
2105 } else {
2106 if (error_ptr)
2107 error_ptr->SetErrorString(
2108 "Invalid stack frame in context for DW_OP_fbreg opcode.");
2109 return false;
2110 }
2111 } else {
2112 if (error_ptr)
2113 error_ptr->SetErrorString(
2114 "NULL execution context for DW_OP_fbreg.\n");
2115 return false;
2116 }
2117
2118 break;
2119
2120 // OPCODE: DW_OP_nop
2121 // OPERANDS: none
2122 // DESCRIPTION: A place holder. It has no effect on the location stack
2123 // or any of its values.
2124 case DW_OP_nop:
2125 break;
2126
2127 // OPCODE: DW_OP_piece
2128 // OPERANDS: 1
2129 // ULEB128: byte size of the piece
2130 // DESCRIPTION: The operand describes the size in bytes of the piece of
2131 // the object referenced by the DWARF expression whose result is at the top
2132 // of the stack. If the piece is located in a register, but does not occupy
2133 // the entire register, the placement of the piece within that register is
2134 // defined by the ABI.
2135 //
2136 // Many compilers store a single variable in sets of registers, or store a
2137 // variable partially in memory and partially in registers. DW_OP_piece
2138 // provides a way of describing how large a part of a variable a particular
2139 // DWARF expression refers to.
2140 case DW_OP_piece: {
2141 LocationDescriptionKind piece_locdesc = dwarf4_location_description_kind;
2142 // Reset for the next piece.
2143 dwarf4_location_description_kind = Memory;
2144
2145 const uint64_t piece_byte_size = opcodes.GetULEB128(&offset);
2146
2147 if (piece_byte_size > 0) {
2148 Value curr_piece;
2149
2150 if (stack.empty()) {
2151 UpdateValueTypeFromLocationDescription(
2152 log, dwarf_cu, LocationDescriptionKind::Empty);
2153 // In a multi-piece expression, this means that the current piece is
2154 // not available. Fill with zeros for now by resizing the data and
2155 // appending it
2156 curr_piece.ResizeData(piece_byte_size);
2157 // Note that "0" is not a correct value for the unknown bits.
2158 // It would be better to also return a mask of valid bits together
2159 // with the expression result, so the debugger can print missing
2160 // members as "<optimized out>" or something.
2161 ::memset(curr_piece.GetBuffer().GetBytes(), 0, piece_byte_size);
2162 pieces.AppendDataToHostBuffer(curr_piece);
2163 } else {
2164 Status error;
2165 // Extract the current piece into "curr_piece"
2166 Value curr_piece_source_value(stack.back());
2167 stack.pop_back();
2168 UpdateValueTypeFromLocationDescription(log, dwarf_cu, piece_locdesc,
2169 &curr_piece_source_value);
2170
2171 const Value::ValueType curr_piece_source_value_type =
2172 curr_piece_source_value.GetValueType();
2173 switch (curr_piece_source_value_type) {
2174 case Value::ValueType::Invalid:
2175 return false;
2176 case Value::ValueType::LoadAddress:
2177 if (process) {
2178 if (curr_piece.ResizeData(piece_byte_size) == piece_byte_size) {
2179 lldb::addr_t load_addr =
2180 curr_piece_source_value.GetScalar().ULongLong(
2181 LLDB_INVALID_ADDRESS0xffffffffffffffffULL);
2182 if (process->ReadMemory(
2183 load_addr, curr_piece.GetBuffer().GetBytes(),
2184 piece_byte_size, error) != piece_byte_size) {
2185 if (error_ptr)
2186 error_ptr->SetErrorStringWithFormat(
2187 "failed to read memory DW_OP_piece(%" PRIu64"llu"
2188 ") from 0x%" PRIx64"llx",
2189 piece_byte_size, load_addr);
2190 return false;
2191 }
2192 } else {
2193 if (error_ptr)
2194 error_ptr->SetErrorStringWithFormat(
2195 "failed to resize the piece memory buffer for "
2196 "DW_OP_piece(%" PRIu64"llu" ")",
2197 piece_byte_size);
2198 return false;
2199 }
2200 }
2201 break;
2202
2203 case Value::ValueType::FileAddress:
2204 case Value::ValueType::HostAddress:
2205 if (error_ptr) {
2206 lldb::addr_t addr = curr_piece_source_value.GetScalar().ULongLong(
2207 LLDB_INVALID_ADDRESS0xffffffffffffffffULL);
2208 error_ptr->SetErrorStringWithFormat(
2209 "failed to read memory DW_OP_piece(%" PRIu64"llu"
2210 ") from %s address 0x%" PRIx64"llx",
2211 piece_byte_size, curr_piece_source_value.GetValueType() ==
2212 Value::ValueType::FileAddress
2213 ? "file"
2214 : "host",
2215 addr);
2216 }
2217 return false;
2218
2219 case Value::ValueType::Scalar: {
2220 uint32_t bit_size = piece_byte_size * 8;
2221 uint32_t bit_offset = 0;
2222 Scalar &scalar = curr_piece_source_value.GetScalar();
2223 if (!scalar.ExtractBitfield(
2224 bit_size, bit_offset)) {
2225 if (error_ptr)
2226 error_ptr->SetErrorStringWithFormat(
2227 "unable to extract %" PRIu64"llu" " bytes from a %" PRIu64"llu"
2228 " byte scalar value.",
2229 piece_byte_size,
2230 (uint64_t)curr_piece_source_value.GetScalar()
2231 .GetByteSize());
2232 return false;
2233 }
2234 // Create curr_piece with bit_size. By default Scalar
2235 // grows to the nearest host integer type.
2236 llvm::APInt fail_value(1, 0, false);
2237 llvm::APInt ap_int = scalar.UInt128(fail_value);
2238 assert(ap_int.getBitWidth() >= bit_size)((void)0);
2239 llvm::ArrayRef<uint64_t> buf{ap_int.getRawData(),
2240 ap_int.getNumWords()};
2241 curr_piece.GetScalar() = Scalar(llvm::APInt(bit_size, buf));
2242 } break;
2243 }
2244
2245 // Check if this is the first piece?
2246 if (op_piece_offset == 0) {
2247 // This is the first piece, we should push it back onto the stack
2248 // so subsequent pieces will be able to access this piece and add
2249 // to it.
2250 if (pieces.AppendDataToHostBuffer(curr_piece) == 0) {
2251 if (error_ptr)
2252 error_ptr->SetErrorString("failed to append piece data");
2253 return false;
2254 }
2255 } else {
2256 // If this is the second or later piece there should be a value on
2257 // the stack.
2258 if (pieces.GetBuffer().GetByteSize() != op_piece_offset) {
2259 if (error_ptr)
2260 error_ptr->SetErrorStringWithFormat(
2261 "DW_OP_piece for offset %" PRIu64"llu"
2262 " but top of stack is of size %" PRIu64"llu",
2263 op_piece_offset, pieces.GetBuffer().GetByteSize());
2264 return false;
2265 }
2266
2267 if (pieces.AppendDataToHostBuffer(curr_piece) == 0) {
2268 if (error_ptr)
2269 error_ptr->SetErrorString("failed to append piece data");
2270 return false;
2271 }
2272 }
2273 }
2274 op_piece_offset += piece_byte_size;
2275 }
2276 } break;
2277
2278 case DW_OP_bit_piece: // 0x9d ULEB128 bit size, ULEB128 bit offset (DWARF3);
2279 if (stack.size() < 1) {
2280 UpdateValueTypeFromLocationDescription(log, dwarf_cu,
2281 LocationDescriptionKind::Empty);
2282 // Reset for the next piece.
2283 dwarf4_location_description_kind = Memory;
2284 if (error_ptr)
2285 error_ptr->SetErrorString(
2286 "Expression stack needs at least 1 item for DW_OP_bit_piece.");
2287 return false;
2288 } else {
2289 UpdateValueTypeFromLocationDescription(
2290 log, dwarf_cu, dwarf4_location_description_kind, &stack.back());
2291 // Reset for the next piece.
2292 dwarf4_location_description_kind = Memory;
2293 const uint64_t piece_bit_size = opcodes.GetULEB128(&offset);
2294 const uint64_t piece_bit_offset = opcodes.GetULEB128(&offset);
2295 switch (stack.back().GetValueType()) {
2296 case Value::ValueType::Invalid:
2297 return false;
2298 case Value::ValueType::Scalar: {
2299 if (!stack.back().GetScalar().ExtractBitfield(piece_bit_size,
2300 piece_bit_offset)) {
2301 if (error_ptr)
2302 error_ptr->SetErrorStringWithFormat(
2303 "unable to extract %" PRIu64"llu" " bit value with %" PRIu64"llu"
2304 " bit offset from a %" PRIu64"llu" " bit scalar value.",
2305 piece_bit_size, piece_bit_offset,
2306 (uint64_t)(stack.back().GetScalar().GetByteSize() * 8));
2307 return false;
2308 }
2309 } break;
2310
2311 case Value::ValueType::FileAddress:
2312 case Value::ValueType::LoadAddress:
2313 case Value::ValueType::HostAddress:
2314 if (error_ptr) {
2315 error_ptr->SetErrorStringWithFormat(
2316 "unable to extract DW_OP_bit_piece(bit_size = %" PRIu64"llu"
2317 ", bit_offset = %" PRIu64"llu" ") from an address value.",
2318 piece_bit_size, piece_bit_offset);
2319 }
2320 return false;
2321 }
2322 }
2323 break;
2324
2325 // OPCODE: DW_OP_implicit_value
2326 // OPERANDS: 2
2327 // ULEB128 size of the value block in bytes
2328 // uint8_t* block bytes encoding value in target's memory
2329 // representation
2330 // DESCRIPTION: Value is immediately stored in block in the debug info with
2331 // the memory representation of the target.
2332 case DW_OP_implicit_value: {
2333 dwarf4_location_description_kind = Implicit;
2334
2335 const uint32_t len = opcodes.GetULEB128(&offset);
2336 const void *data = opcodes.GetData(&offset, len);
2337
2338 if (!data) {
2339 LLDB_LOG(log, "Evaluate_DW_OP_implicit_value: could not be read data")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "Evaluate_DW_OP_implicit_value: could not be read data"
); } while (0)
;
2340 LLDB_ERRORF(error_ptr, "Could not evaluate %s.",do { if (error_ptr) { (error_ptr)->SetErrorStringWithFormat
(("Could not evaluate %s."), DW_OP_value_to_name(op)); } } while
(0);
2341 DW_OP_value_to_name(op))do { if (error_ptr) { (error_ptr)->SetErrorStringWithFormat
(("Could not evaluate %s."), DW_OP_value_to_name(op)); } } while
(0);
;
2342 return false;
2343 }
2344
2345 Value result(data, len);
2346 stack.push_back(result);
2347 break;
2348 }
2349
2350 case DW_OP_implicit_pointer: {
2351 dwarf4_location_description_kind = Implicit;
2352 LLDB_ERRORF(error_ptr, "Could not evaluate %s.", DW_OP_value_to_name(op))do { if (error_ptr) { (error_ptr)->SetErrorStringWithFormat
(("Could not evaluate %s."), DW_OP_value_to_name(op)); } } while
(0);
;
2353 return false;
2354 }
2355
2356 // OPCODE: DW_OP_push_object_address
2357 // OPERANDS: none
2358 // DESCRIPTION: Pushes the address of the object currently being
2359 // evaluated as part of evaluation of a user presented expression. This
2360 // object may correspond to an independent variable described by its own
2361 // DIE or it may be a component of an array, structure, or class whose
2362 // address has been dynamically determined by an earlier step during user
2363 // expression evaluation.
2364 case DW_OP_push_object_address:
2365 if (object_address_ptr)
2366 stack.push_back(*object_address_ptr);
2367 else {
2368 if (error_ptr)
2369 error_ptr->SetErrorString("DW_OP_push_object_address used without "
2370 "specifying an object address");
2371 return false;
2372 }
2373 break;
2374
2375 // OPCODE: DW_OP_call2
2376 // OPERANDS:
2377 // uint16_t compile unit relative offset of a DIE
2378 // DESCRIPTION: Performs subroutine calls during evaluation
2379 // of a DWARF expression. The operand is the 2-byte unsigned offset of a
2380 // debugging information entry in the current compilation unit.
2381 //
2382 // Operand interpretation is exactly like that for DW_FORM_ref2.
2383 //
2384 // This operation transfers control of DWARF expression evaluation to the
2385 // DW_AT_location attribute of the referenced DIE. If there is no such
2386 // attribute, then there is no effect. Execution of the DWARF expression of
2387 // a DW_AT_location attribute may add to and/or remove from values on the
2388 // stack. Execution returns to the point following the call when the end of
2389 // the attribute is reached. Values on the stack at the time of the call
2390 // may be used as parameters by the called expression and values left on
2391 // the stack by the called expression may be used as return values by prior
2392 // agreement between the calling and called expressions.
2393 case DW_OP_call2:
2394 if (error_ptr)
2395 error_ptr->SetErrorString("Unimplemented opcode DW_OP_call2.");
2396 return false;
2397 // OPCODE: DW_OP_call4
2398 // OPERANDS: 1
2399 // uint32_t compile unit relative offset of a DIE
2400 // DESCRIPTION: Performs a subroutine call during evaluation of a DWARF
2401 // expression. For DW_OP_call4, the operand is a 4-byte unsigned offset of
2402 // a debugging information entry in the current compilation unit.
2403 //
2404 // Operand interpretation DW_OP_call4 is exactly like that for
2405 // DW_FORM_ref4.
2406 //
2407 // This operation transfers control of DWARF expression evaluation to the
2408 // DW_AT_location attribute of the referenced DIE. If there is no such
2409 // attribute, then there is no effect. Execution of the DWARF expression of
2410 // a DW_AT_location attribute may add to and/or remove from values on the
2411 // stack. Execution returns to the point following the call when the end of
2412 // the attribute is reached. Values on the stack at the time of the call
2413 // may be used as parameters by the called expression and values left on
2414 // the stack by the called expression may be used as return values by prior
2415 // agreement between the calling and called expressions.
2416 case DW_OP_call4:
2417 if (error_ptr)
2418 error_ptr->SetErrorString("Unimplemented opcode DW_OP_call4.");
2419 return false;
2420
2421 // OPCODE: DW_OP_stack_value
2422 // OPERANDS: None
2423 // DESCRIPTION: Specifies that the object does not exist in memory but
2424 // rather is a constant value. The value from the top of the stack is the
2425 // value to be used. This is the actual object value and not the location.
2426 case DW_OP_stack_value:
2427 dwarf4_location_description_kind = Implicit;
2428 if (stack.empty()) {
2429 if (error_ptr)
2430 error_ptr->SetErrorString(
2431 "Expression stack needs at least 1 item for DW_OP_stack_value.");
2432 return false;
2433 }
2434 stack.back().SetValueType(Value::ValueType::Scalar);
2435 break;
2436
2437 // OPCODE: DW_OP_convert
2438 // OPERANDS: 1
2439 // A ULEB128 that is either a DIE offset of a
2440 // DW_TAG_base_type or 0 for the generic (pointer-sized) type.
2441 //
2442 // DESCRIPTION: Pop the top stack element, convert it to a
2443 // different type, and push the result.
2444 case DW_OP_convert: {
2445 if (stack.size() < 1) {
2446 if (error_ptr)
2447 error_ptr->SetErrorString(
2448 "Expression stack needs at least 1 item for DW_OP_convert.");
2449 return false;
2450 }
2451 const uint64_t die_offset = opcodes.GetULEB128(&offset);
2452 uint64_t bit_size;
2453 bool sign;
2454 if (die_offset == 0) {
2455 // The generic type has the size of an address on the target
2456 // machine and an unspecified signedness. Scalar has no
2457 // "unspecified signedness", so we use unsigned types.
2458 if (!module_sp) {
2459 if (error_ptr)
2460 error_ptr->SetErrorString("No module");
2461 return false;
2462 }
2463 sign = false;
2464 bit_size = module_sp->GetArchitecture().GetAddressByteSize() * 8;
2465 if (!bit_size) {
2466 if (error_ptr)
2467 error_ptr->SetErrorString("unspecified architecture");
2468 return false;
2469 }
2470 } else {
2471 // Retrieve the type DIE that the value is being converted to.
2472 // FIXME: the constness has annoying ripple effects.
2473 DWARFDIE die = const_cast<DWARFUnit *>(dwarf_cu)->GetDIE(die_offset);
2474 if (!die) {
2475 if (error_ptr)
2476 error_ptr->SetErrorString("Cannot resolve DW_OP_convert type DIE");
2477 return false;
2478 }
2479 uint64_t encoding =
2480 die.GetAttributeValueAsUnsigned(DW_AT_encoding, DW_ATE_hi_user);
2481 bit_size = die.GetAttributeValueAsUnsigned(DW_AT_byte_size, 0) * 8;
2482 if (!bit_size)
2483 bit_size = die.GetAttributeValueAsUnsigned(DW_AT_bit_size, 0);
2484 if (!bit_size) {
2485 if (error_ptr)
2486 error_ptr->SetErrorString("Unsupported type size in DW_OP_convert");
2487 return false;
2488 }
2489 switch (encoding) {
2490 case DW_ATE_signed:
2491 case DW_ATE_signed_char:
2492 sign = true;
2493 break;
2494 case DW_ATE_unsigned:
2495 case DW_ATE_unsigned_char:
2496 sign = false;
2497 break;
2498 default:
2499 if (error_ptr)
2500 error_ptr->SetErrorString("Unsupported encoding in DW_OP_convert");
2501 return false;
2502 }
2503 }
2504 Scalar &top = stack.back().ResolveValue(exe_ctx);
2505 top.TruncOrExtendTo(bit_size, sign);
2506 break;
2507 }
2508
2509 // OPCODE: DW_OP_call_frame_cfa
2510 // OPERANDS: None
2511 // DESCRIPTION: Specifies a DWARF expression that pushes the value of
2512 // the canonical frame address consistent with the call frame information
2513 // located in .debug_frame (or in the FDEs of the eh_frame section).
2514 case DW_OP_call_frame_cfa:
2515 if (frame) {
2516 // Note that we don't have to parse FDEs because this DWARF expression
2517 // is commonly evaluated with a valid stack frame.
2518 StackID id = frame->GetStackID();
2519 addr_t cfa = id.GetCallFrameAddress();
2520 if (cfa != LLDB_INVALID_ADDRESS0xffffffffffffffffULL) {
2521 stack.push_back(Scalar(cfa));
2522 stack.back().SetValueType(Value::ValueType::LoadAddress);
2523 } else if (error_ptr)
2524 error_ptr->SetErrorString("Stack frame does not include a canonical "
2525 "frame address for DW_OP_call_frame_cfa "
2526 "opcode.");
2527 } else {
2528 if (error_ptr)
2529 error_ptr->SetErrorString("Invalid stack frame in context for "
2530 "DW_OP_call_frame_cfa opcode.");
2531 return false;
2532 }
2533 break;
2534
2535 // OPCODE: DW_OP_form_tls_address (or the old pre-DWARFv3 vendor extension
2536 // opcode, DW_OP_GNU_push_tls_address)
2537 // OPERANDS: none
2538 // DESCRIPTION: Pops a TLS offset from the stack, converts it to
2539 // an address in the current thread's thread-local storage block, and
2540 // pushes it on the stack.
2541 case DW_OP_form_tls_address:
2542 case DW_OP_GNU_push_tls_address: {
2543 if (stack.size() < 1) {
2544 if (error_ptr) {
2545 if (op == DW_OP_form_tls_address)
2546 error_ptr->SetErrorString(
2547 "DW_OP_form_tls_address needs an argument.");
2548 else
2549 error_ptr->SetErrorString(
2550 "DW_OP_GNU_push_tls_address needs an argument.");
2551 }
2552 return false;
2553 }
2554
2555 if (!exe_ctx || !module_sp) {
2556 if (error_ptr)
2557 error_ptr->SetErrorString("No context to evaluate TLS within.");
2558 return false;
2559 }
2560
2561 Thread *thread = exe_ctx->GetThreadPtr();
2562 if (!thread) {
2563 if (error_ptr)
2564 error_ptr->SetErrorString("No thread to evaluate TLS within.");
2565 return false;
2566 }
2567
2568 // Lookup the TLS block address for this thread and module.
2569 const addr_t tls_file_addr =
2570 stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS0xffffffffffffffffULL);
2571 const addr_t tls_load_addr =
2572 thread->GetThreadLocalData(module_sp, tls_file_addr);
2573
2574 if (tls_load_addr == LLDB_INVALID_ADDRESS0xffffffffffffffffULL) {
2575 if (error_ptr)
2576 error_ptr->SetErrorString(
2577 "No TLS data currently exists for this thread.");
2578 return false;
2579 }
2580
2581 stack.back().GetScalar() = tls_load_addr;
2582 stack.back().SetValueType(Value::ValueType::LoadAddress);
2583 } break;
2584
2585 // OPCODE: DW_OP_addrx (DW_OP_GNU_addr_index is the legacy name.)
2586 // OPERANDS: 1
2587 // ULEB128: index to the .debug_addr section
2588 // DESCRIPTION: Pushes an address to the stack from the .debug_addr
2589 // section with the base address specified by the DW_AT_addr_base attribute
2590 // and the 0 based index is the ULEB128 encoded index.
2591 case DW_OP_addrx:
2592 case DW_OP_GNU_addr_index: {
2593 if (!dwarf_cu) {
2594 if (error_ptr)
2595 error_ptr->SetErrorString("DW_OP_GNU_addr_index found without a "
2596 "compile unit being specified");
2597 return false;
2598 }
2599 uint64_t index = opcodes.GetULEB128(&offset);
2600 lldb::addr_t value = ReadAddressFromDebugAddrSection(dwarf_cu, index);
2601 stack.push_back(Scalar(value));
2602 stack.back().SetValueType(Value::ValueType::FileAddress);
2603 } break;
2604
2605 // OPCODE: DW_OP_GNU_const_index
2606 // OPERANDS: 1
2607 // ULEB128: index to the .debug_addr section
2608 // DESCRIPTION: Pushes an constant with the size of a machine address to
2609 // the stack from the .debug_addr section with the base address specified
2610 // by the DW_AT_addr_base attribute and the 0 based index is the ULEB128
2611 // encoded index.
2612 case DW_OP_GNU_const_index: {
2613 if (!dwarf_cu) {
2614 if (error_ptr)
2615 error_ptr->SetErrorString("DW_OP_GNU_const_index found without a "
2616 "compile unit being specified");
2617 return false;
2618 }
2619 uint64_t index = opcodes.GetULEB128(&offset);
2620 lldb::addr_t value = ReadAddressFromDebugAddrSection(dwarf_cu, index);
2621 stack.push_back(Scalar(value));
2622 } break;
2623
2624 case DW_OP_GNU_entry_value:
2625 case DW_OP_entry_value: {
2626 if (!Evaluate_DW_OP_entry_value(stack, exe_ctx, reg_ctx, opcodes, offset,
2627 error_ptr, log)) {
2628 LLDB_ERRORF(error_ptr, "Could not evaluate %s.",do { if (error_ptr) { (error_ptr)->SetErrorStringWithFormat
(("Could not evaluate %s."), DW_OP_value_to_name(op)); } } while
(0);
2629 DW_OP_value_to_name(op))do { if (error_ptr) { (error_ptr)->SetErrorStringWithFormat
(("Could not evaluate %s."), DW_OP_value_to_name(op)); } } while
(0);
;
2630 return false;
2631 }
2632 break;
2633 }
2634
2635 default:
2636 if (error_ptr)
2637 error_ptr->SetErrorStringWithFormatv(
2638 "Unhandled opcode {0} in DWARFExpression", LocationAtom(op));
2639 return false;
2640 }
2641 }
2642
2643 if (stack.empty()) {
2644 // Nothing on the stack, check if we created a piece value from DW_OP_piece
2645 // or DW_OP_bit_piece opcodes
2646 if (pieces.GetBuffer().GetByteSize()) {
2647 result = pieces;
2648 return true;
2649 }
2650 if (error_ptr)
2651 error_ptr->SetErrorString("Stack empty after evaluation.");
2652 return false;
2653 }
2654
2655 UpdateValueTypeFromLocationDescription(
2656 log, dwarf_cu, dwarf4_location_description_kind, &stack.back());
2657
2658 if (log && log->GetVerbose()) {
2659 size_t count = stack.size();
2660 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Stack after operation has %" "llu" " values:"
, (uint64_t)count); } while (0)
2661 "Stack after operation has %" PRIu64 " values:", (uint64_t)count)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Stack after operation has %" "llu" " values:"
, (uint64_t)count); } while (0)
;
2662 for (size_t i = 0; i < count; ++i) {
2663 StreamString new_value;
2664 new_value.Printf("[%" PRIu64"llu" "]", (uint64_t)i);
2665 stack[i].Dump(&new_value);
2666 LLDB_LOGF(log, " %s", new_value.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf(" %s", new_value.GetData()); } while
(0)
;
2667 }
2668 }
2669 result = stack.back();
2670 return true; // Return true on success
2671}
2672
2673static DataExtractor ToDataExtractor(const llvm::DWARFLocationExpression &loc,
2674 ByteOrder byte_order, uint32_t addr_size) {
2675 auto buffer_sp =
2676 std::make_shared<DataBufferHeap>(loc.Expr.data(), loc.Expr.size());
2677 return DataExtractor(buffer_sp, byte_order, addr_size);
2678}
2679
2680llvm::Optional<DataExtractor>
2681DWARFExpression::GetLocationExpression(addr_t load_function_start,
2682 addr_t addr) const {
2683 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS(1u << 8));
2684
2685 std::unique_ptr<llvm::DWARFLocationTable> loctable_up =
2686 m_dwarf_cu->GetLocationTable(m_data);
2687 llvm::Optional<DataExtractor> result;
2688 uint64_t offset = 0;
2689 auto lookup_addr =
2690 [&](uint32_t index) -> llvm::Optional<llvm::object::SectionedAddress> {
2691 addr_t address = ReadAddressFromDebugAddrSection(m_dwarf_cu, index);
2692 if (address == LLDB_INVALID_ADDRESS0xffffffffffffffffULL)
2693 return llvm::None;
2694 return llvm::object::SectionedAddress{address};
2695 };
2696 auto process_list = [&](llvm::Expected<llvm::DWARFLocationExpression> loc) {
2697 if (!loc) {
2698 LLDB_LOG_ERROR(log, loc.takeError(), "{0}")do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (loc.takeError()); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "{0}"); } else ::llvm::consumeError(::std::move(error_private
)); } while (0)
;
2699 return true;
2700 }
2701 if (loc->Range) {
2702 // This relocates low_pc and high_pc by adding the difference between the
2703 // function file address, and the actual address it is loaded in memory.
2704 addr_t slide = load_function_start - m_loclist_addresses->func_file_addr;
2705 loc->Range->LowPC += slide;
2706 loc->Range->HighPC += slide;
2707
2708 if (loc->Range->LowPC <= addr && addr < loc->Range->HighPC)
2709 result = ToDataExtractor(*loc, m_data.GetByteOrder(),
2710 m_data.GetAddressByteSize());
2711 }
2712 return !result;
2713 };
2714 llvm::Error E = loctable_up->visitAbsoluteLocationList(
2715 offset, llvm::object::SectionedAddress{m_loclist_addresses->cu_file_addr},
2716 lookup_addr, process_list);
2717 if (E)
2718 LLDB_LOG_ERROR(log, std::move(E), "{0}")do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (std::move(E)); if (log_private && error_private) {
log_private->FormatError(::std::move(error_private), "/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/source/Expression/DWARFExpression.cpp"
, __func__, "{0}"); } else ::llvm::consumeError(::std::move(error_private
)); } while (0)
;
2719 return result;
2720}
2721
2722bool DWARFExpression::MatchesOperand(StackFrame &frame,
2723 const Instruction::Operand &operand) {
2724 using namespace OperandMatchers;
2725
2726 RegisterContextSP reg_ctx_sp = frame.GetRegisterContext();
2727 if (!reg_ctx_sp) {
2728 return false;
2729 }
2730
2731 DataExtractor opcodes;
2732 if (IsLocationList()) {
2733 SymbolContext sc = frame.GetSymbolContext(eSymbolContextFunction);
2734 if (!sc.function)
2735 return false;
2736
2737 addr_t load_function_start =
2738 sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
2739 if (load_function_start == LLDB_INVALID_ADDRESS0xffffffffffffffffULL)
2740 return false;
2741
2742 addr_t pc = frame.GetFrameCodeAddress().GetLoadAddress(
2743 frame.CalculateTarget().get());
2744
2745 if (llvm::Optional<DataExtractor> expr = GetLocationExpression(load_function_start, pc))
2746 opcodes = std::move(*expr);
2747 else
2748 return false;
2749 } else
2750 opcodes = m_data;
2751
2752
2753 lldb::offset_t op_offset = 0;
2754 uint8_t opcode = opcodes.GetU8(&op_offset);
2755
2756 if (opcode == DW_OP_fbreg) {
2757 int64_t offset = opcodes.GetSLEB128(&op_offset);
2758
2759 DWARFExpression *fb_expr = frame.GetFrameBaseExpression(nullptr);
2760 if (!fb_expr) {
2761 return false;
2762 }
2763
2764 auto recurse = [&frame, fb_expr](const Instruction::Operand &child) {
2765 return fb_expr->MatchesOperand(frame, child);
2766 };
2767
2768 if (!offset &&
2769 MatchUnaryOp(MatchOpType(Instruction::Operand::Type::Dereference),
2770 recurse)(operand)) {
2771 return true;
2772 }
2773
2774 return MatchUnaryOp(
2775 MatchOpType(Instruction::Operand::Type::Dereference),
2776 MatchBinaryOp(MatchOpType(Instruction::Operand::Type::Sum),
2777 MatchImmOp(offset), recurse))(operand);
2778 }
2779
2780 bool dereference = false;
2781 const RegisterInfo *reg = nullptr;
2782 int64_t offset = 0;
2783
2784 if (opcode >= DW_OP_reg0 && opcode <= DW_OP_reg31) {
2785 reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, opcode - DW_OP_reg0);
2786 } else if (opcode >= DW_OP_breg0 && opcode <= DW_OP_breg31) {
2787 offset = opcodes.GetSLEB128(&op_offset);
2788 reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, opcode - DW_OP_breg0);
2789 } else if (opcode == DW_OP_regx) {
2790 uint32_t reg_num = static_cast<uint32_t>(opcodes.GetULEB128(&op_offset));
2791 reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, reg_num);
2792 } else if (opcode == DW_OP_bregx) {
2793 uint32_t reg_num = static_cast<uint32_t>(opcodes.GetULEB128(&op_offset));
2794 offset = opcodes.GetSLEB128(&op_offset);
2795 reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, reg_num);
2796 } else {
2797 return false;
2798 }
2799
2800 if (!reg) {
2801 return false;
2802 }
2803
2804 if (dereference) {
2805 if (!offset &&
2806 MatchUnaryOp(MatchOpType(Instruction::Operand::Type::Dereference),
2807 MatchRegOp(*reg))(operand)) {
2808 return true;
2809 }
2810
2811 return MatchUnaryOp(
2812 MatchOpType(Instruction::Operand::Type::Dereference),
2813 MatchBinaryOp(MatchOpType(Instruction::Operand::Type::Sum),
2814 MatchRegOp(*reg),
2815 MatchImmOp(offset)))(operand);
2816 } else {
2817 return MatchRegOp(*reg)(operand);
2818 }
2819}
2820

/usr/src/gnu/usr.bin/clang/liblldbExpression/../../../llvm/lldb/include/lldb/Utility/DataExtractor.h

1//===-- DataExtractor.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_DATAEXTRACTOR_H
10#define LLDB_UTILITY_DATAEXTRACTOR_H
11
12#include "lldb/Utility/Endian.h"
13#include "lldb/lldb-defines.h"
14#include "lldb/lldb-enumerations.h"
15#include "lldb/lldb-forward.h"
16#include "lldb/lldb-types.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/Support/DataExtractor.h"
19#include "llvm/Support/SwapByteOrder.h"
20
21#include <cassert>
22#include <cstdint>
23#include <cstring>
24
25namespace lldb_private {
26class Log;
27class Stream;
28}
29namespace llvm {
30template <typename T> class SmallVectorImpl;
31}
32
33
34namespace lldb_private {
35
36/// \class DataExtractor DataExtractor.h "lldb/Core/DataExtractor.h" An data
37/// extractor class.
38///
39/// DataExtractor is a class that can extract data (swapping if needed) from a
40/// data buffer. The data buffer can be caller owned, or can be shared data
41/// that can be shared between multiple DataExtractor instances. Multiple
42/// DataExtractor objects can share the same data, yet extract values in
43/// different address sizes and byte order modes. Each object can have a
44/// unique position in the shared data and extract data from different
45/// offsets.
46///
47/// \see DataBuffer
48class DataExtractor {
49public:
50 /// \typedef DataExtractor::Type
51 /// Type enumerations used in the dump routines.
52 enum Type {
53 TypeUInt8, ///< Format output as unsigned 8 bit integers
54 TypeChar, ///< Format output as characters
55 TypeUInt16, ///< Format output as unsigned 16 bit integers
56 TypeUInt32, ///< Format output as unsigned 32 bit integers
57 TypeUInt64, ///< Format output as unsigned 64 bit integers
58 TypePointer, ///< Format output as pointers
59 TypeULEB128, ///< Format output as ULEB128 numbers
60 TypeSLEB128 ///< Format output as SLEB128 numbers
61 };
62
63 /// Default constructor.
64 ///
65 /// Initialize all members to a default empty state.
66 DataExtractor();
67
68 /// Construct with a buffer that is owned by the caller.
69 ///
70 /// This constructor allows us to use data that is owned by the caller. The
71 /// data must stay around as long as this object is valid.
72 ///
73 /// \param[in] data
74 /// A pointer to caller owned data.
75 ///
76 /// \param[in] data_length
77 /// The length in bytes of \a data.
78 ///
79 /// \param[in] byte_order
80 /// A byte order of the data that we are extracting from.
81 ///
82 /// \param[in] addr_size
83 /// A new address byte size value.
84 ///
85 /// \param[in] target_byte_size
86 /// A size of a target byte in 8-bit host bytes
87 DataExtractor(const void *data, lldb::offset_t data_length,
88 lldb::ByteOrder byte_order, uint32_t addr_size,
89 uint32_t target_byte_size = 1);
90
91 /// Construct with shared data.
92 ///
93 /// Copies the data shared pointer which adds a reference to the contained
94 /// in \a data_sp. The shared data reference is reference counted to ensure
95 /// the data lives as long as anyone still has a valid shared pointer to the
96 /// data in \a data_sp.
97 ///
98 /// \param[in] data_sp
99 /// A shared pointer to data.
100 ///
101 /// \param[in] byte_order
102 /// A byte order of the data that we are extracting from.
103 ///
104 /// \param[in] addr_size
105 /// A new address byte size value.
106 ///
107 /// \param[in] target_byte_size
108 /// A size of a target byte in 8-bit host bytes
109 DataExtractor(const lldb::DataBufferSP &data_sp, lldb::ByteOrder byte_order,
110 uint32_t addr_size, uint32_t target_byte_size = 1);
111
112 /// Construct with a subset of \a data.
113 ///
114 /// Initialize this object with a subset of the data bytes in \a data. If \a
115 /// data contains shared data, then a reference to the shared data will be
116 /// added to ensure the shared data stays around as long as any objects have
117 /// references to the shared data. The byte order value and the address size
118 /// settings are copied from \a data. If \a offset is not a valid offset in
119 /// \a data, then no reference to the shared data will be added. If there
120 /// are not \a length bytes available in \a data starting at \a offset, the
121 /// length will be truncated to contain as many bytes as possible.
122 ///
123 /// \param[in] data
124 /// Another DataExtractor object that contains data.
125 ///
126 /// \param[in] offset
127 /// The offset into \a data at which the subset starts.
128 ///
129 /// \param[in] length
130 /// The length in bytes of the subset of data.
131 ///
132 /// \param[in] target_byte_size
133 /// A size of a target byte in 8-bit host bytes
134 DataExtractor(const DataExtractor &data, lldb::offset_t offset,
135 lldb::offset_t length, uint32_t target_byte_size = 1);
136
137 DataExtractor(const DataExtractor &rhs);
138
139 /// Assignment operator.
140 ///
141 /// Copies all data, byte order and address size settings from \a rhs into
142 /// this object. If \a rhs contains shared data, a reference to that shared
143 /// data will be added.
144 ///
145 /// \param[in] rhs
146 /// Another DataExtractor object to copy.
147 ///
148 /// \return
149 /// A const reference to this object.
150 const DataExtractor &operator=(const DataExtractor &rhs);
151
152 /// Destructor
153 ///
154 /// If this object contains a valid shared data reference, the reference
155 /// count on the data will be decremented, and if zero, the data will be
156 /// freed.
157 virtual ~DataExtractor();
158
159 uint32_t getTargetByteSize() const { return m_target_byte_size; }
160
161 /// Clears the object state.
162 ///
163 /// Clears the object contents back to a default invalid state, and release
164 /// any references to shared data that this object may contain.
165 void Clear();
166
167 /// Dumps the binary data as \a type objects to stream \a s (or to Log() if
168 /// \a s is nullptr) starting \a offset bytes into the data and stopping
169 /// after dumping \a length bytes. The offset into the data is displayed at
170 /// the beginning of each line and can be offset by base address \a
171 /// base_addr. \a num_per_line objects will be displayed on each line.
172 ///
173 /// \param[in] log
174 /// The log to dump the output to.
175 ///
176 /// \param[in] offset
177 /// The offset into the data at which to start dumping.
178 ///
179 /// \param[in] length
180 /// The number of bytes to dump.
181 ///
182 /// \param[in] base_addr
183 /// The base address that gets added to the offset displayed on
184 /// each line.
185 ///
186 /// \param[in] num_per_line
187 /// The number of \a type objects to display on each line.
188 ///
189 /// \param[in] type
190 /// The type of objects to use when dumping data from this
191 /// object. See DataExtractor::Type.
192 ///
193 /// \return
194 /// The offset at which dumping ended.
195 lldb::offset_t PutToLog(Log *log, lldb::offset_t offset,
196 lldb::offset_t length, uint64_t base_addr,
197 uint32_t num_per_line, Type type) const;
198
199 /// Extract an arbitrary number of bytes in the specified byte order.
200 ///
201 /// Attemps to extract \a length bytes starting at \a offset bytes into this
202 /// data in the requested byte order (\a dst_byte_order) and place the
203 /// results in \a dst. \a dst must be at least \a length bytes long.
204 ///
205 /// \param[in] offset
206 /// The offset in bytes into the contained data at which to
207 /// start extracting.
208 ///
209 /// \param[in] length
210 /// The number of bytes to extract.
211 ///
212 /// \param[in] dst_byte_order
213 /// A byte order of the data that we want when the value in
214 /// copied to \a dst.
215 ///
216 /// \param[out] dst
217 /// The buffer that will receive the extracted value if there
218 /// are enough bytes available in the current data.
219 ///
220 /// \return
221 /// The number of bytes that were extracted which will be \a
222 /// length when the value is successfully extracted, or zero
223 /// if there aren't enough bytes at the specified offset.
224 size_t ExtractBytes(lldb::offset_t offset, lldb::offset_t length,
225 lldb::ByteOrder dst_byte_order, void *dst) const;
226
227 /// Extract an address from \a *offset_ptr.
228 ///
229 /// Extract a single address from the data and update the offset pointed to
230 /// by \a offset_ptr. The size of the extracted address comes from the \a
231 /// m_addr_size member variable and should be set correctly prior to
232 /// extracting any address values.
233 ///
234 /// \param[in,out] offset_ptr
235 /// A pointer to an offset within the data that will be advanced
236 /// by the appropriate number of bytes if the value is extracted
237 /// correctly. If the offset is out of bounds or there are not
238 /// enough bytes to extract this value, the offset will be left
239 /// unmodified.
240 ///
241 /// \return
242 /// The extracted address value.
243 uint64_t GetAddress(lldb::offset_t *offset_ptr) const;
244
245 uint64_t GetAddress_unchecked(lldb::offset_t *offset_ptr) const;
246
247 /// Get the current address size.
248 ///
249 /// Return the size in bytes of any address values this object will extract.
250 ///
251 /// \return
252 /// The size in bytes of address values that will be extracted.
253 uint32_t GetAddressByteSize() const { return m_addr_size; }
254
255 /// Get the number of bytes contained in this object.
256 ///
257 /// \return
258 /// The total number of bytes of data this object refers to.
259 uint64_t GetByteSize() const { return m_end - m_start; }
260
261 /// Extract a C string from \a *offset_ptr.
262 ///
263 /// Returns a pointer to a C String from the data at the offset pointed to
264 /// by \a offset_ptr. A variable length NULL terminated C string will be
265 /// extracted and the \a offset_ptr will be updated with the offset of the
266 /// byte that follows the NULL terminator byte.
267 ///
268 /// \param[in,out] offset_ptr
269 /// A pointer to an offset within the data that will be advanced
270 /// by the appropriate number of bytes if the value is extracted
271 /// correctly. If the offset is out of bounds or there are not
272 /// enough bytes to extract this value, the offset will be left
273 /// unmodified.
274 ///
275 /// \return
276 /// A pointer to the C string value in the data. If the offset
277 /// pointed to by \a offset_ptr is out of bounds, or if the
278 /// offset plus the length of the C string is out of bounds,
279 /// nullptr will be returned.
280 const char *GetCStr(lldb::offset_t *offset_ptr) const;
281
282 /// Extract a C string from \a *offset_ptr with field size \a len.
283 ///
284 /// Returns a pointer to a C String from the data at the offset pointed to
285 /// by \a offset_ptr, with a field length of \a len.
286 /// A NULL terminated C string will be extracted and the \a offset_ptr
287 /// will be updated with the offset of the byte that follows the fixed
288 /// length field.
289 ///
290 /// \param[in,out] offset_ptr
291 /// A pointer to an offset within the data that will be advanced
292 /// by the appropriate number of bytes if the value is extracted
293 /// correctly. If the offset is out of bounds or there are not
294 /// enough bytes to extract this value, the offset will be left
295 /// unmodified.
296 ///
297 /// \return
298 /// A pointer to the C string value in the data. If the offset
299 /// pointed to by \a offset_ptr is out of bounds, or if the
300 /// offset plus the length of the field is out of bounds, or if
301 /// the field does not contain a NULL terminator byte, nullptr will
302 /// be returned.
303 const char *GetCStr(lldb::offset_t *offset_ptr, lldb::offset_t len) const;
304
305 /// Extract \a length bytes from \a *offset_ptr.
306 ///
307 /// Returns a pointer to a bytes in this object's data at the offset pointed
308 /// to by \a offset_ptr. If \a length is zero or too large, then the offset
309 /// pointed to by \a offset_ptr will not be updated and nullptr will be
310 /// returned.
311 ///
312 /// \param[in,out] offset_ptr
313 /// A pointer to an offset within the data that will be advanced
314 /// by the appropriate number of bytes if the value is extracted
315 /// correctly. If the offset is out of bounds or there are not
316 /// enough bytes to extract this value, the offset will be left
317 /// unmodified.
318 ///
319 /// \param[in] length
320 /// The optional length of a string to extract. If the value is
321 /// zero, a NULL terminated C string will be extracted.
322 ///
323 /// \return
324 /// A pointer to the bytes in this object's data if the offset
325 /// and length are valid, or nullptr otherwise.
326 const void *GetData(lldb::offset_t *offset_ptr, lldb::offset_t length) const {
327 const uint8_t *ptr = PeekData(*offset_ptr, length);
328 if (ptr)
329 *offset_ptr += length;
330 return ptr;
331 }
332
333 /// Copy \a length bytes from \a *offset, without swapping bytes.
334 ///
335 /// \param[in] offset
336 /// The offset into this data from which to start copying
337 ///
338 /// \param[in] length
339 /// The length of the data to copy from this object
340 ///
341 /// \param[out] dst
342 /// The buffer to place the output data.
343 ///
344 /// \return
345 /// Returns the number of bytes that were copied, or zero if
346 /// anything goes wrong.
347 lldb::offset_t CopyData(lldb::offset_t offset, lldb::offset_t length,
348 void *dst) const;
349
350 /// Copy \a dst_len bytes from \a *offset_ptr and ensure the copied data is
351 /// treated as a value that can be swapped to match the specified byte
352 /// order.
353 ///
354 /// For values that are larger than the supported integer sizes, this
355 /// function can be used to extract data in a specified byte order. It can
356 /// also be used to copy a smaller integer value from to a larger value. The
357 /// extra bytes left over will be padded correctly according to the byte
358 /// order of this object and the \a dst_byte_order. This can be very handy
359 /// when say copying a partial data value into a register.
360 ///
361 /// \param[in] src_offset
362 /// The offset into this data from which to start copying an endian
363 /// entity
364 ///
365 /// \param[in] src_len
366 /// The length of the endian data to copy from this object into the \a
367 /// dst object
368 ///
369 /// \param[out] dst
370 /// The buffer where to place the endian data. The data might need to be
371 /// byte swapped (and appropriately padded with zeroes if \a src_len !=
372 /// \a dst_len) if \a dst_byte_order does not match the byte order in
373 /// this object.
374 ///
375 /// \param[in] dst_len
376 /// The length number of bytes that the endian value will occupy is \a
377 /// dst.
378 ///
379 /// \param[in] dst_byte_order
380 /// The byte order that the endian value should be in the \a dst buffer.
381 ///
382 /// \return
383 /// Returns the number of bytes that were copied, or zero if anything
384 /// goes wrong.
385 lldb::offset_t CopyByteOrderedData(lldb::offset_t src_offset,
386 lldb::offset_t src_len, void *dst,
387 lldb::offset_t dst_len,
388 lldb::ByteOrder dst_byte_order) const;
389
390 /// Get the data end pointer.
391 ///
392 /// \return
393 /// Returns a pointer to the next byte contained in this
394 /// object's data, or nullptr of there is no data in this object.
395 const uint8_t *GetDataEnd() const { return m_end; }
396
397 /// Get the shared data offset.
398 ///
399 /// Get the offset of the first byte of data in the shared data (if any).
400 ///
401 /// \return
402 /// If this object contains shared data, this function returns
403 /// the offset in bytes into that shared data, zero otherwise.
404 size_t GetSharedDataOffset() const;
405
406 /// Get the data start pointer.
407 ///
408 /// \return
409 /// Returns a pointer to the first byte contained in this
410 /// object's data, or nullptr of there is no data in this object.
411 const uint8_t *GetDataStart() const { return m_start; }
412
413 /// Extract a float from \a *offset_ptr.
414 ///
415 /// Extract a single float value.
416 ///
417 /// \param[in,out] offset_ptr
418 /// A pointer to an offset within the data that will be advanced
419 /// by the appropriate number of bytes if the value is extracted
420 /// correctly. If the offset is out of bounds or there are not
421 /// enough bytes to extract this value, the offset will be left
422 /// unmodified.
423 ///
424 /// \return
425 /// The floating value that was extracted, or zero on failure.
426 float GetFloat(lldb::offset_t *offset_ptr) const;
427
428 double GetDouble(lldb::offset_t *offset_ptr) const;
429
430 long double GetLongDouble(lldb::offset_t *offset_ptr) const;
431
432 /// Extract an integer of size \a byte_size from \a *offset_ptr.
433 ///
434 /// Extract a single integer value and update the offset pointed to by \a
435 /// offset_ptr. The size of the extracted integer is specified by the \a
436 /// byte_size argument. \a byte_size must have a value >= 1 and <= 4 since
437 /// the return value is only 32 bits wide.
438 ///
439 /// \param[in,out] offset_ptr
440 /// A pointer to an offset within the data that will be advanced
441 /// by the appropriate number of bytes if the value is extracted
442 /// correctly. If the offset is out of bounds or there are not
443 /// enough bytes to extract this value, the offset will be left
444 /// unmodified.
445 ///
446 /// \param[in] byte_size
447 /// The size in byte of the integer to extract.
448 ///
449 /// \return
450 /// The integer value that was extracted, or zero on failure.
451 uint32_t GetMaxU32(lldb::offset_t *offset_ptr, size_t byte_size) const;
452
453 /// Extract an unsigned integer of size \a byte_size from \a *offset_ptr.
454 ///
455 /// Extract a single unsigned integer value and update the offset pointed to
456 /// by \a offset_ptr. The size of the extracted integer is specified by the
457 /// \a byte_size argument. \a byte_size must have a value greater than or
458 /// equal to one and less than or equal to eight since the return value is
459 /// 64 bits wide.
460 ///
461 /// \param[in,out] offset_ptr
462 /// A pointer to an offset within the data that will be advanced
463 /// by the appropriate number of bytes if the value is extracted
464 /// correctly. If the offset is out of bounds or there are not
465 /// enough bytes to extract this value, the offset will be left
466 /// unmodified.
467 ///
468 /// \param[in] byte_size
469 /// The size in byte of the integer to extract.
470 ///
471 /// \return
472 /// The unsigned integer value that was extracted, or zero on
473 /// failure.
474 uint64_t GetMaxU64(lldb::offset_t *offset_ptr, size_t byte_size) const;
475
476 uint64_t GetMaxU64_unchecked(lldb::offset_t *offset_ptr,
477 size_t byte_size) const;
478
479 /// Extract an signed integer of size \a byte_size from \a *offset_ptr.
480 ///
481 /// Extract a single signed integer value (sign extending if required) and
482 /// update the offset pointed to by \a offset_ptr. The size of the extracted
483 /// integer is specified by the \a byte_size argument. \a byte_size must
484 /// have a value greater than or equal to one and less than or equal to
485 /// eight since the return value is 64 bits wide.
486 ///
487 /// \param[in,out] offset_ptr
488 /// A pointer to an offset within the data that will be advanced
489 /// by the appropriate number of bytes if the value is extracted
490 /// correctly. If the offset is out of bounds or there are not
491 /// enough bytes to extract this value, the offset will be left
492 /// unmodified.
493 ///
494 /// \param[in] byte_size
495 /// The size in byte of the integer to extract.
496 ///
497 /// \return
498 /// The sign extended signed integer value that was extracted,
499 /// or zero on failure.
500 int64_t GetMaxS64(lldb::offset_t *offset_ptr, size_t byte_size) const;
501
502 /// Extract an unsigned integer of size \a byte_size from \a *offset_ptr,
503 /// then extract the bitfield from this value if \a bitfield_bit_size is
504 /// non-zero.
505 ///
506 /// Extract a single unsigned integer value and update the offset pointed to
507 /// by \a offset_ptr. The size of the extracted integer is specified by the
508 /// \a byte_size argument. \a byte_size must have a value greater than or
509 /// equal to one and less than or equal to 8 since the return value is 64
510 /// bits wide.
511 ///
512 /// \param[in,out] offset_ptr
513 /// A pointer to an offset within the data that will be advanced
514 /// by the appropriate number of bytes if the value is extracted
515 /// correctly. If the offset is out of bounds or there are not
516 /// enough bytes to extract this value, the offset will be left
517 /// unmodified.
518 ///
519 /// \param[in] size
520 /// The size in byte of the integer to extract.
521 ///
522 /// \param[in] bitfield_bit_size
523 /// The size in bits of the bitfield value to extract, or zero
524 /// to just extract the entire integer value.
525 ///
526 /// \param[in] bitfield_bit_offset
527 /// The bit offset of the bitfield value in the extracted
528 /// integer. For little-endian data, this is the offset of
529 /// the LSB of the bitfield from the LSB of the integer.
530 /// For big-endian data, this is the offset of the MSB of the
531 /// bitfield from the MSB of the integer.
532 ///
533 /// \return
534 /// The unsigned bitfield integer value that was extracted, or
535 /// zero on failure.
536 uint64_t GetMaxU64Bitfield(lldb::offset_t *offset_ptr, size_t size,
537 uint32_t bitfield_bit_size,
538 uint32_t bitfield_bit_offset) const;
539
540 /// Extract an signed integer of size \a size from \a *offset_ptr, then
541 /// extract and sign-extend the bitfield from this value if \a
542 /// bitfield_bit_size is non-zero.
543 ///
544 /// Extract a single signed integer value (sign-extending if required) and
545 /// update the offset pointed to by \a offset_ptr. The size of the extracted
546 /// integer is specified by the \a size argument. \a size must
547 /// have a value greater than or equal to one and less than or equal to
548 /// eight since the return value is 64 bits wide.
549 ///
550 /// \param[in,out] offset_ptr
551 /// A pointer to an offset within the data that will be advanced
552 /// by the appropriate number of bytes if the value is extracted
553 /// correctly. If the offset is out of bounds or there are not
554 /// enough bytes to extract this value, the offset will be left
555 /// unmodified.
556 ///
557 /// \param[in] size
558 /// The size in bytes of the integer to extract.
559 ///
560 /// \param[in] bitfield_bit_size
561 /// The size in bits of the bitfield value to extract, or zero
562 /// to just extract the entire integer value.
563 ///
564 /// \param[in] bitfield_bit_offset
565 /// The bit offset of the bitfield value in the extracted
566 /// integer. For little-endian data, this is the offset of
567 /// the LSB of the bitfield from the LSB of the integer.
568 /// For big-endian data, this is the offset of the MSB of the
569 /// bitfield from the MSB of the integer.
570 ///
571 /// \return
572 /// The signed bitfield integer value that was extracted, or
573 /// zero on failure.
574 int64_t GetMaxS64Bitfield(lldb::offset_t *offset_ptr, size_t size,
575 uint32_t bitfield_bit_size,
576 uint32_t bitfield_bit_offset) const;
577
578 /// Get the current byte order value.
579 ///
580 /// \return
581 /// The current byte order value from this object's internal
582 /// state.
583 lldb::ByteOrder GetByteOrder() const { return m_byte_order; }
584
585 /// Extract a uint8_t value from \a *offset_ptr.
586 ///
587 /// Extract a single uint8_t from the binary data at the offset pointed to
588 /// by \a offset_ptr, and advance the offset on success.
589 ///
590 /// \param[in,out] offset_ptr
591 /// A pointer to an offset within the data that will be advanced
592 /// by the appropriate number of bytes if the value is extracted
593 /// correctly. If the offset is out of bounds or there are not
594 /// enough bytes to extract this value, the offset will be left
595 /// unmodified.
596 ///
597 /// \return
598 /// The extracted uint8_t value.
599 uint8_t GetU8(lldb::offset_t *offset_ptr) const;
600
601 uint8_t GetU8_unchecked(lldb::offset_t *offset_ptr) const {
602 uint8_t val = m_start[*offset_ptr];
603 *offset_ptr += 1;
604 return val;
605 }
606
607 uint16_t GetU16_unchecked(lldb::offset_t *offset_ptr) const;
608
609 uint32_t GetU32_unchecked(lldb::offset_t *offset_ptr) const;
610
611 uint64_t GetU64_unchecked(lldb::offset_t *offset_ptr) const;
612 /// Extract \a count uint8_t values from \a *offset_ptr.
613 ///
614 /// Extract \a count uint8_t values from the binary data at the offset
615 /// pointed to by \a offset_ptr, and advance the offset on success. The
616 /// extracted values are copied into \a dst.
617 ///
618 /// \param[in,out] offset_ptr
619 /// A pointer to an offset within the data that will be advanced
620 /// by the appropriate number of bytes if the value is extracted
621 /// correctly. If the offset is out of bounds or there are not
622 /// enough bytes to extract this value, the offset will be left
623 /// unmodified.
624 ///
625 /// \param[out] dst
626 /// A buffer to copy \a count uint8_t values into. \a dst must
627 /// be large enough to hold all requested data.
628 ///
629 /// \param[in] count
630 /// The number of uint8_t values to extract.
631 ///
632 /// \return
633 /// \a dst if all values were properly extracted and copied,
634 /// nullptr otherwise.
635 void *GetU8(lldb::offset_t *offset_ptr, void *dst, uint32_t count) const;
636
637 /// Extract a uint16_t value from \a *offset_ptr.
638 ///
639 /// Extract a single uint16_t from the binary data at the offset pointed to
640 /// by \a offset_ptr, and update the offset on success.
641 ///
642 /// \param[in,out] offset_ptr
643 /// A pointer to an offset within the data that will be advanced
644 /// by the appropriate number of bytes if the value is extracted
645 /// correctly. If the offset is out of bounds or there are not
646 /// enough bytes to extract this value, the offset will be left
647 /// unmodified.
648 ///
649 /// \return
650 /// The extracted uint16_t value.
651 uint16_t GetU16(lldb::offset_t *offset_ptr) const;
652
653 /// Extract \a count uint16_t values from \a *offset_ptr.
654 ///
655 /// Extract \a count uint16_t values from the binary data at the offset
656 /// pointed to by \a offset_ptr, and advance the offset on success. The
657 /// extracted values are copied into \a dst.
658 ///
659 /// \param[in,out] offset_ptr
660 /// A pointer to an offset within the data that will be advanced
661 /// by the appropriate number of bytes if the value is extracted
662 /// correctly. If the offset is out of bounds or there are not
663 /// enough bytes to extract this value, the offset will be left
664 /// unmodified.
665 ///
666 /// \param[out] dst
667 /// A buffer to copy \a count uint16_t values into. \a dst must
668 /// be large enough to hold all requested data.
669 ///
670 /// \param[in] count
671 /// The number of uint16_t values to extract.
672 ///
673 /// \return
674 /// \a dst if all values were properly extracted and copied,
675 /// nullptr otherwise.
676 void *GetU16(lldb::offset_t *offset_ptr, void *dst, uint32_t count) const;
677
678 /// Extract a uint32_t value from \a *offset_ptr.
679 ///
680 /// Extract a single uint32_t from the binary data at the offset pointed to
681 /// by \a offset_ptr, and update the offset on success.
682 ///
683 /// \param[in,out] offset_ptr
684 /// A pointer to an offset within the data that will be advanced
685 /// by the appropriate number of bytes if the value is extracted
686 /// correctly. If the offset is out of bounds or there are not
687 /// enough bytes to extract this value, the offset will be left
688 /// unmodified.
689 ///
690 /// \return
691 /// The extracted uint32_t value.
692 uint32_t GetU32(lldb::offset_t *offset_ptr) const;
693
694 /// Extract \a count uint32_t values from \a *offset_ptr.
695 ///
696 /// Extract \a count uint32_t values from the binary data at the offset
697 /// pointed to by \a offset_ptr, and advance the offset on success. The
698 /// extracted values are copied into \a dst.
699 ///
700 /// \param[in,out] offset_ptr
701 /// A pointer to an offset within the data that will be advanced
702 /// by the appropriate number of bytes if the value is extracted
703 /// correctly. If the offset is out of bounds or there are not
704 /// enough bytes to extract this value, the offset will be left
705 /// unmodified.
706 ///
707 /// \param[out] dst
708 /// A buffer to copy \a count uint32_t values into. \a dst must
709 /// be large enough to hold all requested data.
710 ///
711 /// \param[in] count
712 /// The number of uint32_t values to extract.
713 ///
714 /// \return
715 /// \a dst if all values were properly extracted and copied,
716 /// nullptr otherwise.
717 void *GetU32(lldb::offset_t *offset_ptr, void *dst, uint32_t count) const;
718
719 /// Extract a uint64_t value from \a *offset_ptr.
720 ///
721 /// Extract a single uint64_t from the binary data at the offset pointed to
722 /// by \a offset_ptr, and update the offset on success.
723 ///
724 /// \param[in,out] offset_ptr
725 /// A pointer to an offset within the data that will be advanced
726 /// by the appropriate number of bytes if the value is extracted
727 /// correctly. If the offset is out of bounds or there are not
728 /// enough bytes to extract this value, the offset will be left
729 /// unmodified.
730 ///
731 /// \return
732 /// The extracted uint64_t value.
733 uint64_t GetU64(lldb::offset_t *offset_ptr) const;
734
735 /// Extract \a count uint64_t values from \a *offset_ptr.
736 ///
737 /// Extract \a count uint64_t values from the binary data at the offset
738 /// pointed to by \a offset_ptr, and advance the offset on success. The
739 /// extracted values are copied into \a dst.
740 ///
741 /// \param[in,out] offset_ptr
742 /// A pointer to an offset within the data that will be advanced
743 /// by the appropriate number of bytes if the value is extracted
744 /// correctly. If the offset is out of bounds or there are not
745 /// enough bytes to extract this value, the offset will be left
746 /// unmodified.
747 ///
748 /// \param[out] dst
749 /// A buffer to copy \a count uint64_t values into. \a dst must
750 /// be large enough to hold all requested data.
751 ///
752 /// \param[in] count
753 /// The number of uint64_t values to extract.
754 ///
755 /// \return
756 /// \a dst if all values were properly extracted and copied,
757 /// nullptr otherwise.
758 void *GetU64(lldb::offset_t *offset_ptr, void *dst, uint32_t count) const;
759
760 /// Extract a signed LEB128 value from \a *offset_ptr.
761 ///
762 /// Extracts an signed LEB128 number from this object's data starting at the
763 /// offset pointed to by \a offset_ptr. The offset pointed to by \a
764 /// offset_ptr will be updated with the offset of the byte following the
765 /// last extracted byte.
766 ///
767 /// \param[in,out] offset_ptr
768 /// A pointer to an offset within the data that will be advanced
769 /// by the appropriate number of bytes if the value is extracted
770 /// correctly. If the offset is out of bounds or there are not
771 /// enough bytes to extract this value, the offset will be left
772 /// unmodified.
773 ///
774 /// \return
775 /// The extracted signed integer value.
776 int64_t GetSLEB128(lldb::offset_t *offset_ptr) const;
777
778 /// Extract a unsigned LEB128 value from \a *offset_ptr.
779 ///
780 /// Extracts an unsigned LEB128 number from this object's data starting at
781 /// the offset pointed to by \a offset_ptr. The offset pointed to by \a
782 /// offset_ptr will be updated with the offset of the byte following the
783 /// last extracted byte.
784 ///
785 /// \param[in,out] offset_ptr
786 /// A pointer to an offset within the data that will be advanced
787 /// by the appropriate number of bytes if the value is extracted
788 /// correctly. If the offset is out of bounds or there are not
789 /// enough bytes to extract this value, the offset will be left
790 /// unmodified.
791 ///
792 /// \return
793 /// The extracted unsigned integer value.
794 uint64_t GetULEB128(lldb::offset_t *offset_ptr) const;
795
796 lldb::DataBufferSP &GetSharedDataBuffer() { return m_data_sp; }
797
798 /// Peek at a C string at \a offset.
799 ///
800 /// Peeks at a string in the contained data. No verification is done to make
801 /// sure the entire string lies within the bounds of this object's data,
802 /// only \a offset is verified to be a valid offset.
803 ///
804 /// \param[in] offset
805 /// An offset into the data.
806 ///
807 /// \return
808 /// A non-nullptr C string pointer if \a offset is a valid offset,
809 /// nullptr otherwise.
810 const char *PeekCStr(lldb::offset_t offset) const;
811
812 /// Peek at a bytes at \a offset.
813 ///
814 /// Returns a pointer to \a length bytes at \a offset as long as there are
815 /// \a length bytes available starting at \a offset.
816 ///
817 /// \return
818 /// A non-nullptr data pointer if \a offset is a valid offset and
819 /// there are \a length bytes available at that offset, nullptr
820 /// otherwise.
821 const uint8_t *PeekData(lldb::offset_t offset, lldb::offset_t length) const {
822 if (ValidOffsetForDataOfSize(offset, length))
823 return m_start + offset;
824 return nullptr;
825 }
826
827 /// Set the address byte size.
828 ///
829 /// Set the size in bytes that will be used when extracting any address and
830 /// pointer values from data contained in this object.
831 ///
832 /// \param[in] addr_size
833 /// The size in bytes to use when extracting addresses.
834 void SetAddressByteSize(uint32_t addr_size) {
835#ifdef LLDB_CONFIGURATION_DEBUG
836 assert(addr_size == 4 || addr_size == 8)((void)0);
837#endif
838 m_addr_size = addr_size;
839 }
840
841 /// Set data with a buffer that is caller owned.
842 ///
843 /// Use data that is owned by the caller when extracting values. The data
844 /// must stay around as long as this object, or any object that copies a
845 /// subset of this object's data, is valid. If \a bytes is nullptr, or \a
846 /// length is zero, this object will contain no data.
847 ///
848 /// \param[in] bytes
849 /// A pointer to caller owned data.
850 ///
851 /// \param[in] length
852 /// The length in bytes of \a bytes.
853 ///
854 /// \param[in] byte_order
855 /// A byte order of the data that we are extracting from.
856 ///
857 /// \return
858 /// The number of bytes that this object now contains.
859 lldb::offset_t SetData(const void *bytes, lldb::offset_t length,
860 lldb::ByteOrder byte_order);
861
862 /// Adopt a subset of \a data.
863 ///
864 /// Set this object's data to be a subset of the data bytes in \a data. If
865 /// \a data contains shared data, then a reference to the shared data will
866 /// be added to ensure the shared data stays around as long as any objects
867 /// have references to the shared data. The byte order and the address size
868 /// settings are copied from \a data. If \a offset is not a valid offset in
869 /// \a data, then no reference to the shared data will be added. If there
870 /// are not \a length bytes available in \a data starting at \a offset, the
871 /// length will be truncated to contains as many bytes as possible.
872 ///
873 /// \param[in] data
874 /// Another DataExtractor object that contains data.
875 ///
876 /// \param[in] offset
877 /// The offset into \a data at which the subset starts.
878 ///
879 /// \param[in] length
880 /// The length in bytes of the subset of \a data.
881 ///
882 /// \return
883 /// The number of bytes that this object now contains.
884 lldb::offset_t SetData(const DataExtractor &data, lldb::offset_t offset,
885 lldb::offset_t length);
886
887 /// Adopt a subset of shared data in \a data_sp.
888 ///
889 /// Copies the data shared pointer which adds a reference to the contained
890 /// in \a data_sp. The shared data reference is reference counted to ensure
891 /// the data lives as long as anyone still has a valid shared pointer to the
892 /// data in \a data_sp. The byte order and address byte size settings remain
893 /// the same. If \a offset is not a valid offset in \a data_sp, then no
894 /// reference to the shared data will be added. If there are not \a length
895 /// bytes available in \a data starting at \a offset, the length will be
896 /// truncated to contains as many bytes as possible.
897 ///
898 /// \param[in] data_sp
899 /// A shared pointer to data.
900 ///
901 /// \param[in] offset
902 /// The offset into \a data_sp at which the subset starts.
903 ///
904 /// \param[in] length
905 /// The length in bytes of the subset of \a data_sp.
906 ///
907 /// \return
908 /// The number of bytes that this object now contains.
909 lldb::offset_t SetData(const lldb::DataBufferSP &data_sp,
910 lldb::offset_t offset = 0,
911 lldb::offset_t length = LLDB_INVALID_OFFSET0xffffffffffffffffULL);
912
913 /// Set the byte_order value.
914 ///
915 /// Sets the byte order of the data to extract. Extracted values will be
916 /// swapped if necessary when decoding.
917 ///
918 /// \param[in] byte_order
919 /// The byte order value to use when extracting data.
920 void SetByteOrder(lldb::ByteOrder byte_order) { m_byte_order = byte_order; }
921
922 /// Skip an LEB128 number at \a *offset_ptr.
923 ///
924 /// Skips a LEB128 number (signed or unsigned) from this object's data
925 /// starting at the offset pointed to by \a offset_ptr. The offset pointed
926 /// to by \a offset_ptr will be updated with the offset of the byte
927 /// following the last extracted byte.
928 ///
929 /// \param[in,out] offset_ptr
930 /// A pointer to an offset within the data that will be advanced
931 /// by the appropriate number of bytes if the value is extracted
932 /// correctly. If the offset is out of bounds or there are not
933 /// enough bytes to extract this value, the offset will be left
934 /// unmodified.
935 ///
936 /// \return
937 /// The number of bytes consumed during the extraction.
938 uint32_t Skip_LEB128(lldb::offset_t *offset_ptr) const;
939
940 /// Test the validity of \a offset.
941 ///
942 /// \return
943 /// true if \a offset is a valid offset into the data in this object,
944 /// false otherwise.
945 bool ValidOffset(lldb::offset_t offset) const {
946 return offset < GetByteSize();
9
Returning the value 1, which participates in a condition later
947 }
948
949 /// Test the availability of \a length bytes of data from \a offset.
950 ///
951 /// \return
952 /// true if \a offset is a valid offset and there are \a
953 /// length bytes available at that offset, false otherwise.
954 bool ValidOffsetForDataOfSize(lldb::offset_t offset,
955 lldb::offset_t length) const {
956 return length <= BytesLeft(offset);
957 }
958
959 size_t Copy(DataExtractor &dest_data) const;
960
961 bool Append(DataExtractor &rhs);
962
963 bool Append(void *bytes, lldb::offset_t length);
964
965 lldb::offset_t BytesLeft(lldb::offset_t offset) const {
966 const lldb::offset_t size = GetByteSize();
967 if (size > offset)
968 return size - offset;
969 return 0;
970 }
971
972 void Checksum(llvm::SmallVectorImpl<uint8_t> &dest, uint64_t max_data = 0);
973
974 llvm::ArrayRef<uint8_t> GetData() const {
975 return {GetDataStart(), size_t(GetByteSize())};
976 }
977
978 llvm::DataExtractor GetAsLLVM() const {
979 return {GetData(), GetByteOrder() == lldb::eByteOrderLittle,
980 uint8_t(GetAddressByteSize())};
981 }
982
983protected:
984 template <typename T> T Get(lldb::offset_t *offset_ptr, T fail_value) const {
985 constexpr size_t src_size = sizeof(T);
986 T val = fail_value;
987
988 const T *src = static_cast<const T *>(GetData(offset_ptr, src_size));
989 if (!src)
990 return val;
991
992 memcpy(&val, src, src_size);
993 if (m_byte_order != endian::InlHostByteOrder())
994 llvm::sys::swapByteOrder(val);
995
996 return val;
997 }
998
999 // Member variables
1000 const uint8_t *m_start = nullptr; ///< A pointer to the first byte of data.
1001 const uint8_t *m_end =
1002 nullptr; ///< A pointer to the byte that is past the end of the data.
1003 lldb::ByteOrder
1004 m_byte_order; ///< The byte order of the data we are extracting from.
1005 uint32_t m_addr_size; ///< The address size to use when extracting addresses.
1006 /// The shared pointer to data that can be shared among multiple instances
1007 lldb::DataBufferSP m_data_sp;
1008 const uint32_t m_target_byte_size = 1;
1009};
1010
1011} // namespace lldb_private
1012
1013#endif // LLDB_UTILITY_DATAEXTRACTOR_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;}
18
Assuming the condition is true
19
Returning the value 1, 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;
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