Skip to main content

rquickjs_core/runtime/
base.rs

1//! QuickJS runtime related types.
2
3use super::{
4    opaque::Opaque, raw::RawRuntime, InterruptHandler, MemoryUsage, PromiseHook, RejectionTracker,
5};
6use crate::allocator::Allocator;
7#[cfg(feature = "loader")]
8use crate::loader::{Loader, Resolver};
9use crate::{qjs, result::JobException, Context, Mut, Ref, Result, Weak};
10use alloc::{ffi::CString, vec::Vec};
11use core::{ptr::NonNull, result::Result as StdResult};
12#[cfg(feature = "parallel")]
13use std::sync::mpsc::{self, Sender};
14
15/// A weak handle to the runtime.
16///
17/// Holding onto this struct does not prevent the runtime from being dropped.
18#[derive(Clone)]
19pub struct WeakRuntime {
20    inner: Weak<Mut<RawRuntime>>,
21    #[cfg(feature = "parallel")]
22    pending_free: Sender<NonNull<qjs::JSContext>>,
23}
24
25impl WeakRuntime {
26    pub fn try_ref(&self) -> Option<Runtime> {
27        self.inner.upgrade().map(|inner| Runtime {
28            inner,
29            #[cfg(feature = "parallel")]
30            pending_free: self.pending_free.clone(),
31        })
32    }
33}
34
35/// QuickJS runtime, entry point of the library.
36#[derive(Clone)]
37pub struct Runtime {
38    pub(crate) inner: Ref<Mut<RawRuntime>>,
39    #[cfg(feature = "parallel")]
40    pub(crate) pending_free: Sender<NonNull<qjs::JSContext>>,
41}
42
43impl Runtime {
44    /// Create a new runtime.
45    ///
46    /// Will generally only fail if not enough memory was available.
47    ///
48    /// # Features
49    /// *If the `"rust-alloc"` feature is enabled the Rust's global allocator will be used in favor of libc's one.*
50    pub fn new() -> Result<Self> {
51        let opaque = Opaque::new();
52        #[cfg(feature = "parallel")]
53        let (pending_free, pending_free_recv) = mpsc::channel();
54        let rt = unsafe {
55            RawRuntime::new(
56                opaque,
57                #[cfg(feature = "parallel")]
58                pending_free_recv,
59            )?
60        };
61        Ok(Self {
62            inner: Ref::new(Mut::new(rt)),
63            #[cfg(feature = "parallel")]
64            pending_free,
65        })
66    }
67
68    /// Create a new runtime using specified allocator
69    ///
70    /// Will generally only fail if not enough memory was available.
71    pub fn new_with_alloc<A>(allocator: A) -> Result<Self>
72    where
73        A: Allocator + 'static,
74    {
75        let opaque = Opaque::new();
76        #[cfg(feature = "parallel")]
77        let (pending_free, pending_free_recv) = mpsc::channel();
78        let rt = unsafe {
79            RawRuntime::new_with_allocator(
80                opaque,
81                allocator,
82                #[cfg(feature = "parallel")]
83                pending_free_recv,
84            )?
85        };
86        Ok(Self {
87            inner: Ref::new(Mut::new(rt)),
88            #[cfg(feature = "parallel")]
89            pending_free,
90        })
91    }
92
93    /// Get weak ref to runtime
94    pub fn weak(&self) -> WeakRuntime {
95        WeakRuntime {
96            inner: Ref::downgrade(&self.inner),
97            #[cfg(feature = "parallel")]
98            pending_free: self.pending_free.clone(),
99        }
100    }
101
102    /// Attaches a versioned backend and returns the guard that owns it.
103    #[cfg(feature = "jit-abi")]
104    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "jit-abi")))]
105    pub fn attach_jit_backend<B>(
106        &self,
107        backend: B,
108    ) -> StdResult<super::RuntimeJitGuard, super::JitBackendAttachError>
109    where
110        B: super::JitBackend,
111    {
112        super::RuntimeJitGuard::attach(self, backend)
113    }
114
115    /// Returns the engine-assigned identity used by JIT artifacts.
116    #[cfg(feature = "jit-abi")]
117    #[doc(hidden)]
118    pub fn jit_runtime_id(&self) -> u64 {
119        self.inner.lock().jit_runtime_id()
120    }
121
122    /// Set a closure which is called when a promise is created, resolved, or chained.
123    #[inline]
124    pub fn set_promise_hook(&self, tracker: Option<PromiseHook>) {
125        unsafe {
126            self.inner.lock().set_promise_hook(tracker);
127        }
128    }
129
130    /// Set a closure which is called when a Promise is rejected.
131    #[inline]
132    pub fn set_host_promise_rejection_tracker(&self, tracker: Option<RejectionTracker>) {
133        unsafe {
134            self.inner
135                .lock()
136                .set_host_promise_rejection_tracker(tracker);
137        }
138    }
139
140    /// Set a closure which is regularly called by the engine when it is executing code.
141    /// If the provided closure returns `true` the interpreter will raise and uncatchable
142    /// exception and return control flow to the caller.
143    #[inline]
144    pub fn set_interrupt_handler(&self, handler: Option<InterruptHandler>) {
145        unsafe {
146            self.inner.lock().set_interrupt_handler(handler);
147        }
148    }
149
150    /// Set the module loader
151    #[cfg(feature = "loader")]
152    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "loader")))]
153    pub fn set_loader<R, L>(&self, resolver: R, loader: L)
154    where
155        R: Resolver + 'static,
156        L: Loader + 'static,
157    {
158        unsafe {
159            self.inner.lock().set_loader(resolver, loader);
160        }
161    }
162
163    /// Set the info of the runtime
164    pub fn set_info<S: Into<Vec<u8>>>(&self, info: S) -> Result<()> {
165        let string = CString::new(info)?;
166        unsafe {
167            self.inner.lock().set_info(string);
168        }
169        Ok(())
170    }
171
172    /// Set a limit on the max amount of memory the runtime will use.
173    ///
174    /// Setting the limit to 0 is equivalent to unlimited memory.
175    ///
176    /// Note that is a Noop when a custom allocator is being used,
177    /// as is the case for the "rust-alloc" or "allocator" features.
178    pub fn set_memory_limit(&self, limit: usize) {
179        unsafe {
180            self.inner.lock().set_memory_limit(limit);
181        }
182    }
183
184    /// Set a limit on the max size of stack the runtime will use.
185    ///
186    /// The default values is 256x1024 bytes.
187    pub fn set_max_stack_size(&self, limit: usize) {
188        unsafe {
189            self.inner.lock().set_max_stack_size(limit);
190        }
191    }
192
193    /// Set a memory threshold for garbage collection.
194    pub fn set_gc_threshold(&self, threshold: usize) {
195        unsafe {
196            self.inner.lock().set_gc_threshold(threshold);
197        }
198    }
199
200    /// Set debug flags for dumping memory
201    pub fn set_dump_flags(&self, flags: u64) {
202        unsafe {
203            self.inner.lock().set_dump_flags(flags);
204        }
205    }
206
207    /// Manually run the garbage collection.
208    ///
209    /// Most of QuickJS values are reference counted and
210    /// will automatically free themselves when they have no more
211    /// references. The garbage collector is only for collecting
212    /// cyclic references.
213    pub fn run_gc(&self) {
214        unsafe {
215            self.inner.lock().run_gc();
216        }
217    }
218
219    /// Get memory usage stats
220    pub fn memory_usage(&self) -> MemoryUsage {
221        unsafe { self.inner.lock().memory_usage() }
222    }
223
224    /// Test for pending jobs
225    ///
226    /// Returns true when at least one job is pending.
227    #[inline]
228    pub fn is_job_pending(&self) -> bool {
229        self.inner.lock().is_job_pending()
230    }
231
232    /// Execute first pending job
233    ///
234    /// Returns true when job was executed or false when queue is empty or error when exception thrown under execution.
235    #[inline]
236    pub fn execute_pending_job(&self) -> StdResult<bool, JobException> {
237        let mut lock = self.inner.lock();
238        lock.update_stack_top();
239        lock.execute_pending_job().map_err(|e| {
240            let ptr = NonNull::new(e).expect("QuickJS returned null ptr for job error");
241            // JS_ExecutePendingJob returns a borrowed context pointer;
242            // dup it so Context can own a reference.
243            unsafe { qjs::JS_DupContext(ptr.as_ptr()) };
244            JobException(unsafe { Context::from_raw(ptr, self.clone()) })
245        })
246    }
247}
248
249// Since all functions which use runtime are behind a mutex
250// sending the runtime to other threads should be fine.
251#[cfg(feature = "parallel")]
252unsafe impl Send for Runtime {}
253#[cfg(feature = "parallel")]
254unsafe impl Send for WeakRuntime {}
255
256// Since a global lock needs to be locked for safe use
257// using runtime in a sync way should be safe as
258// simultaneous accesses is synchronized behind a lock.
259#[cfg(feature = "parallel")]
260unsafe impl Sync for Runtime {}
261#[cfg(feature = "parallel")]
262unsafe impl Sync for WeakRuntime {}
263
264#[cfg(test)]
265mod test {
266    use super::*;
267    #[test]
268    fn base_runtime() {
269        let rt = Runtime::new().unwrap();
270        rt.set_info("test runtime").unwrap();
271        rt.set_memory_limit(0xFFFF);
272        rt.set_gc_threshold(0xFF);
273        rt.run_gc();
274    }
275
276    #[test]
277    fn set_max_stack_size_large_values() {
278        let rt = Runtime::new().unwrap();
279        rt.set_max_stack_size(usize::MAX);
280        let ctx = crate::Context::full(&rt).unwrap();
281        ctx.with(|ctx| {
282            ctx.eval::<i32, _>("1 + 1").unwrap();
283        });
284        rt.set_max_stack_size(isize::MAX as usize);
285        ctx.with(|ctx| {
286            ctx.eval::<i32, _>("1 + 1").unwrap();
287        });
288        rt.set_max_stack_size(0);
289        ctx.with(|ctx| {
290            ctx.eval::<i32, _>("1 + 1").unwrap();
291        });
292        rt.set_max_stack_size(256 * 1024);
293        ctx.with(|ctx| {
294            ctx.eval::<i32, _>("1 + 1").unwrap();
295        });
296    }
297
298    #[test]
299    fn context_dropped_while_lock_held() {
300        let rt = Runtime::new().unwrap();
301        let ctx1 = crate::Context::full(&rt).unwrap();
302        let ctx2 = crate::Context::full(&rt).unwrap();
303
304        ctx1.with(|_| {
305            drop(ctx2);
306        });
307    }
308
309    #[test]
310    #[cfg(feature = "parallel")]
311    fn context_parked_by_other_thread_is_still_freed() {
312        use std::sync::{Arc, Barrier};
313        use std::{thread, time::Duration};
314
315        let rt = Runtime::new().unwrap();
316        let ctx1 = crate::Context::full(&rt).unwrap();
317        let ctx2 = crate::Context::full(&rt).unwrap();
318
319        let barrier = Arc::new(Barrier::new(2));
320        let barrier_holder = barrier.clone();
321        let holder = thread::spawn(move || {
322            ctx1.with(|_| {
323                barrier_holder.wait();
324                thread::sleep(Duration::from_millis(100));
325            });
326        });
327
328        barrier.wait();
329        // The lock is held by the other thread, so this parks rather than
330        // freeing. Tearing the runtime down afterwards has to release it;
331        // `JS_FreeRuntime` aborts if any context is still alive.
332        drop(ctx2);
333
334        holder.join().unwrap();
335        drop(rt);
336    }
337}