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