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