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