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