tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

142 lignes · 5460 octetsBrut · Historique
1//! Callbacks from C into Louise (ADR 0015).
2//!
3//! An extern that takes a Louise function hands C a trampoline and a
4//! [`Callback`] as its `void *` environment. The trampoline converts C
5//! arguments to values and calls [`tl_callback_call`], which runs the
6//! closure **in the actor that called into C, on its stack and its
7//! thread**, while that extern call is in progress:
8//!
9//! - **No suspension.** C frames sit on the actor's fiber, and C code may
10//! rely on its thread (thread-locals, locks), so the fiber must neither
11//! park nor move. While a callback is possible, preemption only refills
12//! the budget (`sched::tl_preempt`), exit signals wait for the extern to
13//! return, and `blocking` externs run inline (`blocking`). The type
14//! checker limits callbacks to `<ffi>`, so they cannot reach `proc`
15//! operations or sockets; `sched::park` aborts if one ever does.
16//! - **Panics stay on the Louise side.** A panic in the closure unwinds
17//! to the trampoline (yield-bubbling never crosses a C frame), and stays
18//! pending in `ctx->yielding`: further calls return unit without running
19//! anything, C runs to completion, [`tl_callback_end`] discards the
20//! extern's result, and the generated code unwinds after the extern
21//! returns, as after any call that may unwind.
22//! - **Ownership.** The closure is the extern's argument, borrowed for the
23//! call; each call duplicates it (closure calls consume `self`).
24//! Arguments are consumed; the result is owned by the trampoline.
25
26use crate::abi::{Callback, Ctx, UNIT, Value, YIELD_NONE};
27use crate::heap::{drop_value, dup_value};
28use crate::prims::call_closure;
29
30/// Arguments a callback can take: five in registers after the closure,
31/// the rest in `ctx->xargs`.
32const MAX_ARGS: usize = 5 + crate::abi::XARGS;
33
34thread_local! {
35 /// Set on threads that must never run Louise code (the blocking pool).
36 static FOREIGN_THREAD: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
37 /// Its address identifies the current thread, cheaply.
38 static THREAD_TOKEN: u8 = const { 0 };
39}
40
41fn thread_token() -> usize {
42 THREAD_TOKEN.with(|t| t as *const u8 as usize)
43}
44
45/// Mark the current thread as one that never runs Louise code.
46pub(crate) fn mark_foreign_thread() {
47 FOREIGN_THREAD.with(|f| f.set(true));
48}
49
50/// Whether the current thread never runs Louise code (the blocking pool).
51pub(crate) fn on_foreign_thread() -> bool {
52 FOREIGN_THREAD.with(std::cell::Cell::get)
53}
54
55fn abort(message: &str) -> ! {
56 crate::console::flush_before_abort();
57 eprintln!("louise: {message}");
58 std::process::abort()
59}
60
61/// Prepare `cb` for passing `fun` (a closure, borrowed for the call) to
62/// C, from the extern call running in `ctx`'s actor.
63///
64/// # Safety
65/// `ctx` must be the running actor's context, `cb` writable, `fun` a live
66/// closure that outlives the matching [`tl_callback_end`].
67#[unsafe(no_mangle)]
68pub unsafe extern "C" fn tl_callback_begin(ctx: *mut Ctx, cb: *mut Callback, fun: Value) {
69 if FOREIGN_THREAD.with(std::cell::Cell::get) {
70 abort(
71 "a callback was set up on the blocking pool (`blocking` externs cannot take callbacks)",
72 );
73 }
74 // SAFETY: caller guarantees a running actor and a writable `cb`.
75 unsafe {
76 crate::sched::enter_callbacks(ctx);
77 cb.write(Callback {
78 ctx,
79 fun,
80 thread: thread_token(),
81 });
82 }
83}
84
85/// Call the callback's closure with `argc` arguments (consumed). Returns
86/// its result (owned), or unit without calling it if the actor is
87/// unwinding (a previous call panicked).
88///
89/// # Safety
90/// `cb` must have been set up by [`tl_callback_begin`]; `args` valid for
91/// `argc` owned values; the closure must take exactly `argc` arguments.
92#[unsafe(no_mangle)]
93pub unsafe extern "C" fn tl_callback_call(
94 cb: *const Callback,
95 argc: usize,
96 args: *const Value,
97) -> Value {
98 // SAFETY: caller guarantees a set-up callback and `argc` arguments.
99 unsafe {
100 let cb = &*cb;
101 if cb.thread != thread_token() {
102 abort(
103 "a callback was called on another thread than its extern call, or after that call returned",
104 );
105 }
106 if argc > MAX_ARGS {
107 abort("a callback takes at most 128 arguments");
108 }
109 let args = std::slice::from_raw_parts(args, argc);
110 if (*cb.ctx).yielding != YIELD_NONE {
111 for a in args {
112 drop_value(cb.ctx, *a);
113 }
114 return UNIT;
115 }
116 call_closure(cb.ctx, dup_value(cb.fun), args)
117 }
118}
119
120/// The extern call that set up `cb` is returning `result` (consumed):
121/// returns it, or drops it and returns unit if a callback panicked (the
122/// caller unwinds and never reads it).
123///
124/// # Safety
125/// `cb` must have been set up by [`tl_callback_begin`] in this call;
126/// `result` must be owned.
127#[unsafe(no_mangle)]
128pub unsafe extern "C" fn tl_callback_end(cb: *mut Callback, result: Value) -> Value {
129 // SAFETY: caller guarantees a set-up callback.
130 unsafe {
131 let ctx = (*cb).ctx;
132 // A late call through a dangling environment aborts if the memory
133 // is still intact (best effort).
134 (*cb).thread = 0;
135 crate::sched::leave_callbacks(ctx);
136 if (*ctx).yielding != YIELD_NONE {
137 drop_value(ctx, result);
138 return UNIT;
139 }
140 result
141 }
142}