Skip to main content

script/dom/bindings/
structuredclone.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! This module implements structured cloning, as defined by [HTML](https://html.spec.whatwg.org/multipage/#safe-passing-of-structured-data).
6
7use std::ffi::CStr;
8use std::os::raw;
9use std::ptr::{self, NonNull};
10
11use js::context::{JSContext, NoGC};
12use js::conversions::ToJSValConvertible;
13use js::gc::RootedVec;
14use js::glue::{
15    CopyJSStructuredCloneData, GetLengthOfJSStructuredCloneData, WriteBytesToJSStructuredCloneData,
16};
17use js::jsapi::{
18    CloneDataPolicy, HandleObject as RawHandleObject, Heap, JS_ReadUint32Pair,
19    JS_STRUCTURED_CLONE_VERSION, JS_WriteUint32Pair, JSContext as RawJSContext, JSObject,
20    JSStructuredCloneCallbacks, JSStructuredCloneReader, JSStructuredCloneWriter,
21    MutableHandleObject as RawMutableHandleObject, StructuredCloneScope, TransferableOwnership,
22};
23use js::jsval::UndefinedValue;
24use js::realm::CurrentRealm;
25use js::rust::wrappers2::{JS_IsExceptionPending, JS_ReadStructuredClone, JS_WriteStructuredClone};
26use js::rust::{
27    CustomAutoRooterGuard, HandleValue, JSAutoStructuredCloneBufferWrapper, MutableHandleValue,
28};
29use rustc_hash::FxHashMap;
30use script_bindings::conversions::IDLInterface;
31use servo_base::id::{
32    BlobId, CryptoKeyId, DomExceptionId, DomMatrixId, DomPointId, DomQuadId, DomRectId, FileId,
33    FileListId, ImageBitmapId, ImageDataId, Index, MessagePortId, NamespaceIndex,
34    OffscreenCanvasId, PipelineNamespaceId, QuotaExceededErrorId,
35};
36use servo_constellation_traits::{
37    BlobImpl, DomException, DomMatrix, DomPoint, DomQuad, DomRect, MessagePortImpl,
38    Serializable as SerializableInterface, SerializableCryptoKey, SerializableFile,
39    SerializableFileList, SerializableImageBitmap, SerializableImageData,
40    SerializableQuotaExceededError, StructuredSerializedData, TransferableOffscreenCanvas,
41    Transferrable as TransferrableInterface, TransformStreamData,
42};
43use strum::IntoEnumIterator;
44
45use crate::dom::bindings::conversions::root_from_object;
46use crate::dom::bindings::error::{Error, Fallible};
47use crate::dom::bindings::root::DomRoot;
48use crate::dom::bindings::serializable::{Serializable, StorageKey};
49use crate::dom::bindings::transferable::Transferable;
50use crate::dom::blob::Blob;
51use crate::dom::cryptokey::CryptoKey;
52use crate::dom::dompoint::DOMPoint;
53use crate::dom::dompointreadonly::DOMPointReadOnly;
54use crate::dom::file::File;
55use crate::dom::filelist::FileList;
56use crate::dom::globalscope::GlobalScope;
57use crate::dom::imagebitmap::ImageBitmap;
58use crate::dom::imagedata::ImageData;
59use crate::dom::messageport::MessagePort;
60use crate::dom::offscreencanvas::OffscreenCanvas;
61use crate::dom::stream::readablestream::ReadableStream;
62use crate::dom::stream::writablestream::WritableStream;
63use crate::dom::types::{
64    DOMException, DOMMatrix, DOMMatrixReadOnly, DOMQuad, DOMRect, DOMRectReadOnly,
65    QuotaExceededError, TransformStream,
66};
67use crate::realms::enter_auto_realm;
68
69// TODO: Should we add Min and Max const to https://github.com/servo/rust-mozjs/blob/master/src/consts.rs?
70// TODO: Determine for sure which value Min and Max should have.
71// NOTE: Current values found at https://dxr.mozilla.org/mozilla-central/
72// rev/ff04d410e74b69acfab17ef7e73e7397602d5a68/js/public/StructuredClone.h#323
73#[repr(u32)]
74pub(super) enum StructuredCloneTags {
75    /// To support additional types, add new tags with values incremented from the last one before Max.
76    Min = 0xFFFF8000,
77    DomBlob = 0xFFFF8001,
78    DomFile = 0xFFFF8002,
79    DomFileList = 0xFFFF8003,
80    MessagePort = 0xFFFF8004,
81    Principals = 0xFFFF8005,
82    DomPointReadOnly = 0xFFFF8006,
83    DomPoint = 0xFFFF8007,
84    ReadableStream = 0xFFFF8008,
85    DomException = 0xFFFF8009,
86    WritableStream = 0xFFFF800A,
87    TransformStream = 0xFFFF800B,
88    ImageBitmap = 0xFFFF800C,
89    OffscreenCanvas = 0xFFFF800D,
90    QuotaExceededError = 0xFFFF800E,
91    DomRect = 0xFFFF800F,
92    DomRectReadOnly = 0xFFFF8010,
93    DomQuad = 0xFFFF8011,
94    DomMatrix = 0xFFFF8012,
95    DomMatrixReadOnly = 0xFFFF8013,
96    ImageData = 0xFFFF8014,
97    CryptoKey = 0xFFFF8015,
98    Max = 0xFFFFFFFF,
99}
100
101impl From<SerializableInterface> for StructuredCloneTags {
102    fn from(v: SerializableInterface) -> Self {
103        match v {
104            SerializableInterface::File => StructuredCloneTags::DomFile,
105            SerializableInterface::FileList => StructuredCloneTags::DomFileList,
106            SerializableInterface::Blob => StructuredCloneTags::DomBlob,
107            SerializableInterface::DomPoint => StructuredCloneTags::DomPoint,
108            SerializableInterface::DomPointReadOnly => StructuredCloneTags::DomPointReadOnly,
109            SerializableInterface::DomRect => StructuredCloneTags::DomRect,
110            SerializableInterface::DomRectReadOnly => StructuredCloneTags::DomRectReadOnly,
111            SerializableInterface::DomQuad => StructuredCloneTags::DomQuad,
112            SerializableInterface::DomMatrix => StructuredCloneTags::DomMatrix,
113            SerializableInterface::DomMatrixReadOnly => StructuredCloneTags::DomMatrixReadOnly,
114            SerializableInterface::DomException => StructuredCloneTags::DomException,
115            SerializableInterface::ImageBitmap => StructuredCloneTags::ImageBitmap,
116            SerializableInterface::QuotaExceededError => StructuredCloneTags::QuotaExceededError,
117            SerializableInterface::ImageData => StructuredCloneTags::ImageData,
118            SerializableInterface::CryptoKey => StructuredCloneTags::CryptoKey,
119        }
120    }
121}
122
123impl From<TransferrableInterface> for StructuredCloneTags {
124    fn from(v: TransferrableInterface) -> Self {
125        match v {
126            TransferrableInterface::ImageBitmap => StructuredCloneTags::ImageBitmap,
127            TransferrableInterface::MessagePort => StructuredCloneTags::MessagePort,
128            TransferrableInterface::OffscreenCanvas => StructuredCloneTags::OffscreenCanvas,
129            TransferrableInterface::ReadableStream => StructuredCloneTags::ReadableStream,
130            TransferrableInterface::WritableStream => StructuredCloneTags::WritableStream,
131            TransferrableInterface::TransformStream => StructuredCloneTags::TransformStream,
132        }
133    }
134}
135
136fn reader_for_type(
137    val: SerializableInterface,
138) -> unsafe fn(
139    cx: &mut JSContext,
140    &GlobalScope,
141    *mut JSStructuredCloneReader,
142    &mut StructuredDataReader<'_>,
143) -> *mut JSObject {
144    match val {
145        SerializableInterface::File => read_object::<File>,
146        SerializableInterface::FileList => read_object::<FileList>,
147        SerializableInterface::Blob => read_object::<Blob>,
148        SerializableInterface::DomPoint => read_object::<DOMPoint>,
149        SerializableInterface::DomPointReadOnly => read_object::<DOMPointReadOnly>,
150        SerializableInterface::DomRect => read_object::<DOMRect>,
151        SerializableInterface::DomRectReadOnly => read_object::<DOMRectReadOnly>,
152        SerializableInterface::DomQuad => read_object::<DOMQuad>,
153        SerializableInterface::DomMatrix => read_object::<DOMMatrix>,
154        SerializableInterface::DomMatrixReadOnly => read_object::<DOMMatrixReadOnly>,
155        SerializableInterface::DomException => read_object::<DOMException>,
156        SerializableInterface::ImageBitmap => read_object::<ImageBitmap>,
157        SerializableInterface::QuotaExceededError => read_object::<QuotaExceededError>,
158        SerializableInterface::ImageData => read_object::<ImageData>,
159        SerializableInterface::CryptoKey => read_object::<CryptoKey>,
160    }
161}
162
163unsafe fn read_object<T: Serializable>(
164    cx: &mut JSContext,
165    owner: &GlobalScope,
166    r: *mut JSStructuredCloneReader,
167    sc_reader: &mut StructuredDataReader<'_>,
168) -> *mut JSObject {
169    let mut name_space: u32 = 0;
170    let mut index: u32 = 0;
171    unsafe {
172        assert!(JS_ReadUint32Pair(
173            r,
174            &mut name_space as *mut u32,
175            &mut index as *mut u32
176        ));
177    }
178    let storage_key = StorageKey { index, name_space };
179
180    // 1. Re-build the key for the storage location
181    // of the serialized object.
182    let id: NamespaceIndex<T::Index> = storage_key.into();
183
184    // 2. Get the transferred object from its storage, using the key.
185    let objects = T::serialized_storage(StructuredData::Reader(sc_reader));
186    let objects_map = objects
187        .as_mut()
188        .expect("The SC holder does not have any relevant objects");
189    let serialized = objects_map
190        .remove(&id)
191        .expect("No object to be deserialized found.");
192    if objects_map.is_empty() {
193        *objects = None;
194    }
195
196    if let Ok(obj) = T::deserialize(cx, owner, serialized) {
197        let reflector = obj.reflector().get_jsobject().get();
198        sc_reader.roots.push(Heap::boxed(reflector));
199        return reflector;
200    }
201    warn!("Reading structured data failed in {:?}.", owner.get_url());
202    ptr::null_mut()
203}
204
205unsafe fn write_object<T: Serializable>(
206    no_gc: &NoGC,
207    interface: SerializableInterface,
208    owner: &GlobalScope,
209    object: &T,
210    w: *mut JSStructuredCloneWriter,
211    sc_writer: &mut StructuredDataWriter,
212) -> bool {
213    if let Ok((new_id, serialized)) = object.serialize(no_gc) {
214        let objects = T::serialized_storage(StructuredData::Writer(sc_writer))
215            .get_or_insert(FxHashMap::default());
216        objects.insert(new_id, serialized);
217        let storage_key = StorageKey::new(new_id);
218
219        unsafe {
220            assert!(JS_WriteUint32Pair(
221                w,
222                StructuredCloneTags::from(interface) as u32,
223                0
224            ));
225            assert!(JS_WriteUint32Pair(
226                w,
227                storage_key.name_space,
228                storage_key.index
229            ));
230        }
231        return true;
232    }
233    warn!("Writing structured data failed in {:?}.", owner.get_url());
234    false
235}
236
237unsafe extern "C" fn read_callback(
238    cx: *mut RawJSContext,
239    r: *mut JSStructuredCloneReader,
240    _policy: *const CloneDataPolicy,
241    tag: u32,
242    _data: u32,
243    closure: *mut raw::c_void,
244) -> *mut JSObject {
245    assert!(
246        tag < StructuredCloneTags::Max as u32,
247        "tag should be lower than StructuredCloneTags::Max"
248    );
249    assert!(
250        tag > StructuredCloneTags::Min as u32,
251        "tag should be higher than StructuredCloneTags::Min"
252    );
253
254    // SAFETY: it is safe to construct a JSContext from engine hook.
255    let mut cx = unsafe { JSContext::from_ptr(NonNull::new(cx).unwrap()) };
256    let cx = &mut cx;
257
258    let sc_reader = unsafe { &mut *(closure as *mut StructuredDataReader<'_>) };
259
260    let mut realm = CurrentRealm::assert(cx);
261    let global = GlobalScope::from_current_realm(&mut realm);
262
263    for serializable in SerializableInterface::iter() {
264        if tag == StructuredCloneTags::from(serializable) as u32 {
265            let reader = reader_for_type(serializable);
266            return unsafe { reader(cx, &global, r, sc_reader) };
267        }
268    }
269
270    ptr::null_mut()
271}
272
273enum OperationError {
274    InterfaceDoesNotMatch,
275    Exception(Error),
276}
277
278unsafe fn try_serialize<T: Serializable + IDLInterface>(
279    cx: &mut JSContext,
280    val: SerializableInterface,
281    object: RawHandleObject,
282    global: &GlobalScope,
283    w: *mut JSStructuredCloneWriter,
284    writer: &mut StructuredDataWriter,
285) -> Result<bool, OperationError> {
286    let object = unsafe { root_from_object::<T>(cx, *object) };
287    if let Ok(obj) = object {
288        return unsafe { Ok(write_object(cx.no_gc(), val, global, &*obj, w, writer)) };
289    }
290    Err(OperationError::InterfaceDoesNotMatch)
291}
292
293type SerializeOperation = unsafe fn(
294    &mut JSContext,
295    SerializableInterface,
296    RawHandleObject,
297    &GlobalScope,
298    *mut JSStructuredCloneWriter,
299    &mut StructuredDataWriter,
300) -> Result<bool, OperationError>;
301
302fn serialize_for_type(val: SerializableInterface) -> SerializeOperation {
303    match val {
304        SerializableInterface::File => try_serialize::<File>,
305        SerializableInterface::FileList => try_serialize::<FileList>,
306        SerializableInterface::Blob => try_serialize::<Blob>,
307        SerializableInterface::DomPoint => try_serialize::<DOMPoint>,
308        SerializableInterface::DomPointReadOnly => try_serialize::<DOMPointReadOnly>,
309        SerializableInterface::DomRect => try_serialize::<DOMRect>,
310        SerializableInterface::DomRectReadOnly => try_serialize::<DOMRectReadOnly>,
311        SerializableInterface::DomQuad => try_serialize::<DOMQuad>,
312        SerializableInterface::DomMatrix => try_serialize::<DOMMatrix>,
313        SerializableInterface::DomMatrixReadOnly => try_serialize::<DOMMatrixReadOnly>,
314        SerializableInterface::DomException => try_serialize::<DOMException>,
315        SerializableInterface::ImageBitmap => try_serialize::<ImageBitmap>,
316        SerializableInterface::QuotaExceededError => try_serialize::<QuotaExceededError>,
317        SerializableInterface::ImageData => try_serialize::<ImageData>,
318        SerializableInterface::CryptoKey => try_serialize::<CryptoKey>,
319    }
320}
321
322unsafe extern "C" fn write_callback(
323    cx: *mut RawJSContext,
324    w: *mut JSStructuredCloneWriter,
325    obj: RawHandleObject,
326    _same_process_scope_required: *mut bool,
327    closure: *mut raw::c_void,
328) -> bool {
329    // SAFETY: it is safe to construct a JSContext from engine hook.
330    let mut cx = unsafe { JSContext::from_ptr(NonNull::new(cx).unwrap()) };
331    let cx = &mut cx;
332
333    let sc_writer = unsafe { &mut *(closure as *mut StructuredDataWriter) };
334
335    let mut realm = CurrentRealm::assert(cx);
336    let global = GlobalScope::from_current_realm(&mut realm);
337
338    for serializable in SerializableInterface::iter() {
339        let serializer = serialize_for_type(serializable);
340        if let Ok(result) = unsafe { serializer(cx, serializable, obj, &global, w, sc_writer) } {
341            return result;
342        }
343    }
344    false
345}
346
347fn receiver_for_type(
348    val: TransferrableInterface,
349) -> fn(
350    &mut JSContext,
351    &GlobalScope,
352    &mut StructuredDataReader<'_>,
353    u64,
354    RawMutableHandleObject,
355) -> Result<(), ()> {
356    match val {
357        TransferrableInterface::ImageBitmap => receive_object::<ImageBitmap>,
358        TransferrableInterface::MessagePort => receive_object::<MessagePort>,
359        TransferrableInterface::OffscreenCanvas => receive_object::<OffscreenCanvas>,
360        TransferrableInterface::ReadableStream => receive_object::<ReadableStream>,
361        TransferrableInterface::WritableStream => receive_object::<WritableStream>,
362        TransferrableInterface::TransformStream => receive_object::<TransformStream>,
363    }
364}
365
366fn receive_object<T: Transferable>(
367    cx: &mut JSContext,
368    owner: &GlobalScope,
369    sc_reader: &mut StructuredDataReader<'_>,
370    extra_data: u64,
371    return_object: RawMutableHandleObject,
372) -> Result<(), ()> {
373    // 1. Re-build the key for the storage location
374    // of the transferred object.
375    let big: [u8; 8] = extra_data.to_ne_bytes();
376    let (name_space, index) = big.split_at(4);
377
378    let namespace_id = PipelineNamespaceId(u32::from_ne_bytes(
379        name_space
380            .try_into()
381            .expect("name_space to be a slice of four."),
382    ));
383    let id: NamespaceIndex<T::Index> = NamespaceIndex {
384        namespace_id,
385        index: Index::new(u32::from_ne_bytes(
386            index.try_into().expect("index to be a slice of four."),
387        ))
388        .expect("Index to be non-zero"),
389    };
390
391    // 2. Get the transferred object from its storage, using the key.
392    let storage = T::serialized_storage(StructuredData::Reader(sc_reader));
393    let serialized = if let Some(objects) = storage.as_mut() {
394        let object = objects.remove(&id).expect("Transferred port to be stored");
395        if objects.is_empty() {
396            *storage = None;
397        }
398        object
399    } else {
400        panic!(
401            "An interface was transfer-received, yet the SC holder does not have any serialized objects"
402        );
403    };
404
405    let Ok(received) = T::transfer_receive(cx, owner, id, serialized) else {
406        return Err(());
407    };
408    return_object.set(received.reflector().rootable().get());
409    sc_reader.roots.push(Heap::boxed(return_object.get()));
410    Ok(())
411}
412
413unsafe extern "C" fn read_transfer_callback(
414    cx: *mut RawJSContext,
415    _r: *mut JSStructuredCloneReader,
416    _policy: *const CloneDataPolicy,
417    tag: u32,
418    _content: *mut raw::c_void,
419    extra_data: u64,
420    closure: *mut raw::c_void,
421    return_object: RawMutableHandleObject,
422) -> bool {
423    let sc_reader = unsafe { &mut *(closure as *mut StructuredDataReader<'_>) };
424    let mut cx = unsafe {
425        // This is safe because we are in SM hook
426        JSContext::from_ptr(
427            NonNull::new(cx).expect("JSContext pointer should not be null in SM hook"),
428        )
429    };
430    let mut realm = CurrentRealm::assert(&mut cx);
431    let owner = GlobalScope::from_current_realm(&mut realm);
432
433    for transferrable in TransferrableInterface::iter() {
434        if tag == StructuredCloneTags::from(transferrable) as u32 {
435            let transfer_receiver = receiver_for_type(transferrable);
436            if transfer_receiver(&mut realm, &owner, sc_reader, extra_data, return_object).is_ok() {
437                return true;
438            }
439        }
440    }
441    false
442}
443
444unsafe fn try_transfer<T: Transferable + IDLInterface>(
445    interface: TransferrableInterface,
446    obj: RawHandleObject,
447    cx: &mut JSContext,
448    sc_writer: &mut StructuredDataWriter,
449    tag: *mut u32,
450    ownership: *mut TransferableOwnership,
451    extra_data: *mut u64,
452) -> Result<(), OperationError> {
453    let object = unsafe { root_from_object::<T>(cx, *obj) };
454    let Ok(object) = object else {
455        return Err(OperationError::InterfaceDoesNotMatch);
456    };
457
458    unsafe { *tag = StructuredCloneTags::from(interface) as u32 };
459    unsafe { *ownership = TransferableOwnership::SCTAG_TMO_CUSTOM };
460
461    let (id, object) = object.transfer(cx).map_err(OperationError::Exception)?;
462
463    // 2. Store the transferred object at a given key.
464    let objects = T::serialized_storage(StructuredData::Writer(sc_writer))
465        .get_or_insert(FxHashMap::default());
466    objects.insert(id, object);
467
468    let index = id.index.0.get();
469
470    let mut big: [u8; 8] = [0; 8];
471    let name_space = id.namespace_id.0.to_ne_bytes();
472    let index = index.to_ne_bytes();
473
474    let (left, right) = big.split_at_mut(4);
475    left.copy_from_slice(&name_space);
476    right.copy_from_slice(&index);
477
478    // 3. Return a u64 representation of the key where the object is stored.
479    unsafe { *extra_data = u64::from_ne_bytes(big) };
480    Ok(())
481}
482
483type TransferOperation = unsafe fn(
484    TransferrableInterface,
485    RawHandleObject,
486    &mut JSContext,
487    &mut StructuredDataWriter,
488    *mut u32,
489    *mut TransferableOwnership,
490    *mut u64,
491) -> Result<(), OperationError>;
492
493fn transfer_for_type(val: TransferrableInterface) -> TransferOperation {
494    match val {
495        TransferrableInterface::ImageBitmap => try_transfer::<ImageBitmap>,
496        TransferrableInterface::MessagePort => try_transfer::<MessagePort>,
497        TransferrableInterface::OffscreenCanvas => try_transfer::<OffscreenCanvas>,
498        TransferrableInterface::ReadableStream => try_transfer::<ReadableStream>,
499        TransferrableInterface::WritableStream => try_transfer::<WritableStream>,
500        TransferrableInterface::TransformStream => try_transfer::<TransformStream>,
501    }
502}
503
504/// <https://html.spec.whatwg.org/multipage/#structuredserializewithtransfer>
505unsafe extern "C" fn write_transfer_callback(
506    cx: *mut RawJSContext,
507    obj: RawHandleObject,
508    closure: *mut raw::c_void,
509    tag: *mut u32,
510    ownership: *mut TransferableOwnership,
511    _content: *mut *mut raw::c_void,
512    extra_data: *mut u64,
513) -> bool {
514    let sc_writer = unsafe { &mut *(closure as *mut StructuredDataWriter) };
515    let mut cx = unsafe {
516        // This is safe because we are in SM hook
517        JSContext::from_ptr(
518            NonNull::new(cx).expect("JSContext pointer should not be null in SM hook"),
519        )
520    };
521    for transferable in TransferrableInterface::iter() {
522        let try_transfer = transfer_for_type(transferable);
523
524        let transfer_result = unsafe {
525            try_transfer(
526                transferable,
527                obj,
528                &mut cx,
529                sc_writer,
530                tag,
531                ownership,
532                extra_data,
533            )
534        };
535        match transfer_result {
536            Err(error) => match error {
537                OperationError::InterfaceDoesNotMatch => {},
538                OperationError::Exception(error) => {
539                    sc_writer.error = Some(error);
540                    return false;
541                },
542            },
543            Ok(..) => return true,
544        }
545    }
546
547    false
548}
549
550unsafe extern "C" fn free_transfer_callback(
551    _tag: u32,
552    _ownership: TransferableOwnership,
553    _content: *mut raw::c_void,
554    _extra_data: u64,
555    _closure: *mut raw::c_void,
556) {
557}
558
559unsafe fn can_transfer_for_type(
560    cx: &mut JSContext,
561    transferable: TransferrableInterface,
562    obj: RawHandleObject,
563) -> Result<bool, ()> {
564    unsafe fn can_transfer<T: Transferable + IDLInterface>(
565        cx: &mut JSContext,
566        obj: RawHandleObject,
567    ) -> Result<bool, ()> {
568        unsafe { root_from_object::<T>(cx, *obj).map(|o| Transferable::can_transfer(&*o)) }
569    }
570
571    unsafe {
572        match transferable {
573            TransferrableInterface::ImageBitmap => can_transfer::<ImageBitmap>(cx, obj),
574            TransferrableInterface::MessagePort => can_transfer::<MessagePort>(cx, obj),
575            TransferrableInterface::OffscreenCanvas => can_transfer::<OffscreenCanvas>(cx, obj),
576            TransferrableInterface::ReadableStream => can_transfer::<ReadableStream>(cx, obj),
577            TransferrableInterface::WritableStream => can_transfer::<WritableStream>(cx, obj),
578            TransferrableInterface::TransformStream => can_transfer::<TransformStream>(cx, obj),
579        }
580    }
581}
582
583unsafe extern "C" fn can_transfer_callback(
584    cx: *mut RawJSContext,
585    obj: RawHandleObject,
586    _same_process_scope_required: *mut bool,
587    _closure: *mut raw::c_void,
588) -> bool {
589    // SAFETY: it is safe to construct a JSContext from engine hook.
590    let mut cx = unsafe { JSContext::from_ptr(NonNull::new(cx).unwrap()) };
591    let cx = &mut cx;
592
593    for transferable in TransferrableInterface::iter() {
594        let can_transfer = unsafe { can_transfer_for_type(cx, transferable, obj) };
595        if let Ok(can_transfer) = can_transfer {
596            return can_transfer;
597        }
598    }
599    false
600}
601
602unsafe extern "C" fn report_error_callback(
603    _cx: *mut RawJSContext,
604    _errorid: u32,
605    closure: *mut raw::c_void,
606    error_message: *const ::std::os::raw::c_char,
607) {
608    let msg_result = unsafe { CStr::from_ptr(error_message).to_str().map(str::to_string) };
609
610    if let Ok(msg) = msg_result {
611        let error = unsafe { &mut *(closure as *mut Option<Error>) };
612
613        if error.is_none() {
614            *error = Some(Error::DataClone(Some(msg)));
615        }
616    }
617}
618
619unsafe extern "C" fn sab_cloned_callback(
620    _cx: *mut RawJSContext,
621    _receiving: bool,
622    _closure: *mut ::std::os::raw::c_void,
623) -> bool {
624    false
625}
626
627static STRUCTURED_CLONE_CALLBACKS: JSStructuredCloneCallbacks = JSStructuredCloneCallbacks {
628    read: Some(read_callback),
629    write: Some(write_callback),
630    reportError: Some(report_error_callback),
631    readTransfer: Some(read_transfer_callback),
632    writeTransfer: Some(write_transfer_callback),
633    freeTransfer: Some(free_transfer_callback),
634    canTransfer: Some(can_transfer_callback),
635    sabCloned: Some(sab_cloned_callback),
636};
637
638pub(crate) enum StructuredData<'a, 'b> {
639    Reader(&'a mut StructuredDataReader<'b>),
640    Writer(&'a mut StructuredDataWriter),
641}
642
643/// Reader and writer structs for results from, and inputs to, structured-data read/write operations.
644/// <https://html.spec.whatwg.org/multipage/#safe-passing-of-structured-data>
645#[repr(C)]
646pub(crate) struct StructuredDataReader<'a> {
647    /// A error record.
648    error: Option<Error>,
649    /// Rooted copies of every deserialized object to ensure they are not garbage collected.
650    roots: RootedVec<'a, Box<Heap<*mut JSObject>>>,
651    /// A map of port implementations,
652    /// used as part of the "transfer-receiving" steps of ports,
653    /// to produce the DOM ports stored in `message_ports` above.
654    pub(crate) port_impls: Option<FxHashMap<MessagePortId, MessagePortImpl>>,
655    /// A map of transform stream implementations,
656    pub(crate) transform_streams_port_impls: Option<FxHashMap<MessagePortId, TransformStreamData>>,
657    /// A map of blob implementations,
658    /// used as part of the "deserialize" steps of blobs,
659    /// to produce the DOM blobs stored in `blobs` above.
660    pub(crate) blob_impls: Option<FxHashMap<BlobId, BlobImpl>>,
661    /// A map of serialized files.
662    pub(crate) files: Option<FxHashMap<FileId, SerializableFile>>,
663    /// A map of serialized file lists.
664    pub(crate) file_lists: Option<FxHashMap<FileListId, SerializableFileList>>,
665    /// A map of serialized points.
666    pub(crate) points: Option<FxHashMap<DomPointId, DomPoint>>,
667    /// A map of serialized rects.
668    pub(crate) rects: Option<FxHashMap<DomRectId, DomRect>>,
669    /// A map of serialized quads.
670    pub(crate) quads: Option<FxHashMap<DomQuadId, DomQuad>>,
671    /// A map of serialized matrices.
672    pub(crate) matrices: Option<FxHashMap<DomMatrixId, DomMatrix>>,
673    /// A map of serialized exceptions.
674    pub(crate) exceptions: Option<FxHashMap<DomExceptionId, DomException>>,
675    /// A map of serialized quota exceeded errors.
676    pub(crate) quota_exceeded_errors:
677        Option<FxHashMap<QuotaExceededErrorId, SerializableQuotaExceededError>>,
678    // A map of serialized image bitmaps.
679    pub(crate) image_bitmaps: Option<FxHashMap<ImageBitmapId, SerializableImageBitmap>>,
680    /// A map of transferred image bitmaps.
681    pub(crate) transferred_image_bitmaps: Option<FxHashMap<ImageBitmapId, SerializableImageBitmap>>,
682    /// A map of transferred offscreen canvases.
683    pub(crate) offscreen_canvases:
684        Option<FxHashMap<OffscreenCanvasId, TransferableOffscreenCanvas>>,
685    // A map of serialized image data.
686    pub(crate) image_data: Option<FxHashMap<ImageDataId, SerializableImageData>>,
687    // A map of serialized crypto keys.
688    pub(crate) crypto_keys: Option<FxHashMap<CryptoKeyId, SerializableCryptoKey>>,
689}
690
691/// A data holder for transferred and serialized objects.
692#[derive(Default)]
693#[repr(C)]
694pub(crate) struct StructuredDataWriter {
695    /// Error record.
696    pub(crate) error: Option<Error>,
697    /// Transferred ports.
698    pub(crate) ports: Option<FxHashMap<MessagePortId, MessagePortImpl>>,
699    /// Transferred transform streams.
700    pub(crate) transform_streams_port: Option<FxHashMap<MessagePortId, TransformStreamData>>,
701    /// Serialized points.
702    pub(crate) points: Option<FxHashMap<DomPointId, DomPoint>>,
703    /// Serialized rects.
704    pub(crate) rects: Option<FxHashMap<DomRectId, DomRect>>,
705    /// Serialized quads.
706    pub(crate) quads: Option<FxHashMap<DomQuadId, DomQuad>>,
707    /// Serialized matrices.
708    pub(crate) matrices: Option<FxHashMap<DomMatrixId, DomMatrix>>,
709    /// Serialized exceptions.
710    pub(crate) exceptions: Option<FxHashMap<DomExceptionId, DomException>>,
711    /// Serialized quota exceeded errors.
712    pub(crate) quota_exceeded_errors:
713        Option<FxHashMap<QuotaExceededErrorId, SerializableQuotaExceededError>>,
714    /// Serialized blobs.
715    pub(crate) blobs: Option<FxHashMap<BlobId, BlobImpl>>,
716    /// Serialized files.
717    pub(crate) files: Option<FxHashMap<FileId, SerializableFile>>,
718    /// Serialized file lists.
719    pub(crate) file_lists: Option<FxHashMap<FileListId, SerializableFileList>>,
720    /// Serialized image bitmaps.
721    pub(crate) image_bitmaps: Option<FxHashMap<ImageBitmapId, SerializableImageBitmap>>,
722    /// Transferred image bitmaps.
723    pub(crate) transferred_image_bitmaps: Option<FxHashMap<ImageBitmapId, SerializableImageBitmap>>,
724    /// Transferred offscreen canvases.
725    pub(crate) offscreen_canvases:
726        Option<FxHashMap<OffscreenCanvasId, TransferableOffscreenCanvas>>,
727    // A map of serialized image data.
728    pub(crate) image_data: Option<FxHashMap<ImageDataId, SerializableImageData>>,
729    // A map of serialized crypto keys.
730    pub(crate) crypto_keys: Option<FxHashMap<CryptoKeyId, SerializableCryptoKey>>,
731}
732
733/// Writes a structured clone. Returns a `DataClone` error if that fails.
734pub(crate) fn write(
735    cx: &mut JSContext,
736    message: HandleValue,
737    transfer: Option<CustomAutoRooterGuard<Vec<*mut JSObject>>>,
738) -> Fallible<StructuredSerializedData> {
739    unsafe {
740        rooted!(&in(cx) let mut val = UndefinedValue());
741        if let Some(transfer) = transfer {
742            transfer.safe_to_jsval(cx, val.handle_mut());
743        }
744        let mut sc_writer = StructuredDataWriter::default();
745        let sc_writer_ptr = &mut sc_writer as *mut _;
746
747        let scbuf = JSAutoStructuredCloneBufferWrapper::new(
748            StructuredCloneScope::DifferentProcess,
749            &STRUCTURED_CLONE_CALLBACKS,
750        );
751        let scdata = &mut ((*scbuf.as_raw_ptr()).data_);
752        let policy = CloneDataPolicy {
753            allowIntraClusterClonableSharedObjects_: false,
754            allowSharedMemoryObjects_: false,
755        };
756        let result = JS_WriteStructuredClone(
757            cx,
758            message,
759            scdata,
760            StructuredCloneScope::DifferentProcess,
761            &policy,
762            &STRUCTURED_CLONE_CALLBACKS,
763            sc_writer_ptr as *mut raw::c_void,
764            val.handle(),
765        );
766        if !result {
767            let error = if JS_IsExceptionPending(cx) {
768                Error::JSFailed
769            } else {
770                sc_writer.error.unwrap_or(Error::DataClone(None))
771            };
772
773            return Err(error);
774        }
775
776        let nbytes = GetLengthOfJSStructuredCloneData(scdata);
777        let mut data = Vec::with_capacity(nbytes);
778        CopyJSStructuredCloneData(scdata, data.as_mut_ptr());
779        data.set_len(nbytes);
780
781        let data = StructuredSerializedData {
782            serialized: data,
783            ports: sc_writer.ports.take(),
784            transform_streams: sc_writer.transform_streams_port.take(),
785            points: sc_writer.points.take(),
786            rects: sc_writer.rects.take(),
787            quads: sc_writer.quads.take(),
788            matrices: sc_writer.matrices.take(),
789            exceptions: sc_writer.exceptions.take(),
790            quota_exceeded_errors: sc_writer.quota_exceeded_errors.take(),
791            blobs: sc_writer.blobs.take(),
792            files: sc_writer.files.take(),
793            file_lists: sc_writer.file_lists.take(),
794            image_bitmaps: sc_writer.image_bitmaps.take(),
795            transferred_image_bitmaps: sc_writer.transferred_image_bitmaps.take(),
796            offscreen_canvases: sc_writer.offscreen_canvases.take(),
797            image_data: sc_writer.image_data.take(),
798            crypto_keys: sc_writer.crypto_keys.take(),
799        };
800
801        Ok(data)
802    }
803}
804
805/// Read structured serialized data, possibly containing transferred objects.
806/// Returns a vec of rooted transfer-received ports, or an error.
807pub(crate) fn read(
808    cx: &mut JSContext,
809    global: &GlobalScope,
810    mut data: StructuredSerializedData,
811    rval: MutableHandleValue,
812) -> Fallible<Vec<DomRoot<MessagePort>>> {
813    let mut realm = enter_auto_realm(cx, global);
814    let cx = &mut realm.current_realm();
815
816    rooted_vec!(let mut roots);
817    let mut sc_reader = StructuredDataReader {
818        error: None,
819        roots,
820        port_impls: data.ports.take(),
821        transform_streams_port_impls: data.transform_streams.take(),
822        blob_impls: data.blobs.take(),
823        files: data.files.take(),
824        file_lists: data.file_lists.take(),
825        points: data.points.take(),
826        rects: data.rects.take(),
827        quads: data.quads.take(),
828        matrices: data.matrices.take(),
829        exceptions: data.exceptions.take(),
830        quota_exceeded_errors: data.quota_exceeded_errors.take(),
831        image_bitmaps: data.image_bitmaps.take(),
832        transferred_image_bitmaps: data.transferred_image_bitmaps.take(),
833        offscreen_canvases: data.offscreen_canvases.take(),
834        image_data: data.image_data.take(),
835        crypto_keys: data.crypto_keys.take(),
836    };
837    let sc_reader_ptr = &mut sc_reader as *mut _;
838    unsafe {
839        let scbuf = JSAutoStructuredCloneBufferWrapper::new(
840            StructuredCloneScope::DifferentProcess,
841            &STRUCTURED_CLONE_CALLBACKS,
842        );
843        let scdata = &mut ((*scbuf.as_raw_ptr()).data_);
844
845        WriteBytesToJSStructuredCloneData(
846            data.serialized.as_mut_ptr() as *const u8,
847            data.serialized.len(),
848            scdata,
849        );
850
851        let result = JS_ReadStructuredClone(
852            cx,
853            scdata,
854            JS_STRUCTURED_CLONE_VERSION,
855            StructuredCloneScope::DifferentProcess,
856            rval,
857            &CloneDataPolicy {
858                allowIntraClusterClonableSharedObjects_: false,
859                allowSharedMemoryObjects_: false,
860            },
861            &STRUCTURED_CLONE_CALLBACKS,
862            sc_reader_ptr as *mut raw::c_void,
863        );
864        if !result {
865            let error = if JS_IsExceptionPending(cx) {
866                Error::JSFailed
867            } else {
868                sc_reader.error.unwrap_or(Error::DataClone(None))
869            };
870
871            return Err(error);
872        }
873
874        let mut message_ports = vec![];
875        for reflector in sc_reader.roots.iter() {
876            let Ok(message_port) = root_from_object::<MessagePort>(cx, reflector.get()) else {
877                continue;
878            };
879            message_ports.push(message_port);
880        }
881        // Any transfer-received port-impls should have been taken out.
882        assert!(sc_reader.port_impls.is_none());
883        Ok(message_ports)
884    }
885}