Skip to main content

sk_runtime/
bridge.rs

1//! The JS↔gpui call boundary: raw `&mut App` / `&mut Window` pointers are published for a bounded scope
2//! with an RAII guard (so a panic cannot leave a dangling pointer), tagged with a [`Phase`]. Host
3//! functions reach them only through [`with_commit`] / [`with_app`]; outside a published scope those
4//! return `None` and the caller must throw a JS error rather than touch gpui.
5
6use std::any::Any;
7use std::cell::Cell;
8use std::ffi::c_void;
9
10use gpui::{App, Window};
11
12#[derive(Clone, Copy, PartialEq, Eq, Debug)]
13pub enum Phase {
14    None,
15    App,
16    Commit,
17    Draw,
18}
19
20thread_local! {
21    static APP: Cell<*mut App> = const { Cell::new(std::ptr::null_mut()) };
22    static WINDOW: Cell<*mut Window> = const { Cell::new(std::ptr::null_mut()) };
23    static PHASE: Cell<Phase> = const { Cell::new(Phase::None) };
24    static POISONED: Cell<bool> = const { Cell::new(false) };
25    static LAST_PANIC: Cell<Option<(String, String)>> = const { Cell::new(None) };
26    static POISON_REASON: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
27    static DRAIN_OWED: Cell<bool> = const { Cell::new(false) };
28}
29
30/// A dispatch made under a gpui listener leaves its microtask checkpoint owed; every JS entry settles it
31/// first ([`settle_owed_drain`]). Call BEFORE the dispatch's call into JS. Keeps the engine's API lock until
32/// settled (JSC drains microtasks when the outermost lock is released). Returns `false` and owes nothing when
33/// JS is already running below the dispatch: owing there keeps a lock past the heap-access release and JSC aborts.
34pub fn owe_drain() -> bool {
35    if DRAIN_OWED.with(|c| c.get()) {
36        return true;
37    }
38    let owed = crate::JsRuntime::try_with(|rt| {
39        let g = rt.raw();
40        // SAFETY: the context is live and this is its VM thread; `rjs_in_js` runs under the lock
41        // just taken, so with JS on the stack the unlock only counts down.
42        unsafe {
43            redjs::ffi::redjs_lock(g);
44            if redjs::glue::rjs_in_js(g) != 0 {
45                redjs::ffi::redjs_unlock(g);
46                return false;
47            }
48        }
49        true
50    })
51    .unwrap_or(false);
52    DRAIN_OWED.with(|c| c.set(owed));
53    owed
54}
55
56pub fn drain_owed() -> bool {
57    DRAIN_OWED.with(|c| c.get())
58}
59
60/// Runs the owed checkpoint, if any, and releases the API lock. Every publication runs it first.
61pub fn settle_owed_drain() {
62    if !DRAIN_OWED.with(|c| c.replace(false)) {
63        return;
64    }
65    crate::JsRuntime::try_with(|rt| {
66        if !poisoned() {
67            rt.ctx().drain_microtasks();
68        }
69        // SAFETY: as in `owe_drain`, which took the lock this releases.
70        unsafe { redjs::ffi::redjs_unlock(rt.raw()) };
71    });
72}
73
74pub fn poisoned() -> bool {
75    POISONED.with(|c| c.get())
76}
77
78pub fn poison() {
79    POISONED.with(|c| c.set(true));
80}
81
82pub fn poison_reason() -> Option<String> {
83    POISON_REASON.with(|r| r.borrow().clone())
84}
85
86/// [`poison`], keeping the first reason given: the panic that broke the runtime, not one that followed.
87pub fn poison_with(reason: String) {
88    poison();
89    POISON_REASON.with(|r| {
90        let mut r = r.borrow_mut();
91        if r.is_none() {
92            *r = Some(reason);
93        }
94    });
95}
96
97pub fn describe_panic(message: &str, location: &str) -> String {
98    if location.is_empty() {
99        message.to_string()
100    } else {
101        format!("{message} at {location}")
102    }
103}
104
105struct Guard(*mut App, *mut Window, Phase);
106
107impl Drop for Guard {
108    fn drop(&mut self) {
109        APP.with(|c| c.set(self.0));
110        WINDOW.with(|c| c.set(self.1));
111        PHASE.with(|c| c.set(self.2));
112    }
113}
114
115/// Publishes `window` + `cx` for the duration of `f`, after settling an owed checkpoint.
116pub fn with_published<R>(
117    window: &mut Window,
118    cx: &mut App,
119    phase: Phase,
120    f: impl FnOnce() -> R,
121) -> R {
122    debug_assert!(matches!(phase, Phase::Commit | Phase::App));
123    let _g = Guard(
124        APP.with(|c| c.replace(cx as *mut App)),
125        WINDOW.with(|c| c.replace(window as *mut Window)),
126        PHASE.with(|c| c.replace(phase)),
127    );
128    settle_owed_drain();
129    f()
130}
131
132pub fn with_published_app<R>(cx: &mut App, f: impl FnOnce() -> R) -> R {
133    let _g = Guard(
134        APP.with(|c| c.replace(cx as *mut App)),
135        WINDOW.with(|c| c.replace(std::ptr::null_mut())),
136        PHASE.with(|c| c.replace(Phase::App)),
137    );
138    settle_owed_drain();
139    f()
140}
141
142/// Runs `f`, a `Window::draw` made inside a publication, as [`Phase::Draw`]: nothing is reachable until it
143/// returns (a forced layout draws from inside `Phase::Commit`; handing the pointers out again would alias).
144pub fn with_draw<R>(f: impl FnOnce() -> R) -> R {
145    let _g = Guard(
146        APP.with(|c| c.get()),
147        WINDOW.with(|c| c.get()),
148        PHASE.with(|c| c.replace(Phase::Draw)),
149    );
150    f()
151}
152
153/// The commit-phase accessor; `None` outside a `Phase::Commit` publication: throw, don't fall back.
154#[inline]
155pub fn with_commit<R>(f: impl FnOnce(&mut Window, &mut App) -> R) -> Option<R> {
156    if PHASE.with(|c| c.get()) != Phase::Commit {
157        return None;
158    }
159    let (a, w) = (APP.with(|c| c.get()), WINDOW.with(|c| c.get()));
160    debug_assert!(!a.is_null() && !w.is_null());
161    // SAFETY: non-null only inside `with_published`, which holds the `&mut`s
162    // for the whole scope; single-threaded (VM thread == gpui main thread).
163    Some(f(unsafe { &mut *w }, unsafe { &mut *a }))
164}
165
166#[inline]
167pub fn with_app<R>(f: impl FnOnce(&mut App) -> R) -> Option<R> {
168    if !matches!(PHASE.with(|c| c.get()), Phase::App | Phase::Commit) {
169        return None;
170    }
171    let a = APP.with(|c| c.get());
172    debug_assert!(!a.is_null());
173    // SAFETY: see `with_commit`.
174    Some(f(unsafe { &mut *a }))
175}
176
177pub fn install_panic_hook() {
178    let prev = std::panic::take_hook();
179    std::panic::set_hook(Box::new(move |info| {
180        let msg = info
181            .payload()
182            .downcast_ref::<&str>()
183            .map(|s| s.to_string())
184            .or_else(|| info.payload().downcast_ref::<String>().cloned())
185            .unwrap_or_else(|| "<non-string panic>".to_string());
186        let loc = info.location().map(|l| l.to_string()).unwrap_or_default();
187        LAST_PANIC.with(|c| c.set(Some((msg, loc))));
188        prev(info);
189    }));
190}
191
192fn throw_error(g: *mut c_void, kind: u32, msg: &str) -> u64 {
193    let utf16: Vec<u16> = msg.encode_utf16().collect();
194    let mut err = 0u64;
195    unsafe {
196        if redjs::ffi::redjs_error_create(g, kind, utf16.as_ptr(), utf16.len(), &mut err) == 0 {
197            redjs::ffi::redjs_throw(g, err);
198        }
199    }
200    redjs::api::Value::undefined().0
201}
202
203pub fn panic_to_js(g: *mut c_void, payload: Box<dyn Any + Send>) -> u64 {
204    let (msg, loc) = LAST_PANIC.with(|c| c.take()).unwrap_or_default();
205    let text = payload
206        .downcast_ref::<&str>()
207        .map(|s| s.to_string())
208        .or_else(|| payload.downcast_ref::<String>().cloned())
209        .unwrap_or(msg);
210    poison_with(describe_panic(&text, &loc));
211    throw_error(g, 0, &format!("native panic at {loc}: {text}"))
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use crate::JsRuntime;
218    use redjs::api::Value;
219
220    fn install_owe(rt: &JsRuntime) {
221        let f = rt
222            .ctx()
223            .function("owe", 0, |_g, _frame| Value::boolean(owe_drain()).0)
224            .unwrap();
225        rt.ctx().global_set("owe", f).unwrap();
226    }
227
228    fn read(rt: &JsRuntime, src: &str) -> String {
229        let v = rt.ctx().eval(src).unwrap();
230        rt.ctx().to_rust_string(v).unwrap()
231    }
232
233    /// Regression: owing a checkpoint under a forced layout's draw kept a lock past the heap access and aborted.
234    #[test]
235    fn a_dispatch_inside_running_js_owes_nothing() {
236        crate::testing::on_js_thread(|| {
237            JsRuntime::with(|rt| {
238                install_owe(rt);
239                rt.ctx()
240                    .eval("globalThis.seen = []; Promise.resolve().then(() => seen.push(owe()))")
241                    .unwrap();
242            });
243            assert!(
244                !drain_owed(),
245                "a dispatch nested in running JS owes nothing"
246            );
247            settle_owed_drain();
248            JsRuntime::with(|rt| {
249                unsafe { redjs::ffi::redjs_gc(rt.raw(), 0) };
250                assert_eq!(
251                    read(rt, "String(seen)"),
252                    "false",
253                    "the reaction ran in JSC's drain, and owed nothing"
254                );
255            });
256        });
257    }
258
259    #[test]
260    fn a_dispatch_outside_js_owes_its_checkpoint_until_it_is_settled() {
261        crate::testing::on_js_thread(|| {
262            assert!(owe_drain());
263            assert!(owe_drain(), "owing twice is one owed checkpoint");
264            JsRuntime::with(|rt| {
265                rt.ctx()
266                    .eval("globalThis.ran = false; Promise.resolve().then(() => { ran = true; })")
267                    .unwrap();
268                assert_eq!(
269                    read(rt, "String(ran)"),
270                    "false",
271                    "a call's end does not drain while the checkpoint is owed"
272                );
273            });
274            settle_owed_drain();
275            assert!(!drain_owed());
276            JsRuntime::with(|rt| {
277                unsafe { redjs::ffi::redjs_gc(rt.raw(), 0) };
278                assert_eq!(
279                    read(rt, "String(ran)"),
280                    "true",
281                    "the settle ran the checkpoint"
282                );
283            });
284        });
285    }
286
287    #[test]
288    fn a_draw_inside_a_publication_freezes_it() {
289        std::thread::spawn(|| {
290            PHASE.with(|c| c.set(Phase::Commit));
291            let inside = with_draw(|| {
292                let hidden = with_commit(|_, _| ()).is_none() && with_app(|_| ()).is_none();
293                (hidden, PHASE.with(|c| c.get()))
294            });
295            assert_eq!(inside, (true, Phase::Draw));
296            assert_eq!(PHASE.with(|c| c.get()), Phase::Commit);
297        })
298        .join()
299        .unwrap();
300    }
301
302    /// Runs on a thread of its own: the poison is per thread.
303    #[test]
304    fn the_first_poison_reason_is_kept() {
305        std::thread::spawn(|| {
306            assert!(!poisoned());
307            assert_eq!(poison_reason(), None);
308            poison_with(describe_panic(
309                "index out of bounds",
310                "crates/x/src/lib.rs:12:5",
311            ));
312            poison_with(describe_panic(
313                "already borrowed",
314                "crates/y/src/lib.rs:1:1",
315            ));
316            assert!(poisoned());
317            assert_eq!(
318                poison_reason().as_deref(),
319                Some("index out of bounds at crates/x/src/lib.rs:12:5")
320            );
321        })
322        .join()
323        .unwrap();
324    }
325}