edlc_codegen_cranelift 0.2.13

Cranelift codegen backend for the EDL compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
/*
 *     EDLc, a compiler for the EDL programming language.
 *     Copyright (C) 2026  Adrian Paskert
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Affero General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Affero General Public License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#[cfg(any(target_arch="x86_64", target_arch="x86"))]
mod x86;
#[cfg(any(target_os="linux", target_os="macos", target_os="freebsd", target_os="openbsd"))]
mod unix;
mod signal_stack;
mod cfi;
mod range_vec;

use std::cell::{LazyCell, RefCell};
use std::fmt::{Display, Formatter};
use std::hash::DefaultHasher;
use std::ops::Index;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use cranelift_codegen::ir::TrapCode;
use log::{error, warn};
#[cfg(feature="serde")]
use serde::{Deserialize, Serialize};
use edlc_core::lexer::SrcPos;
use edlc_core::prelude::{AmorphusDataCopy, HirPhase, MirPhase, ModuleSrc, TrapInfo, TypeArgument, TypeArguments};
use edlc_core::prelude::mir_backend::Backend;
use edlc_core::prelude::mir_funcs::{MirFuncId, MirFuncRegistry};
use edlc_core::prelude::mir_type::MirTypeId;
#[cfg(any(target_os="linux", target_os="macos", target_os="freebsd", target_os="openbsd"))]
pub use unix::{TrapHandler, jit_panic, cause_jit_async_panic, jit_sync_panic};
pub use range_vec::{RangeVec, RangeVecIter};
use crate::compiler::{UnwindInfo, JIT};

#[cfg_attr(feature="serde", derive(Serialize, Deserialize))]
#[derive(Debug)]
pub enum PrintableBacktraceElement {
    Jit {
        pos: SrcPos,
        src: ModuleSrc,
        func: MirFuncId,
    },
    JitUnknown {
        func: MirFuncId,
        offset: u32,
    },
    Host {
        func: usize,
        offset: u32,
    },
}

#[cfg_attr(feature="serde", derive(Serialize, Deserialize))]
#[derive(Default, Debug)]
pub struct PrintableBacktrace {
    pub trace: Vec<PrintableBacktraceElement>,
}


#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
struct BacktraceFlags(u32);

const FLAG_JIT_FRAME: u32 = 0b1;

impl BacktraceFlags {
    pub fn set_jit_frame(mut self) -> Self {
        self.0 |= FLAG_JIT_FRAME;
        self
    }

    pub fn jit_frame(&self) -> bool {
        self.0 & FLAG_JIT_FRAME != 0
    }
}

#[derive(Default, Clone, Copy, Debug)]
pub struct BacktraceEntry {
    /// Function pointer in which the location lives.
    /// This is guaranteed to always be a function generated by the JIT.
    func: usize,
    /// Code offset of the panic (from the base addr).
    loc: u32,
    flags: BacktraceFlags,
}

pub struct Backtrace {
    trace: Box<[BacktraceEntry]>,
    len: usize,
}


const BACKTRACE_SIZE_MAX: usize = 32;

impl Backtrace {
    fn new() -> Self {
        let trace = vec![const { BacktraceEntry {
            loc: 0,
            func: 0,
            flags: BacktraceFlags(0),
        } }; BACKTRACE_SIZE_MAX];
        Backtrace {
            trace: trace.into_boxed_slice(),
            len: 0,
        }
    }

    fn push(&mut self, entry: BacktraceEntry) {
        if self.len >= BACKTRACE_SIZE_MAX {
            return;
        }
        self.trace[self.len] = entry;
        self.len += 1;
    }

    fn slice(&self) -> &[BacktraceEntry] {
        &self.trace[..self.len]
    }

    fn clear(&mut self) {
        self.len = 0;
    }

    fn len(&self) -> usize {
        self.len
    }

    fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns true if the panic unwind was initiated by a synchronous panic.
    fn synchronous(&self) -> bool {
        if let Some(first) = self.slice().first() {
            first.func as *const u8 == jit_sync_panic as *const u8
        } else {
            false
        }
    }

    /// Returns true if it is safe to resume program execution after this point.
    /// Some panic unwinds can be recovered gracefully, whereas other panics are completely unsafe
    /// to resume, as not all cleanup routines are executed.
    pub fn is_recoverable(&self) -> bool {
        let mut iter = self.slice().iter();
        let Some(first) = iter.next() else {
            return true;
        };
        if first.flags.jit_frame() {
            return true;
        }
        if first.func as *const u8 != jit_sync_panic as *const u8 {
            error!("[EDL-JIT] non-synchronous panic originating in host frames");
            return false; // non-synchronous panic originating in host frames
        }
        let Some(next) = iter.next() else {
            return true;
        };
        if next.flags.jit_frame() {
            return true; // jit_sync_panic was called from JIT -> we are recoverable
        }
        let Some(next) = iter.next() else {
            return true;
        };
        if !next.flags.jit_frame() {
            error!("[EDL-JIT] jit_sync_panic called from a host function that is nested more than \
            one function call away from JIT frame");
            return false; // jit_sync_panic was called from a host function that is not directly
                          // called from the JIT -> cleanup routine in host frame not executed
        }
        true
    }

    fn get_panic_type(&self, debug_frames: &UnwindInfo) -> Option<PanicType> {
        let Some(first) = self.slice().first() else {
            return None;
        };
        if let Some(id) = debug_frames.find_id(&first.func) {
            if let Some(source_frame) = debug_frames.get_source(&id) {
                if let Some(trap_code) = source_frame.trap_code(first.loc) {
                    match *trap_code {
                        TrapCode::BAD_CONVERSION_TO_INTEGER => Some(PanicType::BadConversionToInteger),
                        TrapCode::HEAP_OUT_OF_BOUNDS => Some(PanicType::HeapOutOfBounds),
                        TrapCode::INTEGER_DIVISION_BY_ZERO => Some(PanicType::DivideByZero),
                        TrapCode::INTEGER_OVERFLOW => Some(PanicType::IntegerOverflow),
                        TrapCode::STACK_OVERFLOW => Some(PanicType::StackOverflow),
                        _ => {
                            // assume that this is a user-defined trap code
                            if let Some(trap_info) = source_frame.trap_info(first.loc) {
                                match trap_info {
                                    TrapInfo::DivideByZero => Some(PanicType::DivideByZero),
                                    TrapInfo::ArrayIndex => Some(PanicType::ArrayIndexOutOfBounds),
                                    TrapInfo::SliceIndex => Some(PanicType::SliceIndexOutOfBounds),
                                    TrapInfo::ArrayRange => Some(PanicType::ArrayRangeOutOfBounds),
                                    TrapInfo::SliceRange => Some(PanicType::SliceRangeOutOfBounds),
                                    TrapInfo::ExplicitPanic => Some(PanicType::Explicit),
                                    TrapInfo::AssertionFailed => Some(PanicType::Assertion),
                                    TrapInfo::Other(reason) => Some(PanicType::Other(reason)),
                                }
                            } else {
                                Some(PanicType::Unknown)
                            }
                        },
                    }
                } else {
                    Some(PanicType::Unknown)
                }
            } else {
                None
            }
        } else {
            None
        }
    }

    fn printable(
        &self,
        debug_frames: &UnwindInfo,
    ) -> PrintableBacktrace {
        let mut out = PrintableBacktrace::default();
        // print stack trace
        for trace in self.slice().iter() {
            let el = if let Some(id) = debug_frames.find_id(&trace.func) {
                if let Some(source_frame) = debug_frames.get_source(&id) {
                    if let Some(loc) = source_frame.source_location(trace.loc) {
                        PrintableBacktraceElement::Jit {
                            func: id,
                            src: loc.src.clone(),
                            pos: loc.pos,
                        }
                    } else {
                        PrintableBacktraceElement::JitUnknown {
                            func: id,
                            offset: trace.loc,
                        }
                    }
                } else {
                    PrintableBacktraceElement::JitUnknown {
                        func: id,
                        offset: trace.loc,
                    }
                }
            } else {
                PrintableBacktraceElement::Host {
                    func: trace.func,
                    offset: trace.loc,
                }
            };
            out.trace.push(el);
        }
        out
    }

    fn print<B: Backend>(
        &self,
        phase: &HirPhase,
        funcs: &MirFuncRegistry<B>,
        debug_frames: &UnwindInfo,
    ) {
        // format trap reason
        let Some(first) = self.slice().first() else {
            return;
        };
        if let Some(id) = debug_frames.find_id(&first.func) {
            if let Some(source_frame) = debug_frames.get_source(&id) {
                if let Some(trap_code) = source_frame.trap_code(first.loc) {
                    match *trap_code {
                        TrapCode::BAD_CONVERSION_TO_INTEGER => {
                            error!("bad conversion to integer");
                        },
                        TrapCode::HEAP_OUT_OF_BOUNDS => {
                            error!("heap out of bounds");
                        },
                        TrapCode::INTEGER_DIVISION_BY_ZERO => {
                            error!("integer division by zero")
                        },
                        TrapCode::INTEGER_OVERFLOW => {
                            error!("integer overflow")
                        },
                        TrapCode::STACK_OVERFLOW => {
                            error!("stack overflow")
                        },
                        _ => {
                            // assume that this is a user-defined trap code
                            if let Some(trap_info) = source_frame.trap_info(first.loc) {
                                match trap_info {
                                    TrapInfo::DivideByZero => {
                                        error!("division by zero");
                                    }
                                    TrapInfo::ArrayIndex => {
                                        error!("array index out of bounds");
                                    }
                                    TrapInfo::SliceIndex => {
                                        error!("slice index out of bounds");
                                    }
                                    TrapInfo::ArrayRange => {
                                        error!("array range out of bounds");
                                    }
                                    TrapInfo::SliceRange => {
                                        error!("slice range out of bounds");
                                    }
                                    TrapInfo::ExplicitPanic => {
                                        error!("explicit panic");
                                    }
                                    TrapInfo::AssertionFailed => {
                                        error!("assertion failed");
                                    }
                                    TrapInfo::Other(reason) => {
                                        error!("{}", reason);
                                    }
                                }
                            } else {
                                error!("<unknown error>");
                            }
                        },
                    }
                } else {
                    error!("<unknown error>");
                }
            }
        }

        // print stack trace
        for trace in self.slice().iter() {
            if let Some(id) = debug_frames.find_id(&trace.func) {
                let edl_func = funcs.get_edl_id(id)
                    .expect("failed to get EDL function id from MIR function id");
                let sig = phase.types.get_fn_signature(edl_func)
                    .expect("failed to get function signature");

                if let Some((pos, src)) = funcs.get_source_information(id) {
                    error!("    {} at {}", TypeArguments::<'_, DefaultHasher>::new(&[
                        TypeArgument::new_edl(sig)
                    ]).printable(&phase.types, &phase.vars), src.format_pos(pos));
                } else {
                    error!("    {}", TypeArguments::<'_, DefaultHasher>::new(&[
                        TypeArgument::new_edl(sig),
                    ]).printable(&phase.types, &phase.vars));
                }

                if let Some(source_frame) = debug_frames.get_source(&id) {
                    if let Some(loc) = source_frame.source_location(trace.loc) {
                        error!("        at {}", loc.src.format_pos(loc.pos));
                    } else {
                        error!("        at <unknown> {:p}", trace.loc as *const ());
                    }
                } else {
                    error!("        at <unknown> {:p}", trace.loc as *const ());
                }
            } else if trace.func as *const u8 == jit_sync_panic as *const u8 {
                error!("    jit_sync_panic (EDL runtime synchronous panic unwind hook)")
            } else {
                error!("    <unknown> {:p}", trace.func as *const ());
                error!("        at <unknown> {:p}", trace.loc as *const ());
            }
        }
    }
}

impl Index<usize> for Backtrace {
    type Output = BacktraceEntry;

    fn index(&self, index: usize) -> &Self::Output {
        self.trace.get(index).unwrap()
    }
}

struct PanicPayload {
    backtrace: Backtrace,
    reached_host: bool,
}

impl PanicPayload {
    fn clear(&mut self) {
        self.backtrace.clear();
        self.reached_host = false;
    }
}

/// Encodes information about a panic.
pub struct PanicData {
    panic: AtomicBool,
    cleaning_up: AtomicBool,
    payload: Mutex<PanicPayload>,
}

thread_local! {
    static PANIC: LazyCell<PanicData> = LazyCell::new(PanicData::new);
}

impl PanicData {
    fn new() -> PanicData {
        PanicData {
            panic: AtomicBool::new(false),
            cleaning_up: AtomicBool::new(false),
            payload: Mutex::new(PanicPayload {
                backtrace: Backtrace::new(),
                reached_host: false,
            }),
        }
    }

    /// Sets the panic data.
    /// If this function is called, the host's safety features will assume that the JIT code paniced
    /// and the stack was unrolled into this collection of panic data.
    fn set<R, F: FnOnce(&mut PanicPayload) -> R>(with: F, default: R) -> R {
        PANIC.with(|panic| {
            panic.panic.store(true, Ordering::Relaxed);
            if let Ok(mut backtrace) = panic.payload.lock() {
                backtrace.clear();
                with(&mut backtrace)
            } else {
                default
            }
        })
    }

    /// Fetches the local panic handling data from thread local storage.
    /// If there was no panic since the last time this function was called, it will return `None`.
    pub fn fetch<Runtime: 'static>(jit: &JIT<Runtime>, hir_phase: &HirPhase) -> Result<(), PanicError> {
        PANIC.with(|panic| if panic
            .panic
            .fetch_and(false, Ordering::Relaxed) {

            let payload = panic.payload.lock().unwrap();
            error!("encountered panic while executing JIT code in thread: {}",
                std::thread::current().name().unwrap_or("unknown"));
            error!("stack trace:");
            let t = payload.backtrace.get_panic_type(&jit.unwind_info)
                .unwrap_or(PanicType::Unknown);
            payload.backtrace.print(hir_phase, &*jit.func_reg.borrow(), &jit.unwind_info);
            error!("end of stack trace.");
            let recoverable = payload.reached_host && payload.backtrace.is_recoverable();
            if recoverable {
                error!("host function reached – attempting to recover through graceful panic protocol");
            } else {
                error!("host function was not reached during unwinding – graceful panic not possible");
                panic!("unrecoverable panic during JIT code execution");
            }

            let backtrace = payload.backtrace.printable(&jit.unwind_info);
            let msg = PanicMessage::take().map(|msg| msg.data);
            Err(PanicError {
                msg,
                graceful: recoverable,
                panic_type: t,
                backtrace,
            })
        } else {
            Ok(())
        })
    }
}

#[cfg_attr(feature="serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PanicType {
    BadConversionToInteger,
    HeapOutOfBounds,
    IntegerOverflow,
    StackOverflow,
    DivideByZero,
    ArrayIndexOutOfBounds,
    SliceIndexOutOfBounds,
    ArrayRangeOutOfBounds,
    SliceRangeOutOfBounds,
    Assertion,
    Explicit,
    Segfault,
    Other(&'static str),
    Unknown,
}

impl Display for PanicType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            PanicType::BadConversionToInteger => write!(f, "bad conversion to integer"),
            PanicType::HeapOutOfBounds => write!(f, "heap out of bounds"),
            PanicType::IntegerOverflow => write!(f, "integer overflow"),
            PanicType::StackOverflow => write!(f, "stack overflow"),
            PanicType::DivideByZero => write!(f, "divide by zero"),
            PanicType::ArrayIndexOutOfBounds => write!(f, "array index out of bounds"),
            PanicType::SliceIndexOutOfBounds => write!(f, "slice index out of bounds"),
            PanicType::ArrayRangeOutOfBounds => write!(f, "array range out of bounds"),
            PanicType::SliceRangeOutOfBounds => write!(f, "slice range out of bounds"),
            PanicType::Assertion => write!(f, "assertion failed"),
            PanicType::Explicit => write!(f, "explicit panic"),
            PanicType::Segfault => write!(f, "segfault panic"),
            PanicType::Other(s) => write!(f, "{s}"),
            PanicType::Unknown => write!(f, "unknown"),
        }
    }
}

#[cfg_attr(feature="serde", derive(Serialize, Deserialize))]
#[derive(Debug)]
pub struct PanicError {
    pub msg: Option<String>,
    pub graceful: bool,
    pub panic_type: PanicType,
    pub backtrace: PrintableBacktrace,
}

impl Display for PanicError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.panic_type)?;
        if let Some(msg) = self.msg.as_ref() {
            write!(f, ": {msg}")?;
        }
        if !self.graceful {
            write!(f, " !non recoverable - aborting!")?;
        }
        Ok(())
    }
}

/// User-defined panic message, that can be passed to a manual call to core::panic.
pub struct PanicMessage {
    pub data: String,
}

thread_local! {
    static PANIC_MSG: RefCell<Option<PanicMessage>> = const { RefCell::new(None) };
}

impl PanicMessage {
    pub fn set(msg: PanicMessage) {
        PANIC_MSG.set(Some(msg));
    }

    fn take() -> Option<PanicMessage> {
        PANIC_MSG.take()
    }
}