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