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