1 //===-- DWARFExpression.cpp -------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Expression/DWARFExpression.h"
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"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Utility/Endian.h"
28 #include "lldb/Symbol/Function.h"
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"
39 #include "Plugins/SymbolFile/DWARF/DWARFUnit.h"
42 using namespace lldb_private;
45 ReadAddressFromDebugAddrSection(const DWARFUnit *dwarf_cu,
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_ADDRESS;
57 // DWARFExpression constructor
58 DWARFExpression::DWARFExpression()
59 : m_module_wp(), m_data(), m_dwarf_cu(nullptr),
60 m_reg_kind(eRegisterKindDWARF) {}
62 DWARFExpression::DWARFExpression(lldb::ModuleSP module_sp,
63 const DataExtractor &data,
64 const DWARFUnit *dwarf_cu)
65 : m_module_wp(), m_data(data), m_dwarf_cu(dwarf_cu),
66 m_reg_kind(eRegisterKindDWARF) {
68 m_module_wp = module_sp;
72 DWARFExpression::~DWARFExpression() {}
74 bool DWARFExpression::IsValid() const { return m_data.GetByteSize() > 0; }
76 void DWARFExpression::UpdateValue(uint64_t const_value,
77 lldb::offset_t const_value_byte_size,
78 uint8_t addr_byte_size) {
79 if (!const_value_byte_size)
83 DataBufferSP(new DataBufferHeap(&const_value, const_value_byte_size)));
84 m_data.SetByteOrder(endian::InlHostByteOrder());
85 m_data.SetAddressByteSize(addr_byte_size);
88 void DWARFExpression::DumpLocation(Stream *s, const DataExtractor &data,
89 lldb::DescriptionLevel level,
91 llvm::DWARFExpression(data.GetAsLLVM(), llvm::dwarf::DWARF_VERSION,
92 data.GetAddressByteSize())
93 .print(s->AsRawOstream(), abi ? &abi->GetMCRegisterInfo() : nullptr,
97 void DWARFExpression::SetLocationListAddresses(addr_t cu_file_addr,
98 addr_t func_file_addr) {
99 m_loclist_addresses = LoclistAddresses{cu_file_addr, func_file_addr};
102 int DWARFExpression::GetRegisterKind() { return m_reg_kind; }
104 void DWARFExpression::SetRegisterKind(RegisterKind reg_kind) {
105 m_reg_kind = reg_kind;
108 bool DWARFExpression::IsLocationList() const {
109 return bool(m_loclist_addresses);
113 /// Implement enough of the DWARFObject interface in order to be able to call
114 /// DWARFLocationTable::dumpLocationList. We don't have access to a real
115 /// DWARFObject here because DWARFExpression is used in non-DWARF scenarios too.
116 class DummyDWARFObject final: public llvm::DWARFObject {
118 DummyDWARFObject(bool IsLittleEndian) : IsLittleEndian(IsLittleEndian) {}
120 bool isLittleEndian() const override { return IsLittleEndian; }
122 llvm::Optional<llvm::RelocAddrEntry> find(const llvm::DWARFSection &Sec,
123 uint64_t Pos) const override {
131 void DWARFExpression::GetDescription(Stream *s, lldb::DescriptionLevel level,
132 addr_t location_list_base_addr,
134 if (IsLocationList()) {
135 // We have a location list
136 lldb::offset_t offset = 0;
137 std::unique_ptr<llvm::DWARFLocationTable> loctable_up =
138 m_dwarf_cu->GetLocationTable(m_data);
140 llvm::MCRegisterInfo *MRI = abi ? &abi->GetMCRegisterInfo() : nullptr;
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 llvm::DIDumpOptions(), s->GetIndentLevel() + 2);
148 // We have a normal location that contains DW_OP location opcodes
149 DumpLocation(s, m_data, level, abi);
153 static bool ReadRegisterValueAsScalar(RegisterContext *reg_ctx,
154 lldb::RegisterKind reg_kind,
155 uint32_t reg_num, Status *error_ptr,
157 if (reg_ctx == nullptr) {
159 error_ptr->SetErrorStringWithFormat("No register context in frame.\n");
161 uint32_t native_reg =
162 reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
163 if (native_reg == LLDB_INVALID_REGNUM) {
165 error_ptr->SetErrorStringWithFormat("Unable to convert register "
166 "kind=%u reg_num=%u to a native "
167 "register number.\n",
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::eValueTypeScalar);
176 value.SetContext(Value::eContextTypeRegisterInfo,
177 const_cast<RegisterInfo *>(reg_info));
182 // If we get this error, then we need to implement a value buffer in
183 // the dwarf expression evaluation function...
185 error_ptr->SetErrorStringWithFormat(
186 "register %s can't be converted to a scalar value",
191 error_ptr->SetErrorStringWithFormat("register %s is not available",
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.
201 static offset_t GetOpcodeDataSize(const DataExtractor &data,
202 const lldb::offset_t data_offset,
204 lldb::offset_t offset = data_offset;
207 case DW_OP_call_ref: // 0x9a 1 address sized offset of DIE (DWARF3)
208 return data.GetAddressByteSize();
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
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
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)
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)
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
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;
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;
389 case DW_OP_implicit_value: // 0x9e ULEB128 size followed by block of that size
392 uint64_t block_len = data.Skip_LEB128(&offset);
394 return offset - data_offset;
397 case DW_OP_entry_value: // 0xa3 ULEB128 size + variable-length block
399 uint64_t subexpr_len = data.GetULEB128(&offset);
400 return (offset - data_offset) + subexpr_len;
406 return LLDB_INVALID_OFFSET;
409 lldb::addr_t DWARFExpression::GetLocation_DW_OP_addr(uint32_t op_addr_idx,
412 if (IsLocationList())
413 return LLDB_INVALID_ADDRESS;
414 lldb::offset_t offset = 0;
415 uint32_t curr_op_addr_idx = 0;
416 while (m_data.ValidOffset(offset)) {
417 const uint8_t op = m_data.GetU8(&offset);
419 if (op == DW_OP_addr) {
420 const lldb::addr_t op_file_addr = m_data.GetAddress(&offset);
421 if (curr_op_addr_idx == op_addr_idx)
425 } else if (op == DW_OP_GNU_addr_index || op == DW_OP_addrx) {
426 uint64_t index = m_data.GetULEB128(&offset);
427 if (curr_op_addr_idx == op_addr_idx) {
433 return ReadAddressFromDebugAddrSection(m_dwarf_cu, index);
437 const offset_t op_arg_size = GetOpcodeDataSize(m_data, offset, op);
438 if (op_arg_size == LLDB_INVALID_OFFSET) {
442 offset += op_arg_size;
445 return LLDB_INVALID_ADDRESS;
448 bool DWARFExpression::Update_DW_OP_addr(lldb::addr_t file_addr) {
449 if (IsLocationList())
451 lldb::offset_t offset = 0;
452 while (m_data.ValidOffset(offset)) {
453 const uint8_t op = m_data.GetU8(&offset);
455 if (op == DW_OP_addr) {
456 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
457 // We have to make a copy of the data as we don't know if this data is
458 // from a read only memory mapped buffer, so we duplicate all of the data
459 // first, then modify it, and if all goes well, we then replace the data
460 // for this expression
462 // So first we copy the data into a heap buffer
463 std::unique_ptr<DataBufferHeap> head_data_up(
464 new DataBufferHeap(m_data.GetDataStart(), m_data.GetByteSize()));
466 // Make en encoder so we can write the address into the buffer using the
467 // correct byte order (endianness)
468 DataEncoder encoder(head_data_up->GetBytes(), head_data_up->GetByteSize(),
469 m_data.GetByteOrder(), addr_byte_size);
471 // Replace the address in the new buffer
472 if (encoder.PutUnsigned(offset, addr_byte_size, file_addr) == UINT32_MAX)
475 // All went well, so now we can reset the data using a shared pointer to
476 // the heap data so "m_data" will now correctly manage the heap data.
477 m_data.SetData(DataBufferSP(head_data_up.release()));
480 const offset_t op_arg_size = GetOpcodeDataSize(m_data, offset, op);
481 if (op_arg_size == LLDB_INVALID_OFFSET)
483 offset += op_arg_size;
489 bool DWARFExpression::ContainsThreadLocalStorage() const {
490 // We are assuming for now that any thread local variable will not have a
491 // location list. This has been true for all thread local variables we have
492 // seen so far produced by any compiler.
493 if (IsLocationList())
495 lldb::offset_t offset = 0;
496 while (m_data.ValidOffset(offset)) {
497 const uint8_t op = m_data.GetU8(&offset);
499 if (op == DW_OP_form_tls_address || op == DW_OP_GNU_push_tls_address)
501 const offset_t op_arg_size = GetOpcodeDataSize(m_data, offset, op);
502 if (op_arg_size == LLDB_INVALID_OFFSET)
505 offset += op_arg_size;
509 bool DWARFExpression::LinkThreadLocalStorage(
510 lldb::ModuleSP new_module_sp,
511 std::function<lldb::addr_t(lldb::addr_t file_addr)> const
512 &link_address_callback) {
513 // We are assuming for now that any thread local variable will not have a
514 // location list. This has been true for all thread local variables we have
515 // seen so far produced by any compiler.
516 if (IsLocationList())
519 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
520 // We have to make a copy of the data as we don't know if this data is from a
521 // read only memory mapped buffer, so we duplicate all of the data first,
522 // then modify it, and if all goes well, we then replace the data for this
525 // So first we copy the data into a heap buffer
526 std::shared_ptr<DataBufferHeap> heap_data_sp(
527 new DataBufferHeap(m_data.GetDataStart(), m_data.GetByteSize()));
529 // Make en encoder so we can write the address into the buffer using the
530 // correct byte order (endianness)
531 DataEncoder encoder(heap_data_sp->GetBytes(), heap_data_sp->GetByteSize(),
532 m_data.GetByteOrder(), addr_byte_size);
534 lldb::offset_t offset = 0;
535 lldb::offset_t const_offset = 0;
536 lldb::addr_t const_value = 0;
537 size_t const_byte_size = 0;
538 while (m_data.ValidOffset(offset)) {
539 const uint8_t op = m_data.GetU8(&offset);
541 bool decoded_data = false;
544 // Remember the const offset in case we later have a
545 // DW_OP_form_tls_address or DW_OP_GNU_push_tls_address
546 const_offset = offset;
547 const_value = m_data.GetU32(&offset);
553 // Remember the const offset in case we later have a
554 // DW_OP_form_tls_address or DW_OP_GNU_push_tls_address
555 const_offset = offset;
556 const_value = m_data.GetU64(&offset);
561 case DW_OP_form_tls_address:
562 case DW_OP_GNU_push_tls_address:
563 // DW_OP_form_tls_address and DW_OP_GNU_push_tls_address must be preceded
564 // by a file address on the stack. We assume that DW_OP_const4u or
565 // DW_OP_const8u is used for these values, and we check that the last
566 // opcode we got before either of these was DW_OP_const4u or
567 // DW_OP_const8u. If so, then we can link the value accodingly. For
568 // Darwin, the value in the DW_OP_const4u or DW_OP_const8u is the file
569 // address of a structure that contains a function pointer, the pthread
570 // key and the offset into the data pointed to by the pthread key. So we
571 // must link this address and also set the module of this expression to
572 // the new_module_sp so we can resolve the file address correctly
573 if (const_byte_size > 0) {
574 lldb::addr_t linked_file_addr = link_address_callback(const_value);
575 if (linked_file_addr == LLDB_INVALID_ADDRESS)
577 // Replace the address in the new buffer
578 if (encoder.PutUnsigned(const_offset, const_byte_size,
579 linked_file_addr) == UINT32_MAX)
592 const offset_t op_arg_size = GetOpcodeDataSize(m_data, offset, op);
593 if (op_arg_size == LLDB_INVALID_OFFSET)
596 offset += op_arg_size;
600 // If we linked the TLS address correctly, update the module so that when the
601 // expression is evaluated it can resolve the file address to a load address
604 m_module_wp = new_module_sp;
605 m_data.SetData(heap_data_sp);
609 bool DWARFExpression::LocationListContainsAddress(addr_t func_load_addr,
610 lldb::addr_t addr) const {
611 if (func_load_addr == LLDB_INVALID_ADDRESS || addr == LLDB_INVALID_ADDRESS)
614 if (!IsLocationList())
617 return GetLocationExpression(func_load_addr, addr) != llvm::None;
620 bool DWARFExpression::DumpLocationForAddress(Stream *s,
621 lldb::DescriptionLevel level,
622 addr_t func_load_addr,
623 addr_t address, ABI *abi) {
624 if (!IsLocationList()) {
625 DumpLocation(s, m_data, level, abi);
628 if (llvm::Optional<DataExtractor> expr =
629 GetLocationExpression(func_load_addr, address)) {
630 DumpLocation(s, *expr, level, abi);
636 static bool Evaluate_DW_OP_entry_value(std::vector<Value> &stack,
637 ExecutionContext *exe_ctx,
638 RegisterContext *reg_ctx,
639 const DataExtractor &opcodes,
640 lldb::offset_t &opcode_offset,
641 Status *error_ptr, Log *log) {
642 // DW_OP_entry_value(sub-expr) describes the location a variable had upon
643 // function entry: this variable location is presumed to be optimized out at
644 // the current PC value. The caller of the function may have call site
645 // information that describes an alternate location for the variable (e.g. a
646 // constant literal, or a spilled stack value) in the parent frame.
648 // Example (this is pseudo-code & pseudo-DWARF, but hopefully illustrative):
650 // void child(int &sink, int x) {
652 // /* "x" gets optimized out. */
654 // /* The location of "x" here is: DW_OP_entry_value($reg2). */
662 // * The callsite information emitted here is:
664 // * DW_TAG_call_site
665 // * DW_AT_return_pc ... (for "child(sink, 123);")
666 // * DW_TAG_call_site_parameter (for "sink")
667 // * DW_AT_location ($reg1)
668 // * DW_AT_call_value ($SP - 8)
669 // * DW_TAG_call_site_parameter (for "x")
670 // * DW_AT_location ($reg2)
671 // * DW_AT_call_value ($literal 123)
673 // * DW_TAG_call_site
674 // * DW_AT_return_pc ... (for "child(sink, 456);")
681 // When the program stops at "++sink" within `child`, the debugger determines
682 // the call site by analyzing the return address. Once the call site is found,
683 // the debugger determines which parameter is referenced by DW_OP_entry_value
684 // and evaluates the corresponding location for that parameter in `parent`.
686 // 1. Find the function which pushed the current frame onto the stack.
687 if ((!exe_ctx || !exe_ctx->HasTargetScope()) || !reg_ctx) {
688 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no exe/reg context");
692 StackFrame *current_frame = exe_ctx->GetFramePtr();
693 Thread *thread = exe_ctx->GetThreadPtr();
694 if (!current_frame || !thread) {
695 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no current frame/thread");
699 Target &target = exe_ctx->GetTargetRef();
700 StackFrameSP parent_frame = nullptr;
701 addr_t return_pc = LLDB_INVALID_ADDRESS;
702 uint32_t current_frame_idx = current_frame->GetFrameIndex();
703 uint32_t num_frames = thread->GetStackFrameCount();
704 for (uint32_t parent_frame_idx = current_frame_idx + 1;
705 parent_frame_idx < num_frames; ++parent_frame_idx) {
706 parent_frame = thread->GetStackFrameAtIndex(parent_frame_idx);
707 // Require a valid sequence of frames.
711 // Record the first valid return address, even if this is an inlined frame,
712 // in order to look up the associated call edge in the first non-inlined
714 if (return_pc == LLDB_INVALID_ADDRESS) {
715 return_pc = parent_frame->GetFrameCodeAddress().GetLoadAddress(&target);
717 "Evaluate_DW_OP_entry_value: immediate ancestor with pc = {0:x}",
721 // If we've found an inlined frame, skip it (these have no call site
723 if (parent_frame->IsInlined())
726 // We've found the first non-inlined parent frame.
729 if (!parent_frame || !parent_frame->GetRegisterContext()) {
730 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no parent frame with reg ctx");
734 Function *parent_func =
735 parent_frame->GetSymbolContext(eSymbolContextFunction).function;
737 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no parent function");
741 // 2. Find the call edge in the parent function responsible for creating the
742 // current activation.
743 Function *current_func =
744 current_frame->GetSymbolContext(eSymbolContextFunction).function;
746 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no current function");
750 CallEdge *call_edge = nullptr;
751 ModuleList &modlist = target.GetImages();
752 ExecutionContext parent_exe_ctx = *exe_ctx;
753 parent_exe_ctx.SetFrameSP(parent_frame);
754 if (!parent_frame->IsArtificial()) {
755 // If the parent frame is not artificial, the current activation may be
756 // produced by an ambiguous tail call. In this case, refuse to proceed.
757 call_edge = parent_func->GetCallEdgeForReturnAddress(return_pc, target);
760 "Evaluate_DW_OP_entry_value: no call edge for retn-pc = {0:x} "
761 "in parent frame {1}",
762 return_pc, parent_func->GetName());
765 Function *callee_func = call_edge->GetCallee(modlist, parent_exe_ctx);
766 if (callee_func != current_func) {
767 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: ambiguous call sequence, "
768 "can't find real parent frame");
772 // The StackFrameList solver machinery has deduced that an unambiguous tail
773 // call sequence that produced the current activation. The first edge in
774 // the parent that points to the current function must be valid.
775 for (auto &edge : parent_func->GetTailCallingEdges()) {
776 if (edge->GetCallee(modlist, parent_exe_ctx) == current_func) {
777 call_edge = edge.get();
783 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: no unambiguous edge from parent "
784 "to current function");
788 // 3. Attempt to locate the DW_OP_entry_value expression in the set of
789 // available call site parameters. If found, evaluate the corresponding
790 // parameter in the context of the parent frame.
791 const uint32_t subexpr_len = opcodes.GetULEB128(&opcode_offset);
792 const void *subexpr_data = opcodes.GetData(&opcode_offset, subexpr_len);
794 LLDB_LOG(log, "Evaluate_DW_OP_entry_value: subexpr could not be read");
798 const CallSiteParameter *matched_param = nullptr;
799 for (const CallSiteParameter ¶m : call_edge->GetCallSiteParameters()) {
800 DataExtractor param_subexpr_extractor;
801 if (!param.LocationInCallee.GetExpressionData(param_subexpr_extractor))
803 lldb::offset_t param_subexpr_offset = 0;
804 const void *param_subexpr_data =
805 param_subexpr_extractor.GetData(¶m_subexpr_offset, subexpr_len);
806 if (!param_subexpr_data ||
807 param_subexpr_extractor.BytesLeft(param_subexpr_offset) != 0)
810 // At this point, the DW_OP_entry_value sub-expression and the callee-side
811 // expression in the call site parameter are known to have the same length.
812 // Check whether they are equal.
814 // Note that an equality check is sufficient: the contents of the
815 // DW_OP_entry_value subexpression are only used to identify the right call
816 // site parameter in the parent, and do not require any special handling.
817 if (memcmp(subexpr_data, param_subexpr_data, subexpr_len) == 0) {
818 matched_param = ¶m;
822 if (!matched_param) {
824 "Evaluate_DW_OP_entry_value: no matching call site param found");
828 // TODO: Add support for DW_OP_push_object_address within a DW_OP_entry_value
829 // subexpresion whenever llvm does.
831 const DWARFExpression ¶m_expr = matched_param->LocationInCaller;
832 if (!param_expr.Evaluate(&parent_exe_ctx,
833 parent_frame->GetRegisterContext().get(),
834 /*loclist_base_addr=*/LLDB_INVALID_ADDRESS,
835 /*initial_value_ptr=*/nullptr,
836 /*object_address_ptr=*/nullptr, result, error_ptr)) {
838 "Evaluate_DW_OP_entry_value: call site param evaluation failed");
842 stack.push_back(result);
846 bool DWARFExpression::Evaluate(ExecutionContextScope *exe_scope,
847 lldb::addr_t loclist_base_load_addr,
848 const Value *initial_value_ptr,
849 const Value *object_address_ptr, Value &result,
850 Status *error_ptr) const {
851 ExecutionContext exe_ctx(exe_scope);
852 return Evaluate(&exe_ctx, nullptr, loclist_base_load_addr, initial_value_ptr,
853 object_address_ptr, result, error_ptr);
856 bool DWARFExpression::Evaluate(ExecutionContext *exe_ctx,
857 RegisterContext *reg_ctx,
858 lldb::addr_t func_load_addr,
859 const Value *initial_value_ptr,
860 const Value *object_address_ptr, Value &result,
861 Status *error_ptr) const {
862 ModuleSP module_sp = m_module_wp.lock();
864 if (IsLocationList()) {
866 StackFrame *frame = nullptr;
868 pc = reg_ctx->GetPC();
870 frame = exe_ctx->GetFramePtr();
873 RegisterContextSP reg_ctx_sp = frame->GetRegisterContext();
876 pc = reg_ctx_sp->GetPC();
879 if (func_load_addr != LLDB_INVALID_ADDRESS) {
880 if (pc == LLDB_INVALID_ADDRESS) {
882 error_ptr->SetErrorString("Invalid PC in frame.");
886 if (llvm::Optional<DataExtractor> expr =
887 GetLocationExpression(func_load_addr, pc)) {
888 return DWARFExpression::Evaluate(
889 exe_ctx, reg_ctx, module_sp, *expr, m_dwarf_cu, m_reg_kind,
890 initial_value_ptr, object_address_ptr, result, error_ptr);
894 error_ptr->SetErrorString("variable not available");
898 // Not a location list, just a single expression.
899 return DWARFExpression::Evaluate(exe_ctx, reg_ctx, module_sp, m_data,
900 m_dwarf_cu, m_reg_kind, initial_value_ptr,
901 object_address_ptr, result, error_ptr);
904 bool DWARFExpression::Evaluate(
905 ExecutionContext *exe_ctx, RegisterContext *reg_ctx,
906 lldb::ModuleSP module_sp, const DataExtractor &opcodes,
907 const DWARFUnit *dwarf_cu, const lldb::RegisterKind reg_kind,
908 const Value *initial_value_ptr, const Value *object_address_ptr,
909 Value &result, Status *error_ptr) {
911 if (opcodes.GetByteSize() == 0) {
913 error_ptr->SetErrorString(
914 "no location, value may have been optimized out");
917 std::vector<Value> stack;
919 Process *process = nullptr;
920 StackFrame *frame = nullptr;
923 process = exe_ctx->GetProcessPtr();
924 frame = exe_ctx->GetFramePtr();
926 if (reg_ctx == nullptr && frame)
927 reg_ctx = frame->GetRegisterContext().get();
929 if (initial_value_ptr)
930 stack.push_back(*initial_value_ptr);
932 lldb::offset_t offset = 0;
936 /// Insertion point for evaluating multi-piece expression.
\13
937 uint64_t op_piece_offset = 0;
938 Value pieces; // Used for DW_OP_piece
940 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
942 while (opcodes.ValidOffset(offset)) {
943 const lldb::offset_t op_offset = offset;
944 const uint8_t op = opcodes.GetU8(&offset);
946 if (log && log->GetVerbose()) {
947 size_t count = stack.size();
948 LLDB_LOGF(log, "Stack before operation has %" PRIu64 " values:",
950 for (size_t i = 0; i < count; ++i) {
951 StreamString new_value;
952 new_value.Printf("[%" PRIu64 "]", (uint64_t)i);
953 stack[i].Dump(&new_value);
954 LLDB_LOGF(log, " %s", new_value.GetData());
956 LLDB_LOGF(log, "0x%8.8" PRIx64 ": %s", op_offset,
957 DW_OP_value_to_name(op));
961 // The DW_OP_addr operation has a single operand that encodes a machine
962 // address and whose size is the size of an address on the target machine.
964 stack.push_back(Scalar(opcodes.GetAddress(&offset)));
965 stack.back().SetValueType(Value::eValueTypeFileAddress);
966 // Convert the file address to a load address, so subsequent
967 // DWARF operators can operate on it.
969 stack.back().ConvertToLoadAddress(module_sp.get(),
970 frame->CalculateTarget().get());
973 // The DW_OP_addr_sect_offset4 is used for any location expressions in
974 // shared libraries that have a location like:
975 // DW_OP_addr(0x1000)
976 // If this address resides in a shared library, then this virtual address
977 // won't make sense when it is evaluated in the context of a running
978 // process where shared libraries have been slid. To account for this, this
979 // new address type where we can store the section pointer and a 4 byte
981 // case DW_OP_addr_sect_offset4:
983 // result_type = eResultTypeFileAddress;
984 // lldb::Section *sect = (lldb::Section
985 // *)opcodes.GetMaxU64(&offset, sizeof(void *));
986 // lldb::addr_t sect_offset = opcodes.GetU32(&offset);
988 // Address so_addr (sect, sect_offset);
989 // lldb::addr_t load_addr = so_addr.GetLoadAddress();
990 // if (load_addr != LLDB_INVALID_ADDRESS)
992 // // We successfully resolve a file address to a load
994 // stack.push_back(load_addr);
1001 // error_ptr->SetErrorStringWithFormat ("Section %s in
1002 // %s is not currently loaded.\n",
1003 // sect->GetName().AsCString(),
1004 // sect->GetModule()->GetFileSpec().GetFilename().AsCString());
1010 // OPCODE: DW_OP_deref
1012 // DESCRIPTION: Pops the top stack entry and treats it as an address.
1013 // The value retrieved from that address is pushed. The size of the data
1014 // retrieved from the dereferenced address is the size of an address on the
1017 if (stack.empty()) {
1019 error_ptr->SetErrorString("Expression stack empty for DW_OP_deref.");
1022 Value::ValueType value_type = stack.back().GetValueType();
1023 switch (value_type) {
1024 case Value::eValueTypeHostAddress: {
1025 void *src = (void *)stack.back().GetScalar().ULongLong();
1027 ::memcpy(&ptr, src, sizeof(void *));
1028 stack.back().GetScalar() = ptr;
1029 stack.back().ClearContext();
1031 case Value::eValueTypeFileAddress: {
1032 auto file_addr = stack.back().GetScalar().ULongLong(
1033 LLDB_INVALID_ADDRESS);
1036 error_ptr->SetErrorStringWithFormat(
1037 "need module to resolve file address for DW_OP_deref");
1041 if (!module_sp->ResolveFileAddress(file_addr, so_addr)) {
1043 error_ptr->SetErrorStringWithFormat(
1044 "failed to resolve file address in module");
1047 addr_t load_Addr = so_addr.GetLoadAddress(exe_ctx->GetTargetPtr());
1048 if (load_Addr == LLDB_INVALID_ADDRESS) {
1050 error_ptr->SetErrorStringWithFormat(
1051 "failed to resolve load address");
1054 stack.back().GetScalar() = load_Addr;
1055 stack.back().SetValueType(Value::eValueTypeLoadAddress);
1056 // Fall through to load address code below...
1058 case Value::eValueTypeLoadAddress:
1061 lldb::addr_t pointer_addr =
1062 stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1064 lldb::addr_t pointer_value =
1065 process->ReadPointerFromMemory(pointer_addr, error);
1066 if (pointer_value != LLDB_INVALID_ADDRESS) {
1067 stack.back().GetScalar() = pointer_value;
1068 stack.back().ClearContext();
1071 error_ptr->SetErrorStringWithFormat(
1072 "Failed to dereference pointer from 0x%" PRIx64
1073 " for DW_OP_deref: %s\n",
1074 pointer_addr, error.AsCString());
1079 error_ptr->SetErrorStringWithFormat(
1080 "NULL process for DW_OP_deref.\n");
1085 error_ptr->SetErrorStringWithFormat(
1086 "NULL execution context for DW_OP_deref.\n");
1097 // OPCODE: DW_OP_deref_size
1099 // 1 - uint8_t that specifies the size of the data to dereference.
1100 // DESCRIPTION: Behaves like the DW_OP_deref operation: it pops the top
1101 // stack entry and treats it as an address. The value retrieved from that
1102 // address is pushed. In the DW_OP_deref_size operation, however, the size
1103 // in bytes of the data retrieved from the dereferenced address is
1104 // specified by the single operand. This operand is a 1-byte unsigned
1105 // integral constant whose value may not be larger than the size of an
1106 // address on the target machine. The data retrieved is zero extended to
1107 // the size of an address on the target machine before being pushed on the
1108 // expression stack.
1109 case DW_OP_deref_size: {
1110 if (stack.empty()) {
1112 error_ptr->SetErrorString(
1113 "Expression stack empty for DW_OP_deref_size.");
1116 uint8_t size = opcodes.GetU8(&offset);
1117 Value::ValueType value_type = stack.back().GetValueType();
1118 switch (value_type) {
1119 case Value::eValueTypeHostAddress: {
1120 void *src = (void *)stack.back().GetScalar().ULongLong();
1122 ::memcpy(&ptr, src, sizeof(void *));
1123 // I can't decide whether the size operand should apply to the bytes in
1125 // lldb-host endianness or the target endianness.. I doubt this'll ever
1126 // come up but I'll opt for assuming big endian regardless.
1135 ptr = ptr & 0xffffff;
1138 ptr = ptr & 0xffffffff;
1140 // the casts are added to work around the case where intptr_t is a 32
1142 // presumably we won't hit the 5..7 cases if (void*) is 32-bits in this
1145 ptr = (intptr_t)ptr & 0xffffffffffULL;
1148 ptr = (intptr_t)ptr & 0xffffffffffffULL;
1151 ptr = (intptr_t)ptr & 0xffffffffffffffULL;
1156 stack.back().GetScalar() = ptr;
1157 stack.back().ClearContext();
1159 case Value::eValueTypeLoadAddress:
1162 lldb::addr_t pointer_addr =
1163 stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1164 uint8_t addr_bytes[sizeof(lldb::addr_t)];
1166 if (process->ReadMemory(pointer_addr, &addr_bytes, size, error) ==
1168 DataExtractor addr_data(addr_bytes, sizeof(addr_bytes),
1169 process->GetByteOrder(), size);
1170 lldb::offset_t addr_data_offset = 0;
1173 stack.back().GetScalar() = addr_data.GetU8(&addr_data_offset);
1176 stack.back().GetScalar() = addr_data.GetU16(&addr_data_offset);
1179 stack.back().GetScalar() = addr_data.GetU32(&addr_data_offset);
1182 stack.back().GetScalar() = addr_data.GetU64(&addr_data_offset);
1185 stack.back().GetScalar() =
1186 addr_data.GetPointer(&addr_data_offset);
1188 stack.back().ClearContext();
1191 error_ptr->SetErrorStringWithFormat(
1192 "Failed to dereference pointer from 0x%" PRIx64
1193 " for DW_OP_deref: %s\n",
1194 pointer_addr, error.AsCString());
1199 error_ptr->SetErrorStringWithFormat(
1200 "NULL process for DW_OP_deref.\n");
1205 error_ptr->SetErrorStringWithFormat(
1206 "NULL execution context for DW_OP_deref.\n");
1217 // OPCODE: DW_OP_xderef_size
1219 // 1 - uint8_t that specifies the size of the data to dereference.
1220 // DESCRIPTION: Behaves like the DW_OP_xderef operation: the entry at
1221 // the top of the stack is treated as an address. The second stack entry is
1222 // treated as an "address space identifier" for those architectures that
1223 // support multiple address spaces. The top two stack elements are popped,
1224 // a data item is retrieved through an implementation-defined address
1225 // calculation and pushed as the new stack top. In the DW_OP_xderef_size
1226 // operation, however, the size in bytes of the data retrieved from the
1227 // dereferenced address is specified by the single operand. This operand is
1228 // a 1-byte unsigned integral constant whose value may not be larger than
1229 // the size of an address on the target machine. The data retrieved is zero
1230 // extended to the size of an address on the target machine before being
1231 // pushed on the expression stack.
1232 case DW_OP_xderef_size:
1234 error_ptr->SetErrorString("Unimplemented opcode: DW_OP_xderef_size.");
1236 // OPCODE: DW_OP_xderef
1238 // DESCRIPTION: Provides an extended dereference mechanism. The entry at
1239 // the top of the stack is treated as an address. The second stack entry is
1240 // treated as an "address space identifier" for those architectures that
1241 // support multiple address spaces. The top two stack elements are popped,
1242 // a data item is retrieved through an implementation-defined address
1243 // calculation and pushed as the new stack top. The size of the data
1244 // retrieved from the dereferenced address is the size of an address on the
1248 error_ptr->SetErrorString("Unimplemented opcode: DW_OP_xderef.");
1251 // All DW_OP_constXXX opcodes have a single operand as noted below:
1254 // DW_OP_const1u 1-byte unsigned integer constant DW_OP_const1s
1255 // 1-byte signed integer constant DW_OP_const2u 2-byte unsigned integer
1256 // constant DW_OP_const2s 2-byte signed integer constant DW_OP_const4u
1257 // 4-byte unsigned integer constant DW_OP_const4s 4-byte signed integer
1258 // constant DW_OP_const8u 8-byte unsigned integer constant DW_OP_const8s
1259 // 8-byte signed integer constant DW_OP_constu unsigned LEB128 integer
1260 // constant DW_OP_consts signed LEB128 integer constant
1262 stack.push_back(Scalar((uint8_t)opcodes.GetU8(&offset)));
1265 stack.push_back(Scalar((int8_t)opcodes.GetU8(&offset)));
1268 stack.push_back(Scalar((uint16_t)opcodes.GetU16(&offset)));
1271 stack.push_back(Scalar((int16_t)opcodes.GetU16(&offset)));
1274 stack.push_back(Scalar((uint32_t)opcodes.GetU32(&offset)));
1277 stack.push_back(Scalar((int32_t)opcodes.GetU32(&offset)));
1280 stack.push_back(Scalar((uint64_t)opcodes.GetU64(&offset)));
1283 stack.push_back(Scalar((int64_t)opcodes.GetU64(&offset)));
1286 stack.push_back(Scalar(opcodes.GetULEB128(&offset)));
1289 stack.push_back(Scalar(opcodes.GetSLEB128(&offset)));
1292 // OPCODE: DW_OP_dup
1294 // DESCRIPTION: duplicates the value at the top of the stack
1296 if (stack.empty()) {
1298 error_ptr->SetErrorString("Expression stack empty for DW_OP_dup.");
1301 stack.push_back(stack.back());
1304 // OPCODE: DW_OP_drop
1306 // DESCRIPTION: pops the value at the top of the stack
1308 if (stack.empty()) {
1310 error_ptr->SetErrorString("Expression stack empty for DW_OP_drop.");
1316 // OPCODE: DW_OP_over
1318 // DESCRIPTION: Duplicates the entry currently second in the stack at
1319 // the top of the stack.
1321 if (stack.size() < 2) {
1323 error_ptr->SetErrorString(
1324 "Expression stack needs at least 2 items for DW_OP_over.");
1327 stack.push_back(stack[stack.size() - 2]);
1330 // OPCODE: DW_OP_pick
1331 // OPERANDS: uint8_t index into the current stack
1332 // DESCRIPTION: The stack entry with the specified index (0 through 255,
1333 // inclusive) is pushed on the stack
1335 uint8_t pick_idx = opcodes.GetU8(&offset);
1336 if (pick_idx < stack.size())
1337 stack.push_back(stack[stack.size() - 1 - pick_idx]);
1340 error_ptr->SetErrorStringWithFormat(
1341 "Index %u out of range for DW_OP_pick.\n", pick_idx);
1346 // OPCODE: DW_OP_swap
1348 // DESCRIPTION: swaps the top two stack entries. The entry at the top
1349 // of the stack becomes the second stack entry, and the second entry
1350 // becomes the top of the stack
1352 if (stack.size() < 2) {
1354 error_ptr->SetErrorString(
1355 "Expression stack needs at least 2 items for DW_OP_swap.");
1359 stack.back() = stack[stack.size() - 2];
1360 stack[stack.size() - 2] = tmp;
1364 // OPCODE: DW_OP_rot
1366 // DESCRIPTION: Rotates the first three stack entries. The entry at
1367 // the top of the stack becomes the third stack entry, the second entry
1368 // becomes the top of the stack, and the third entry becomes the second
1371 if (stack.size() < 3) {
1373 error_ptr->SetErrorString(
1374 "Expression stack needs at least 3 items for DW_OP_rot.");
1377 size_t last_idx = stack.size() - 1;
1378 Value old_top = stack[last_idx];
1379 stack[last_idx] = stack[last_idx - 1];
1380 stack[last_idx - 1] = stack[last_idx - 2];
1381 stack[last_idx - 2] = old_top;
1385 // OPCODE: DW_OP_abs
1387 // DESCRIPTION: pops the top stack entry, interprets it as a signed
1388 // value and pushes its absolute value. If the absolute value can not be
1389 // represented, the result is undefined.
1391 if (stack.empty()) {
1393 error_ptr->SetErrorString(
1394 "Expression stack needs at least 1 item for DW_OP_abs.");
1396 } else if (!stack.back().ResolveValue(exe_ctx).AbsoluteValue()) {
1398 error_ptr->SetErrorString(
1399 "Failed to take the absolute value of the first stack item.");
1404 // OPCODE: DW_OP_and
1406 // DESCRIPTION: pops the top two stack values, performs a bitwise and
1407 // operation on the two, and pushes the result.
1409 if (stack.size() < 2) {
1411 error_ptr->SetErrorString(
1412 "Expression stack needs at least 2 items for DW_OP_and.");
1417 stack.back().ResolveValue(exe_ctx) =
1418 stack.back().ResolveValue(exe_ctx) & tmp.ResolveValue(exe_ctx);
1422 // OPCODE: DW_OP_div
1424 // DESCRIPTION: pops the top two stack values, divides the former second
1425 // entry by the former top of the stack using signed division, and pushes
1428 if (stack.size() < 2) {
1430 error_ptr->SetErrorString(
1431 "Expression stack needs at least 2 items for DW_OP_div.");
1435 if (tmp.ResolveValue(exe_ctx).IsZero()) {
1437 error_ptr->SetErrorString("Divide by zero.");
1442 stack.back().ResolveValue(exe_ctx) / tmp.ResolveValue(exe_ctx);
1443 if (!stack.back().ResolveValue(exe_ctx).IsValid()) {
1445 error_ptr->SetErrorString("Divide failed.");
1452 // OPCODE: DW_OP_minus
1454 // DESCRIPTION: pops the top two stack values, subtracts the former top
1455 // of the stack from the former second entry, and pushes the result.
1457 if (stack.size() < 2) {
1459 error_ptr->SetErrorString(
1460 "Expression stack needs at least 2 items for DW_OP_minus.");
1465 stack.back().ResolveValue(exe_ctx) =
1466 stack.back().ResolveValue(exe_ctx) - tmp.ResolveValue(exe_ctx);
1470 // OPCODE: DW_OP_mod
1472 // DESCRIPTION: pops the top two stack values and pushes the result of
1473 // the calculation: former second stack entry modulo the former top of the
1476 if (stack.size() < 2) {
1478 error_ptr->SetErrorString(
1479 "Expression stack needs at least 2 items for DW_OP_mod.");
1484 stack.back().ResolveValue(exe_ctx) =
1485 stack.back().ResolveValue(exe_ctx) % tmp.ResolveValue(exe_ctx);
1489 // OPCODE: DW_OP_mul
1491 // DESCRIPTION: pops the top two stack entries, multiplies them
1492 // together, and pushes the result.
1494 if (stack.size() < 2) {
1496 error_ptr->SetErrorString(
1497 "Expression stack needs at least 2 items for DW_OP_mul.");
1502 stack.back().ResolveValue(exe_ctx) =
1503 stack.back().ResolveValue(exe_ctx) * tmp.ResolveValue(exe_ctx);
1507 // OPCODE: DW_OP_neg
1509 // DESCRIPTION: pops the top stack entry, and pushes its negation.
1511 if (stack.empty()) {
1513 error_ptr->SetErrorString(
1514 "Expression stack needs at least 1 item for DW_OP_neg.");
1517 if (!stack.back().ResolveValue(exe_ctx).UnaryNegate()) {
1519 error_ptr->SetErrorString("Unary negate failed.");
1525 // OPCODE: DW_OP_not
1527 // DESCRIPTION: pops the top stack entry, and pushes its bitwise
1530 if (stack.empty()) {
1532 error_ptr->SetErrorString(
1533 "Expression stack needs at least 1 item for DW_OP_not.");
1536 if (!stack.back().ResolveValue(exe_ctx).OnesComplement()) {
1538 error_ptr->SetErrorString("Logical NOT failed.");
1546 // DESCRIPTION: pops the top two stack entries, performs a bitwise or
1547 // operation on the two, and pushes the result.
1549 if (stack.size() < 2) {
1551 error_ptr->SetErrorString(
1552 "Expression stack needs at least 2 items for DW_OP_or.");
1557 stack.back().ResolveValue(exe_ctx) =
1558 stack.back().ResolveValue(exe_ctx) | tmp.ResolveValue(exe_ctx);
1562 // OPCODE: DW_OP_plus
1564 // DESCRIPTION: pops the top two stack entries, adds them together, and
1565 // pushes the result.
1567 if (stack.size() < 2) {
1569 error_ptr->SetErrorString(
1570 "Expression stack needs at least 2 items for DW_OP_plus.");
1575 stack.back().GetScalar() += tmp.GetScalar();
1579 // OPCODE: DW_OP_plus_uconst
1581 // DESCRIPTION: pops the top stack entry, adds it to the unsigned LEB128
1582 // constant operand and pushes the result.
1583 case DW_OP_plus_uconst:
1584 if (stack.empty()) {
1586 error_ptr->SetErrorString(
1587 "Expression stack needs at least 1 item for DW_OP_plus_uconst.");
1590 const uint64_t uconst_value = opcodes.GetULEB128(&offset);
1591 // Implicit conversion from a UINT to a Scalar...
1592 stack.back().GetScalar() += uconst_value;
1593 if (!stack.back().GetScalar().IsValid()) {
1595 error_ptr->SetErrorString("DW_OP_plus_uconst failed.");
1601 // OPCODE: DW_OP_shl
1603 // DESCRIPTION: pops the top two stack entries, shifts the former
1604 // second entry left by the number of bits specified by the former top of
1605 // the stack, and pushes the result.
1607 if (stack.size() < 2) {
1609 error_ptr->SetErrorString(
1610 "Expression stack needs at least 2 items for DW_OP_shl.");
1615 stack.back().ResolveValue(exe_ctx) <<= tmp.ResolveValue(exe_ctx);
1619 // OPCODE: DW_OP_shr
1621 // DESCRIPTION: pops the top two stack entries, shifts the former second
1622 // entry right logically (filling with zero bits) by the number of bits
1623 // specified by the former top of the stack, and pushes the result.
1625 if (stack.size() < 2) {
1627 error_ptr->SetErrorString(
1628 "Expression stack needs at least 2 items for DW_OP_shr.");
1633 if (!stack.back().ResolveValue(exe_ctx).ShiftRightLogical(
1634 tmp.ResolveValue(exe_ctx))) {
1636 error_ptr->SetErrorString("DW_OP_shr failed.");
1642 // OPCODE: DW_OP_shra
1644 // DESCRIPTION: pops the top two stack entries, shifts the former second
1645 // entry right arithmetically (divide the magnitude by 2, keep the same
1646 // sign for the result) by the number of bits specified by the former top
1647 // of the stack, and pushes the result.
1649 if (stack.size() < 2) {
1651 error_ptr->SetErrorString(
1652 "Expression stack needs at least 2 items for DW_OP_shra.");
1657 stack.back().ResolveValue(exe_ctx) >>= tmp.ResolveValue(exe_ctx);
1661 // OPCODE: DW_OP_xor
1663 // DESCRIPTION: pops the top two stack entries, performs the bitwise
1664 // exclusive-or operation on the two, and pushes the result.
1666 if (stack.size() < 2) {
1668 error_ptr->SetErrorString(
1669 "Expression stack needs at least 2 items for DW_OP_xor.");
1674 stack.back().ResolveValue(exe_ctx) =
1675 stack.back().ResolveValue(exe_ctx) ^ tmp.ResolveValue(exe_ctx);
1679 // OPCODE: DW_OP_skip
1680 // OPERANDS: int16_t
1681 // DESCRIPTION: An unconditional branch. Its single operand is a 2-byte
1682 // signed integer constant. The 2-byte constant is the number of bytes of
1683 // the DWARF expression to skip forward or backward from the current
1684 // operation, beginning after the 2-byte constant.
1686 int16_t skip_offset = (int16_t)opcodes.GetU16(&offset);
1687 lldb::offset_t new_offset = offset + skip_offset;
1688 if (opcodes.ValidOffset(new_offset))
1689 offset = new_offset;
1692 error_ptr->SetErrorString("Invalid opcode offset in DW_OP_skip.");
1697 // OPCODE: DW_OP_bra
1698 // OPERANDS: int16_t
1699 // DESCRIPTION: A conditional branch. Its single operand is a 2-byte
1700 // signed integer constant. This operation pops the top of stack. If the
1701 // value popped is not the constant 0, the 2-byte constant operand is the
1702 // number of bytes of the DWARF expression to skip forward or backward from
1703 // the current operation, beginning after the 2-byte constant.
1705 if (stack.empty()) {
1707 error_ptr->SetErrorString(
1708 "Expression stack needs at least 1 item for DW_OP_bra.");
1713 int16_t bra_offset = (int16_t)opcodes.GetU16(&offset);
1715 if (tmp.ResolveValue(exe_ctx) != zero) {
1716 lldb::offset_t new_offset = offset + bra_offset;
1717 if (opcodes.ValidOffset(new_offset))
1718 offset = new_offset;
1721 error_ptr->SetErrorString("Invalid opcode offset in DW_OP_bra.");
1730 // DESCRIPTION: pops the top two stack values, compares using the
1731 // equals (==) operator.
1732 // STACK RESULT: push the constant value 1 onto the stack if the result
1733 // of the operation is true or the constant value 0 if the result of the
1734 // operation is false.
1736 if (stack.size() < 2) {
1738 error_ptr->SetErrorString(
1739 "Expression stack needs at least 2 items for DW_OP_eq.");
1744 stack.back().ResolveValue(exe_ctx) =
1745 stack.back().ResolveValue(exe_ctx) == tmp.ResolveValue(exe_ctx);
1751 // DESCRIPTION: pops the top two stack values, compares using the
1752 // greater than or equal to (>=) operator.
1753 // STACK RESULT: push the constant value 1 onto the stack if the result
1754 // of the operation is true or the constant value 0 if the result of the
1755 // operation is false.
1757 if (stack.size() < 2) {
1759 error_ptr->SetErrorString(
1760 "Expression stack needs at least 2 items for DW_OP_ge.");
1765 stack.back().ResolveValue(exe_ctx) =
1766 stack.back().ResolveValue(exe_ctx) >= tmp.ResolveValue(exe_ctx);
1772 // DESCRIPTION: pops the top two stack values, compares using the
1773 // greater than (>) operator.
1774 // STACK RESULT: push the constant value 1 onto the stack if the result
1775 // of the operation is true or the constant value 0 if the result of the
1776 // operation is false.
1778 if (stack.size() < 2) {
1780 error_ptr->SetErrorString(
1781 "Expression stack needs at least 2 items for DW_OP_gt.");
1786 stack.back().ResolveValue(exe_ctx) =
1787 stack.back().ResolveValue(exe_ctx) > tmp.ResolveValue(exe_ctx);
1793 // DESCRIPTION: pops the top two stack values, compares using the
1794 // less than or equal to (<=) operator.
1795 // STACK RESULT: push the constant value 1 onto the stack if the result
1796 // of the operation is true or the constant value 0 if the result of the
1797 // operation is false.
1799 if (stack.size() < 2) {
1801 error_ptr->SetErrorString(
1802 "Expression stack needs at least 2 items for DW_OP_le.");
1807 stack.back().ResolveValue(exe_ctx) =
1808 stack.back().ResolveValue(exe_ctx) <= tmp.ResolveValue(exe_ctx);
1814 // DESCRIPTION: pops the top two stack values, compares using the
1815 // less than (<) operator.
1816 // STACK RESULT: push the constant value 1 onto the stack if the result
1817 // of the operation is true or the constant value 0 if the result of the
1818 // operation is false.
1820 if (stack.size() < 2) {
1822 error_ptr->SetErrorString(
1823 "Expression stack needs at least 2 items for DW_OP_lt.");
1828 stack.back().ResolveValue(exe_ctx) =
1829 stack.back().ResolveValue(exe_ctx) < tmp.ResolveValue(exe_ctx);
1835 // DESCRIPTION: pops the top two stack values, compares using the
1836 // not equal (!=) operator.
1837 // STACK RESULT: push the constant value 1 onto the stack if the result
1838 // of the operation is true or the constant value 0 if the result of the
1839 // operation is false.
1841 if (stack.size() < 2) {
1843 error_ptr->SetErrorString(
1844 "Expression stack needs at least 2 items for DW_OP_ne.");
1849 stack.back().ResolveValue(exe_ctx) =
1850 stack.back().ResolveValue(exe_ctx) != tmp.ResolveValue(exe_ctx);
1854 // OPCODE: DW_OP_litn
1856 // DESCRIPTION: encode the unsigned literal values from 0 through 31.
1857 // STACK RESULT: push the unsigned literal constant value onto the top
1891 stack.push_back(Scalar((uint64_t)(op - DW_OP_lit0)));
1894 // OPCODE: DW_OP_regN
1896 // DESCRIPTION: Push the value in register n on the top of the stack.
1929 reg_num = op - DW_OP_reg0;
1931 if (ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, error_ptr, tmp))
1932 stack.push_back(tmp);
1936 // OPCODE: DW_OP_regx
1938 // ULEB128 literal operand that encodes the register.
1939 // DESCRIPTION: Push the value in register on the top of the stack.
1941 reg_num = opcodes.GetULEB128(&offset);
1942 if (ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, error_ptr, tmp))
1943 stack.push_back(tmp);
1948 // OPCODE: DW_OP_bregN
1950 // SLEB128 offset from register N
1951 // DESCRIPTION: Value is in memory at the address specified by register
1952 // N plus an offset.
1984 case DW_OP_breg31: {
1985 reg_num = op - DW_OP_breg0;
1987 if (ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, error_ptr,
1989 int64_t breg_offset = opcodes.GetSLEB128(&offset);
1990 tmp.ResolveValue(exe_ctx) += (uint64_t)breg_offset;
1992 stack.push_back(tmp);
1993 stack.back().SetValueType(Value::eValueTypeLoadAddress);
1997 // OPCODE: DW_OP_bregx
1999 // ULEB128 literal operand that encodes the register.
2000 // SLEB128 offset from register N
2001 // DESCRIPTION: Value is in memory at the address specified by register
2002 // N plus an offset.
2004 reg_num = opcodes.GetULEB128(&offset);
2006 if (ReadRegisterValueAsScalar(reg_ctx, reg_kind, reg_num, error_ptr,
2008 int64_t breg_offset = opcodes.GetSLEB128(&offset);
2009 tmp.ResolveValue(exe_ctx) += (uint64_t)breg_offset;
2011 stack.push_back(tmp);
2012 stack.back().SetValueType(Value::eValueTypeLoadAddress);
2021 if (frame->GetFrameBaseValue(value, error_ptr)) {
2022 int64_t fbreg_offset = opcodes.GetSLEB128(&offset);
2023 value += fbreg_offset;
2024 stack.push_back(value);
2025 stack.back().SetValueType(Value::eValueTypeLoadAddress);
2030 error_ptr->SetErrorString(
2031 "Invalid stack frame in context for DW_OP_fbreg opcode.");
2036 error_ptr->SetErrorStringWithFormat(
2037 "NULL execution context for DW_OP_fbreg.\n");
2043 // OPCODE: DW_OP_nop
2045 // DESCRIPTION: A place holder. It has no effect on the location stack
2046 // or any of its values.
2050 // OPCODE: DW_OP_piece
2052 // ULEB128: byte size of the piece
2053 // DESCRIPTION: The operand describes the size in bytes of the piece of
2054 // the object referenced by the DWARF expression whose result is at the top
2055 // of the stack. If the piece is located in a register, but does not occupy
2056 // the entire register, the placement of the piece within that register is
2057 // defined by the ABI.
2059 // Many compilers store a single variable in sets of registers, or store a
2060 // variable partially in memory and partially in registers. DW_OP_piece
2061 // provides a way of describing how large a part of a variable a particular
2062 // DWARF expression refers to.
2064 const uint64_t piece_byte_size = opcodes.GetULEB128(&offset);
2066 if (piece_byte_size > 0) {
2069 if (stack.empty()) {
2070 // In a multi-piece expression, this means that the current piece is
2071 // not available. Fill with zeros for now by resizing the data and
2073 curr_piece.ResizeData(piece_byte_size);
2074 // Note that "0" is not a correct value for the unknown bits.
2075 // It would be better to also return a mask of valid bits together
2076 // with the expression result, so the debugger can print missing
2077 // members as "<optimized out>" or something.
2078 ::memset(curr_piece.GetBuffer().GetBytes(), 0, piece_byte_size);
2079 pieces.AppendDataToHostBuffer(curr_piece);
2082 // Extract the current piece into "curr_piece"
2083 Value curr_piece_source_value(stack.back());
2086 const Value::ValueType curr_piece_source_value_type =
2087 curr_piece_source_value.GetValueType();
2088 switch (curr_piece_source_value_type) {
2089 case Value::eValueTypeLoadAddress:
2091 if (curr_piece.ResizeData(piece_byte_size) == piece_byte_size) {
2092 lldb::addr_t load_addr =
2093 curr_piece_source_value.GetScalar().ULongLong(
2094 LLDB_INVALID_ADDRESS);
2095 if (process->ReadMemory(
2096 load_addr, curr_piece.GetBuffer().GetBytes(),
2097 piece_byte_size, error) != piece_byte_size) {
2099 error_ptr->SetErrorStringWithFormat(
2100 "failed to read memory DW_OP_piece(%" PRIu64
2101 ") from 0x%" PRIx64,
2102 piece_byte_size, load_addr);
2107 error_ptr->SetErrorStringWithFormat(
2108 "failed to resize the piece memory buffer for "
2109 "DW_OP_piece(%" PRIu64 ")",
2116 case Value::eValueTypeFileAddress:
2117 case Value::eValueTypeHostAddress:
2119 lldb::addr_t addr = curr_piece_source_value.GetScalar().ULongLong(
2120 LLDB_INVALID_ADDRESS);
2121 error_ptr->SetErrorStringWithFormat(
2122 "failed to read memory DW_OP_piece(%" PRIu64
2123 ") from %s address 0x%" PRIx64,
2124 piece_byte_size, curr_piece_source_value.GetValueType() ==
2125 Value::eValueTypeFileAddress
2132 case Value::eValueTypeScalar: {
2133 uint32_t bit_size = piece_byte_size * 8;
2134 uint32_t bit_offset = 0;
2135 Scalar &scalar = curr_piece_source_value.GetScalar();
2136 if (!scalar.ExtractBitfield(
2137 bit_size, bit_offset)) {
2139 error_ptr->SetErrorStringWithFormat(
2140 "unable to extract %" PRIu64 " bytes from a %" PRIu64
2141 " byte scalar value.",
2143 (uint64_t)curr_piece_source_value.GetScalar()
2147 // Create curr_piece with bit_size. By default Scalar
2148 // grows to the nearest host integer type.
2149 llvm::APInt fail_value(1, 0, false);
2150 llvm::APInt ap_int = scalar.UInt128(fail_value);
2151 assert(ap_int.getBitWidth() >= bit_size);
2152 llvm::ArrayRef<uint64_t> buf{ap_int.getRawData(),
2153 ap_int.getNumWords()};
2154 curr_piece.GetScalar() = Scalar(llvm::APInt(bit_size, buf));
2157 case Value::eValueTypeVector: {
2158 if (curr_piece_source_value.GetVector().length >= piece_byte_size)
2159 curr_piece_source_value.GetVector().length = piece_byte_size;
2162 error_ptr->SetErrorStringWithFormat(
2163 "unable to extract %" PRIu64 " bytes from a %" PRIu64
2164 " byte vector value.",
2166 (uint64_t)curr_piece_source_value.GetVector().length);
2172 // Check if this is the first piece?
2173 if (op_piece_offset == 0) {
2174 // This is the first piece, we should push it back onto the stack
2175 // so subsequent pieces will be able to access this piece and add
2177 if (pieces.AppendDataToHostBuffer(curr_piece) == 0) {
2179 error_ptr->SetErrorString("failed to append piece data");
2183 // If this is the second or later piece there should be a value on
2185 if (pieces.GetBuffer().GetByteSize() != op_piece_offset) {
2187 error_ptr->SetErrorStringWithFormat(
2188 "DW_OP_piece for offset %" PRIu64
2189 " but top of stack is of size %" PRIu64,
2190 op_piece_offset, pieces.GetBuffer().GetByteSize());
2194 if (pieces.AppendDataToHostBuffer(curr_piece) == 0) {
2196 error_ptr->SetErrorString("failed to append piece data");
2201 op_piece_offset += piece_byte_size;
2205 case DW_OP_bit_piece: // 0x9d ULEB128 bit size, ULEB128 bit offset (DWARF3);
2206 if (stack.size() < 1) {
2208 error_ptr->SetErrorString(
2209 "Expression stack needs at least 1 item for DW_OP_bit_piece.");
2212 const uint64_t piece_bit_size = opcodes.GetULEB128(&offset);
2213 const uint64_t piece_bit_offset = opcodes.GetULEB128(&offset);
2214 switch (stack.back().GetValueType()) {
2215 case Value::eValueTypeScalar: {
2216 if (!stack.back().GetScalar().ExtractBitfield(piece_bit_size,
2217 piece_bit_offset)) {
2219 error_ptr->SetErrorStringWithFormat(
2220 "unable to extract %" PRIu64 " bit value with %" PRIu64
2221 " bit offset from a %" PRIu64 " bit scalar value.",
2222 piece_bit_size, piece_bit_offset,
2223 (uint64_t)(stack.back().GetScalar().GetByteSize() * 8));
2228 case Value::eValueTypeFileAddress:
2229 case Value::eValueTypeLoadAddress:
2230 case Value::eValueTypeHostAddress:
2232 error_ptr->SetErrorStringWithFormat(
2233 "unable to extract DW_OP_bit_piece(bit_size = %" PRIu64
2234 ", bit_offset = %" PRIu64 ") from an address value.",
2235 piece_bit_size, piece_bit_offset);
2239 case Value::eValueTypeVector:
2241 error_ptr->SetErrorStringWithFormat(
2242 "unable to extract DW_OP_bit_piece(bit_size = %" PRIu64
2243 ", bit_offset = %" PRIu64 ") from a vector value.",
2244 piece_bit_size, piece_bit_offset);
2251 // OPCODE: DW_OP_push_object_address
2253 // DESCRIPTION: Pushes the address of the object currently being
2254 // evaluated as part of evaluation of a user presented expression. This
2255 // object may correspond to an independent variable described by its own
2256 // DIE or it may be a component of an array, structure, or class whose
2257 // address has been dynamically determined by an earlier step during user
2258 // expression evaluation.
2259 case DW_OP_push_object_address:
2260 if (object_address_ptr)
2261 stack.push_back(*object_address_ptr);
2264 error_ptr->SetErrorString("DW_OP_push_object_address used without "
2265 "specifying an object address");
2270 // OPCODE: DW_OP_call2
2272 // uint16_t compile unit relative offset of a DIE
2273 // DESCRIPTION: Performs subroutine calls during evaluation
2274 // of a DWARF expression. The operand is the 2-byte unsigned offset of a
2275 // debugging information entry in the current compilation unit.
2277 // Operand interpretation is exactly like that for DW_FORM_ref2.
2279 // This operation transfers control of DWARF expression evaluation to the
2280 // DW_AT_location attribute of the referenced DIE. If there is no such
2281 // attribute, then there is no effect. Execution of the DWARF expression of
2282 // a DW_AT_location attribute may add to and/or remove from values on the
2283 // stack. Execution returns to the point following the call when the end of
2284 // the attribute is reached. Values on the stack at the time of the call
2285 // may be used as parameters by the called expression and values left on
2286 // the stack by the called expression may be used as return values by prior
2287 // agreement between the calling and called expressions.
2290 error_ptr->SetErrorString("Unimplemented opcode DW_OP_call2.");
2292 // OPCODE: DW_OP_call4
2294 // uint32_t compile unit relative offset of a DIE
2295 // DESCRIPTION: Performs a subroutine call during evaluation of a DWARF
2296 // expression. For DW_OP_call4, the operand is a 4-byte unsigned offset of
2297 // a debugging information entry in the current compilation unit.
2299 // Operand interpretation DW_OP_call4 is exactly like that for
2302 // This operation transfers control of DWARF expression evaluation to the
2303 // DW_AT_location attribute of the referenced DIE. If there is no such
2304 // attribute, then there is no effect. Execution of the DWARF expression of
2305 // a DW_AT_location attribute may add to and/or remove from values on the
2306 // stack. Execution returns to the point following the call when the end of
2307 // the attribute is reached. Values on the stack at the time of the call
2308 // may be used as parameters by the called expression and values left on
2309 // the stack by the called expression may be used as return values by prior
2310 // agreement between the calling and called expressions.
2313 error_ptr->SetErrorString("Unimplemented opcode DW_OP_call4.");
2316 // OPCODE: DW_OP_stack_value
2318 // DESCRIPTION: Specifies that the object does not exist in memory but
2319 // rather is a constant value. The value from the top of the stack is the
2320 // value to be used. This is the actual object value and not the location.
2321 case DW_OP_stack_value:
2322 stack.back().SetValueType(Value::eValueTypeScalar);
2325 // OPCODE: DW_OP_convert
2327 // A ULEB128 that is either a DIE offset of a
2328 // DW_TAG_base_type or 0 for the generic (pointer-sized) type.
2330 // DESCRIPTION: Pop the top stack element, convert it to a
2331 // different type, and push the result.
2332 case DW_OP_convert: {
2333 if (stack.size() < 1) {
2335 error_ptr->SetErrorString(
2336 "Expression stack needs at least 1 item for DW_OP_convert.");
2339 const uint64_t die_offset = opcodes.GetULEB128(&offset);
2340 Scalar::Type type = Scalar::e_void;
2342 if (die_offset == 0) {
2343 // The generic type has the size of an address on the target
2344 // machine and an unspecified signedness. Scalar has no
2345 // "unspecified signedness", so we use unsigned types.
2348 error_ptr->SetErrorString("No module");
2351 bit_size = module_sp->GetArchitecture().GetAddressByteSize() * 8;
2354 error_ptr->SetErrorString("unspecified architecture");
2357 type = Scalar::GetBestTypeForBitSize(bit_size, false);
2359 // Retrieve the type DIE that the value is being converted to.
2360 // FIXME: the constness has annoying ripple effects.
2361 DWARFDIE die = const_cast<DWARFUnit *>(dwarf_cu)->GetDIE(die_offset);
2364 error_ptr->SetErrorString("Cannot resolve DW_OP_convert type DIE");
2368 die.GetAttributeValueAsUnsigned(DW_AT_encoding, DW_ATE_hi_user);
2369 bit_size = die.GetAttributeValueAsUnsigned(DW_AT_byte_size, 0) * 8;
2371 bit_size = die.GetAttributeValueAsUnsigned(DW_AT_bit_size, 0);
2374 error_ptr->SetErrorString("Unsupported type size in DW_OP_convert");
2379 case DW_ATE_signed_char:
2380 type = Scalar::GetBestTypeForBitSize(bit_size, true);
2382 case DW_ATE_unsigned:
2383 case DW_ATE_unsigned_char:
2384 type = Scalar::GetBestTypeForBitSize(bit_size, false);
2388 error_ptr->SetErrorString("Unsupported encoding in DW_OP_convert");
2392 if (type == Scalar::e_void) {
2394 error_ptr->SetErrorString("Unsupported pointer size");
2397 Scalar &top = stack.back().ResolveValue(exe_ctx);
2398 top.TruncOrExtendTo(type, bit_size);
2402 // OPCODE: DW_OP_call_frame_cfa
2404 // DESCRIPTION: Specifies a DWARF expression that pushes the value of
2405 // the canonical frame address consistent with the call frame information
2406 // located in .debug_frame (or in the FDEs of the eh_frame section).
2407 case DW_OP_call_frame_cfa:
2409 // Note that we don't have to parse FDEs because this DWARF expression
2410 // is commonly evaluated with a valid stack frame.
2411 StackID id = frame->GetStackID();
2412 addr_t cfa = id.GetCallFrameAddress();
2413 if (cfa != LLDB_INVALID_ADDRESS) {
2414 stack.push_back(Scalar(cfa));
2415 stack.back().SetValueType(Value::eValueTypeLoadAddress);
2416 } else if (error_ptr)
2417 error_ptr->SetErrorString("Stack frame does not include a canonical "
2418 "frame address for DW_OP_call_frame_cfa "
2422 error_ptr->SetErrorString("Invalid stack frame in context for "
2423 "DW_OP_call_frame_cfa opcode.");
2428 // OPCODE: DW_OP_form_tls_address (or the old pre-DWARFv3 vendor extension
2429 // opcode, DW_OP_GNU_push_tls_address)
2431 // DESCRIPTION: Pops a TLS offset from the stack, converts it to
2432 // an address in the current thread's thread-local storage block, and
2433 // pushes it on the stack.
2434 case DW_OP_form_tls_address:
2435 case DW_OP_GNU_push_tls_address: {
2436 if (stack.size() < 1) {
2438 if (op == DW_OP_form_tls_address)
2439 error_ptr->SetErrorString(
2440 "DW_OP_form_tls_address needs an argument.");
2442 error_ptr->SetErrorString(
2443 "DW_OP_GNU_push_tls_address needs an argument.");
2448 if (!exe_ctx || !module_sp) {
2450 error_ptr->SetErrorString("No context to evaluate TLS within.");
2454 Thread *thread = exe_ctx->GetThreadPtr();
2457 error_ptr->SetErrorString("No thread to evaluate TLS within.");
2461 // Lookup the TLS block address for this thread and module.
2462 const addr_t tls_file_addr =
2463 stack.back().GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
2464 const addr_t tls_load_addr =
2465 thread->GetThreadLocalData(module_sp, tls_file_addr);
2467 if (tls_load_addr == LLDB_INVALID_ADDRESS) {
2469 error_ptr->SetErrorString(
2470 "No TLS data currently exists for this thread.");
2474 stack.back().GetScalar() = tls_load_addr;
2475 stack.back().SetValueType(Value::eValueTypeLoadAddress);
2478 // OPCODE: DW_OP_addrx (DW_OP_GNU_addr_index is the legacy name.)
2480 // ULEB128: index to the .debug_addr section
2481 // DESCRIPTION: Pushes an address to the stack from the .debug_addr
2482 // section with the base address specified by the DW_AT_addr_base attribute
2483 // and the 0 based index is the ULEB128 encoded index.
2485 case DW_OP_GNU_addr_index: {
2488 error_ptr->SetErrorString("DW_OP_GNU_addr_index found without a "
2489 "compile unit being specified");
2492 uint64_t index = opcodes.GetULEB128(&offset);
2493 lldb::addr_t value = ReadAddressFromDebugAddrSection(dwarf_cu, index);
2494 stack.push_back(Scalar(value));
2495 stack.back().SetValueType(Value::eValueTypeFileAddress);
2498 // OPCODE: DW_OP_GNU_const_index
2500 // ULEB128: index to the .debug_addr section
2501 // DESCRIPTION: Pushes an constant with the size of a machine address to
2502 // the stack from the .debug_addr section with the base address specified
2503 // by the DW_AT_addr_base attribute and the 0 based index is the ULEB128
2505 case DW_OP_GNU_const_index: {
2508 error_ptr->SetErrorString("DW_OP_GNU_const_index found without a "
2509 "compile unit being specified");
2512 uint64_t index = opcodes.GetULEB128(&offset);
2513 lldb::addr_t value = ReadAddressFromDebugAddrSection(dwarf_cu, index);
2514 stack.push_back(Scalar(value));
2517 case DW_OP_entry_value: {
2518 if (!Evaluate_DW_OP_entry_value(stack, exe_ctx, reg_ctx, opcodes, offset,
2520 LLDB_ERRORF(error_ptr, "Could not evaluate %s.",
2521 DW_OP_value_to_name(op));
2528 LLDB_LOGF(log, "Unhandled opcode %s in DWARFExpression.",
2529 DW_OP_value_to_name(op));
2534 if (stack.empty()) {
2535 // Nothing on the stack, check if we created a piece value from DW_OP_piece
2536 // or DW_OP_bit_piece opcodes
2537 if (pieces.GetBuffer().GetByteSize()) {
2541 error_ptr->SetErrorString("Stack empty after evaluation.");
2545 if (log && log->GetVerbose()) {
2546 size_t count = stack.size();
2547 LLDB_LOGF(log, "Stack after operation has %" PRIu64 " values:",
2549 for (size_t i = 0; i < count; ++i) {
2550 StreamString new_value;
2551 new_value.Printf("[%" PRIu64 "]", (uint64_t)i);
2552 stack[i].Dump(&new_value);
2553 LLDB_LOGF(log, " %s", new_value.GetData());
2556 result = stack.back();
2558 return true; // Return true on success
2561 static bool print_dwarf_exp_op(Stream &s, const DataExtractor &data,
2562 lldb::offset_t *offset_ptr, int address_size,
2563 int dwarf_ref_size) {
2564 uint8_t opcode = data.GetU8(offset_ptr);
2565 DRC_class opcode_class;
2571 opcode_class = DW_OP_value_to_class(opcode) & (~DRC_DWARFv3);
2573 s.Printf("%s ", DW_OP_value_to_name(opcode));
2575 /* Does this take zero parameters? If so we can shortcut this function. */
2576 if (opcode_class == DRC_ZEROOPERANDS)
2579 if (opcode_class == DRC_TWOOPERANDS && opcode == DW_OP_bregx) {
2580 uint = data.GetULEB128(offset_ptr);
2581 sint = data.GetSLEB128(offset_ptr);
2582 s.Printf("%" PRIu64 " %" PRIi64, uint, sint);
2585 if (opcode_class == DRC_TWOOPERANDS && opcode == DW_OP_entry_value) {
2586 uint = data.GetULEB128(offset_ptr);
2587 s.Printf("%" PRIu64 " ", uint);
2590 if (opcode_class != DRC_ONEOPERAND) {
2591 s.Printf("UNKNOWN OP %u", opcode);
2597 size = address_size;
2667 case DW_OP_deref_size:
2668 case DW_OP_xderef_size:
2681 case DW_OP_call_ref:
2682 size = dwarf_ref_size;
2686 case DW_OP_plus_uconst:
2688 case DW_OP_GNU_addr_index:
2689 case DW_OP_GNU_const_index:
2690 case DW_OP_entry_value:
2694 s.Printf("UNKNOWN ONE-OPERAND OPCODE, #%u", opcode);
2700 sint = (int8_t)data.GetU8(offset_ptr);
2701 s.Printf("%+" PRIi64, sint);
2704 sint = (int16_t)data.GetU16(offset_ptr);
2705 s.Printf("%+" PRIi64, sint);
2708 sint = (int32_t)data.GetU32(offset_ptr);
2709 s.Printf("%+" PRIi64, sint);
2712 sint = (int64_t)data.GetU64(offset_ptr);
2713 s.Printf("%+" PRIi64, sint);
2716 sint = data.GetSLEB128(offset_ptr);
2717 s.Printf("%+" PRIi64, sint);
2720 uint = data.GetU8(offset_ptr);
2721 s.Printf("0x%2.2" PRIx64, uint);
2724 uint = data.GetU16(offset_ptr);
2725 s.Printf("0x%4.4" PRIx64, uint);
2728 uint = data.GetU32(offset_ptr);
2729 s.Printf("0x%8.8" PRIx64, uint);
2732 uint = data.GetU64(offset_ptr);
2733 s.Printf("0x%16.16" PRIx64, uint);
2736 uint = data.GetULEB128(offset_ptr);
2737 s.Printf("0x%" PRIx64, uint);
2744 bool DWARFExpression::PrintDWARFExpression(Stream &s, const DataExtractor &data,
2745 int address_size, int dwarf_ref_size,
2746 bool location_expression) {
2748 lldb::offset_t offset = 0;
2749 while (data.ValidOffset(offset)) {
2750 if (location_expression && op_count > 0)
2754 if (!print_dwarf_exp_op(s, data, &offset, address_size, dwarf_ref_size))
2762 void DWARFExpression::PrintDWARFLocationList(
2763 Stream &s, const DWARFUnit *cu, const DataExtractor &debug_loc_data,
2764 lldb::offset_t offset) {
2765 uint64_t start_addr, end_addr;
2766 uint32_t addr_size = DWARFUnit::GetAddressByteSize(cu);
2767 s.SetAddressByteSize(DWARFUnit::GetAddressByteSize(cu));
2768 dw_addr_t base_addr = cu ? cu->GetBaseAddress() : 0;
2769 while (debug_loc_data.ValidOffset(offset)) {
2770 start_addr = debug_loc_data.GetMaxU64(&offset, addr_size);
2771 end_addr = debug_loc_data.GetMaxU64(&offset, addr_size);
2773 if (start_addr == 0 && end_addr == 0)
2776 s.PutCString("\n ");
2779 DumpAddressRange(s.AsRawOstream(), start_addr + base_addr,
2780 end_addr + base_addr, cu->GetAddressByteSize(), nullptr,
2782 uint32_t loc_length = debug_loc_data.GetU16(&offset);
2784 DataExtractor locationData(debug_loc_data, offset, loc_length);
2785 PrintDWARFExpression(s, locationData, addr_size, 4, false);
2786 offset += loc_length;
2790 static DataExtractor ToDataExtractor(const llvm::DWARFLocationExpression &loc,
2791 ByteOrder byte_order, uint32_t addr_size) {
2793 std::make_shared<DataBufferHeap>(loc.Expr.data(), loc.Expr.size());
2794 return DataExtractor(buffer_sp, byte_order, addr_size);
2797 llvm::Optional<DataExtractor>
2798 DWARFExpression::GetLocationExpression(addr_t load_function_start,
2799 addr_t addr) const {
2800 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
2802 std::unique_ptr<llvm::DWARFLocationTable> loctable_up =
2803 m_dwarf_cu->GetLocationTable(m_data);
2804 llvm::Optional<DataExtractor> result;
2805 uint64_t offset = 0;
2807 [&](uint32_t index) -> llvm::Optional<llvm::object::SectionedAddress> {
2808 addr_t address = ReadAddressFromDebugAddrSection(m_dwarf_cu, index);
2809 if (address == LLDB_INVALID_ADDRESS)
2811 return llvm::object::SectionedAddress{address};
2813 auto process_list = [&](llvm::Expected<llvm::DWARFLocationExpression> loc) {
2815 LLDB_LOG_ERROR(log, loc.takeError(), "{0}");
2819 // This relocates low_pc and high_pc by adding the difference between the
2820 // function file address, and the actual address it is loaded in memory.
2821 addr_t slide = load_function_start - m_loclist_addresses->func_file_addr;
2822 loc->Range->LowPC += slide;
2823 loc->Range->HighPC += slide;
2825 if (loc->Range->LowPC <= addr && addr < loc->Range->HighPC)
2826 result = ToDataExtractor(*loc, m_data.GetByteOrder(),
2827 m_data.GetAddressByteSize());
2831 llvm::Error E = loctable_up->visitAbsoluteLocationList(
2832 offset, llvm::object::SectionedAddress{m_loclist_addresses->cu_file_addr},
2833 lookup_addr, process_list);
2835 LLDB_LOG_ERROR(log, std::move(E), "{0}");
2839 bool DWARFExpression::MatchesOperand(StackFrame &frame,
2840 const Instruction::Operand &operand) {
2841 using namespace OperandMatchers;
2843 RegisterContextSP reg_ctx_sp = frame.GetRegisterContext();
2848 DataExtractor opcodes;
2849 if (IsLocationList()) {
2850 SymbolContext sc = frame.GetSymbolContext(eSymbolContextFunction);
2854 addr_t load_function_start =
2855 sc.function->GetAddressRange().GetBaseAddress().GetFileAddress();
2856 if (load_function_start == LLDB_INVALID_ADDRESS)
2859 addr_t pc = frame.GetFrameCodeAddress().GetLoadAddress(
2860 frame.CalculateTarget().get());
2862 if (llvm::Optional<DataExtractor> expr = GetLocationExpression(load_function_start, pc))
2863 opcodes = std::move(*expr);
2870 lldb::offset_t op_offset = 0;
2871 uint8_t opcode = opcodes.GetU8(&op_offset);
2873 if (opcode == DW_OP_fbreg) {
2874 int64_t offset = opcodes.GetSLEB128(&op_offset);
2876 DWARFExpression *fb_expr = frame.GetFrameBaseExpression(nullptr);
2881 auto recurse = [&frame, fb_expr](const Instruction::Operand &child) {
2882 return fb_expr->MatchesOperand(frame, child);
2886 MatchUnaryOp(MatchOpType(Instruction::Operand::Type::Dereference),
2887 recurse)(operand)) {
2891 return MatchUnaryOp(
2892 MatchOpType(Instruction::Operand::Type::Dereference),
2893 MatchBinaryOp(MatchOpType(Instruction::Operand::Type::Sum),
2894 MatchImmOp(offset), recurse))(operand);
2897 bool dereference = false;
2898 const RegisterInfo *reg = nullptr;
2901 if (opcode >= DW_OP_reg0 && opcode <= DW_OP_reg31) {
2902 reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, opcode - DW_OP_reg0);
2903 } else if (opcode >= DW_OP_breg0 && opcode <= DW_OP_breg31) {
2904 offset = opcodes.GetSLEB128(&op_offset);
2905 reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, opcode - DW_OP_breg0);
2906 } else if (opcode == DW_OP_regx) {
2907 uint32_t reg_num = static_cast<uint32_t>(opcodes.GetULEB128(&op_offset));
2908 reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, reg_num);
2909 } else if (opcode == DW_OP_bregx) {
2910 uint32_t reg_num = static_cast<uint32_t>(opcodes.GetULEB128(&op_offset));
2911 offset = opcodes.GetSLEB128(&op_offset);
2912 reg = reg_ctx_sp->GetRegisterInfo(m_reg_kind, reg_num);
2923 MatchUnaryOp(MatchOpType(Instruction::Operand::Type::Dereference),
2924 MatchRegOp(*reg))(operand)) {
2928 return MatchUnaryOp(
2929 MatchOpType(Instruction::Operand::Type::Dereference),
2930 MatchBinaryOp(MatchOpType(Instruction::Operand::Type::Sum),
2932 MatchImmOp(offset)))(operand);
2934 return MatchRegOp(*reg)(operand);