edlc_codegen_cranelift 0.2.17

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
/*
 *     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/>.
 */

use crate::codegen::FunctionTranslator;
use crate::compiler::JIT;
use crate::error::{JITError, JITErrorType};
use crate::prelude::SSARepr;
use cranelift_codegen::ir::{types, InstBuilder, MemFlags, TrapCode, Value};
use cranelift_jit::JITModule;
use cranelift_module::{DataDescription, DataId, Linkage, Module, ModuleError};
use edlc_core::prelude::mir_type::MirTypeId;
use edlc_core::prelude::{MirError, MirPhase};
use std::sync::OnceLock;
use std::{mem, ptr, slice};

#[macro_export]
/// Creates a panic in the JIT executor and causes the current function to return with
/// uninitialized data.
///
/// # Safety
///
/// This macro **must only** be used in intrinsic functions which are **only** called by EDL
/// code.
/// In any other contexts, this will probably cause UB, since the inserted return instruction
/// returns uninitialized data.
macro_rules! jit_intrinsic_panic(
    ($val:expr) => (
        log::error!("JIT panic: {}", $val);
        $crate::compiler::panic_handle::RawPanicHandle::panic_global($val).unwrap();
        return unsafe { std::mem::MaybeUninit::uninit().assume_init() };
    );
);
pub use jit_intrinsic_panic;
use crate::trap;

static mut GLOBAL_JIT_PANIC_HANDLE: OnceLock<RawPanicHandle> = OnceLock::new();

pub struct RawPanicHandle {
    location: *const u8,
    size: usize,
    #[allow(dead_code)]
    stack_trace_size: usize,
    target_ptr_size: usize,
}

/// Layout of a panic:
///
/// 1. N-byte header
/// 2. N-byte stack trace depth
/// 3. n-byte message
/// 3.1 1-byte length
/// 3.2 message bytes
///
/// Here, N is the number of bytes in a pointer and n is an arbitrary buffer size.
/// For the header, currently only the first byte is actually important; it should be interpreted
/// as a boolean value and indicates if a panic is currently being unwound.
pub struct PanicHandle {
    location: DataId,
    size: usize,
    stack_trace_size: usize,
}

impl PanicHandle {
    pub fn new(
        data_context: &mut DataDescription,
        module: &mut JITModule,
        size: usize,
        stack_trace_size: usize,
    ) -> Result<Self, ModuleError> {
        assert!(size <= 256, "stack trace message in panic handler must be <= 256 bytes in size");

        // reserve space for global error handling
        let header_size = module.target_config().pointer_bytes() as usize * 2;
        data_context.define_zeroinit(header_size + size * stack_trace_size);
        let id = module
            .declare_data("__panic_handle", Linkage::Export, true, false)?;
        module.define_data(id, data_context)?;
        module.finalize_definitions()?;
        data_context.clear();

        Ok(Self {
            location: id,
            size,
            stack_trace_size,
        })
    }

    /// Sets the global panic handle to the value of this panic handle.
    ///
    /// If the global panic handle is already defined, this function will error.
    pub fn set_global(&self, module: &JITModule) -> Result<(), JITError> {
        let (ptr, _) = module
            .get_finalized_data(self.location);
        unsafe {
            #[allow(static_mut_refs)]
            GLOBAL_JIT_PANIC_HANDLE.set(RawPanicHandle {
                location: ptr,
                size: self.size,
                stack_trace_size: self.stack_trace_size,
                target_ptr_size: module.target_config().pointer_bytes() as usize,
            }).map_err(|_| JITError {
                ty: JITErrorType::RuntimeError("tried to redefine global panic handle".to_string())
            })?;
        }
        Ok(())
    }
}

impl<Runtime> JIT<Runtime> {
    /// Checks if the JIT has panicked during the last execution run.
    /// This should usually be done after every call to the JIT to correctly catch & forward
    /// panics originating in EDL.
    ///
    /// # Safety
    ///
    /// This function requires raw buffer access, which is naturally unsafe.
    /// However, as long as the panic handler has been initiated correctly, this should be
    /// perfectly safe.
    pub unsafe fn has_panicked(&self) -> Result<bool, MirError<JIT<Runtime>>> {
        let (ptr, _) = self.module
            .get_finalized_data(self.panic_handle.location);

        let has_panicked = ptr::read::<u8>(ptr);
        if has_panicked != 0 {
            return Ok(true)
        }
        Ok(false)
    }

