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