Skip to main content

script_bindings/
wrap.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/. */
4use std::ffi::c_void;
5use std::ptr;
6
7use js::JSCLASS_IS_GLOBAL;
8use js::context::JSContext;
9use js::gc::{HandleObject, MutableHandleObject};
10use js::glue::SetProxyReservedSlot;
11use js::jsapi::{JS_SetReservedSlot, JSAutoRealm, JSClass, JSObject};
12use js::jsval::{PrivateValue, UndefinedValue};
13use js::rust::wrappers2::{
14    JS_InitializePropertiesFromCompatibleNativeObject, JS_WrapObject, NewProxyObject,
15};
16use js::rust::{Handle, get_context_realm, get_object_class, get_object_realm};
17
18use crate::conversions::DOM_OBJECT_SLOT;
19use crate::import::module::JS_GetReservedSlot;
20use crate::js::JS_NewObjectWithGivenProto;
21use crate::proxyhandler::ensure_expando_object;
22use crate::root::{DomRoot, MaybeUnreflectedDom, Root};
23use crate::utils::DOM_PROTO_UNFORGEABLE_HOLDER_SLOT;
24use crate::{DomObject, DomTypes, MutDomObject};
25
26type ProtoObjectFn = fn(&mut js::context::JSContext, HandleObject, MutableHandleObject);
27
28/// TODO: unforgeable is missing
29pub(crate) struct WrapConfig {
30    pub(crate) is_maybe_cross_origin_object: bool,
31    pub(crate) is_proxy: bool,
32    pub(crate) proxy_handler: Option<*const c_void>,
33    pub(crate) class: Option<&'static JSClass>,
34    // this function has to be more general because we do not have the correct type for globalscope.
35    pub(crate) proto_object_fn: ProtoObjectFn,
36    pub(crate) has_legacy_unforgeable_members: bool,
37}
38
39#[cfg_attr(crown, allow(crown::unrooted_must_root))]
40pub(crate) unsafe fn wrap<T: MutDomObject, D: DomTypes>(
41    cx: &mut JSContext,
42    scope: &D::GlobalScope,
43    given_proto: Option<js::rust::Handle<*mut JSObject>>,
44    raw: Root<MaybeUnreflectedDom<T>>,
45    config: WrapConfig,
46) -> DomRoot<T> {
47    unsafe {
48        rooted!(&in(cx) let mut obj = ptr::null_mut::<JSObject>());
49        wrap_object(
50            cx,
51            &scope.reflector().get_jsobject(),
52            given_proto,
53            raw.as_ptr() as *const c_void,
54            &config,
55            obj.handle_mut(),
56        );
57        raw.reflect_with(obj.get())
58    }
59}
60
61// `wrap` is instantiated many times, so we move most of the code into this non-generic helper.
62unsafe fn wrap_object(
63    cx: &mut JSContext,
64    scope: &HandleObject,
65    given_proto: Option<js::rust::Handle<*mut JSObject>>,
66    raw: *const c_void,
67    config: &WrapConfig,
68    mut rval: MutableHandleObject,
69) {
70    unsafe {
71        assert!(!scope.get().is_null());
72        assert!(((*get_object_class(scope.get())).flags & JSCLASS_IS_GLOBAL) != 0);
73        let _ac = JSAutoRealm::new(cx.raw_cx(), scope.get());
74
75        rooted!(&in(cx) let mut canonical_proto = ptr::null_mut::<JSObject>());
76        (config.proto_object_fn)(cx, *scope, canonical_proto.handle_mut());
77        assert!(!canonical_proto.is_null());
78
79        if config.is_proxy {
80            let handler: *const libc::c_void = config.proxy_handler.unwrap();
81
82            if config.is_maybe_cross_origin_object {
83                rval.set(NewProxyObject(
84                    cx,
85                    handler,
86                    Handle::undefined(),
87                    ptr::null_mut(),
88                    ptr::null(),
89                    true,
90                ));
91            } else {
92                rval.set(NewProxyObject(
93                    cx,
94                    handler,
95                    Handle::undefined(),
96                    canonical_proto.get(),
97                    ptr::null(),
98                    false,
99                ));
100            };
101
102            assert!(!rval.is_null());
103            SetProxyReservedSlot(rval.get(), 0, &PrivateValue(raw));
104        } else {
105            rooted!(&in(cx) let mut proto = ptr::null_mut::<JSObject>());
106            if let Some(given) = given_proto {
107                proto.set(*given);
108                if get_context_realm(cx.raw_cx()) != get_object_realm(*given) {
109                    assert!(JS_WrapObject(cx, proto.handle_mut()));
110                }
111            } else {
112                proto.set(*canonical_proto);
113            }
114            rval.set(JS_NewObjectWithGivenProto(
115                cx,
116                Some(config.class.unwrap()),
117                proto.handle(),
118            ));
119            assert!(!rval.is_null());
120            JS_SetReservedSlot(rval.get(), DOM_OBJECT_SLOT, &PrivateValue(raw));
121        };
122
123        // From here on we copy the legacy unforgeable properties to instance which was originally in a different function.
124        if config.has_legacy_unforgeable_members {
125            rooted!(&in(cx) let mut expando = ptr::null_mut::<JSObject>());
126            if config.is_proxy {
127                ensure_expando_object(cx, rval.handle(), expando.handle_mut());
128            }
129
130            let copy_fn = JS_InitializePropertiesFromCompatibleNativeObject;
131
132            let mut slot = UndefinedValue();
133            JS_GetReservedSlot(
134                canonical_proto.get(),
135                DOM_PROTO_UNFORGEABLE_HOLDER_SLOT,
136                &mut slot,
137            );
138            rooted!(&in(cx) let mut unforgeable_holder = ptr::null_mut::<JSObject>());
139            unforgeable_holder.handle_mut().set(slot.to_object());
140            if config.is_proxy {
141                assert!(copy_fn(cx, expando.handle(), unforgeable_holder.handle()));
142            } else {
143                assert!(copy_fn(cx, rval.handle(), unforgeable_holder.handle()));
144            }
145        }
146    }
147}