rquickjs_core/runtime/
base.rs1use 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#[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#[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 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 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 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 #[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 #[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 #[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 #[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 #[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 #[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 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 pub fn set_memory_limit(&self, limit: usize) {
179 unsafe {
180 self.inner.lock().set_memory_limit(limit);
181 }
182 }
183
184 pub fn set_max_stack_size(&self, limit: usize) {
188 unsafe {
189 self.inner.lock().set_max_stack_size(limit);
190 }
191 }
192
193 pub fn set_gc_threshold(&self, threshold: usize) {
195 unsafe {
196 self.inner.lock().set_gc_threshold(threshold);
197 }
198 }
199
200 pub fn set_dump_flags(&self, flags: u64) {
202 unsafe {
203 self.inner.lock().set_dump_flags(flags);
204 }
205 }
206
207 pub fn run_gc(&self) {
214 unsafe {
215 self.inner.lock().run_gc();
216 }
217 }
218
219 pub fn memory_usage(&self) -> MemoryUsage {
221 unsafe { self.inner.lock().memory_usage() }
222 }
223
224 #[inline]
228 pub fn is_job_pending(&self) -> bool {
229 self.inner.lock().is_job_pending()
230 }
231
232 #[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 unsafe { qjs::JS_DupContext(ptr.as_ptr()) };
244 JobException(unsafe { Context::from_raw(ptr, self.clone()) })
245 })
246 }
247}
248
249#[cfg(feature = "parallel")]
252unsafe impl Send for Runtime {}
253#[cfg(feature = "parallel")]
254unsafe impl Send for WeakRuntime {}
255
256#[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 drop(ctx2);
333
334 holder.join().unwrap();
335 drop(rt);
336 }
337}