    /// Checks if the EDL panic hook is activated and unwinds the panic into Rusts native panic
    /// handler, if it is.
    ///
    /// # Safety
    ///
    /// This function requires raw buffer access, which is naturally unsafe.
    /// However, as long as the panic handler has been initiated correctly, this should be
    /// perfectly safe.
    pub unsafe fn unwind_panic(&self) -> Result<(), JITError> {
        let (ptr, _) = self.module
            .get_finalized_data(self.panic_handle.location);

        let has_panicked = ptr::read::<u8>(ptr);
        if has_panicked == 0 {
            return Ok(());
        }

        let mut raw_ptr = ptr as usize + self.module.target_config().pointer_bytes() as usize;
        let stack_trace_size = ptr::read::<usize>(raw_ptr as *const u8 as *const usize);
        raw_ptr += self.module.target_config().pointer_bytes() as usize;

        let mut stack_trace = Vec::new();
        for depth in 0..stack_trace_size {
            let len = ptr::read::<u8>(raw_ptr as *const u8) as usize;
            raw_ptr += 1;
            let slice = slice::from_raw_parts(raw_ptr as *const u8, len);
            stack_trace.push(format!("{}: {}\n", depth, std::str::from_utf8_unchecked(slice)));
            raw_ptr += self.panic_handle.size - 1;
        }

        self.reset_panic_handler()?;
        Err(JITError {
            ty: JITErrorType::RuntimePanic(stack_trace),
        })
    }

    /// # Safety
    ///
    /// This function requires raw buffer access, which is naturally unsafe.
    /// However, as long as the panic handler has been initiated correctly, this should be
    /// perfectly safe.
    pub unsafe fn reset_panic_handler(&self) -> Result<(), JITError> {
        let (ptr, _) = self.module
            .get_finalized_data(self.panic_handle.location);
        ptr::write_bytes(ptr as *mut u8, 0, mem::size_of::<usize>() * 2);
        Ok(())
    }

    /// Causes a panic in the EDL executor.
    /// The panic will be unwound along the current EDL call stack, producing a proper stack trace.
    /// Finally, the panic is returned as a JITError in the Rust code that tried to execute the
    /// faulty EDL code.
    ///
    /// # Safety
    ///
    /// This function requires raw buffer access, which is naturally unsafe.
    /// However, as long as the panic handler has been initiated correctly, this should be
    /// perfectly safe.
    pub unsafe fn panic(&self, msg: &str) -> Result<(), JITError> {
        let (ptr, _) = self.module
            .get_finalized_data(self.panic_handle.location);

        let mut raw_ptr = ptr as usize;
        ptr::write::<u8>(raw_ptr as *mut u8, 0xff);
        raw_ptr += self.module.target_config().pointer_bytes() as usize;

        ptr::write::<usize>(raw_ptr as *mut usize, 1);
        raw_ptr += self.module.target_config().pointer_bytes() as usize;

        let bytes = msg.as_bytes();
        let len = usize::min(bytes.len(), self.panic_handle.size - 1);
        ptr::write::<u8>(raw_ptr as *mut u8, len as u8);

        for (idx, &b) in bytes.iter().enumerate() {
            raw_ptr += 1;
            if idx >= len {
                break;
            }

            ptr::write::<u8>(raw_ptr as *mut u8, b);
        }
        Ok(())
    }
}


impl RawPanicHandle {
    pub fn has_global_panicked() -> Result<bool, JITError> {
        unsafe {
            #[allow(static_mut_refs)]
            if let Some(global) = GLOBAL_JIT_PANIC_HANDLE.get() {
                global.has_panicked()
            } else {
                Ok(false)
            }
        }
    }

    pub fn unwind_global() -> Result<(), JITError> {
        unsafe {
            #[allow(static_mut_refs)]
            if let Some(global) = GLOBAL_JIT_PANIC_HANDLE.get() {
                global.unwind_panic()
            } else {
                Err(JITError {
                    ty: JITErrorType::RuntimeError(
                        "Tried to unwind global panic on empty panic handler".to_string())
                })
            }
        }
    }

    pub fn unwind_global_no_reset() -> Result<(), JITError> {
        unsafe {
            #[allow(static_mut_refs)]
            if let Some(global) = GLOBAL_JIT_PANIC_HANDLE.get() {
                global.unwind_panic_no_reset()
            } else {
                Err(JITError {
                    ty: JITErrorType::RuntimeError(
                        "Tried to unwind global panic on empty panic handler".to_string())
                })
            }
        }
    }

    pub fn reset_global() -> Result<(), JITError> {
        unsafe {
            #[allow(static_mut_refs)]
            if let Some(global) = GLOBAL_JIT_PANIC_HANDLE.get() {
                global.reset()
            } else {
                Err(JITError {
                    ty: JITErrorType::RuntimeError(
                        "Tried to reset global panic on empty panic handler".to_string())
                })
            }
        }
    }

    pub fn panic_global(msg: &str) -> Result<(), JITError> {
        unsafe {
            #[allow(static_mut_refs)]
            if let Some(global) = GLOBAL_JIT_PANIC_HANDLE.get() {
                global.panic(msg)
            } else {
                Err(JITError {
                    ty: JITErrorType::RuntimeError(
                        "Tried to invoke global panic on empty panic handler".to_string())
                })
            }
        }
    }

