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