script/dom/bindings/reflector.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
5use js::context::JSContext;
6use script_bindings::reflector::DomGlobalGeneric;
7use script_bindings::root::DomRoot;
8
9use crate::DomTypeHolder;
10use crate::dom::types::GlobalScope;
11use crate::realms::enter_auto_realm;
12
13pub(crate) trait DomGlobal {
14 /// Returns the [relevant global] in the same realm as the callee object.
15 /// Will enter the realm of the global to ensure the global is only
16 /// accessed from the correct realm.
17 ///
18 /// [relevant global]: https://html.spec.whatwg.org/multipage/#concept-relevant-global
19 fn global(&self) -> DomRoot<GlobalScope>;
20}
21
22impl<T: DomGlobalGeneric<DomTypeHolder>> DomGlobal for T {
23 #[expect(unsafe_code)]
24 fn global(&self) -> DomRoot<GlobalScope> {
25 // SAFETY: We only use this `cx` to enter a realm. That does not
26 // incur a GC and hence is safe to perform. We do not want to
27 // pass a `cx` as parameter to this function, as this used in
28 // loads of places. At the same time, it also isn't necessary in
29 // nearly all cases to enter realm, since we are already in the
30 // correct realm.
31 //
32 // However, there are cases where it is difficult to ensure that
33 // we are in the correct realm. Hence we always enter a realm here
34 // even if that is unnecessary at times.
35 let cx = unsafe { JSContext::get_from_thread() };
36 let cx = &mut cx.expect("JS runtime has shut down");
37 let _realm = enter_auto_realm(cx, self);
38 <Self as DomGlobalGeneric<DomTypeHolder>>::global_from_reflector(self)
39 }
40}