    pub fn has_panicked(&self) -> Result<bool, JITError> {
        unsafe {
            let has_panicked = ptr::read::<u8>(self.location);
            if has_panicked != 0 {
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// Unwraps the EDL panic stack into a JIT error.
    /// If a panic has been unwound, the panic stack is automatically reset by this method.
    pub fn unwind_panic(&self) -> Result<(), JITError> {
        unsafe {
            let res = self.unwind_panic_no_reset();
            if res.is_err() {
                self.reset()?;
            }
            res
        }
    }

    /// Unwraps the EDL panic stack into a JIT error.
    /// If a panic has been unwound, the panic stack will not be reset by this method.
    pub unsafe fn unwind_panic_no_reset(&self) -> Result<(), JITError> {
        let has_panicked = ptr::read::<u8>(self.location);
        if has_panicked == 0 {
            return Ok(());
        }

        let mut raw_ptr = self.location as usize + self.target_ptr_size;
        let stack_trace_size = ptr::read::<usize>(raw_ptr as *const u8 as *const usize);
        raw_ptr += self.target_ptr_size;

        let mut stack_trace = Vec::new();
        for depth in 0..stack_trace_size {
            let len = ptr::read::<u8>(raw_ptr as *const u8) as usize;
            raw_ptr += 1;
            let slice = slice::from_raw_parts(raw_ptr as *const u8, len);
            stack_trace.push(format!("{}: {}\n", depth, std::str::from_utf8_unchecked(slice)));
            raw_ptr += self.size - 1;
        }

        Err(JITError {
            ty: JITErrorType::RuntimePanic(stack_trace),
        })
    }

    pub fn reset(&self) -> Result<(), JITError> {
        unsafe {
            ptr::write_bytes(self.location as *mut u8, 0, self.target_ptr_size * 2);
        }
        Ok(())
    }

    pub fn panic(&self, msg: &str) -> Result<(), JITError> {
        unsafe {
            let mut raw_ptr = self.location as usize;
            ptr::write::<u8>(raw_ptr as *mut u8, 0xff);
            raw_ptr += self.target_ptr_size;

            ptr::write::<usize>(raw_ptr as *mut usize, 1);
            raw_ptr += self.target_ptr_size;

            let bytes = msg.as_bytes();
            let len = usize::min(bytes.len(), self.size - 1);
            ptr::write::<u8>(raw_ptr as *mut u8, len as u8);

            for (idx, &b) in bytes.iter().enumerate() {
                raw_ptr += 1;
                if idx >= len {
                    break;
                }
                ptr::write::<u8>(raw_ptr as *mut u8, b);
            }
        }
        Ok(())
    }
}

impl<'jit, Runtime> FunctionTranslator<'jit, Runtime> {
    fn store_stack_trace_entry(&mut self, msg: &str, ptr: Value) -> Result<(), MirError<JIT<Runtime>>> {
        let bytes = msg.as_bytes();
        let len = usize::min(bytes.len(), self.panic_handle.size - 1);
        let val = self.builder.ins().iconst(types::I8, len as i64);

        let mut off = self.module.target_config().pointer_bytes() as i32 * 2;
        self.builder
            .ins()
            .store(MemFlags::new(), val, ptr, off);

        for (idx, &b) in bytes.iter().enumerate() {
            off += 1;
            if idx >= len {
                break;
            }

            let val = self.builder
                .ins()
                .iconst(types::I8, b as i64);
            self.builder
                .ins()
                .store(MemFlags::new(), val, ptr, off);
        }
        Ok(())
    }

    /// Causes the EDL code to panic and unwind.
    pub fn panic(&mut self, msg: &str) -> Result<(), MirError<JIT<Runtime>>> {
        let data = self.module.declare_data_in_func(
            self.panic_handle.location,
            self.builder.func
        );
        let ptr = self.builder.ins().symbol_value(
            self.module.target_config().pointer_type(),
            data,
        );

        // set panic handle to `true`
        let val = self.builder.ins().iconst(types::I8, 0xff);
        self.builder.ins().store(MemFlags::new(), val, ptr, 0);
        // set stack trace depth to 1
        let ptr_ty = self.module.target_config().pointer_type();
        let val = self.builder.ins().iconst(ptr_ty, 1);
        self.builder.ins().store(MemFlags::new(), val, ptr, ptr_ty.bytes() as i32);

        // store message into buffer and set length
        self.store_stack_trace_entry(msg, ptr)?;
        self.builder.ins().trap(TrapCode::unwrap_user(trap::EXPLICIT_PANIC));
        Ok(())
    }
}