cranelift_codegen/isa/unwind/
systemv.rs1use crate::isa::unwind::UnwindInst;
4use crate::machinst::Reg;
5use crate::result::CodegenResult;
6use crate::{CodegenError, binemit::CodeOffset};
7use alloc::vec::Vec;
8use gimli::write::{Address, FrameDescriptionEntry};
9
10#[cfg(feature = "enable-serde")]
11use serde_derive::{Deserialize, Serialize};
12
13type Register = u16;
14
15#[expect(missing_docs, reason = "self-describing variants")]
17#[derive(Debug, PartialEq, Eq)]
18pub enum RegisterMappingError {
19 MissingBank,
20 UnsupportedArchitecture,
21 UnsupportedRegisterBank(&'static str),
22}
23
24impl core::error::Error for RegisterMappingError {}
27
28impl core::fmt::Display for RegisterMappingError {
29 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
30 match self {
31 RegisterMappingError::MissingBank => write!(f, "unable to find bank for register info"),
32 RegisterMappingError::UnsupportedArchitecture => write!(
33 f,
34 "register mapping is currently only implemented for x86_64"
35 ),
36 RegisterMappingError::UnsupportedRegisterBank(bank) => {
37 write!(f, "unsupported register bank: {bank}")
38 }
39 }
40 }
41}
42
43#[derive(Clone, Debug, PartialEq, Eq)]
48#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
49pub(crate) enum CallFrameInstruction {
50 Cfa(Register, i32),
51 CfaRegister(Register),
52 CfaOffset(i32),
53 Restore(Register),
54 Undefined(Register),
55 SameValue(Register),
56 Offset(Register, i32),
57 ValOffset(Register, i32),
58 Register(Register, Register),
59 RememberState,
60 RestoreState,
61 ArgsSize(u32),
62 Aarch64SetPointerAuth {
65 return_addresses: bool,
66 },
67}
68
69impl From<gimli::write::CallFrameInstruction> for CallFrameInstruction {
70 fn from(cfi: gimli::write::CallFrameInstruction) -> Self {
71 use gimli::write::CallFrameInstruction;
72
73 match cfi {
74 CallFrameInstruction::Cfa(reg, offset) => Self::Cfa(reg.0, offset),
75 CallFrameInstruction::CfaRegister(reg) => Self::CfaRegister(reg.0),
76 CallFrameInstruction::CfaOffset(offset) => Self::CfaOffset(offset),
77 CallFrameInstruction::Restore(reg) => Self::Restore(reg.0),
78 CallFrameInstruction::Undefined(reg) => Self::Undefined(reg.0),
79 CallFrameInstruction::SameValue(reg) => Self::SameValue(reg.0),
80 CallFrameInstruction::Offset(reg, offset) => Self::Offset(reg.0, offset),
81 CallFrameInstruction::ValOffset(reg, offset) => Self::ValOffset(reg.0, offset),
82 CallFrameInstruction::Register(reg1, reg2) => Self::Register(reg1.0, reg2.0),
83 CallFrameInstruction::RememberState => Self::RememberState,
84 CallFrameInstruction::RestoreState => Self::RestoreState,
85 CallFrameInstruction::ArgsSize(size) => Self::ArgsSize(size),
86 _ => {
87 panic!("CallFrameInstruction with Expression not supported");
91 }
92 }
93 }
94}
95
96impl From<CallFrameInstruction> for gimli::write::CallFrameInstruction {
97 fn from(cfi: CallFrameInstruction) -> gimli::write::CallFrameInstruction {
98 use CallFrameInstruction as ClifCfi;
99 use gimli::{Register, write::CallFrameInstruction as GimliCfi, write::Expression};
100
101 match cfi {
102 ClifCfi::Cfa(reg, offset) => GimliCfi::Cfa(Register(reg), offset),
103 ClifCfi::CfaRegister(reg) => GimliCfi::CfaRegister(Register(reg)),
104 ClifCfi::CfaOffset(offset) => GimliCfi::CfaOffset(offset),
105 ClifCfi::Restore(reg) => GimliCfi::Restore(Register(reg)),
106 ClifCfi::Undefined(reg) => GimliCfi::Undefined(Register(reg)),
107 ClifCfi::SameValue(reg) => GimliCfi::SameValue(Register(reg)),
108 ClifCfi::Offset(reg, offset) => GimliCfi::Offset(Register(reg), offset),
109 ClifCfi::ValOffset(reg, offset) => GimliCfi::ValOffset(Register(reg), offset),
110 ClifCfi::Register(reg1, reg2) => GimliCfi::Register(Register(reg1), Register(reg2)),
111 ClifCfi::RememberState => GimliCfi::RememberState,
112 ClifCfi::RestoreState => GimliCfi::RestoreState,
113 ClifCfi::ArgsSize(size) => GimliCfi::ArgsSize(size),
114 ClifCfi::Aarch64SetPointerAuth { return_addresses } => {
115 let mut expr = Expression::new();
121 expr.op(if return_addresses {
122 gimli::DW_OP_lit1
123 } else {
124 gimli::DW_OP_lit0
125 });
126 const RA_SIGN_STATE: Register = Register(34);
127 GimliCfi::ValExpression(RA_SIGN_STATE, expr)
128 }
129 }
130 }
131}
132
133pub(crate) trait RegisterMapper<Reg> {
135 fn map(&self, reg: Reg) -> Result<Register, RegisterMappingError>;
137 fn fp(&self) -> Option<Register> {
139 None
140 }
141 fn lr(&self) -> Option<Register> {
143 None
144 }
145 fn lr_offset(&self) -> Option<u32> {
147 None
148 }
149 fn frame_move_lr_and_offset(&self) -> Option<(Register, i32)> {
151 None
152 }
153}
154
155#[derive(Clone, Debug, PartialEq, Eq)]
159#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
160pub struct UnwindInfo {
161 instructions: Vec<(u32, CallFrameInstruction)>,
162 len: u32,
163}
164
165pub(crate) fn caller_sp_to_cfa_offset() -> u32 {
167 0
169}
170
171pub(crate) fn create_unwind_info_from_insts<MR: RegisterMapper<Reg>>(
172 insts: &[(CodeOffset, UnwindInst)],
173 code_len: usize,
174 mr: &MR,
175) -> CodegenResult<UnwindInfo> {
176 let mut instructions = vec![];
177
178 let mut cfa_offset = 0;
179 let mut clobber_offset_to_cfa = 0;
180 for &(instruction_offset, ref inst) in insts {
181 match inst {
182 &UnwindInst::PushFrameRegs {
183 offset_upward_to_caller_sp,
184 } => {
185 instructions.push((
188 instruction_offset,
189 CallFrameInstruction::CfaOffset(offset_upward_to_caller_sp as i32),
190 ));
191 instructions.push((
194 instruction_offset,
195 CallFrameInstruction::Offset(
196 mr.fp().unwrap(),
197 -(offset_upward_to_caller_sp as i32),
198 ),
199 ));
200 if let Some(lr) = mr.lr() {
203 instructions.push((
204 instruction_offset,
205 CallFrameInstruction::Offset(
206 lr,
207 -(offset_upward_to_caller_sp as i32)
208 + mr.lr_offset().expect("LR offset not provided") as i32,
209 ),
210 ));
211 }
212 }
213 &UnwindInst::DefineNewFrame {
214 offset_upward_to_caller_sp,
215 offset_downward_to_clobbers,
216 } => {
217 if let Some(fp) = mr.fp() {
223 instructions.push((instruction_offset, CallFrameInstruction::CfaRegister(fp)));
224 }
225 cfa_offset = offset_upward_to_caller_sp;
228 clobber_offset_to_cfa = offset_upward_to_caller_sp + offset_downward_to_clobbers;
231 }
232 &UnwindInst::StackAlloc { size } => {
233 if mr.fp().is_none() {
236 cfa_offset += size;
237 instructions.push((
238 instruction_offset,
239 CallFrameInstruction::CfaOffset(cfa_offset as i32),
240 ));
241 }
242 }
243 &UnwindInst::SaveReg {
244 clobber_offset,
245 reg,
246 } => {
247 let reg = mr
248 .map(reg.into())
249 .map_err(|e| CodegenError::RegisterMappingError(e))?;
250 let off = (clobber_offset as i32) - (clobber_offset_to_cfa as i32);
251 instructions.push((instruction_offset, CallFrameInstruction::Offset(reg, off)));
252 }
253 &UnwindInst::RegStackOffset {
254 clobber_offset,
255 reg,
256 } => {
257 let reg = mr
258 .map(reg.into())
259 .map_err(|e| CodegenError::RegisterMappingError(e))?;
260 let off = (clobber_offset as i32) - (clobber_offset_to_cfa as i32);
261 instructions.push((
262 instruction_offset,
263 CallFrameInstruction::ValOffset(reg, off),
264 ));
265 }
266 &UnwindInst::FrameRecordMoved { size } => {
267 cfa_offset += size;
270 clobber_offset_to_cfa += size;
271 let offset = cfa_offset as i32;
272 instructions.extend([
273 (instruction_offset, CallFrameInstruction::CfaOffset(offset)),
274 (
275 instruction_offset,
276 CallFrameInstruction::Offset(mr.fp().unwrap(), -offset),
277 ),
278 ]);
279 let (lr, lr_offset) = mr
280 .frame_move_lr_and_offset()
281 .expect("FrameRecordMoved requires a return-address slot");
282 instructions.push((
283 instruction_offset,
284 CallFrameInstruction::Offset(lr, lr_offset - offset),
285 ));
286 }
287 &UnwindInst::Aarch64SetPointerAuth { return_addresses } => {
288 instructions.push((
289 instruction_offset,
290 CallFrameInstruction::Aarch64SetPointerAuth { return_addresses },
291 ));
292 }
293 }
294 }
295
296 Ok(UnwindInfo {
297 instructions,
298 len: code_len as u32,
299 })
300}
301
302impl UnwindInfo {
303 pub fn to_fde(&self, address: Address) -> gimli::write::FrameDescriptionEntry {
305 let mut fde = FrameDescriptionEntry::new(address, self.len);
306
307 for (offset, inst) in &self.instructions {
308 fde.add_instruction(*offset, inst.clone().into());
309 }
310
311 fde
312 }
313}