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