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