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