1 //===-- DWARFCallFrameInfo.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/Symbol/DWARFCallFrameInfo.h"
10 #include "lldb/Core/Module.h"
11 #include "lldb/Core/Section.h"
12 #include "lldb/Core/dwarf.h"
13 #include "lldb/Host/Host.h"
14 #include "lldb/Symbol/ObjectFile.h"
15 #include "lldb/Symbol/UnwindPlan.h"
16 #include "lldb/Target/RegisterContext.h"
17 #include "lldb/Target/Thread.h"
18 #include "lldb/Utility/ArchSpec.h"
19 #include "lldb/Utility/LLDBLog.h"
20 #include "lldb/Utility/Log.h"
21 #include "lldb/Utility/Timer.h"
22 #include <cstring>
23 #include <list>
24 
25 using namespace lldb;
26 using namespace lldb_private;
27 
28 // GetDwarfEHPtr
29 //
30 // Used for calls when the value type is specified by a DWARF EH Frame pointer
31 // encoding.
32 static uint64_t
33 GetGNUEHPointer(const DataExtractor &DE, offset_t *offset_ptr,
34                 uint32_t eh_ptr_enc, addr_t pc_rel_addr, addr_t text_addr,
35                 addr_t data_addr) //, BSDRelocs *data_relocs) const
36 {
37   if (eh_ptr_enc == DW_EH_PE_omit)
38     return ULLONG_MAX; // Value isn't in the buffer...
39 
40   uint64_t baseAddress = 0;
41   uint64_t addressValue = 0;
42   const uint32_t addr_size = DE.GetAddressByteSize();
43   assert(addr_size == 4 || addr_size == 8);
44 
45   bool signExtendValue = false;
46   // Decode the base part or adjust our offset
47   switch (eh_ptr_enc & 0x70) {
48   case DW_EH_PE_pcrel:
49     signExtendValue = true;
50     baseAddress = *offset_ptr;
51     if (pc_rel_addr != LLDB_INVALID_ADDRESS)
52       baseAddress += pc_rel_addr;
53     //      else
54     //          Log::GlobalWarning ("PC relative pointer encoding found with
55     //          invalid pc relative address.");
56     break;
57 
58   case DW_EH_PE_textrel:
59     signExtendValue = true;
60     if (text_addr != LLDB_INVALID_ADDRESS)
61       baseAddress = text_addr;
62     //      else
63     //          Log::GlobalWarning ("text relative pointer encoding being
64     //          decoded with invalid text section address, setting base address
65     //          to zero.");
66     break;
67 
68   case DW_EH_PE_datarel:
69     signExtendValue = true;
70     if (data_addr != LLDB_INVALID_ADDRESS)
71       baseAddress = data_addr;
72     //      else
73     //          Log::GlobalWarning ("data relative pointer encoding being
74     //          decoded with invalid data section address, setting base address
75     //          to zero.");
76     break;
77 
78   case DW_EH_PE_funcrel:
79     signExtendValue = true;
80     break;
81 
82   case DW_EH_PE_aligned: {
83     // SetPointerSize should be called prior to extracting these so the pointer
84     // size is cached
85     assert(addr_size != 0);
86     if (addr_size) {
87       // Align to a address size boundary first
88       uint32_t alignOffset = *offset_ptr % addr_size;
89       if (alignOffset)
90         offset_ptr += addr_size - alignOffset;
91     }
92   } break;
93 
94   default:
95     break;
96   }
97 
98   // Decode the value part
99   switch (eh_ptr_enc & DW_EH_PE_MASK_ENCODING) {
100   case DW_EH_PE_absptr: {
101     addressValue = DE.GetAddress(offset_ptr);
102     //          if (data_relocs)
103     //              addressValue = data_relocs->Relocate(*offset_ptr -
104     //              addr_size, *this, addressValue);
105   } break;
106   case DW_EH_PE_uleb128:
107     addressValue = DE.GetULEB128(offset_ptr);
108     break;
109   case DW_EH_PE_udata2:
110     addressValue = DE.GetU16(offset_ptr);
111     break;
112   case DW_EH_PE_udata4:
113     addressValue = DE.GetU32(offset_ptr);
114     break;
115   case DW_EH_PE_udata8:
116     addressValue = DE.GetU64(offset_ptr);
117     break;
118   case DW_EH_PE_sleb128:
119     addressValue = DE.GetSLEB128(offset_ptr);
120     break;
121   case DW_EH_PE_sdata2:
122     addressValue = (int16_t)DE.GetU16(offset_ptr);
123     break;
124   case DW_EH_PE_sdata4:
125     addressValue = (int32_t)DE.GetU32(offset_ptr);
126     break;
127   case DW_EH_PE_sdata8:
128     addressValue = (int64_t)DE.GetU64(offset_ptr);
129     break;
130   default:
131     // Unhandled encoding type
132     assert(eh_ptr_enc);
133     break;
134   }
135 
136   // Since we promote everything to 64 bit, we may need to sign extend
137   if (signExtendValue && addr_size < sizeof(baseAddress)) {
138     uint64_t sign_bit = 1ull << ((addr_size * 8ull) - 1ull);
139     if (sign_bit & addressValue) {
140       uint64_t mask = ~sign_bit + 1;
141       addressValue |= mask;
142     }
143   }
144   return baseAddress + addressValue;
145 }
146 
147 DWARFCallFrameInfo::DWARFCallFrameInfo(ObjectFile &objfile,
148                                        SectionSP &section_sp, Type type)
149     : m_objfile(objfile), m_section_sp(section_sp), m_type(type) {}
150 
151 bool DWARFCallFrameInfo::GetUnwindPlan(const Address &addr,
152                                        UnwindPlan &unwind_plan) {
153   return GetUnwindPlan(AddressRange(addr, 1), unwind_plan);
154 }
155 
156 bool DWARFCallFrameInfo::GetUnwindPlan(const AddressRange &range,
157                                        UnwindPlan &unwind_plan) {
158   FDEEntryMap::Entry fde_entry;
159   Address addr = range.GetBaseAddress();
160 
161   // Make sure that the Address we're searching for is the same object file as
162   // this DWARFCallFrameInfo, we only store File offsets in m_fde_index.
163   ModuleSP module_sp = addr.GetModule();
164   if (module_sp.get() == nullptr || module_sp->GetObjectFile() == nullptr ||
165       module_sp->GetObjectFile() != &m_objfile)
166     return false;
167 
168   if (llvm::Optional<FDEEntryMap::Entry> entry = GetFirstFDEEntryInRange(range))
169     return FDEToUnwindPlan(entry->data, addr, unwind_plan);
170   return false;
171 }
172 
173 bool DWARFCallFrameInfo::GetAddressRange(Address addr, AddressRange &range) {
174 
175   // Make sure that the Address we're searching for is the same object file as
176   // this DWARFCallFrameInfo, we only store File offsets in m_fde_index.
177   ModuleSP module_sp = addr.GetModule();
178   if (module_sp.get() == nullptr || module_sp->GetObjectFile() == nullptr ||
179       module_sp->GetObjectFile() != &m_objfile)
180     return false;
181 
182   if (m_section_sp.get() == nullptr || m_section_sp->IsEncrypted())
183     return false;
184   GetFDEIndex();
185   FDEEntryMap::Entry *fde_entry =
186       m_fde_index.FindEntryThatContains(addr.GetFileAddress());
187   if (!fde_entry)
188     return false;
189 
190   range = AddressRange(fde_entry->base, fde_entry->size,
191                        m_objfile.GetSectionList());
192   return true;
193 }
194 
195 llvm::Optional<DWARFCallFrameInfo::FDEEntryMap::Entry>
196 DWARFCallFrameInfo::GetFirstFDEEntryInRange(const AddressRange &range) {
197   if (!m_section_sp || m_section_sp->IsEncrypted())
198     return llvm::None;
199 
200   GetFDEIndex();
201 
202   addr_t start_file_addr = range.GetBaseAddress().GetFileAddress();
203   const FDEEntryMap::Entry *fde =
204       m_fde_index.FindEntryThatContainsOrFollows(start_file_addr);
205   if (fde && fde->DoesIntersect(
206                  FDEEntryMap::Range(start_file_addr, range.GetByteSize())))
207     return *fde;
208 
209   return llvm::None;
210 }
211 
212 void DWARFCallFrameInfo::GetFunctionAddressAndSizeVector(
213     FunctionAddressAndSizeVector &function_info) {
214   GetFDEIndex();
215   const size_t count = m_fde_index.GetSize();
216   function_info.Clear();
217   if (count > 0)
218     function_info.Reserve(count);
219   for (size_t i = 0; i < count; ++i) {
220     const FDEEntryMap::Entry *func_offset_data_entry =
221         m_fde_index.GetEntryAtIndex(i);
222     if (func_offset_data_entry) {
223       FunctionAddressAndSizeVector::Entry function_offset_entry(
224           func_offset_data_entry->base, func_offset_data_entry->size);
225       function_info.Append(function_offset_entry);
226     }
227   }
228 }
229 
230 const DWARFCallFrameInfo::CIE *
231 DWARFCallFrameInfo::GetCIE(dw_offset_t cie_offset) {
232   cie_map_t::iterator pos = m_cie_map.find(cie_offset);
233 
234   if (pos != m_cie_map.end()) {
235     // Parse and cache the CIE
236     if (pos->second == nullptr)
237       pos->second = ParseCIE(cie_offset);
238 
239     return pos->second.get();
240   }
241   return nullptr;
242 }
243 
244 DWARFCallFrameInfo::CIESP
245 DWARFCallFrameInfo::ParseCIE(const dw_offset_t cie_offset) {
246   CIESP cie_sp(new CIE(cie_offset));
247   lldb::offset_t offset = cie_offset;
248   if (!m_cfi_data_initialized)
249     GetCFIData();
250   uint32_t length = m_cfi_data.GetU32(&offset);
251   dw_offset_t cie_id, end_offset;
252   bool is_64bit = (length == UINT32_MAX);
253   if (is_64bit) {
254     length = m_cfi_data.GetU64(&offset);
255     cie_id = m_cfi_data.GetU64(&offset);
256     end_offset = cie_offset + length + 12;
257   } else {
258     cie_id = m_cfi_data.GetU32(&offset);
259     end_offset = cie_offset + length + 4;
260   }
261   if (length > 0 && ((m_type == DWARF && cie_id == UINT32_MAX) ||
262                      (m_type == EH && cie_id == 0ul))) {
263     size_t i;
264     //    cie.offset = cie_offset;
265     //    cie.length = length;
266     //    cie.cieID = cieID;
267     cie_sp->ptr_encoding = DW_EH_PE_absptr; // default
268     cie_sp->version = m_cfi_data.GetU8(&offset);
269     if (cie_sp->version > CFI_VERSION4) {
270       Host::SystemLog(Host::eSystemLogError,
271                       "CIE parse error: CFI version %d is not supported\n",
272                       cie_sp->version);
273       return nullptr;
274     }
275 
276     for (i = 0; i < CFI_AUG_MAX_SIZE; ++i) {
277       cie_sp->augmentation[i] = m_cfi_data.GetU8(&offset);
278       if (cie_sp->augmentation[i] == '\0') {
279         // Zero out remaining bytes in augmentation string
280         for (size_t j = i + 1; j < CFI_AUG_MAX_SIZE; ++j)
281           cie_sp->augmentation[j] = '\0';
282 
283         break;
284       }
285     }
286 
287     if (i == CFI_AUG_MAX_SIZE &&
288         cie_sp->augmentation[CFI_AUG_MAX_SIZE - 1] != '\0') {
289       Host::SystemLog(Host::eSystemLogError,
290                       "CIE parse error: CIE augmentation string was too large "
291                       "for the fixed sized buffer of %d bytes.\n",
292                       CFI_AUG_MAX_SIZE);
293       return nullptr;
294     }
295 
296     // m_cfi_data uses address size from target architecture of the process may
297     // ignore these fields?
298     if (m_type == DWARF && cie_sp->version >= CFI_VERSION4) {
299       cie_sp->address_size = m_cfi_data.GetU8(&offset);
300       cie_sp->segment_size = m_cfi_data.GetU8(&offset);
301     }
302 
303     cie_sp->code_align = (uint32_t)m_cfi_data.GetULEB128(&offset);
304     cie_sp->data_align = (int32_t)m_cfi_data.GetSLEB128(&offset);
305 
306     cie_sp->return_addr_reg_num =
307         m_type == DWARF && cie_sp->version >= CFI_VERSION3
308             ? static_cast<uint32_t>(m_cfi_data.GetULEB128(&offset))
309             : m_cfi_data.GetU8(&offset);
310 
311     if (cie_sp->augmentation[0]) {
312       // Get the length of the eh_frame augmentation data which starts with a
313       // ULEB128 length in bytes
314       const size_t aug_data_len = (size_t)m_cfi_data.GetULEB128(&offset);
315       const size_t aug_data_end = offset + aug_data_len;
316       const size_t aug_str_len = strlen(cie_sp->augmentation);
317       // A 'z' may be present as the first character of the string.
318       // If present, the Augmentation Data field shall be present. The contents
319       // of the Augmentation Data shall be interpreted according to other
320       // characters in the Augmentation String.
321       if (cie_sp->augmentation[0] == 'z') {
322         // Extract the Augmentation Data
323         size_t aug_str_idx = 0;
324         for (aug_str_idx = 1; aug_str_idx < aug_str_len; aug_str_idx++) {
325           char aug = cie_sp->augmentation[aug_str_idx];
326           switch (aug) {
327           case 'L':
328             // Indicates the presence of one argument in the Augmentation Data
329             // of the CIE, and a corresponding argument in the Augmentation
330             // Data of the FDE. The argument in the Augmentation Data of the
331             // CIE is 1-byte and represents the pointer encoding used for the
332             // argument in the Augmentation Data of the FDE, which is the
333             // address of a language-specific data area (LSDA). The size of the
334             // LSDA pointer is specified by the pointer encoding used.
335             cie_sp->lsda_addr_encoding = m_cfi_data.GetU8(&offset);
336             break;
337 
338           case 'P':
339             // Indicates the presence of two arguments in the Augmentation Data
340             // of the CIE. The first argument is 1-byte and represents the
341             // pointer encoding used for the second argument, which is the
342             // address of a personality routine handler. The size of the
343             // personality routine pointer is specified by the pointer encoding
344             // used.
345             //
346             // The address of the personality function will be stored at this
347             // location.  Pre-execution, it will be all zero's so don't read it
348             // until we're trying to do an unwind & the reloc has been
349             // resolved.
350             {
351               uint8_t arg_ptr_encoding = m_cfi_data.GetU8(&offset);
352               const lldb::addr_t pc_rel_addr = m_section_sp->GetFileAddress();
353               cie_sp->personality_loc = GetGNUEHPointer(
354                   m_cfi_data, &offset, arg_ptr_encoding, pc_rel_addr,
355                   LLDB_INVALID_ADDRESS, LLDB_INVALID_ADDRESS);
356             }
357             break;
358 
359           case 'R':
360             // A 'R' may be present at any position after the
361             // first character of the string. The Augmentation Data shall
362             // include a 1 byte argument that represents the pointer encoding
363             // for the address pointers used in the FDE. Example: 0x1B ==
364             // DW_EH_PE_pcrel | DW_EH_PE_sdata4
365             cie_sp->ptr_encoding = m_cfi_data.GetU8(&offset);
366             break;
367           }
368         }
369       } else if (strcmp(cie_sp->augmentation, "eh") == 0) {
370         // If the Augmentation string has the value "eh", then the EH Data
371         // field shall be present
372       }
373 
374       // Set the offset to be the end of the augmentation data just in case we
375       // didn't understand any of the data.
376       offset = (uint32_t)aug_data_end;
377     }
378 
379     if (end_offset > offset) {
380       cie_sp->inst_offset = offset;
381       cie_sp->inst_length = end_offset - offset;
382     }
383     while (offset < end_offset) {
384       uint8_t inst = m_cfi_data.GetU8(&offset);
385       uint8_t primary_opcode = inst & 0xC0;
386       uint8_t extended_opcode = inst & 0x3F;
387 
388       if (!HandleCommonDwarfOpcode(primary_opcode, extended_opcode,
389                                    cie_sp->data_align, offset,
390                                    cie_sp->initial_row))
391         break; // Stop if we hit an unrecognized opcode
392     }
393   }
394 
395   return cie_sp;
396 }
397 
398 void DWARFCallFrameInfo::GetCFIData() {
399   if (!m_cfi_data_initialized) {
400     Log *log = GetLog(LLDBLog::Unwind);
401     if (log)
402       m_objfile.GetModule()->LogMessage(log, "Reading EH frame info");
403     m_objfile.ReadSectionData(m_section_sp.get(), m_cfi_data);
404     m_cfi_data_initialized = true;
405   }
406 }
407 // Scan through the eh_frame or debug_frame section looking for FDEs and noting
408 // the start/end addresses of the functions and a pointer back to the
409 // function's FDE for later expansion. Internalize CIEs as we come across them.
410 
411 void DWARFCallFrameInfo::GetFDEIndex() {
412   if (m_section_sp.get() == nullptr || m_section_sp->IsEncrypted())
413     return;
414 
415   if (m_fde_index_initialized)
416     return;
417 
418   std::lock_guard<std::mutex> guard(m_fde_index_mutex);
419 
420   if (m_fde_index_initialized) // if two threads hit the locker
421     return;
422 
423   LLDB_SCOPED_TIMERF("%s - %s", LLVM_PRETTY_FUNCTION,
424                      m_objfile.GetFileSpec().GetFilename().AsCString(""));
425 
426   bool clear_address_zeroth_bit = false;
427   if (ArchSpec arch = m_objfile.GetArchitecture()) {
428     if (arch.GetTriple().getArch() == llvm::Triple::arm ||
429         arch.GetTriple().getArch() == llvm::Triple::thumb)
430       clear_address_zeroth_bit = true;
431   }
432 
433   lldb::offset_t offset = 0;
434   if (!m_cfi_data_initialized)
435     GetCFIData();
436   while (m_cfi_data.ValidOffsetForDataOfSize(offset, 8)) {
437     const dw_offset_t current_entry = offset;
438     dw_offset_t cie_id, next_entry, cie_offset;
439     uint32_t len = m_cfi_data.GetU32(&offset);
440     bool is_64bit = (len == UINT32_MAX);
441     if (is_64bit) {
442       len = m_cfi_data.GetU64(&offset);
443       cie_id = m_cfi_data.GetU64(&offset);
444       next_entry = current_entry + len + 12;
445       cie_offset = current_entry + 12 - cie_id;
446     } else {
447       cie_id = m_cfi_data.GetU32(&offset);
448       next_entry = current_entry + len + 4;
449       cie_offset = current_entry + 4 - cie_id;
450     }
451 
452     if (next_entry > m_cfi_data.GetByteSize() + 1) {
453       Host::SystemLog(Host::eSystemLogError, "error: Invalid fde/cie next "
454                                              "entry offset of 0x%x found in "
455                                              "cie/fde at 0x%x\n",
456                       next_entry, current_entry);
457       // Don't trust anything in this eh_frame section if we find blatantly
458       // invalid data.
459       m_fde_index.Clear();
460       m_fde_index_initialized = true;
461       return;
462     }
463 
464     // An FDE entry contains CIE_pointer in debug_frame in same place as cie_id
465     // in eh_frame. CIE_pointer is an offset into the .debug_frame section. So,
466     // variable cie_offset should be equal to cie_id for debug_frame.
467     // FDE entries with cie_id == 0 shouldn't be ignored for it.
468     if ((cie_id == 0 && m_type == EH) || cie_id == UINT32_MAX || len == 0) {
469       auto cie_sp = ParseCIE(current_entry);
470       if (!cie_sp) {
471         // Cannot parse, the reason is already logged
472         m_fde_index.Clear();
473         m_fde_index_initialized = true;
474         return;
475       }
476 
477       m_cie_map[current_entry] = std::move(cie_sp);
478       offset = next_entry;
479       continue;
480     }
481 
482     if (m_type == DWARF)
483       cie_offset = cie_id;
484 
485     if (cie_offset > m_cfi_data.GetByteSize()) {
486       Host::SystemLog(Host::eSystemLogError,
487                       "error: Invalid cie offset of 0x%x "
488                       "found in cie/fde at 0x%x\n",
489                       cie_offset, current_entry);
490       // Don't trust anything in this eh_frame section if we find blatantly
491       // invalid data.
492       m_fde_index.Clear();
493       m_fde_index_initialized = true;
494       return;
495     }
496 
497     const CIE *cie = GetCIE(cie_offset);
498     if (cie) {
499       const lldb::addr_t pc_rel_addr = m_section_sp->GetFileAddress();
500       const lldb::addr_t text_addr = LLDB_INVALID_ADDRESS;
501       const lldb::addr_t data_addr = LLDB_INVALID_ADDRESS;
502 
503       lldb::addr_t addr =
504           GetGNUEHPointer(m_cfi_data, &offset, cie->ptr_encoding, pc_rel_addr,
505                           text_addr, data_addr);
506       if (clear_address_zeroth_bit)
507         addr &= ~1ull;
508 
509       lldb::addr_t length = GetGNUEHPointer(
510           m_cfi_data, &offset, cie->ptr_encoding & DW_EH_PE_MASK_ENCODING,
511           pc_rel_addr, text_addr, data_addr);
512       FDEEntryMap::Entry fde(addr, length, current_entry);
513       m_fde_index.Append(fde);
514     } else {
515       Host::SystemLog(Host::eSystemLogError, "error: unable to find CIE at "
516                                              "0x%8.8x for cie_id = 0x%8.8x for "
517                                              "entry at 0x%8.8x.\n",
518                       cie_offset, cie_id, current_entry);
519     }
520     offset = next_entry;
521   }
522   m_fde_index.Sort();
523   m_fde_index_initialized = true;
524 }
525 
526 bool DWARFCallFrameInfo::FDEToUnwindPlan(dw_offset_t dwarf_offset,
527                                          Address startaddr,
528                                          UnwindPlan &unwind_plan) {
529   Log *log = GetLog(LLDBLog::Unwind);
530   lldb::offset_t offset = dwarf_offset;
531   lldb::offset_t current_entry = offset;
532 
533   if (m_section_sp.get() == nullptr || m_section_sp->IsEncrypted())
534     return false;
535 
536   if (!m_cfi_data_initialized)
537     GetCFIData();
538 
539   uint32_t length = m_cfi_data.GetU32(&offset);
540   dw_offset_t cie_offset;
541   bool is_64bit = (length == UINT32_MAX);
542   if (is_64bit) {
543     length = m_cfi_data.GetU64(&offset);
544     cie_offset = m_cfi_data.GetU64(&offset);
545   } else {
546     cie_offset = m_cfi_data.GetU32(&offset);
547   }
548 
549   // FDE entries with zeroth cie_offset may occur for debug_frame.
550   assert(!(m_type == EH && 0 == cie_offset) && cie_offset != UINT32_MAX);
551 
552   // Translate the CIE_id from the eh_frame format, which is relative to the
553   // FDE offset, into a __eh_frame section offset
554   if (m_type == EH) {
555     unwind_plan.SetSourceName("eh_frame CFI");
556     cie_offset = current_entry + (is_64bit ? 12 : 4) - cie_offset;
557     unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolNo);
558   } else {
559     unwind_plan.SetSourceName("DWARF CFI");
560     // In theory the debug_frame info should be valid at all call sites
561     // ("asynchronous unwind info" as it is sometimes called) but in practice
562     // gcc et al all emit call frame info for the prologue and call sites, but
563     // not for the epilogue or all the other locations during the function
564     // reliably.
565     unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolNo);
566   }
567   unwind_plan.SetSourcedFromCompiler(eLazyBoolYes);
568 
569   const CIE *cie = GetCIE(cie_offset);
570   assert(cie != nullptr);
571 
572   const dw_offset_t end_offset = current_entry + length + (is_64bit ? 12 : 4);
573 
574   const lldb::addr_t pc_rel_addr = m_section_sp->GetFileAddress();
575   const lldb::addr_t text_addr = LLDB_INVALID_ADDRESS;
576   const lldb::addr_t data_addr = LLDB_INVALID_ADDRESS;
577   lldb::addr_t range_base =
578       GetGNUEHPointer(m_cfi_data, &offset, cie->ptr_encoding, pc_rel_addr,
579                       text_addr, data_addr);
580   lldb::addr_t range_len = GetGNUEHPointer(
581       m_cfi_data, &offset, cie->ptr_encoding & DW_EH_PE_MASK_ENCODING,
582       pc_rel_addr, text_addr, data_addr);
583   AddressRange range(range_base, m_objfile.GetAddressByteSize(),
584                      m_objfile.GetSectionList());
585   range.SetByteSize(range_len);
586 
587   addr_t lsda_data_file_address = LLDB_INVALID_ADDRESS;
588 
589   if (cie->augmentation[0] == 'z') {
590     uint32_t aug_data_len = (uint32_t)m_cfi_data.GetULEB128(&offset);
591     if (aug_data_len != 0 && cie->lsda_addr_encoding != DW_EH_PE_omit) {
592       offset_t saved_offset = offset;
593       lsda_data_file_address =
594           GetGNUEHPointer(m_cfi_data, &offset, cie->lsda_addr_encoding,
595                           pc_rel_addr, text_addr, data_addr);
596       if (offset - saved_offset != aug_data_len) {
597         // There is more in the augmentation region than we know how to process;
598         // don't read anything.
599         lsda_data_file_address = LLDB_INVALID_ADDRESS;
600       }
601       offset = saved_offset;
602     }
603     offset += aug_data_len;
604   }
605   unwind_plan.SetUnwindPlanForSignalTrap(
606     strchr(cie->augmentation, 'S') ? eLazyBoolYes : eLazyBoolNo);
607 
608   Address lsda_data;
609   Address personality_function_ptr;
610 
611   if (lsda_data_file_address != LLDB_INVALID_ADDRESS &&
612       cie->personality_loc != LLDB_INVALID_ADDRESS) {
613     m_objfile.GetModule()->ResolveFileAddress(lsda_data_file_address,
614                                               lsda_data);
615     m_objfile.GetModule()->ResolveFileAddress(cie->personality_loc,
616                                               personality_function_ptr);
617   }
618 
619   if (lsda_data.IsValid() && personality_function_ptr.IsValid()) {
620     unwind_plan.SetLSDAAddress(lsda_data);
621     unwind_plan.SetPersonalityFunctionPtr(personality_function_ptr);
622   }
623 
624   uint32_t code_align = cie->code_align;
625   int32_t data_align = cie->data_align;
626 
627   unwind_plan.SetPlanValidAddressRange(range);
628   UnwindPlan::Row *cie_initial_row = new UnwindPlan::Row;
629   *cie_initial_row = cie->initial_row;
630   UnwindPlan::RowSP row(cie_initial_row);
631 
632   unwind_plan.SetRegisterKind(GetRegisterKind());
633   unwind_plan.SetReturnAddressRegister(cie->return_addr_reg_num);
634 
635   std::vector<UnwindPlan::RowSP> stack;
636 
637   UnwindPlan::Row::RegisterLocation reg_location;
638   while (m_cfi_data.ValidOffset(offset) && offset < end_offset) {
639     uint8_t inst = m_cfi_data.GetU8(&offset);
640     uint8_t primary_opcode = inst & 0xC0;
641     uint8_t extended_opcode = inst & 0x3F;
642 
643     if (!HandleCommonDwarfOpcode(primary_opcode, extended_opcode, data_align,
644                                  offset, *row)) {
645       if (primary_opcode) {
646         switch (primary_opcode) {
647         case DW_CFA_advance_loc: // (Row Creation Instruction)
648         { // 0x40 - high 2 bits are 0x1, lower 6 bits are delta
649           // takes a single argument that represents a constant delta. The
650           // required action is to create a new table row with a location value
651           // that is computed by taking the current entry's location value and
652           // adding (delta * code_align). All other values in the new row are
653           // initially identical to the current row.
654           unwind_plan.AppendRow(row);
655           UnwindPlan::Row *newrow = new UnwindPlan::Row;
656           *newrow = *row.get();
657           row.reset(newrow);
658           row->SlideOffset(extended_opcode * code_align);
659           break;
660         }
661 
662         case DW_CFA_restore: { // 0xC0 - high 2 bits are 0x3, lower 6 bits are
663                                // register
664           // takes a single argument that represents a register number. The
665           // required action is to change the rule for the indicated register
666           // to the rule assigned it by the initial_instructions in the CIE.
667           uint32_t reg_num = extended_opcode;
668           // We only keep enough register locations around to unwind what is in
669           // our thread, and these are organized by the register index in that
670           // state, so we need to convert our eh_frame register number from the
671           // EH frame info, to a register index
672 
673           if (unwind_plan.IsValidRowIndex(0) &&
674               unwind_plan.GetRowAtIndex(0)->GetRegisterInfo(reg_num,
675                                                             reg_location))
676             row->SetRegisterInfo(reg_num, reg_location);
677           break;
678         }
679         }
680       } else {
681         switch (extended_opcode) {
682         case DW_CFA_set_loc: // 0x1 (Row Creation Instruction)
683         {
684           // DW_CFA_set_loc takes a single argument that represents an address.
685           // The required action is to create a new table row using the
686           // specified address as the location. All other values in the new row
687           // are initially identical to the current row. The new location value
688           // should always be greater than the current one.
689           unwind_plan.AppendRow(row);
690           UnwindPlan::Row *newrow = new UnwindPlan::Row;
691           *newrow = *row.get();
692           row.reset(newrow);
693           row->SetOffset(m_cfi_data.GetAddress(&offset) -
694                          startaddr.GetFileAddress());
695           break;
696         }
697 
698         case DW_CFA_advance_loc1: // 0x2 (Row Creation Instruction)
699         {
700           // takes a single uword argument that represents a constant delta.
701           // This instruction is identical to DW_CFA_advance_loc except for the
702           // encoding and size of the delta argument.
703           unwind_plan.AppendRow(row);
704           UnwindPlan::Row *newrow = new UnwindPlan::Row;
705           *newrow = *row.get();
706           row.reset(newrow);
707           row->SlideOffset(m_cfi_data.GetU8(&offset) * code_align);
708           break;
709         }
710 
711         case DW_CFA_advance_loc2: // 0x3 (Row Creation Instruction)
712         {
713           // takes a single uword argument that represents a constant delta.
714           // This instruction is identical to DW_CFA_advance_loc except for the
715           // encoding and size of the delta argument.
716           unwind_plan.AppendRow(row);
717           UnwindPlan::Row *newrow = new UnwindPlan::Row;
718           *newrow = *row.get();
719           row.reset(newrow);
720           row->SlideOffset(m_cfi_data.GetU16(&offset) * code_align);
721           break;
722         }
723 
724         case DW_CFA_advance_loc4: // 0x4 (Row Creation Instruction)
725         {
726           // takes a single uword argument that represents a constant delta.
727           // This instruction is identical to DW_CFA_advance_loc except for the
728           // encoding and size of the delta argument.
729           unwind_plan.AppendRow(row);
730           UnwindPlan::Row *newrow = new UnwindPlan::Row;
731           *newrow = *row.get();
732           row.reset(newrow);
733           row->SlideOffset(m_cfi_data.GetU32(&offset) * code_align);
734           break;
735         }
736 
737         case DW_CFA_restore_extended: // 0x6
738         {
739           // takes a single unsigned LEB128 argument that represents a register
740           // number. This instruction is identical to DW_CFA_restore except for
741           // the encoding and size of the register argument.
742           uint32_t reg_num = (uint32_t)m_cfi_data.GetULEB128(&offset);
743           if (unwind_plan.IsValidRowIndex(0) &&
744               unwind_plan.GetRowAtIndex(0)->GetRegisterInfo(reg_num,
745                                                             reg_location))
746             row->SetRegisterInfo(reg_num, reg_location);
747           break;
748         }
749 
750         case DW_CFA_remember_state: // 0xA
751         {
752           // These instructions define a stack of information. Encountering the
753           // DW_CFA_remember_state instruction means to save the rules for
754           // every register on the current row on the stack. Encountering the
755           // DW_CFA_restore_state instruction means to pop the set of rules off
756           // the stack and place them in the current row. (This operation is
757           // useful for compilers that move epilogue code into the body of a
758           // function.)
759           stack.push_back(row);
760           UnwindPlan::Row *newrow = new UnwindPlan::Row;
761           *newrow = *row.get();
762           row.reset(newrow);
763           break;
764         }
765 
766         case DW_CFA_restore_state: // 0xB
767         {
768           // These instructions define a stack of information. Encountering the
769           // DW_CFA_remember_state instruction means to save the rules for
770           // every register on the current row on the stack. Encountering the
771           // DW_CFA_restore_state instruction means to pop the set of rules off
772           // the stack and place them in the current row. (This operation is
773           // useful for compilers that move epilogue code into the body of a
774           // function.)
775           if (stack.empty()) {
776             LLDB_LOGF(log,
777                       "DWARFCallFrameInfo::%s(dwarf_offset: %" PRIx32
778                       ", startaddr: %" PRIx64
779                       " encountered DW_CFA_restore_state but state stack "
780                       "is empty. Corrupt unwind info?",
781                       __FUNCTION__, dwarf_offset, startaddr.GetFileAddress());
782             break;
783           }
784           lldb::addr_t offset = row->GetOffset();
785           row = stack.back();
786           stack.pop_back();
787           row->SetOffset(offset);
788           break;
789         }
790 
791         case DW_CFA_GNU_args_size: // 0x2e
792         {
793           // The DW_CFA_GNU_args_size instruction takes an unsigned LEB128
794           // operand representing an argument size. This instruction specifies
795           // the total of the size of the arguments which have been pushed onto
796           // the stack.
797 
798           // TODO: Figure out how we should handle this.
799           m_cfi_data.GetULEB128(&offset);
800           break;
801         }
802 
803         case DW_CFA_val_offset:    // 0x14
804         case DW_CFA_val_offset_sf: // 0x15
805         default:
806           break;
807         }
808       }
809     }
810   }
811   unwind_plan.AppendRow(row);
812 
813   return true;
814 }
815 
816 bool DWARFCallFrameInfo::HandleCommonDwarfOpcode(uint8_t primary_opcode,
817                                                  uint8_t extended_opcode,
818                                                  int32_t data_align,
819                                                  lldb::offset_t &offset,
820                                                  UnwindPlan::Row &row) {
821   UnwindPlan::Row::RegisterLocation reg_location;
822 
823   if (primary_opcode) {
824     switch (primary_opcode) {
825     case DW_CFA_offset: { // 0x80 - high 2 bits are 0x2, lower 6 bits are
826                           // register
827       // takes two arguments: an unsigned LEB128 constant representing a
828       // factored offset and a register number. The required action is to
829       // change the rule for the register indicated by the register number to
830       // be an offset(N) rule with a value of (N = factored offset *
831       // data_align).
832       uint8_t reg_num = extended_opcode;
833       int32_t op_offset = (int32_t)m_cfi_data.GetULEB128(&offset) * data_align;
834       reg_location.SetAtCFAPlusOffset(op_offset);
835       row.SetRegisterInfo(reg_num, reg_location);
836       return true;
837     }
838     }
839   } else {
840     switch (extended_opcode) {
841     case DW_CFA_nop: // 0x0
842       return true;
843 
844     case DW_CFA_offset_extended: // 0x5
845     {
846       // takes two unsigned LEB128 arguments representing a register number and
847       // a factored offset. This instruction is identical to DW_CFA_offset
848       // except for the encoding and size of the register argument.
849       uint32_t reg_num = (uint32_t)m_cfi_data.GetULEB128(&offset);
850       int32_t op_offset = (int32_t)m_cfi_data.GetULEB128(&offset) * data_align;
851       UnwindPlan::Row::RegisterLocation reg_location;
852       reg_location.SetAtCFAPlusOffset(op_offset);
853       row.SetRegisterInfo(reg_num, reg_location);
854       return true;
855     }
856 
857     case DW_CFA_undefined: // 0x7
858     {
859       // takes a single unsigned LEB128 argument that represents a register
860       // number. The required action is to set the rule for the specified
861       // register to undefined.
862       uint32_t reg_num = (uint32_t)m_cfi_data.GetULEB128(&offset);
863       UnwindPlan::Row::RegisterLocation reg_location;
864       reg_location.SetUndefined();
865       row.SetRegisterInfo(reg_num, reg_location);
866       return true;
867     }
868 
869     case DW_CFA_same_value: // 0x8
870     {
871       // takes a single unsigned LEB128 argument that represents a register
872       // number. The required action is to set the rule for the specified
873       // register to same value.
874       uint32_t reg_num = (uint32_t)m_cfi_data.GetULEB128(&offset);
875       UnwindPlan::Row::RegisterLocation reg_location;
876       reg_location.SetSame();
877       row.SetRegisterInfo(reg_num, reg_location);
878       return true;
879     }
880 
881     case DW_CFA_register: // 0x9
882     {
883       // takes two unsigned LEB128 arguments representing register numbers. The
884       // required action is to set the rule for the first register to be the
885       // second register.
886       uint32_t reg_num = (uint32_t)m_cfi_data.GetULEB128(&offset);
887       uint32_t other_reg_num = (uint32_t)m_cfi_data.GetULEB128(&offset);
888       UnwindPlan::Row::RegisterLocation reg_location;
889       reg_location.SetInRegister(other_reg_num);
890       row.SetRegisterInfo(reg_num, reg_location);
891       return true;
892     }
893 
894     case DW_CFA_def_cfa: // 0xC    (CFA Definition Instruction)
895     {
896       // Takes two unsigned LEB128 operands representing a register number and
897       // a (non-factored) offset. The required action is to define the current
898       // CFA rule to use the provided register and offset.
899       uint32_t reg_num = (uint32_t)m_cfi_data.GetULEB128(&offset);
900       int32_t op_offset = (int32_t)m_cfi_data.GetULEB128(&offset);
901       row.GetCFAValue().SetIsRegisterPlusOffset(reg_num, op_offset);
902       return true;
903     }
904 
905     case DW_CFA_def_cfa_register: // 0xD    (CFA Definition Instruction)
906     {
907       // takes a single unsigned LEB128 argument representing a register
908       // number. The required action is to define the current CFA rule to use
909       // the provided register (but to keep the old offset).
910       uint32_t reg_num = (uint32_t)m_cfi_data.GetULEB128(&offset);
911       row.GetCFAValue().SetIsRegisterPlusOffset(reg_num,
912                                                 row.GetCFAValue().GetOffset());
913       return true;
914     }
915 
916     case DW_CFA_def_cfa_offset: // 0xE    (CFA Definition Instruction)
917     {
918       // Takes a single unsigned LEB128 operand representing a (non-factored)
919       // offset. The required action is to define the current CFA rule to use
920       // the provided offset (but to keep the old register).
921       int32_t op_offset = (int32_t)m_cfi_data.GetULEB128(&offset);
922       row.GetCFAValue().SetIsRegisterPlusOffset(
923           row.GetCFAValue().GetRegisterNumber(), op_offset);
924       return true;
925     }
926 
927     case DW_CFA_def_cfa_expression: // 0xF    (CFA Definition Instruction)
928     {
929       size_t block_len = (size_t)m_cfi_data.GetULEB128(&offset);
930       const uint8_t *block_data =
931           static_cast<const uint8_t *>(m_cfi_data.GetData(&offset, block_len));
932       row.GetCFAValue().SetIsDWARFExpression(block_data, block_len);
933       return true;
934     }
935 
936     case DW_CFA_expression: // 0x10
937     {
938       // Takes two operands: an unsigned LEB128 value representing a register
939       // number, and a DW_FORM_block value representing a DWARF expression. The
940       // required action is to change the rule for the register indicated by
941       // the register number to be an expression(E) rule where E is the DWARF
942       // expression. That is, the DWARF expression computes the address. The
943       // value of the CFA is pushed on the DWARF evaluation stack prior to
944       // execution of the DWARF expression.
945       uint32_t reg_num = (uint32_t)m_cfi_data.GetULEB128(&offset);
946       uint32_t block_len = (uint32_t)m_cfi_data.GetULEB128(&offset);
947       const uint8_t *block_data =
948           static_cast<const uint8_t *>(m_cfi_data.GetData(&offset, block_len));
949       UnwindPlan::Row::RegisterLocation reg_location;
950       reg_location.SetAtDWARFExpression(block_data, block_len);
951       row.SetRegisterInfo(reg_num, reg_location);
952       return true;
953     }
954 
955     case DW_CFA_offset_extended_sf: // 0x11
956     {
957       // takes two operands: an unsigned LEB128 value representing a register
958       // number and a signed LEB128 factored offset. This instruction is
959       // identical to DW_CFA_offset_extended except that the second operand is
960       // signed and factored.
961       uint32_t reg_num = (uint32_t)m_cfi_data.GetULEB128(&offset);
962       int32_t op_offset = (int32_t)m_cfi_data.GetSLEB128(&offset) * data_align;
963       UnwindPlan::Row::RegisterLocation reg_location;
964       reg_location.SetAtCFAPlusOffset(op_offset);
965       row.SetRegisterInfo(reg_num, reg_location);
966       return true;
967     }
968 
969     case DW_CFA_def_cfa_sf: // 0x12   (CFA Definition Instruction)
970     {
971       // Takes two operands: an unsigned LEB128 value representing a register
972       // number and a signed LEB128 factored offset. This instruction is
973       // identical to DW_CFA_def_cfa except that the second operand is signed
974       // and factored.
975       uint32_t reg_num = (uint32_t)m_cfi_data.GetULEB128(&offset);
976       int32_t op_offset = (int32_t)m_cfi_data.GetSLEB128(&offset) * data_align;
977       row.GetCFAValue().SetIsRegisterPlusOffset(reg_num, op_offset);
978       return true;
979     }
980 
981     case DW_CFA_def_cfa_offset_sf: // 0x13   (CFA Definition Instruction)
982     {
983       // takes a signed LEB128 operand representing a factored offset. This
984       // instruction is identical to  DW_CFA_def_cfa_offset except that the
985       // operand is signed and factored.
986       int32_t op_offset = (int32_t)m_cfi_data.GetSLEB128(&offset) * data_align;
987       uint32_t cfa_regnum = row.GetCFAValue().GetRegisterNumber();
988       row.GetCFAValue().SetIsRegisterPlusOffset(cfa_regnum, op_offset);
989       return true;
990     }
991 
992     case DW_CFA_val_expression: // 0x16
993     {
994       // takes two operands: an unsigned LEB128 value representing a register
995       // number, and a DW_FORM_block value representing a DWARF expression. The
996       // required action is to change the rule for the register indicated by
997       // the register number to be a val_expression(E) rule where E is the
998       // DWARF expression. That is, the DWARF expression computes the value of
999       // the given register. The value of the CFA is pushed on the DWARF
1000       // evaluation stack prior to execution of the DWARF expression.
1001       uint32_t reg_num = (uint32_t)m_cfi_data.GetULEB128(&offset);
1002       uint32_t block_len = (uint32_t)m_cfi_data.GetULEB128(&offset);
1003       const uint8_t *block_data =
1004           (const uint8_t *)m_cfi_data.GetData(&offset, block_len);
1005       reg_location.SetIsDWARFExpression(block_data, block_len);
1006       row.SetRegisterInfo(reg_num, reg_location);
1007       return true;
1008     }
1009     }
1010   }
1011   return false;
1012 }
1013 
1014 void DWARFCallFrameInfo::ForEachFDEEntries(
1015     const std::function<bool(lldb::addr_t, uint32_t, dw_offset_t)> &callback) {
1016   GetFDEIndex();
1017 
1018   for (size_t i = 0, c = m_fde_index.GetSize(); i < c; ++i) {
1019     const FDEEntryMap::Entry &entry = m_fde_index.GetEntryRef(i);
1020     if (!callback(entry.base, entry.size, entry.data))
1021       break;
1022   }
1023 }
1024