]> git.lizzy.rs Git - rust.git/blob - src/debuginfo/unwind.rs
Add a feature flag for the JIT
[rust.git] / src / debuginfo / unwind.rs
1 use crate::prelude::*;
2
3 use cranelift_codegen::isa::{TargetIsa, unwind::UnwindInfo};
4
5 use gimli::write::{Address, CieId, EhFrame, FrameTable, Section};
6
7 use crate::backend::WriteDebugInfo;
8
9 pub(crate) struct UnwindContext<'tcx> {
10     tcx: TyCtxt<'tcx>,
11     frame_table: FrameTable,
12     cie_id: Option<CieId>,
13 }
14
15 impl<'tcx> UnwindContext<'tcx> {
16     pub(crate) fn new(
17         tcx: TyCtxt<'tcx>,
18         isa: &dyn TargetIsa,
19     ) -> Self {
20         let mut frame_table = FrameTable::default();
21
22
23         let cie_id = if let Some(cie) = isa.create_systemv_cie() {
24             Some(frame_table.add_cie(cie))
25         } else {
26             None
27         };
28
29         UnwindContext {
30             tcx,
31             frame_table,
32             cie_id,
33         }
34     }
35
36     pub(crate) fn add_function(&mut self, func_id: FuncId, context: &Context, isa: &dyn TargetIsa) {
37         let unwind_info = if let Some(unwind_info) = context.create_unwind_info(isa).unwrap() {
38             unwind_info
39         } else {
40             return;
41         };
42
43         match unwind_info {
44             UnwindInfo::SystemV(unwind_info) => {
45                 self.frame_table.add_fde(self.cie_id.unwrap(), unwind_info.to_fde(Address::Symbol {
46                     symbol: func_id.as_u32() as usize,
47                     addend: 0,
48                 }));
49             },
50             UnwindInfo::WindowsX64(_) => {
51                 // FIXME implement this
52             }
53         }
54     }
55
56     pub(crate) fn emit<P: WriteDebugInfo>(self, product: &mut P) {
57         let mut eh_frame = EhFrame::from(super::emit::WriterRelocate::new(super::target_endian(self.tcx)));
58         self.frame_table.write_eh_frame(&mut eh_frame).unwrap();
59
60         if !eh_frame.0.writer.slice().is_empty() {
61             let id = eh_frame.id();
62             let section_id = product.add_debug_section(id, eh_frame.0.writer.into_vec());
63             let mut section_map = FxHashMap::default();
64             section_map.insert(id, section_id);
65
66             for reloc in &eh_frame.0.relocs {
67                 product.add_debug_reloc(&section_map, &section_id, reloc);
68             }
69         }
70     }
71
72     #[cfg(feature = "jit")]
73     pub(crate) unsafe fn register_jit(
74         self,
75         jit_module: &mut Module<cranelift_simplejit::SimpleJITBackend>,
76     ) -> Option<UnwindRegistry> {
77         let mut eh_frame = EhFrame::from(super::emit::WriterRelocate::new(super::target_endian(self.tcx)));
78         self.frame_table.write_eh_frame(&mut eh_frame).unwrap();
79
80         if eh_frame.0.writer.slice().is_empty() {
81             return None;
82         }
83
84         let mut eh_frame = eh_frame.0.relocate_for_jit(jit_module);
85
86         // GCC expects a terminating "empty" length, so write a 0 length at the end of the table.
87         eh_frame.extend(&[0, 0, 0, 0]);
88
89         let mut registrations = Vec::new();
90
91         // =======================================================================
92         // Everything after this line up to the end of the file is loosly based on
93         // https://github.com/bytecodealliance/wasmtime/blob/4471a82b0c540ff48960eca6757ccce5b1b5c3e4/crates/jit/src/unwind/systemv.rs
94         cfg_if::cfg_if! {
95             if #[cfg(target_os = "macos")] {
96                 // On macOS, `__register_frame` takes a pointer to a single FDE
97                 let start = eh_frame.as_ptr();
98                 let end = start.add(eh_frame.len());
99                 let mut current = start;
100
101                 // Walk all of the entries in the frame table and register them
102                 while current < end {
103                     let len = std::ptr::read::<u32>(current as *const u32) as usize;
104
105                     // Skip over the CIE
106                     if current != start {
107                         __register_frame(current);
108                         registrations.push(current as usize);
109                     }
110
111                     // Move to the next table entry (+4 because the length itself is not inclusive)
112                     current = current.add(len + 4);
113                 }
114             } else {
115                 // On other platforms, `__register_frame` will walk the FDEs until an entry of length 0
116                 let ptr = eh_frame.as_ptr();
117                 __register_frame(ptr);
118                 registrations.push(ptr as usize);
119             }
120         }
121
122         Some(UnwindRegistry {
123             _frame_table: eh_frame,
124             registrations,
125         })
126     }
127 }
128
129 /// Represents a registry of function unwind information for System V ABI.
130 pub(crate) struct UnwindRegistry {
131     _frame_table: Vec<u8>,
132     registrations: Vec<usize>,
133 }
134
135 extern "C" {
136     // libunwind import
137     fn __register_frame(fde: *const u8);
138     fn __deregister_frame(fde: *const u8);
139 }
140
141 impl Drop for UnwindRegistry {
142     fn drop(&mut self) {
143         unsafe {
144             // libgcc stores the frame entries as a linked list in decreasing sort order
145             // based on the PC value of the registered entry.
146             //
147             // As we store the registrations in increasing order, it would be O(N^2) to
148             // deregister in that order.
149             //
150             // To ensure that we just pop off the first element in the list upon every
151             // deregistration, walk our list of registrations backwards.
152             for fde in self.registrations.iter().rev() {
153                 __deregister_frame(*fde as *const _);
154             }
155         }
156     }
157 }