Skip to main content

quickjs/
bjson.rs

1//! `JS_WriteObject`/`JS_ReadObject`: a serialised copy of a value's graph.
2//!
3//! # The format is ours
4//!
5//! The reference's binary JSON is an implementation detail of its own bytecode compiler: an
6//! atom table, then a tree of tags, tuned so that a bundle of precompiled modules is small.
7//! Nothing outside the engine reads it, and `tests/test_bjson.js` — the acceptance driver —
8//! asserts a **round trip** (`toStr(write(x)) == toStr(read(write(x)))`) with no hard-coded
9//! bytes anywhere: the one place that printed hex is inside `if (0)`.
10//!
11//! So this writes its own format, and says so rather than pretending to be
12//!
13//! ```text
14//! header   : u8 version
15//! tag      : one of the `TAG_*` bytes below
16//! length   : unsigned LEB128
17//! ```
18//!
19//! What it *does* keep from the reference is the property that makes the format worth
20//! having at all: with `JS_WRITE_OBJ_REFERENCE`, an object is written once and referred to by
21//! index afterwards, so a cycle survives a round trip and two properties that were the same
22//! object are still the same object afterwards.
23//!
24//! # What cannot be written
25//!
26//! A function, a module, a proxy, a regular expression or a host class instance has no
27//! serialisation: the reference answers `TypeError: unsupported object class` for exactly the
28//! same set (its `default` arm in `JS_WriteObjectRec`). Writing one would need something to
29//! point at in a process that may not have the code any more.
30
31use std::collections::HashMap;
32
33use engine::builtins::typedarray::ELEMENT_TYPES;
34use engine::object::{BufferStorage, JsObject, PropertyKey};
35use engine::{Gc, Interp, Value};
36
37use crate::jsvalue::{self, JsValue};
38use crate::runtime::{self, JsContext};
39use crate::value_helpers::jsvalue_of;
40
41/// The format's version byte. Bumped when a tag changes meaning, never otherwise.
42const VERSION: u8 = 1;
43
44const TAG_UNDEFINED: u8 = 1;
45const TAG_NULL: u8 = 2;
46const TAG_FALSE: u8 = 3;
47const TAG_TRUE: u8 = 4;
48const TAG_INT32: u8 = 5;
49const TAG_FLOAT64: u8 = 6;
50const TAG_STRING: u8 = 7;
51const TAG_OBJECT: u8 = 8;
52const TAG_ARRAY: u8 = 9;
53const TAG_BIGINT: u8 = 10;
54const TAG_TYPED_ARRAY: u8 = 11;
55const TAG_ARRAY_BUFFER: u8 = 12;
56const TAG_DATE: u8 = 13;
57const TAG_OBJECT_VALUE: u8 = 14;
58const TAG_REFERENCE: u8 = 15;
59
60/// `JS_WRITE_OBJ_REFERENCE`: write shared objects once and refer to them by index.
61pub const WRITE_OBJ_REFERENCE: i32 = 1 << 3;
62/// `JS_WRITE_OBJ_BYTECODE`: accepted and ignored — this engine serialises values only.
63pub const WRITE_OBJ_BYTECODE: i32 = 1 << 0;
64/// `JS_READ_OBJ_REFERENCE`: resolve `TAG_REFERENCE` against the objects read so far.
65pub const READ_OBJ_REFERENCE: i32 = 1 << 3;
66/// `JS_READ_OBJ_BYTECODE`: accepted and ignored, like [`WRITE_OBJ_BYTECODE`].
67pub const READ_OBJ_BYTECODE: i32 = 1 << 0;
68/// `JS_WRITE_OBJ_SAB`/`JS_READ_OBJ_SAB`: no `SharedArrayBuffer` exists in this engine.
69pub const WRITE_OBJ_SAB: i32 = 1 << 2;
70/// See [`WRITE_OBJ_SAB`].
71pub const READ_OBJ_SAB: i32 = 1 << 2;
72/// `JS_WRITE_OBJ_BSWAP`: byte-swapped output is a big-endian host's problem, and this
73/// engine writes little-endian always. Accepted, ignored.
74pub const WRITE_OBJ_BSWAP: i32 = 1 << 1;
75
76// ---------------------------------------------------------------------------
77// Writing
78// ---------------------------------------------------------------------------
79
80/// The state one `JS_WriteObject` call carries.
81struct Writer {
82    out: Vec<u8>,
83    /// Objects already written, by address, so a second sighting becomes a reference.
84    ///
85    /// Address, not `Gc` identity by contents: two distinct objects with equal contents must
86    /// stay two objects, which is the whole point of the reference mode.
87    seen: HashMap<usize, u64>,
88    /// Whether references are allowed at all. Without them a shared object is an error,
89    /// because a copy would change the graph's shape silently.
90    allow_reference: bool,
91    /// Objects on the current path, so a cycle *without* reference mode is caught here
92    /// rather than recursing until the stack ends.
93    marks: Vec<usize>,
94}
95
96/// Serialise `value`.
97///
98/// # Errors
99///
100/// The reference's own messages: `circular reference` for a cycle without
101/// `JS_WRITE_OBJ_REFERENCE`, `only value properties are supported` for an enumerable
102/// accessor, and `unsupported object class` for anything with no serialisation.
103pub fn write(interp: &Interp<'_>, value: &Value, flags: i32) -> Result<Vec<u8>, String> {
104    let mut writer = Writer {
105        out: vec![VERSION],
106        seen: HashMap::new(),
107        allow_reference: flags & WRITE_OBJ_REFERENCE != 0,
108        marks: Vec::new(),
109    };
110    writer.value(interp, value)?;
111    Ok(writer.out)
112}
113
114impl Writer {
115    fn byte(&mut self, byte: u8) {
116        self.out.push(byte);
117    }
118
119    fn bytes(&mut self, bytes: &[u8]) {
120        self.out.extend_from_slice(bytes);
121    }
122
123    fn leb(&mut self, mut value: u64) {
124        loop {
125            let byte = (value & 0x7f) as u8;
126            value >>= 7;
127            if value == 0 {
128                self.byte(byte);
129                return;
130            }
131            self.byte(byte | 0x80);
132        }
133    }
134
135    fn string(&mut self, text: &engine::value::Wtf8) {
136        let bytes = text.as_bytes();
137        self.leb(bytes.len() as u64);
138        let bytes = bytes.to_vec();
139        self.bytes(&bytes);
140    }
141
142    fn value(&mut self, interp: &Interp<'_>, value: &Value) -> Result<(), String> {
143        match value {
144            Value::Undefined => self.byte(TAG_UNDEFINED),
145            Value::Null => self.byte(TAG_NULL),
146            Value::Bool(false) => self.byte(TAG_FALSE),
147            Value::Bool(true) => self.byte(TAG_TRUE),
148            // `-0.0` and `NaN` only survive as a float, and `1.0` and `1` are the same
149            // number to every reader — so an integral `f64` is written as an int when it
150            // fits, which is what keeps a round trip's `typeof` stable.
151            Value::Int(number) => {
152                self.byte(TAG_INT32);
153                self.bytes(&number.to_le_bytes());
154            }
155            Value::Float(number) => {
156                if number.fract() == 0.0
157                    && *number >= i32::MIN as f64
158                    && *number <= i32::MAX as f64
159                    && !(*number == 0.0 && number.is_sign_negative())
160                {
161                    self.byte(TAG_INT32);
162                    self.bytes(&(*number as i32).to_le_bytes());
163                } else {
164                    self.byte(TAG_FLOAT64);
165                    self.bytes(&number.to_le_bytes());
166                }
167            }
168            Value::String(text) => {
169                self.byte(TAG_STRING);
170                self.string(text.wtf8());
171            }
172            Value::BigInt(big) => {
173                // Decimal text, not limbs: the format stays readable and the conversion is
174                // one call each way rather than a private limb layout leaking into a file
175                // format.
176                self.byte(TAG_BIGINT);
177                self.byte(u8::from(big.is_negative()));
178                let text = big.abs().to_decimal_string();
179                self.leb(text.len() as u64);
180                self.bytes(text.as_bytes());
181            }
182            Value::Symbol(_) => return Err("unsupported tag (symbol)".to_string()),
183            Value::Object(object) => self.object(interp, object)?,
184            // An array's hole is `undefined` to every reader but `in` and `forEach`, and the
185            // reference's writer does the same: its fast-array loop writes `JS_UNDEFINED`
186            // for the slots past the dense prefix, so `[1,,3]` round-trips to `[1,undefined,3]`
187            // — the same elements, one of which is now present. Reporting a hole as an
188            // unsupported tag instead made the acceptance driver fail on `[1, , 2, , 3]`.
189            Value::Hole => self.byte(TAG_UNDEFINED),
190            // The two operand-stack markers and `Uninitialized` never reach a serialiser; a
191            // caller that hands one over is a bug in this layer.
192            Value::CatchOffset(_) | Value::ReturnAddress(_) | Value::Uninitialized => {
193                return Err(format!("unsupported tag (internal marker {value:?})"));
194            }
195        }
196        Ok(())
197    }
198
199    fn object(&mut self, interp: &Interp<'_>, object: &Gc<JsObject>) -> Result<(), String> {
200        let address = object.address();
201        if self.allow_reference {
202            if let Some(&index) = self.seen.get(&address) {
203                self.byte(TAG_REFERENCE);
204                self.leb(index);
205                return Ok(());
206            }
207            self.seen.insert(address, self.seen.len() as u64);
208        } else {
209            if self.marks.contains(&address) {
210                return Err("circular reference".to_string());
211            }
212            self.marks.push(address);
213        }
214        let result = self.object_body(interp, object);
215        if !self.allow_reference {
216            self.marks.pop();
217        }
218        result
219    }
220
221    fn object_body(&mut self, interp: &Interp<'_>, object: &Gc<JsObject>) -> Result<(), String> {
222        // A function, a module namespace, a proxy or a host-class instance has no
223        // serialisation. Checked before the shapes below, because a *callable* object is an
224        // ordinary one in every other respect — without this a function was written as an
225        // empty object, which is a silent copy of the wrong thing rather than the reference's
226        // `unsupported object class`.
227        if object.is_callable()
228            || object.host_class_id().is_some()
229            || object.proxy_state().is_some()
230            || object.is_regexp()
231        {
232            return Err("unsupported object class".to_string());
233        }
234        if object.is_array() {
235            self.byte(TAG_ARRAY);
236            let length = object.array_length().unwrap_or(0);
237            self.leb(length as u64);
238            for index in 0..length {
239                // A hole and an explicit `undefined` are the same element to every reader
240                // that is not `in`/`forEach`, and the reference writes a hole as
241                // `JS_UNDEFINED` too.
242                let element = object.array_get(index).unwrap_or(Value::Undefined);
243                self.value(interp, &element)?;
244            }
245            return Ok(());
246        }
247        if let Some(storage) = object.array_buffer_storage() {
248            self.array_buffer(&storage)?;
249            return Ok(());
250        }
251        if let Some((buffer, element, offset, length)) = object.typed_array_parts() {
252            self.byte(TAG_TYPED_ARRAY);
253            self.byte(element as u8);
254            self.leb(length as u64);
255            self.leb(offset as u64);
256            // The buffer goes last because it may be a reference to one already written —
257            // which is exactly the case a set of views over one buffer produces.
258            self.object(interp, &buffer)?;
259            return Ok(());
260        }
261        if interp
262            .internal_get(object, "_class")
263            .is_some_and(|tag| tag.to_js_string() == "Date")
264        {
265            self.byte(TAG_DATE);
266            let value = interp
267                .internal_get(object, "_date_value")
268                .map(|value| value.to_number())
269                .unwrap_or(f64::NAN);
270            self.value(interp, &Value::Float(value))?;
271            return Ok(());
272        }
273        if let Some(boxed) = interp.internal_get(object, "_value") {
274            // `new Number(1)`, `new String("ab")`, `new Boolean(true)` and `Object(1n)` are
275            // wrappers: the primitive is the whole content, so the read side rebuilds the
276            // wrapper from it rather than storing a class id.
277            self.byte(TAG_OBJECT_VALUE);
278            self.value(interp, &boxed)?;
279            return Ok(());
280        }
281        self.byte(TAG_OBJECT);
282        // Only enumerable own string properties, which is what the reference writes: a
283        // symbol key cannot be represented in a format that has no symbol table, and a
284        // non-enumerable one is not part of the object's data in any JSON-like sense.
285        let mut entries: Vec<(engine::value::Wtf8, Value)> = Vec::new();
286        for key in object.own_property_keys_in_definition_order() {
287            if key.is_symbol() {
288                continue;
289            }
290            let Some(property) = object.own_property_key(&key) else {
291                continue;
292            };
293            if !property.enumerable {
294                continue;
295            }
296            if property.is_accessor() {
297                return Err("only value properties are supported".to_string());
298            }
299            let Some(value) = property.value else {
300                continue;
301            };
302            let PropertyKey::String(text) = &key else {
303                continue;
304            };
305            entries.push((text.clone(), value));
306        }
307        self.leb(entries.len() as u64);
308        for (key, value) in entries {
309            self.string(&key);
310            self.value(interp, &value)?;
311        }
312        Ok(())
313    }
314
315    fn array_buffer(
316        &mut self,
317        storage: &std::rc::Rc<std::cell::RefCell<BufferStorage>>,
318    ) -> Result<(), String> {
319        let storage = storage.borrow();
320        if storage.detached {
321            return Err("ArrayBuffer is detached".to_string());
322        }
323        self.byte(TAG_ARRAY_BUFFER);
324        self.leb(storage.bytes.len() as u64);
325        // Resizability needs its own byte: `new ArrayBuffer(4, {maxByteLength: 4})` and
326        // `new ArrayBuffer(4)` have the same two numbers and are still different buffers —
327        // one accepts `resize`, the other throws. Inferring the flag by comparing the lengths
328        // made `assert(ab.resizable)` fail for exactly that case.
329        match storage.max_byte_length {
330            Some(max) => {
331                self.byte(1);
332                self.leb(max as u64);
333            }
334            None => self.byte(0),
335        }
336        let bytes = storage.bytes.clone();
337        drop(storage);
338        self.bytes(&bytes);
339        Ok(())
340    }
341}
342
343// ---------------------------------------------------------------------------
344// Reading
345// ---------------------------------------------------------------------------
346
347/// The state one `JS_ReadObject` call carries.
348struct Reader<'a, 'h, 'i> {
349    input: &'a [u8],
350    position: usize,
351    /// Two lifetimes because an `Interp` is itself borrowed from a heap: `'h` is the heap,
352    /// `'i` the borrow of the interpreter.
353    interp: &'i mut Interp<'h>,
354    allow_reference: bool,
355    /// Every object created so far, in creation order: `TAG_REFERENCE` indexes this.
356    created: Vec<Gc<JsObject>>,
357}
358
359/// Read a value written by [`write`].
360///
361/// # Errors
362///
363/// Truncated input, an unknown tag, or a reference when references were not allowed. A
364/// corrupt buffer must never be able to make the engine read past its end, which is why
365/// every field is bounds-checked here rather than by the caller.
366pub fn read<'h, 'i>(interp: &'i mut Interp<'h>, input: &[u8], flags: i32) -> Result<Value, String> {
367    if input.is_empty() {
368        return Err("invalid object format".to_string());
369    }
370    if input[0] != VERSION {
371        return Err(format!("unsupported object version ({})", input[0]));
372    }
373    let mut reader = Reader {
374        input,
375        position: 1,
376        interp,
377        allow_reference: flags & READ_OBJ_REFERENCE != 0,
378        created: Vec::new(),
379    };
380    reader.value()
381}
382
383impl<'a, 'h, 'i> Reader<'a, 'h, 'i> {
384    fn byte(&mut self) -> Result<u8, String> {
385        let byte = *self
386            .input
387            .get(self.position)
388            .ok_or_else(|| "invalid object format".to_string())?;
389        self.position += 1;
390        Ok(byte)
391    }
392
393    fn bytes(&mut self, count: usize) -> Result<&'a [u8], String> {
394        let end = self
395            .position
396            .checked_add(count)
397            .ok_or_else(|| "invalid object format".to_string())?;
398        let slice = self
399            .input
400            .get(self.position..end)
401            .ok_or_else(|| "invalid object format".to_string())?;
402        self.position = end;
403        // SAFETY-free widening: the slice borrows from `self.input`, whose lifetime is
404        // `'a`, and `self.position` is only a cursor.
405        Ok(slice)
406    }
407
408    fn leb(&mut self) -> Result<u64, String> {
409        let mut value = 0u64;
410        let mut shift = 0;
411        loop {
412            let byte = self.byte()?;
413            value |= u64::from(byte & 0x7f)
414                .checked_shl(shift)
415                .ok_or_else(|| "invalid object format".to_string())?;
416            if byte & 0x80 == 0 {
417                return Ok(value);
418            }
419            shift += 7;
420            if shift > 63 {
421                return Err("invalid object format".to_string());
422            }
423        }
424    }
425
426    fn leb_usize(&mut self) -> Result<usize, String> {
427        let value = self.leb()?;
428        usize::try_from(value).map_err(|_| "invalid object format".to_string())
429    }
430
431    fn value(&mut self) -> Result<Value, String> {
432        let tag = self.byte()?;
433        match tag {
434            TAG_UNDEFINED => Ok(Value::Undefined),
435            TAG_NULL => Ok(Value::Null),
436            TAG_FALSE => Ok(Value::Bool(false)),
437            TAG_TRUE => Ok(Value::Bool(true)),
438            TAG_INT32 => {
439                let bytes = self.bytes(4)?;
440                Ok(Value::Int(i32::from_le_bytes([
441                    bytes[0], bytes[1], bytes[2], bytes[3],
442                ])))
443            }
444            TAG_FLOAT64 => {
445                let bytes = self.bytes(8)?;
446                Ok(Value::Float(f64::from_le_bytes([
447                    bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
448                ])))
449            }
450            TAG_STRING => {
451                let length = self.leb_usize()?;
452                let bytes = self.bytes(length)?;
453                let text = engine::value::Wtf8::from_wtf8_bytes(bytes)
454                    .ok_or_else(|| "invalid object format".to_string())?;
455                Ok(Value::string_wtf8(self.interp.heap, text))
456            }
457            TAG_BIGINT => {
458                let negative = self.byte()? != 0;
459                let length = self.leb_usize()?;
460                let bytes = self.bytes(length)?;
461                let text =
462                    std::str::from_utf8(bytes).map_err(|_| "invalid object format".to_string())?;
463                let big = engine::bigint::BigInt::from_string(text)
464                    .ok_or_else(|| "invalid object format".to_string())?;
465                Ok(self
466                    .interp
467                    .bigint(if negative { big.negate() } else { big }))
468            }
469            TAG_ARRAY => {
470                let length = self.leb_usize()?;
471                // Created *empty and registered* before its elements are read. The index a
472                // `TAG_REFERENCE` carries is the order of first sighting on the *write*
473                // side, which registers an object before writing its body — so a reader
474                // that registered after filling would number the objects differently and
475                // every reference past the first would land on the wrong one. That is what
476                // `bjson_test_reference` caught: the cycle resolved to the wrong objects.
477                let array = JsObject::array(
478                    self.interp.heap,
479                    Some(self.interp.realm.array_proto.clone()),
480                    0,
481                );
482                self.created.push(array.clone());
483                for _ in 0..length {
484                    let element = self.value()?;
485                    array.array_push(self.interp.heap, element);
486                }
487                Ok(Value::Object(array))
488            }
489            TAG_OBJECT => {
490                let count = self.leb_usize()?;
491                // Created *before* its properties are read, so a property that refers back
492                // to this object finds it: that is what makes a self-referential `o.x = o`
493                // survive with reference mode on.
494                let proto = self.interp.realm.object_proto.clone();
495                let object = self.interp.new_object(Some(proto));
496                self.created.push(object.clone());
497                for _ in 0..count {
498                    let length = self.leb_usize()?;
499                    let key_bytes = self.bytes(length)?;
500                    let key = engine::value::Wtf8::from_wtf8_bytes(key_bytes)
501                        .ok_or_else(|| "invalid object format".to_string())?
502                        .to_string_lossy()
503                        .into_owned();
504                    let value = self.value()?;
505                    object.define(&key, engine::Property::with_attributes(value, true, true));
506                }
507                Ok(Value::Object(object))
508            }
509            TAG_ARRAY_BUFFER => {
510                let byte_length = self.leb_usize()?;
511                let resizable = self.byte()? != 0;
512                // The order is the writer's: flag, then the ceiling, then the bytes.
513                let max = if resizable {
514                    Some(self.leb_usize()?)
515                } else {
516                    None
517                };
518                let proto = self
519                    .interp
520                    .realm
521                    .array_buffer_proto
522                    .clone()
523                    .unwrap_or_else(|| self.interp.realm.object_proto.clone());
524                let buffer = self.interp.new_object(Some(proto));
525                // Registered before the bytes are read, for the same reason the array is:
526                // the index is first-sighting order on both sides.
527                self.created.push(buffer.clone());
528                let bytes = self.bytes(byte_length)?.to_vec();
529                let storage = match max {
530                    Some(max) => BufferStorage::resizable(bytes, max),
531                    None => BufferStorage::fixed(bytes),
532                };
533                buffer.set_array_buffer(std::rc::Rc::new(std::cell::RefCell::new(storage)));
534                Ok(Value::Object(buffer))
535            }
536            TAG_TYPED_ARRAY => {
537                let element = ELEMENT_TYPES
538                    .get(self.byte()? as usize)
539                    .map(|(element, _)| *element)
540                    .ok_or_else(|| "invalid object format".to_string())?;
541                let length = self.leb_usize()?;
542                let offset = self.leb_usize()?;
543                let proto = self
544                    .interp
545                    .realm
546                    .typed_array_protos
547                    .get(element as usize)
548                    .cloned()
549                    .or_else(|| self.interp.realm.typed_array_proto.clone())
550                    .unwrap_or_else(|| self.interp.realm.object_proto.clone());
551                // The view is registered as a plain object first and becomes a view once its
552                // buffer has been read: the writer registered *it* before writing the
553                // buffer, so a reference to the view may appear inside the buffer's own
554                // subtree and has to resolve to this object.
555                let view = self.interp.new_object(Some(proto));
556                self.created.push(view.clone());
557                let buffer = self.value()?;
558                let Some(buffer) = buffer.as_object().cloned() else {
559                    return Err("invalid object format".to_string());
560                };
561                view.set_typed_array(buffer, element, offset, length);
562                Ok(Value::Object(view))
563            }
564            TAG_DATE => {
565                let proto = self.interp.realm.date_proto.clone();
566                let object = self.interp.new_object(Some(proto));
567                self.created.push(object.clone());
568                self.interp
569                    .internal_set(&object, "_class", self.interp.string("Date"));
570                let value = self.value()?.to_number();
571                self.interp
572                    .internal_set(&object, "_date_value", Value::Float(value));
573                Ok(Value::Object(object))
574            }
575            TAG_OBJECT_VALUE => {
576                // A wrapper is rebuilt by `object_from`, the same function `Object(x)` uses,
577                // so `instanceof String` and `.valueOf()` work on the result without a
578                // second implementation of boxing.
579                // Created and registered *before* the primitive is read, because that is
580                // the order the writer registered them in: it reserves the index when it
581                // first sees the wrapper, then writes the primitive.
582                let object = self.interp.new_object(None);
583                self.created.push(object.clone());
584                let primitive = self.value()?;
585                self.interp
586                    .fill_wrapper(&object, &primitive)
587                    .map_err(|_| "invalid object format".to_string())?;
588                Ok(Value::Object(object))
589            }
590            TAG_REFERENCE => {
591                if !self.allow_reference {
592                    return Err("invalid object format".to_string());
593                }
594                let index = self.leb_usize()?;
595                let object = self
596                    .created
597                    .get(index)
598                    .cloned()
599                    .ok_or_else(|| "invalid object format".to_string())?;
600                Ok(Value::Object(object))
601            }
602            other => Err(format!("unsupported tag ({other})")),
603        }
604    }
605}
606
607// ---------------------------------------------------------------------------
608// The C API
609// ---------------------------------------------------------------------------
610
611/// `JS_WriteObject`: serialise `obj` into a block the caller frees with `js_free`.
612///
613/// # Safety
614///
615/// `psize` must be null or writable, and `obj` a live `JSValue`.
616#[unsafe(no_mangle)]
617pub unsafe extern "C" fn JS_WriteObject(
618    ctx: *mut JsContext,
619    psize: *mut usize,
620    obj: JsValue,
621    flags: i32,
622) -> *mut u8 {
623    if !psize.is_null() {
624        // SAFETY: the caller guarantees a writable pointer.
625        unsafe { *psize = 0 };
626    }
627    let Some(context) = (unsafe { ctx.as_ref() }) else {
628        return std::ptr::null_mut();
629    };
630    let Some(value) = (unsafe { runtime::argument(obj) }) else {
631        runtime::throw_error(context, "TypeError", "not a value");
632        return std::ptr::null_mut();
633    };
634    let written = context.with_current_interp(|interp| write(interp, &value, flags));
635    let bytes = match written {
636        Ok(bytes) => bytes,
637        Err(message) => {
638            // The reference puts almost every one of these in a `TypeError`, and the driver
639            // checks `e instanceof TypeError` for the circular case.
640            runtime::throw_error(context, "TypeError", &message);
641            return std::ptr::null_mut();
642        }
643    };
644    // The block comes from `js_malloc`, because the C side frees it with `js_free` and a
645    // `Vec`'s pointer is not something that function understands.
646    // SAFETY: `alloc_raw` has no preconditions beyond a size.
647    let block = unsafe { crate::alloc::alloc_raw(bytes.len()) };
648    if block.is_null() {
649        runtime::throw_error(context, "InternalError", "out of memory");
650        return std::ptr::null_mut();
651    }
652    // SAFETY: `block` is `bytes.len()` bytes of writable storage by `alloc_raw`'s contract.
653    unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), block, bytes.len()) };
654    if !psize.is_null() {
655        // SAFETY: the caller guarantees a writable pointer.
656        unsafe { *psize = bytes.len() };
657    }
658    block
659}
660
661/// `JS_ReadObject`: rebuild the value `buf` describes.
662///
663/// # Safety
664///
665/// `buf` must point at `buf_len` readable bytes that stay alive for the call.
666#[unsafe(no_mangle)]
667pub unsafe extern "C" fn JS_ReadObject(
668    ctx: *mut JsContext,
669    buf: *const u8,
670    buf_len: usize,
671    flags: i32,
672) -> JsValue {
673    let Some(context) = (unsafe { ctx.as_ref() }) else {
674        return jsvalue::EXCEPTION;
675    };
676    if buf.is_null() {
677        runtime::throw_error(context, "TypeError", "invalid object format");
678        return jsvalue::EXCEPTION;
679    }
680    // SAFETY: the caller guarantees `buf_len` readable bytes.
681    let input = unsafe { std::slice::from_raw_parts(buf, buf_len) };
682    let read = context.with_current_interp(|interp| read(interp, input, flags));
683    match read {
684        Ok(value) => jsvalue_of(value),
685        Err(message) => runtime::throw_error(context, "TypeError", &message),
686    }
687}
688
689/// `JS_GetArrayBuffer`: the bytes of an `ArrayBuffer`, for a C module to read.
690///
691/// The pointer is borrowed, not owned: it stays valid until the buffer is detached, resized
692/// or collected, which is exactly the contract the reference's own getter has. A resizable
693/// or fixed buffer answers the same way — a resize may move the bytes, and the caller is
694/// expected to re-fetch after asking a script to run.
695///
696/// # Safety
697///
698/// `psize` must be null or writable, and `obj` a live `JSValue`.
699#[unsafe(no_mangle)]
700pub unsafe extern "C" fn JS_GetArrayBuffer(
701    ctx: *mut JsContext,
702    psize: *mut usize,
703    obj: JsValue,
704) -> *mut u8 {
705    if !psize.is_null() {
706        // SAFETY: the caller guarantees a writable pointer.
707        unsafe { *psize = 0 };
708    }
709    let Some(context) = (unsafe { ctx.as_ref() }) else {
710        return std::ptr::null_mut();
711    };
712    let Some(value) = (unsafe { runtime::argument(obj) }) else {
713        runtime::throw_error(context, "TypeError", "not a value");
714        return std::ptr::null_mut();
715    };
716    let Some(storage) = value
717        .as_object()
718        .and_then(|object| object.array_buffer_storage())
719    else {
720        runtime::throw_error(context, "TypeError", "not an ArrayBuffer");
721        return std::ptr::null_mut();
722    };
723    let storage = storage.borrow();
724    if storage.detached {
725        runtime::throw_error(context, "TypeError", "ArrayBuffer is detached");
726        return std::ptr::null_mut();
727    }
728    if !psize.is_null() {
729        // SAFETY: the caller guarantees a writable pointer.
730        unsafe { *psize = storage.bytes.len() };
731    }
732    // Borrowed out of the storage's `Vec`: the reference hands out `abuf->data` the same
733    // way, and the lifetime is the buffer's, not the borrow's.
734    let bytes = storage.bytes.as_ptr() as *mut u8;
735    drop(storage);
736    bytes
737}
738
739/// `JS_NewArrayBufferCopy`: a new `ArrayBuffer` holding a copy of `len` bytes at `buf`.
740///
741/// # Safety
742///
743/// `buf` must point at `len` readable bytes, or be null with `len == 0`.
744#[unsafe(no_mangle)]
745pub unsafe extern "C" fn JS_NewArrayBufferCopy(
746    ctx: *mut JsContext,
747    buf: *const u8,
748    len: usize,
749) -> JsValue {
750    let Some(context) = (unsafe { ctx.as_ref() }) else {
751        return jsvalue::EXCEPTION;
752    };
753    if buf.is_null() && len != 0 {
754        runtime::throw_error(context, "TypeError", "null pointer");
755        return jsvalue::EXCEPTION;
756    }
757    let bytes = if len == 0 {
758        Vec::new()
759    } else {
760        // SAFETY: the caller guarantees `len` readable bytes.
761        unsafe { std::slice::from_raw_parts(buf, len) }.to_vec()
762    };
763    context.with_current_interp(|interp| {
764        let proto = interp
765            .realm
766            .array_buffer_proto
767            .clone()
768            .unwrap_or_else(|| interp.realm.object_proto.clone());
769        let buffer = interp.new_object(Some(proto));
770        buffer.set_array_buffer(std::rc::Rc::new(std::cell::RefCell::new(
771            BufferStorage::fixed(bytes),
772        )));
773        jsvalue_of(Value::Object(buffer))
774    })
775}