quickjs/state.rs
1//! Runtime and context state: limits, GC, opaque pointers, context values, memory reporting
2//! and `JS_PrintValue`.
3//!
4//! # Which of these are real and which are "accepted and recorded"
5//!
6//! A limit that the engine does not enforce must not pretend to. `JS_SetMemoryLimit` and
7//! `JS_SetMaxStackSize` map onto `Runtime::set_memory_limit`/`set_stack_size`, which the
8//! allocator and the call-depth check already consult — so those are real.
9//! `JS_SetGCThreshold` maps onto the heap's threshold, also real.
10//! `JS_SetInterruptHandler` is real but only checked where the engine already yields
11//! (`docs/m15-plan.md` §5: not between every opcode), and that limit is stated in the README.
12//! `JS_SetCanBlock`, `JS_SetStripInfo` and `JS_SetRuntimeInfo` are recorded and have no
13//! observable effect, which is stated at each one.
14//!
15//! # Why the memory report is not a fabrication
16//!
17//! `JS_ComputeMemoryUsage` fills a `JSMemoryUsage` whose fields a C program prints. Filling
18//! them with plausible-looking zeros would be worse than filling the ones that are actually
19//! known: a host that logs `malloc_size` and sees `0` knows the number is unavailable, whereas
20//! one that sees an invented `4096` believes it.
21//!
22//! Every field is now measured by the engine's own walk (`engine::memory::compute`), which
23//! visits the live heap blocks and downcasts — the same design as the reference's
24//! `JS_ComputeMemoryUsage`, which walks its object lists. The one field pair left at zero is
25//! `shape_count`/`shape_size`: this engine has no hidden-class sharing, so there is nothing to
26//! count, and `JS_DumpMemoryUsage` prints it as `(not modelled)` rather than as a measured
27//! zero.
28
29use core::ffi::{c_char, c_int, c_void};
30
31use engine::Value;
32
33use crate::cdefs::{Bool, JSMemoryUsage, JSPrintValueOptions, PrintValueWrite};
34use crate::conversions::arg;
35use crate::jsvalue::{self, JsValue};
36use crate::runtime::{self, JsContext, JsRuntime};
37use crate::value_helpers::jsvalue_of;
38
39// ---------------------------------------------------------------------------
40// Limits
41// ---------------------------------------------------------------------------
42
43/// `JS_SetMemoryLimit`: refuse an allocation that would take the heap past `limit` bytes.
44///
45/// **`0` means "no memory at all", not "no limit".** The reference's `malloc_limit` is a
46/// `size_t` initialised to `-1`, and `js_malloc` fails when `malloc_size + size > limit`, so
47/// a host that wants to remove a limit passes `(size_t)-1`. That is worth stating because it
48/// is the opposite of what a "0 disables it" instinct expects, and getting it wrong here
49/// would have made every allocation after the call fail — which is exactly what happened
50/// when this layer first mapped `0` onto "unlimited" and `tests/c/embed.c` caught it.
51///
52/// # Safety
53///
54/// `rt` must be a live runtime.
55#[unsafe(no_mangle)]
56pub unsafe extern "C" fn JS_SetMemoryLimit(rt: *mut JsRuntime, limit: usize) {
57 let Some(runtime) = (unsafe { rt.as_ref() }) else {
58 return;
59 };
60 // SAFETY: the engine runtime is boxed and this pointer is the only writer; the C API is
61 // single-threaded per runtime by contract, and `&mut` through a raw pointer is how a
62 // `*mut JSRuntime` reaches it.
63 let engine = unsafe { &mut *(runtime.engine_ptr() as *mut engine::Runtime) };
64 // `Some(limit)`, always: a limit of zero is a real limit (nothing may be allocated),
65 // which is what the reference does. The engine's `Option` is only for "no limit", and
66 // that arrives as `(size_t)-1` from the host.
67 engine.set_memory_limit(if limit == usize::MAX {
68 None
69 } else {
70 Some(limit)
71 });
72}
73
74/// `JS_SetMaxStackSize`: cap the call depth, `0` to disable the check.
75///
76/// # Safety
77///
78/// `rt` must be a live runtime.
79#[unsafe(no_mangle)]
80pub unsafe extern "C" fn JS_SetMaxStackSize(rt: *mut JsRuntime, stack_size: usize) {
81 let Some(runtime) = (unsafe { rt.as_ref() }) else {
82 return;
83 };
84 // SAFETY: as `JS_SetMemoryLimit`.
85 let engine = unsafe { &mut *(runtime.engine_ptr() as *mut engine::Runtime) };
86 let limit = if stack_size == 0 {
87 None
88 } else {
89 Some(stack_size)
90 };
91 engine.set_stack_size(limit);
92 // The engine's field is what a *later* context picks up; a context that already ran
93 // something owns its interpreter, and it has to be told now — the same ordering problem
94 // [`JS_SetMemoryLimit`] had, which the heap solves for memory and the interpreter cannot.
95 if let Some(limit) = limit {
96 for context in runtime.live_contexts() {
97 // SAFETY: every pointer in the list is live until `JS_FreeContext`.
98 if let Some(context) = unsafe { context.as_ref() } {
99 context.set_stack_limit(limit);
100 }
101 }
102 }
103}
104
105/// `JS_SetGCThreshold`: collect once the heap holds `threshold` bytes.
106///
107/// # Safety
108///
109/// `rt` must be a live runtime.
110#[unsafe(no_mangle)]
111pub unsafe extern "C" fn JS_SetGCThreshold(rt: *mut JsRuntime, gc_threshold: usize) {
112 let Some(runtime) = (unsafe { rt.as_ref() }) else {
113 return;
114 };
115 runtime.set_gc_threshold(gc_threshold);
116 runtime.engine.heap().set_threshold(gc_threshold);
117}
118
119/// `JS_SetInterruptHandler`: call `cb` periodically while a script runs.
120///
121/// Returning non-zero from the callback aborts the script. The engine checks the handler at
122/// the sites it already yields at (loop back-edges and calls), which is enough for "stop this
123/// runaway script" and *not* enough for single-stepping — see the README's limitations
124/// section, where that is stated as the reason `debugger` is not implemented on top of it.
125///
126/// # Safety
127///
128/// `rt` must be a live runtime and `cb`, if non-null, a `JSInterruptHandler`.
129#[unsafe(no_mangle)]
130pub unsafe extern "C" fn JS_SetInterruptHandler(
131 rt: *mut JsRuntime,
132 cb: crate::cdefs::InterruptHandler,
133 opaque: *mut c_void,
134) {
135 let Some(runtime) = (unsafe { rt.as_ref() }) else {
136 return;
137 };
138 runtime.set_interrupt_handler(cb, opaque);
139 // A context that already ran something has a live interpreter, and it has to learn about
140 // the handler now rather than at its next entry point: `JS_SetInterruptHandler` is
141 // documented as taking effect for the *next* evaluation, which is also the next poll.
142 for context in runtime.live_contexts() {
143 // SAFETY: every pointer in the list is live until `JS_FreeContext`.
144 if let Some(context) = unsafe { context.as_ref() } {
145 context.install_interrupt_hook();
146 }
147 }
148}
149
150/// `JS_RunGC`: collect now.
151///
152/// # Safety
153///
154/// `rt` must be a live runtime.
155#[unsafe(no_mangle)]
156pub unsafe extern "C" fn JS_RunGC(rt: *mut JsRuntime) {
157 let Some(runtime) = (unsafe { rt.as_ref() }) else {
158 return;
159 };
160 runtime.engine.run_gc();
161}
162
163/// `JS_UpdateStackTop`: tell the engine where this thread's stack starts.
164///
165/// The engine measures depth in frames rather than bytes, so there is no stack top to update.
166/// The reference needs this after a thread switch; a C host that moves a runtime between
167/// threads still gets the frame-based check, which is thread-independent.
168///
169/// # Safety
170///
171/// The argument is ignored.
172#[unsafe(no_mangle)]
173pub unsafe extern "C" fn JS_UpdateStackTop(_rt: *mut JsRuntime) {}
174
175/// `JS_SetCanBlock`: whether a blocking operation (a synchronous `Atomics.wait`) is allowed.
176///
177/// # Safety
178///
179/// `rt` must be a live runtime.
180#[unsafe(no_mangle)]
181pub unsafe extern "C" fn JS_SetCanBlock(rt: *mut JsRuntime, can_block: Bool) {
182 let Some(runtime) = (unsafe { rt.as_ref() }) else {
183 return;
184 };
185 runtime.set_can_block(can_block != 0);
186}
187
188/// `JS_SetStripInfo`: record how much debug info to keep.
189///
190/// The engine never compiles debug info away, so the flag is stored and has no effect. A host
191/// that sets it still gets full stack traces, which is the safe direction (more information,
192/// not less).
193///
194/// # Safety
195///
196/// `rt` must be a live runtime.
197#[unsafe(no_mangle)]
198pub unsafe extern "C" fn JS_SetStripInfo(rt: *mut JsRuntime, flags: c_int) {
199 if let Some(runtime) = unsafe { rt.as_ref() } {
200 runtime.set_strip_info(flags);
201 }
202}
203
204/// `JS_GetStripInfo`: the value last given to [`JS_SetStripInfo`].
205///
206/// # Safety
207///
208/// `rt` must be a live runtime.
209#[unsafe(no_mangle)]
210pub unsafe extern "C" fn JS_GetStripInfo(rt: *mut JsRuntime) -> c_int {
211 match unsafe { rt.as_ref() } {
212 Some(runtime) => runtime.strip_info(),
213 None => 0,
214 }
215}
216
217/// `JS_SetRuntimeInfo`: a label for diagnostics.
218///
219/// # Safety
220///
221/// `info` must be null or NUL-terminated, and outlive the runtime as the header requires.
222#[unsafe(no_mangle)]
223pub unsafe extern "C" fn JS_SetRuntimeInfo(rt: *mut JsRuntime, info: *const c_char) {
224 if let Some(runtime) = unsafe { rt.as_ref() } {
225 runtime.set_info(info);
226 }
227}
228
229/// `JS_GetRuntimeOpaque`: the host's pointer.
230///
231/// # Safety
232///
233/// `rt` must be a live runtime.
234#[unsafe(no_mangle)]
235pub unsafe extern "C" fn JS_GetRuntimeOpaque(rt: *mut JsRuntime) -> *mut c_void {
236 match unsafe { rt.as_ref() } {
237 Some(runtime) => runtime.opaque(),
238 None => std::ptr::null_mut(),
239 }
240}
241
242/// `JS_SetRuntimeOpaque`.
243///
244/// # Safety
245///
246/// `rt` must be a live runtime.
247#[unsafe(no_mangle)]
248pub unsafe extern "C" fn JS_SetRuntimeOpaque(rt: *mut JsRuntime, opaque: *mut c_void) {
249 if let Some(runtime) = unsafe { rt.as_ref() } {
250 runtime.set_opaque(opaque);
251 }
252}
253
254/// `JS_NewRuntime2`: a runtime with the host's allocator.
255///
256/// The engine's allocations go through Rust's global allocator, which a C-supplied
257/// `JSMallocFunctions` cannot replace without a per-runtime allocator threaded through `Gc`.
258/// The runtime is created with the default allocator and the functions are ignored; a caller
259/// that needs its own allocator must not use this library. Recorded in the README.
260///
261/// # Safety
262///
263/// `mf` is ignored; the answer is a live runtime, or null when allocation fails.
264#[unsafe(no_mangle)]
265pub unsafe extern "C" fn JS_NewRuntime2(
266 _mf: *const crate::cdefs::JSMallocFunctions,
267 _opaque: *mut c_void,
268) -> *mut JsRuntime {
269 Box::into_raw(JsRuntime::new())
270}
271
272// ---------------------------------------------------------------------------
273// Contexts
274// ---------------------------------------------------------------------------
275
276/// `JS_DupContext`: raise the context's reference count and answer the same pointer.
277///
278/// The reference does exactly this — a context is not copyable, only reference-counted — and
279/// the count is what makes the documented idiom safe: hand a context to a callback, release
280/// it when the callback returns, and the host's own release still finds it alive.
281///
282/// # Safety
283///
284/// `ctx` must be a live context.
285#[unsafe(no_mangle)]
286pub unsafe extern "C" fn JS_DupContext(ctx: *mut JsContext) -> *mut JsContext {
287 if let Some(context) = unsafe { ctx.as_ref() } {
288 context.raise_refs();
289 }
290 ctx
291}
292
293/// `JS_GetContextOpaque`.
294///
295/// # Safety
296///
297/// `ctx` must be a live context.
298#[unsafe(no_mangle)]
299pub unsafe extern "C" fn JS_GetContextOpaque(ctx: *mut JsContext) -> *mut c_void {
300 match unsafe { ctx.as_ref() } {
301 Some(context) => context.opaque(),
302 None => std::ptr::null_mut(),
303 }
304}
305
306/// `JS_SetContextOpaque`.
307///
308/// # Safety
309///
310/// `ctx` must be a live context.
311#[unsafe(no_mangle)]
312pub unsafe extern "C" fn JS_SetContextOpaque(ctx: *mut JsContext, opaque: *mut c_void) {
313 if let Some(context) = unsafe { ctx.as_ref() } {
314 context.set_opaque(opaque);
315 }
316}
317
318/// `JS_SetContextValue`: store a value at one of the context's private slots.
319///
320/// # Safety
321///
322/// `ctx` must be a live context; `val`'s reference is consumed.
323#[unsafe(no_mangle)]
324pub unsafe extern "C" fn JS_SetContextValue(ctx: *mut JsContext, idx: c_int, val: JsValue) {
325 let Some(context) = (unsafe { ctx.as_ref() }) else {
326 // SAFETY: the C API consumes the reference whatever happens.
327 unsafe { runtime::release(val) };
328 return;
329 };
330 let value = unsafe { arg(val) }.unwrap_or(Value::Undefined);
331 // SAFETY: the C API consumes it.
332 unsafe { runtime::release(val) };
333 context.set_value(idx, value);
334}
335
336/// `JS_GetContextValue`: the value at slot `idx`, or `undefined`.
337///
338/// # Safety
339///
340/// `ctx` must be a live context.
341#[unsafe(no_mangle)]
342pub unsafe extern "C" fn JS_GetContextValue(ctx: *mut JsContext, idx: c_int) -> JsValue {
343 let Some(context) = (unsafe { ctx.as_ref() }) else {
344 return jsvalue::EXCEPTION;
345 };
346 match context.value(idx) {
347 Some(value) => jsvalue_of(value),
348 None => jsvalue::UNDEFINED,
349 }
350}
351
352/// `JS_NewContextRaw`: a context with no intrinsics installed.
353///
354/// The engine installs its builtins when it builds an interpreter, at which point a context
355/// *has* an interpreter and the intrinsic set is no longer a choice. So this is
356/// `JS_NewContext`: a raw context here still has `Object` and `Array`. A caller that wanted
357/// the reduced context must not use this library; the README says so next to
358/// `JS_AddIntrinsicIntl`.
359///
360/// # Safety
361///
362/// `rt` must be a live runtime.
363#[unsafe(no_mangle)]
364pub unsafe extern "C" fn JS_NewContextRaw(rt: *mut JsRuntime) -> *mut JsContext {
365 // SAFETY: the caller's contract is `JS_NewContext`'s.
366 unsafe { crate::runtime::JS_NewContext(rt) }
367}
368
369// ---------------------------------------------------------------------------
370// Memory usage
371// ---------------------------------------------------------------------------
372
373/// `JS_ComputeMemoryUsage`: fill `s` with what this runtime occupies.
374///
375/// Every field is measured, by the engine's own walk (`engine::memory::compute`). It used to
376/// fill two and zero the rest; now the only fields left at zero are the ones this engine
377/// genuinely has no equivalent for, and each is commented where it is set below.
378///
379/// # Safety
380///
381/// `rt` must be a live runtime and `s` writable.
382#[unsafe(no_mangle)]
383pub unsafe extern "C" fn JS_ComputeMemoryUsage(rt: *mut JsRuntime, s: *mut JSMemoryUsage) {
384 if s.is_null() {
385 return;
386 }
387 let mut usage = JSMemoryUsage::default();
388 if let Some(runtime) = unsafe { rt.as_ref() } {
389 let (measured, _) = engine::memory::compute(runtime.engine.heap());
390 usage.malloc_count = measured.malloc_count;
391 usage.malloc_size = measured.malloc_size;
392 usage.memory_used_count = measured.memory_used_count;
393 usage.memory_used_size = measured.memory_used_size;
394 // -1 for "no limit", which is the reference's `(size_t)-1` and is what the table
395 // prints; `JS_SetMemoryLimit(rt, 0)` therefore reports 0, not "unlimited".
396 usage.malloc_limit = measured.malloc_limit;
397 usage.str_count = measured.str_count;
398 usage.str_size = measured.str_size;
399 usage.obj_count = measured.obj_count;
400 usage.obj_size = measured.obj_size;
401 usage.prop_count = measured.prop_count;
402 usage.prop_size = measured.prop_size;
403 usage.shape_count = measured.shape_count;
404 usage.shape_size = measured.shape_size;
405 usage.js_func_count = measured.js_func_count;
406 usage.js_func_size = measured.js_func_size;
407 usage.js_func_code_size = measured.js_func_code_size;
408 usage.js_func_pc2line_count = measured.js_func_pc2line_count;
409 usage.js_func_pc2line_size = measured.js_func_pc2line_size;
410 usage.c_func_count = measured.c_func_count;
411 usage.array_count = measured.array_count;
412 usage.fast_array_count = measured.fast_array_count;
413 usage.fast_array_elements = measured.fast_array_elements;
414 usage.binary_object_count = measured.binary_object_count;
415 usage.binary_object_size = measured.binary_object_size;
416 // `atom_count`/`atom_size` are the C API's own interned names: the engine has no atom
417 // table (property keys are ordinary strings there), but this layer *does* intern the
418 // names a C host passes in, and a binding that leaks atoms wants to see them.
419 let atoms = runtime.atoms.borrow();
420 usage.atom_count = i64::try_from(atoms.len()).unwrap_or(i64::MAX);
421 }
422 // SAFETY: the caller guarantees a writable pointer.
423 unsafe { s.write(usage) };
424}
425
426/// `JS_DumpMemoryUsage`: print the report to `fp`.
427///
428/// The same table `qjs -d` prints, rendered by the same function
429/// (`engine::memory::dump`), so a C host and the CLI cannot drift apart. The reference's
430/// `JS_DumpMemoryUsage(stdout, &stats, rt)` needs `rt` for its per-class census; the caller
431/// passes the one it computed `s` from.
432///
433/// # Safety
434///
435/// `fp` must be a writable `FILE *` and `s` a filled `JSMemoryUsage`.
436#[unsafe(no_mangle)]
437pub unsafe extern "C" fn JS_DumpMemoryUsage(
438 fp: *mut c_void,
439 s: *const JSMemoryUsage,
440 rt: *mut JsRuntime,
441) {
442 if fp.is_null() || s.is_null() {
443 return;
444 }
445 // SAFETY: the caller guarantees a live `FILE *` and a filled structure.
446 let usage = unsafe { &*s };
447 let census = match unsafe { rt.as_ref() } {
448 Some(runtime) => engine::memory::compute(runtime.engine.heap()).1,
449 None => engine::memory::ClassCensus::default(),
450 };
451 let report = engine::memory::dump(&memory_usage_of(usage), &census);
452 // SAFETY: `fp` is a `FILE *` the caller opened; `fwrite` reads `len` bytes from `report`.
453 unsafe { fwrite(report.as_ptr().cast(), 1, report.len(), fp) };
454}
455
456// `fwrite(3)`, declared here rather than reached through `libc`.
457//
458// `libc` is a `cfg(unix)` dependency of this crate — its only job is `dlopen`, which has no
459// Windows equivalent here (`src/modules.rs` reports native modules as unloadable there).
460// `fwrite` is not in that category: it is C89 and every Windows toolchain this could be
461// built with links it from the CRT, so an `extern "C"` declaration is both portable and one
462// fewer platform-specific dependency.
463unsafe extern "C" {
464 /// The C library's buffered write.
465 fn fwrite(ptr: *const c_void, size: usize, count: usize, stream: *mut c_void) -> usize;
466}
467
468/// The C struct, as the engine's own structure — field for field, so the renderer takes one
469/// type rather than two.
470fn memory_usage_of(usage: &JSMemoryUsage) -> engine::memory::MemoryUsage {
471 engine::memory::MemoryUsage {
472 malloc_count: usage.malloc_count,
473 malloc_size: usage.malloc_size,
474 memory_used_count: usage.memory_used_count,
475 memory_used_size: usage.memory_used_size,
476 malloc_limit: usage.malloc_limit,
477 str_count: usage.str_count,
478 str_size: usage.str_size,
479 obj_count: usage.obj_count,
480 obj_size: usage.obj_size,
481 prop_count: usage.prop_count,
482 prop_size: usage.prop_size,
483 shape_count: usage.shape_count,
484 shape_size: usage.shape_size,
485 js_func_count: usage.js_func_count,
486 js_func_size: usage.js_func_size,
487 js_func_code_size: usage.js_func_code_size,
488 js_func_pc2line_count: usage.js_func_pc2line_count,
489 js_func_pc2line_size: usage.js_func_pc2line_size,
490 c_func_count: usage.c_func_count,
491 array_count: usage.array_count,
492 fast_array_count: usage.fast_array_count,
493 fast_array_elements: usage.fast_array_elements,
494 binary_object_count: usage.binary_object_count,
495 binary_object_size: usage.binary_object_size,
496 }
497}
498
499// ---------------------------------------------------------------------------
500// Printing a value
501// ---------------------------------------------------------------------------
502
503/// `JS_PrintValueSetDefaultOptions`: the options a fresh `JSPrintValueOptions` should hold.
504///
505/// **Not** zeros: the reference fills in `max_depth = 2`, `max_string_length = 1000` and
506/// `max_item_count = 100`. This function used to write zeros and the symbol table said that
507/// was "the header's default" — the header says nothing of the kind, and its implementation
508/// in `quickjs.c` is five lines of explicit assignment. A host that called this and then
509/// `JS_PrintValue` got an unbounded dump where the reference truncates at depth 2.
510///
511/// # Safety
512///
513/// `options` must be writable.
514#[unsafe(no_mangle)]
515pub unsafe extern "C" fn JS_PrintValueSetDefaultOptions(options: *mut JSPrintValueOptions) {
516 if options.is_null() {
517 return;
518 }
519 // SAFETY: the caller guarantees a writable pointer.
520 unsafe {
521 options.write(JSPrintValueOptions {
522 show_hidden: 0,
523 raw_dump: 0,
524 max_depth: 2,
525 max_string_length: 1000,
526 max_item_count: 100,
527 });
528 }
529}
530
531/// `JS_PrintValue`: render `val` through `write_func`.
532///
533/// The rendering is the engine's own `describe` (the one a REPL uses), which prints strings
534/// quoted, objects as `{ a: 1 }` and functions as `[Function: f]`. The options are accepted
535/// but only `show_hidden` is honoured, by way of the same describe; the three limits are not,
536/// and a caller relying on `max_depth` gets an unbounded rendering — stated in the README.
537///
538/// # Safety
539///
540/// `write_func` must be a `JSPrintValueWrite`; `val` a live `JSValue`.
541#[unsafe(no_mangle)]
542pub unsafe extern "C" fn JS_PrintValue(
543 ctx: *mut JsContext,
544 write_func: PrintValueWrite,
545 write_opaque: *mut c_void,
546 val: JsValue,
547 options: *const JSPrintValueOptions,
548) {
549 let Some(context) = (unsafe { ctx.as_ref() }) else {
550 return;
551 };
552 let Some(value) = (unsafe { arg(val) }) else {
553 return;
554 };
555 // `options` may be null, and then the reference's defaults apply (depth 2, 1000
556 // characters, 100 items) — the same numbers `JS_PrintValueSetDefaultOptions` writes.
557 let limits = if options.is_null() {
558 engine::print::PrintLimits::default()
559 } else {
560 // SAFETY: the caller guarantees the pointer is readable for the duration of the call.
561 let options = unsafe { &*options };
562 engine::print::PrintLimits {
563 // Zero does **not** mean "print nothing": the header says "0 = no limit", so it
564 // has to become a number large enough to never trigger. The fields are
565 // `uint32_t` in the header, which is why `as usize` is a widening conversion.
566 max_depth: if options.max_depth == 0 {
567 usize::MAX
568 } else {
569 options.max_depth as usize
570 },
571 max_string_length: if options.max_string_length == 0 {
572 usize::MAX
573 } else {
574 options.max_string_length as usize
575 },
576 max_item_count: if options.max_item_count == 0 {
577 usize::MAX
578 } else {
579 options.max_item_count as usize
580 },
581 }
582 };
583 let text = context.with_current_interp(|interp| {
584 match engine::print::sprint_limited(interp, &value, limits) {
585 Ok(text) => text,
586 // A printer that fails must not take the reporter down with it; the reference falls
587 // back to the class name, and so does this.
588 Err(_) => format!("[{}]", value.type_of()),
589 }
590 });
591 emit(write_func, write_opaque, &text);
592}
593
594/// `JS_PrintValueRT`: the same, found through a runtime rather than a context.
595///
596/// # Safety
597///
598/// `write_func` must be a `JS_PrintValueWrite`; `val` a live `JSValue`.
599#[unsafe(no_mangle)]
600pub unsafe extern "C" fn JS_PrintValueRT(
601 rt: *mut JsRuntime,
602 write_func: PrintValueWrite,
603 write_opaque: *mut c_void,
604 val: JsValue,
605 options: *const JSPrintValueOptions,
606) {
607 let Some(runtime) = (unsafe { rt.as_ref() }) else {
608 return;
609 };
610 // Whichever context exists is the one whose realm the value belongs to; a value with no
611 // context is printed by the first one, which is right because every context in a runtime
612 // shares its atoms and its class table.
613 let contexts = runtime.live_contexts();
614 if let Some(&context) = contexts.first() {
615 // SAFETY: the pointer is live until `JS_FreeContext`.
616 unsafe { JS_PrintValue(context, write_func, write_opaque, val, options) }
617 }
618}
619
620/// Hand `text` to a C write callback.
621fn emit(write_func: PrintValueWrite, write_opaque: *mut c_void, text: &str) {
622 let Some(write_func) = write_func else {
623 return;
624 };
625 // SAFETY: the caller guarantees the callback matches the header's signature, and the
626 // slice outlives the call.
627 unsafe { write_func(write_opaque, text.as_ptr().cast(), text.len()) };
628}
629
630/// `JS_HasException`: whether a call left an exception behind.
631///
632/// # Safety
633///
634/// `ctx` must be a live context.
635#[unsafe(no_mangle)]
636pub unsafe extern "C" fn JS_HasException(ctx: *mut JsContext) -> Bool {
637 match unsafe { ctx.as_ref() } {
638 Some(context) => c_int::from(context.has_pending()),
639 None => 0,
640 }
641}
642
643/// `JS_ThrowOutOfMemory`: raise the engine's out-of-memory error.
644///
645/// # Safety
646///
647/// `ctx` must be a live context.
648#[unsafe(no_mangle)]
649pub unsafe extern "C" fn JS_ThrowOutOfMemory(ctx: *mut JsContext) -> JsValue {
650 let Some(context) = (unsafe { ctx.as_ref() }) else {
651 return jsvalue::EXCEPTION;
652 };
653 let value = context.throw_out_of_memory();
654 context.set_pending(value);
655 jsvalue::EXCEPTION
656}
657
658/// `JS_ThrowSyntaxError`, `JS_ThrowTypeError`, `JS_ThrowReferenceError`,
659/// `JS_ThrowInternalError`: the four `JS_Throw*` spellings not already exported.
660///
661/// Each one is variadic in the header. Ours reads only `fmt`, for the reason
662/// `JS_ThrowRangeError` documents: a variadic Rust function is not expressible on stable, and
663/// a wrong-arity call would be worse than one that ignores surplus arguments.
664///
665/// # Safety
666///
667/// `ctx` must be a live context, `fmt` null or NUL-terminated.
668#[unsafe(no_mangle)]
669pub unsafe extern "C" fn JS_ThrowSyntaxError(ctx: *mut JsContext, fmt: *const c_char) -> JsValue {
670 // SAFETY: the caller's contract is `throw_named`'s.
671 unsafe { throw_named(ctx, "SyntaxError", fmt) }
672}
673
674/// `JS_ThrowTypeError`. See [`JS_ThrowSyntaxError`].
675///
676/// # Safety
677///
678/// As [`JS_ThrowSyntaxError`].
679#[unsafe(no_mangle)]
680pub unsafe extern "C" fn JS_ThrowTypeError(ctx: *mut JsContext, fmt: *const c_char) -> JsValue {
681 // SAFETY: the caller's contract is `throw_named`'s.
682 unsafe { throw_named(ctx, "TypeError", fmt) }
683}
684
685/// `JS_ThrowReferenceError`. See [`JS_ThrowSyntaxError`].
686///
687/// # Safety
688///
689/// As [`JS_ThrowSyntaxError`].
690#[unsafe(no_mangle)]
691pub unsafe extern "C" fn JS_ThrowReferenceError(
692 ctx: *mut JsContext,
693 fmt: *const c_char,
694) -> JsValue {
695 // SAFETY: the caller's contract is `throw_named`'s.
696 unsafe { throw_named(ctx, "ReferenceError", fmt) }
697}
698
699/// `JS_ThrowInternalError`. See [`JS_ThrowSyntaxError`].
700///
701/// # Safety
702///
703/// As [`JS_ThrowSyntaxError`].
704#[unsafe(no_mangle)]
705pub unsafe extern "C" fn JS_ThrowInternalError(ctx: *mut JsContext, fmt: *const c_char) -> JsValue {
706 // SAFETY: the caller's contract is `throw_named`'s.
707 unsafe { throw_named(ctx, "InternalError", fmt) }
708}
709
710/// The shared body of the four above.
711unsafe fn throw_named(ctx: *mut JsContext, name: &str, fmt: *const c_char) -> JsValue {
712 let Some(context) = (unsafe { ctx.as_ref() }) else {
713 return jsvalue::EXCEPTION;
714 };
715 // SAFETY: the caller guarantees a NUL-terminated format string.
716 let message = unsafe { crate::conversions::c_text(fmt) };
717 runtime::throw_error(context, name, &message)
718}