rquickjs_core/runtime/
base.rs1use super::{
4 opaque::RuntimeOpaque, raw::RawRuntime, InterruptHandler, MemoryUsage, PromiseHook,
5 RejectionTracker,
6};
7use crate::allocator::Allocator;
8#[cfg(feature = "loader")]
9use crate::loader::{Loader, Resolver};
10use crate::{Mut, Ref, Result, Weak};
11use alloc::{ffi::CString, vec::Vec};
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<crate::context::owner::OwnedContext>,
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<crate::context::owner::OwnedContext>,
41}
42
43impl Runtime {
44 pub fn new() -> Result<Self> {
51 let opaque = RuntimeOpaque::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 = RuntimeOpaque::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 #[inline]
104 pub fn set_promise_hook(&self, tracker: Option<PromiseHook>) {
105 unsafe {
106 self.inner.lock().set_promise_hook(tracker);
107 }
108 }
109
110 #[inline]
112 pub fn set_host_promise_rejection_tracker(&self, tracker: Option<RejectionTracker>) {
113 unsafe {
114 self.inner
115 .lock()
116 .set_host_promise_rejection_tracker(tracker);
117 }
118 }
119
120 #[inline]
124 pub fn set_interrupt_handler(&self, handler: Option<InterruptHandler>) {
125 unsafe {
126 self.inner.lock().set_interrupt_handler(handler);
127 }
128 }
129
130 #[cfg(feature = "loader")]
132 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "loader")))]
133 pub fn set_loader<R, L>(&self, resolver: R, loader: L)
134 where
135 R: Resolver + 'static,
136 L: Loader + 'static,
137 {
138 unsafe {
139 self.inner.lock().set_loader(resolver, loader);
140 }
141 }
142
143 pub fn set_info<S: Into<Vec<u8>>>(&self, info: S) -> Result<()> {
145 let string = CString::new(info)?;
146 unsafe {
147 self.inner.lock().set_info(string);
148 }
149 Ok(())
150 }
151
152 pub fn set_memory_limit(&self, limit: usize) {
159 unsafe {
160 self.inner.lock().set_memory_limit(limit);
161 }
162 }
163
164 pub fn set_max_stack_size(&self, limit: usize) {
168 unsafe {
169 self.inner.lock().set_max_stack_size(limit);
170 }
171 }
172
173 pub fn set_gc_threshold(&self, threshold: usize) {
175 unsafe {
176 self.inner.lock().set_gc_threshold(threshold);
177 }
178 }
179
180 pub fn set_dump_flags(&self, flags: u64) {
182 unsafe {
183 self.inner.lock().set_dump_flags(flags);
184 }
185 }
186
187 pub fn run_gc(&self) {
194 unsafe {
195 self.inner.lock().run_gc();
196 }
197 }
198
199 pub fn memory_usage(&self) -> MemoryUsage {
201 unsafe { self.inner.lock().memory_usage() }
202 }
203
204 #[inline]
208 pub fn is_job_pending(&self) -> bool {
209 self.inner.lock().is_job_pending()
210 }
211}
212
213#[cfg(feature = "parallel")]
216unsafe impl Send for Runtime {}
217#[cfg(feature = "parallel")]
218unsafe impl Send for WeakRuntime {}
219
220#[cfg(feature = "parallel")]
224unsafe impl Sync for Runtime {}
225#[cfg(feature = "parallel")]
226unsafe impl Sync for WeakRuntime {}
227
228#[cfg(test)]
229mod test {
230 use super::*;
231 #[test]
232 fn base_runtime() {
233 let rt = Runtime::new().unwrap();
234 rt.set_info("test runtime").unwrap();
235 rt.set_memory_limit(0xFFFF);
236 rt.set_gc_threshold(0xFF);
237 rt.run_gc();
238 }
239
240 #[test]
241 fn set_max_stack_size_large_values() {
242 let rt = Runtime::new().unwrap();
243 rt.set_max_stack_size(usize::MAX);
244 let ctx = crate::Context::full(&rt).unwrap();
245 ctx.with(|ctx| {
246 ctx.eval::<i32, _>("1 + 1").unwrap();
247 });
248 rt.set_max_stack_size(isize::MAX as usize);
249 ctx.with(|ctx| {
250 ctx.eval::<i32, _>("1 + 1").unwrap();
251 });
252 rt.set_max_stack_size(0);
253 ctx.with(|ctx| {
254 ctx.eval::<i32, _>("1 + 1").unwrap();
255 });
256 rt.set_max_stack_size(256 * 1024);
257 ctx.with(|ctx| {
258 ctx.eval::<i32, _>("1 + 1").unwrap();
259 });
260 }
261
262 #[test]
263 fn context_dropped_while_lock_held() {
264 let rt = Runtime::new().unwrap();
265 let ctx1 = crate::Context::full(&rt).unwrap();
266 let ctx2 = crate::Context::full(&rt).unwrap();
267
268 ctx1.with(|_| {
269 drop(ctx2);
270 });
271 }
272
273 #[test]
274 #[cfg(feature = "parallel")]
275 fn context_parked_by_other_thread_is_still_freed() {
276 use std::sync::{Arc, Barrier};
277 use std::{thread, time::Duration};
278
279 let rt = Runtime::new().unwrap();
280 let ctx1 = crate::Context::full(&rt).unwrap();
281 let ctx2 = crate::Context::full(&rt).unwrap();
282
283 let barrier = Arc::new(Barrier::new(2));
284 let barrier_holder = barrier.clone();
285 let holder = thread::spawn(move || {
286 ctx1.with(|_| {
287 barrier_holder.wait();
288 thread::sleep(Duration::from_millis(100));
289 });
290 });
291
292 barrier.wait();
293 drop(ctx2);
297
298 holder.join().unwrap();
299 drop(rt);
300 }
301}