Skip to main content

script/dom/globalscope/
globalscope.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 std::borrow::Cow;
6use std::cell::{Cell, OnceCell, Ref, RefCell};
7use std::collections::hash_map::Entry;
8use std::collections::{HashMap, HashSet, VecDeque};
9use std::ffi::CStr;
10use std::mem;
11use std::ops::{Deref, Index};
12use std::rc::Rc;
13use std::sync::Arc;
14use std::sync::atomic::{AtomicBool, Ordering};
15use std::thread::JoinHandle;
16use std::time::{Duration, Instant};
17
18use content_security_policy::CspList;
19use crossbeam_channel::Sender;
20#[cfg(feature = "devtools")]
21use devtools_traits::{PageError, ScriptToDevtoolsControlMsg, get_time_stamp};
22use dom_struct::dom_struct;
23use embedder_traits::{
24    ConsoleLogLevel, EmbedderMsg, JavaScriptEvaluationError, ScriptToEmbedderChan,
25};
26use fonts::{FontContext, WebFontDocumentContext};
27use js::context::{JSContext, NoGC};
28use js::jsapi::{GetNonCCWObjectGlobal, HandleObject, Heap, JSObject};
29use js::jsval::UndefinedValue;
30use js::panic::maybe_resume_unwind;
31use js::realm::CurrentRealm;
32use js::rust::wrappers2::{Compile1, CurrentGlobalOrNull, JS_ExecuteScript};
33use js::rust::{
34    HandleValue, MutableHandleValue, ParentRuntime, get_object_class, transform_str_to_source_text,
35};
36use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL};
37use net_traits::blob_url_store::BlobBuf;
38use net_traits::filemanager_thread::{
39    FileManagerResult, FileManagerThreadMsg, ReadFileProgress, RelativePos,
40};
41use net_traits::image_cache::ImageCache;
42use net_traits::policy_container::PolicyContainer;
43use net_traits::request::{
44    InsecureRequestsPolicy, Origin as RequestOrigin, Referrer, RequestBuilder, RequestClient,
45    UpgradeInsecureNavigations,
46};
47use net_traits::{CoreResourceMsg, CoreResourceThread, ReferrerPolicy, ResourceThreads};
48use profile_traits::{
49    generic_callback as profile_generic_callback, generic_channel as profile_generic_channel,
50    mem as profile_mem, time as profile_time,
51};
52use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
53use script_bindings::callback::{OwnerWindow, RootedCallback, TracedCallback};
54use script_bindings::cell::{DomRefCell, RefMut};
55use script_bindings::domstring::TracedDOMString;
56use script_bindings::interfaces::GlobalScopeHelpers;
57use script_bindings::reflector::DomObject;
58use script_bindings::settings_stack::run_a_script;
59use servo_base::generic_channel;
60use servo_base::generic_channel::{GenericCallback, GenericSend};
61use servo_base::id::{
62    BlobId, BroadcastChannelRouterId, MessagePortId, MessagePortRouterId, PipelineId,
63    ServiceWorkerId, ServiceWorkerRegistrationId, TEST_WEBVIEW_ID, WebViewId,
64};
65use servo_config::pref;
66use servo_constellation_traits::{
67    BlobData, BlobImpl, BroadcastChannelMsg, ConstellationInterest, FileBlob, MessagePortImpl,
68    PortMessageTask, ScriptToConstellationChan, ScriptToConstellationMessage,
69    ScriptToConstellationSender, ServiceWorkerState,
70};
71use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
72use storage_traits::StorageThreads;
73use strum::VariantArray;
74use timers::{TimerEventRequest, TimerId};
75use uuid::Uuid;
76#[cfg(feature = "webgpu")]
77use webgpu_traits::{DeviceLostReason, WebGPUDevice};
78
79use crate::DomTypeHolder;
80use crate::dom::bindings::codegen::Bindings::BroadcastChannelBinding::BroadcastChannelMethods;
81use crate::dom::bindings::codegen::Bindings::EventSourceBinding::EventSource_Binding::EventSourceMethods;
82use crate::dom::bindings::codegen::Bindings::FunctionBinding::Function;
83use crate::dom::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions;
84use crate::dom::bindings::codegen::Bindings::NotificationBinding::NotificationPermissionCallback;
85use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::{
86    PermissionName, PermissionState,
87};
88#[cfg(feature = "webgpu")]
89use crate::dom::bindings::codegen::Bindings::WebGPUBinding::GPUDeviceLostReason;
90use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
91use crate::dom::bindings::codegen::Bindings::WorkerGlobalScopeBinding::WorkerGlobalScopeMethods;
92use crate::dom::bindings::conversions::{root_from_object, root_from_object_static};
93#[cfg(feature = "js_backtrace")]
94use crate::dom::bindings::error::LAST_EXCEPTION_BACKTRACE;
95use crate::dom::bindings::error::{
96    ErrorInfo, Fallible, report_pending_exception, take_and_report_pending_exception_for_api,
97};
98use crate::dom::bindings::frozenarray::CachedFrozenArray;
99use crate::dom::bindings::inheritance::Castable;
100use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
101use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
102use crate::dom::bindings::settings_stack::{entry_global, incumbent_global};
103use crate::dom::bindings::str::DOMString;
104use crate::dom::bindings::structuredclone;
105use crate::dom::bindings::trace::{CustomTraceable, HashMapTracedValues};
106use crate::dom::bindings::weakref::{DOMTracker, WeakRef};
107use crate::dom::blob::Blob;
108use crate::dom::dedicatedworkerglobalscope::{
109    DedicatedWorkerControlMsg, DedicatedWorkerGlobalScope,
110};
111use crate::dom::dissimilaroriginwindow::DissimilarOriginWindow;
112use crate::dom::errorevent::ErrorEvent;
113use crate::dom::event::{Event, EventBubbles, EventCancelable};
114use crate::dom::eventsource::EventSource;
115use crate::dom::eventtarget::EventTarget;
116use crate::dom::file::File;
117use crate::dom::globalscope::auto_close_worker::AutoCloseWorker;
118use crate::dom::globalscope::broadcastchannel::BroadcastChannel;
119use crate::dom::globalscope::listeners::{
120    BlobInfo, BlobResult, BlobTracker, BroadcastChannelState, BroadcastListener, FileListener,
121    FileListenerCallback, FileListenerState, FileListenerTarget, ManagedMessagePort,
122    MessageListener, MessagePortState,
123};
124use crate::dom::idbfactory::IDBFactory;
125use crate::dom::messageport::MessagePort;
126use crate::dom::paintworkletglobalscope::PaintWorkletGlobalScope;
127use crate::dom::performance::performance::Performance;
128use crate::dom::performance::performanceentry::EntryType;
129use crate::dom::promise::RootedPromise;
130use crate::dom::readablestream::{CrossRealmTransformReadable, ReadableStream};
131use crate::dom::serviceworker::ServiceWorker;
132use crate::dom::serviceworkerglobalscope::ServiceWorkerGlobalScope;
133use crate::dom::serviceworkerregistration::ServiceWorkerRegistration;
134use crate::dom::sharedworkerglobalscope::SharedWorkerGlobalScope;
135use crate::dom::stream::underlyingsourcecontainer::UnderlyingSourceType;
136use crate::dom::stream::writablestream::CrossRealmTransformWritable;
137use crate::dom::transformstream::CrossRealmTransform;
138#[cfg(feature = "devtools")]
139use crate::dom::types::DebuggerGlobalScope;
140use crate::dom::types::{AbortSignal, MessageEvent};
141#[cfg(feature = "webgpu")]
142use crate::dom::webgpu::gpudevice::GPUDevice;
143#[cfg(feature = "webgpu")]
144use crate::dom::webgpu::identityhub::IdentityHub;
145use crate::dom::window::{FontCspHandler, FontNetworkTimingHandler, Window};
146use crate::dom::workerglobalscope::WorkerGlobalScope;
147use crate::dom::workletglobalscope::WorkletGlobalScope;
148use crate::event_loop::script_thread::{ScriptThread, with_script_thread};
149use crate::event_loop::timers::{
150    IsInterval, JsTimerTaskData, OneshotTimerCallback, OneshotTimerHandle, OneshotTimers,
151    RootedInternalTimerCallback, TimerCallback, TimerEventId, TimerSource,
152};
153use crate::fetch::fetch::FetchGroup;
154use crate::fetch::network_listener::{FetchResponseListener, NetworkListener};
155use crate::messaging::{CommonScriptMsg, ScriptEventLoopReceiver, ScriptEventLoopSender};
156use crate::realms::enter_auto_realm;
157use crate::runtime::job_queue::MicrotaskRunnable;
158use crate::runtime::script_runtime::ThreadSafeJSContext;
159use crate::scripting::fetching_options::ScriptFetchOptions;
160use crate::scripting::import_map::ImportMap;
161use crate::scripting::script_execution::{
162    ScriptOptions, fill_compile_options, maybe_associate_with_script,
163};
164use crate::scripting::script_module::{ModuleRequest, ModuleStatus, ResolvedModule};
165use crate::tasks::task_manager::TaskManager;
166use crate::tasks::task_source::SendableTaskSource;
167use crate::unminify::unminified_path;
168
169#[dom_struct]
170pub(crate) struct GlobalScope {
171    eventtarget: EventTarget,
172
173    /// The message-port router id for this global, if it is managing ports.
174    message_port_state: DomRefCell<MessagePortState>,
175
176    /// The broadcast channels state this global, if it is managing any.
177    broadcast_channel_state: DomRefCell<BroadcastChannelState>,
178
179    /// Tracks the number of active listeners per constellation interest category.
180    /// When the count transitions from 0 to 1, a RegisterInterest message is sent.
181    /// When it transitions from 1 to 0, an UnregisterInterest message is sent.
182    #[no_trace]
183    constellation_interest_counts: RefCell<FxHashMap<ConstellationInterest, usize>>,
184
185    /// The blobs managed by this global, if any.
186    blob_state: DomRefCell<HashMapTracedValues<BlobId, BlobInfo, FxBuildHasher>>,
187
188    /// <https://w3c.github.io/ServiceWorker/#environment-settings-object-service-worker-registration-object-map>
189    registration_map: DomRefCell<
190        HashMapTracedValues<
191            ServiceWorkerRegistrationId,
192            Dom<ServiceWorkerRegistration>,
193            FxBuildHasher,
194        >,
195    >,
196
197    /// <https://w3c.github.io/IndexedDB/#factory-interface>
198    indexeddb: MutNullableDom<IDBFactory>,
199
200    /// <https://w3c.github.io/ServiceWorker/#environment-settings-object-service-worker-object-map>
201    worker_map: DomRefCell<HashMapTracedValues<ServiceWorkerId, Dom<ServiceWorker>, FxBuildHasher>>,
202
203    /// Timers (milliseconds) used by the Console API.
204    console_timers: DomRefCell<HashMap<TracedDOMString, Instant>>,
205
206    /// For providing instructions to an optional devtools server.
207    #[no_trace]
208    #[cfg(feature = "devtools")]
209    devtools_chan: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
210
211    /// For sending messages to the memory profiler.
212    #[no_trace]
213    mem_profiler_chan: profile_mem::ProfilerChan,
214
215    /// For sending messages to the time profiler.
216    #[no_trace]
217    time_profiler_chan: profile_time::ProfilerChan,
218
219    /// A handle for communicating messages to the constellation thread.
220    #[no_trace]
221    script_to_constellation_sender: ScriptToConstellationSender,
222
223    /// A handle for communicating messages to the Embedder.
224    #[no_trace]
225    script_to_embedder_chan: ScriptToEmbedderChan,
226
227    /// <https://html.spec.whatwg.org/multipage/#in-error-reporting-mode>
228    in_error_reporting_mode: Cell<bool>,
229
230    /// Associated resource threads for use by DOM objects like XMLHttpRequest,
231    /// including resource_thread and filemanager_thread
232    #[no_trace]
233    resource_threads: ResourceThreads,
234
235    /// Associated resource threads for use by DOM objects like XMLHttpRequest,
236    /// including indexeddb thread and storage_thread
237    #[no_trace]
238    storage_threads: StorageThreads,
239
240    /// <https://html.spec.whatwg.org/multipage/#concept-environment-creation-url>
241    #[no_trace]
242    creation_url: DomRefCell<ServoUrl>,
243
244    /// <https://html.spec.whatwg.org/multipage/#concept-environment-top-level-creation-url>
245    #[no_trace]
246    top_level_creation_url: DomRefCell<Option<ServoUrl>>,
247
248    /// A map for storing the previous permission state read results.
249    permission_state_invocation_results: DomRefCell<HashMap<PermissionName, PermissionState>>,
250
251    /// Vector storing closing references of all workers
252    list_auto_close_worker: DomRefCell<Vec<AutoCloseWorker>>,
253
254    /// Vector storing references of all eventsources.
255    event_source_tracker: DOMTracker<EventSource>,
256
257    /// Dependent AbortSignals that must be kept alive per
258    /// <https://dom.spec.whatwg.org/#abort-signal-garbage-collection?
259    abort_signal_dependents: DomRefCell<FxHashSet<Dom<AbortSignal>>>,
260
261    /// Storage for watching rejected promises waiting for some client to
262    /// consume their rejection.
263    /// Promises in this list have been rejected in the last turn of the
264    /// event loop without the rejection being handled.
265    /// Note that this can contain nullptrs in place of promises removed because
266    /// they're consumed before it'd be reported.
267    ///
268    /// <https://html.spec.whatwg.org/multipage/#about-to-be-notified-rejected-promises-list>
269    #[ignore_malloc_size_of = "mozjs"]
270    // `Heap` values must stay boxed, as they need semantics like `Pin`
271    // (that is, they cannot be moved).
272    #[allow(clippy::vec_box)]
273    uncaught_rejections: DomRefCell<Vec<Box<Heap<*mut JSObject>>>>,
274
275    /// Promises in this list have previously been reported as rejected
276    /// (because they were in the above list), but the rejection was handled
277    /// in the last turn of the event loop.
278    ///
279    /// <https://html.spec.whatwg.org/multipage/#outstanding-rejected-promises-weak-set>
280    #[ignore_malloc_size_of = "mozjs"]
281    // `Heap` values must stay boxed, as they need semantics like `Pin`
282    // (that is, they cannot be moved).
283    #[allow(clippy::vec_box)]
284    consumed_rejections: DomRefCell<Vec<Box<Heap<*mut JSObject>>>>,
285
286    /// Identity Manager for WebGPU resources
287    #[ignore_malloc_size_of = "defined in wgpu"]
288    #[no_trace]
289    #[cfg(feature = "webgpu")]
290    gpu_id_hub: Arc<IdentityHub>,
291
292    /// WebGPU devices
293    #[cfg(feature = "webgpu")]
294    gpu_devices: DomRefCell<HashMapTracedValues<WebGPUDevice, WeakRef<GPUDevice>, FxBuildHasher>>,
295
296    // https://w3c.github.io/performance-timeline/#supportedentrytypes-attribute
297    frozen_supported_performance_entry_types: CachedFrozenArray,
298
299    /// The stack of active group labels for the Console APIs.
300    console_group_stack: DomRefCell<Vec<TracedDOMString>>,
301
302    /// The count map for the Console APIs.
303    ///
304    /// <https://console.spec.whatwg.org/#count>
305    console_count_map: DomRefCell<HashMap<TracedDOMString, usize>>,
306
307    /// Is considered in a secure context
308    inherited_secure_context: Option<bool>,
309
310    /// Directory to store unminified scripts for this window if unminify-js
311    /// opt is enabled.
312    unminified_js_dir: Option<String>,
313
314    /// The byte length queuing strategy size function that will be initialized once
315    /// `size` getter of `ByteLengthQueuingStrategy` is called.
316    ///
317    /// <https://streams.spec.whatwg.org/#byte-length-queuing-strategy-size-function>
318    byte_length_queuing_strategy_size_function: OnceCell<TracedCallback<Function>>,
319
320    /// The count queuing strategy size function that will be initialized once
321    /// `size` getter of `CountQueuingStrategy` is called.
322    ///
323    /// <https://streams.spec.whatwg.org/#count-queuing-strategy-size-function>
324    count_queuing_strategy_size_function: OnceCell<TracedCallback<Function>>,
325
326    notification_permission_request_callback_map:
327        DomRefCell<HashMap<String, TracedCallback<NotificationPermissionCallback>>>,
328
329    /// An import map allows control over module specifier resolution.
330    /// For now, only Window global objects have their import map modified from the initial empty one.
331    ///
332    /// <https://html.spec.whatwg.org/multipage/#import-maps>
333    import_map: DomRefCell<ImportMap>,
334
335    /// <https://html.spec.whatwg.org/multipage/#resolved-module-set>
336    resolved_module_set: DomRefCell<HashSet<ResolvedModule>>,
337
338    /// <https://fetch.spec.whatwg.org/#environment-settings-object-fetch-group>
339    fetch_group: DomRefCell<FetchGroup>,
340
341    /// <https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-insecure-navigations-set>
342    #[no_trace]
343    inherited_upgrade_insecure_navigations_set: DomRefCell<HashSet<UpgradeInsecureNavigations>>,
344}
345
346impl GlobalScope {
347    /// Terminate any ongoing fetches, close event source, and clear loaded script modules.
348    pub(crate) fn tear_down(&self) {
349        self.fetch_group_mut().terminate(self);
350        self.close_event_sources();
351        if let Some(window) = self.downcast::<Window>() &&
352            let Some(cookie_store) = window.cookie_store()
353        {
354            cookie_store.clean_up();
355        }
356        self.with_module_map(|module_map| std::mem::take(&mut *module_map.borrow_mut()));
357
358        // Dedicated and shared workers have their own font context (service workers share one),
359        // so free the WebRender font resources it created.
360        if (self.is::<DedicatedWorkerGlobalScope>() || self.is::<SharedWorkerGlobalScope>()) &&
361            let Some(webview_id) = self.webview_id()
362        {
363            self.font_context()
364                .remove_all_webrender_resources(webview_id.into());
365        }
366    }
367
368    /// <https://storage.spec.whatwg.org/#obtain-a-storage-key-for-non-storage-purposes>
369    pub(crate) fn obtain_storage_key_for_non_storage_purposes(&self) -> ImmutableOrigin {
370        // Step 1: Let origin be environment’s origin if environment is an environment settings object; otherwise environment’s creation URL’s origin.
371        // Step 2: Return a tuple consisting of origin.
372        self.origin().immutable().clone()
373    }
374
375    /// <https://storage.spec.whatwg.org/#obtain-a-storage-key>
376    pub(crate) fn obtain_storage_key(&self) -> Option<ImmutableOrigin> {
377        // Step 1: Let key be the result of running obtain a storage key for non-storage purposes
378        // with environment.
379        let key = self.obtain_storage_key_for_non_storage_purposes();
380
381        // Step 2: If key's origin is an opaque origin, then return failure.
382        if let ImmutableOrigin::Opaque(_) = key {
383            return None;
384        }
385
386        // Step 3: If the user has disabled storage, then return failure.
387        if !pref!(dom_indexeddb_enabled) {
388            return None;
389        }
390
391        // Step 4: Return key.
392        Some(key)
393    }
394
395    pub(crate) fn webview_id(&self) -> Option<WebViewId> {
396        if let Some(window) = self.downcast::<Window>() {
397            return Some(window.webview_id());
398        }
399        if let Some(worker) = self.downcast::<DedicatedWorkerGlobalScope>() {
400            return Some(worker.webview_id());
401        }
402        if let Some(worker) = self.downcast::<SharedWorkerGlobalScope>() {
403            return Some(worker.webview_id());
404        }
405        // TODO: This should only return None for ServiceWorkerGlobalScope.
406        None
407    }
408
409    #[allow(clippy::too_many_arguments)]
410    pub(crate) fn new_inherited(
411        #[cfg(feature = "devtools")] devtools_chan: Option<
412            GenericCallback<ScriptToDevtoolsControlMsg>,
413        >,
414        mem_profiler_chan: profile_mem::ProfilerChan,
415        time_profiler_chan: profile_time::ProfilerChan,
416        script_to_constellation_sender: ScriptToConstellationSender,
417        script_to_embedder_chan: ScriptToEmbedderChan,
418        resource_threads: ResourceThreads,
419        storage_threads: StorageThreads,
420        creation_url: ServoUrl,
421        top_level_creation_url: Option<ServoUrl>,
422        #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
423        inherited_secure_context: Option<bool>,
424        inherited_upgrade_insecure_navigations_set: HashSet<UpgradeInsecureNavigations>,
425        unminify_js: bool,
426    ) -> Self {
427        let resource_threads_sender = resource_threads.sender();
428        Self {
429            message_port_state: DomRefCell::new(MessagePortState::UnManaged),
430            broadcast_channel_state: DomRefCell::new(BroadcastChannelState::UnManaged),
431            constellation_interest_counts: Default::default(),
432            blob_state: Default::default(),
433            eventtarget: EventTarget::new_inherited(),
434            registration_map: DomRefCell::new(HashMapTracedValues::new_fx()),
435            indexeddb: Default::default(),
436            worker_map: DomRefCell::new(HashMapTracedValues::new_fx()),
437            console_timers: DomRefCell::new(Default::default()),
438            #[cfg(feature = "devtools")]
439            devtools_chan,
440            mem_profiler_chan,
441            time_profiler_chan,
442            script_to_constellation_sender,
443            script_to_embedder_chan,
444            in_error_reporting_mode: Default::default(),
445            resource_threads,
446            storage_threads,
447            creation_url: DomRefCell::new(creation_url),
448            top_level_creation_url: DomRefCell::new(top_level_creation_url),
449            permission_state_invocation_results: Default::default(),
450            list_auto_close_worker: Default::default(),
451            event_source_tracker: DOMTracker::new(),
452            abort_signal_dependents: Default::default(),
453            uncaught_rejections: Default::default(),
454            consumed_rejections: Default::default(),
455            #[cfg(feature = "webgpu")]
456            gpu_id_hub,
457            #[cfg(feature = "webgpu")]
458            gpu_devices: DomRefCell::new(HashMapTracedValues::new_fx()),
459            frozen_supported_performance_entry_types: CachedFrozenArray::new(),
460            console_group_stack: DomRefCell::new(Vec::new()),
461            console_count_map: Default::default(),
462            inherited_secure_context,
463            unminified_js_dir: unminify_js.then(|| unminified_path("unminified-js")),
464            byte_length_queuing_strategy_size_function: OnceCell::new(),
465            count_queuing_strategy_size_function: OnceCell::new(),
466            notification_permission_request_callback_map: Default::default(),
467            import_map: Default::default(),
468            resolved_module_set: Default::default(),
469            fetch_group: DomRefCell::new(FetchGroup::new(resource_threads_sender)),
470            inherited_upgrade_insecure_navigations_set: DomRefCell::new(
471                inherited_upgrade_insecure_navigations_set,
472            ),
473        }
474    }
475
476    /// The message-port router Id of the global, if any
477    pub(super) fn port_router_id(&self) -> Option<MessagePortRouterId> {
478        if let MessagePortState::Managed(id, _message_ports) = &*self.message_port_state.borrow() {
479            Some(*id)
480        } else {
481            None
482        }
483    }
484
485    /// Is this global managing a given port?
486    pub(super) fn is_managing_port(&self, port_id: &MessagePortId) -> bool {
487        if let MessagePortState::Managed(_router_id, message_ports) =
488            &*self.message_port_state.borrow()
489        {
490            return message_ports.contains_key(port_id);
491        }
492        false
493    }
494
495    fn with_timers<T>(&self, f: impl FnOnce(&OneshotTimers) -> T) -> T {
496        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
497            f(worker.timers())
498        } else if let Some(window) = self.downcast::<Window>() {
499            window.with_timers(f)
500        } else {
501            unreachable!("Unsupported global type retrieving timers")
502        }
503    }
504
505    /// The context used to load web fonts for this global, for both windows and workers.
506    pub(crate) fn web_font_context(&self, no_gc: &NoGC) -> WebFontDocumentContext {
507        let task_source = self
508            .task_manager()
509            .dom_manipulation_task_source()
510            .to_sendable();
511        WebFontDocumentContext {
512            policy_container: self.policy_container(),
513            request_client: self.request_client(Some(no_gc)),
514            document_url: self.api_base_url(),
515            csp_handler: Box::new(FontCspHandler {
516                task_source: task_source.clone(),
517            }),
518            network_timing_handler: Box::new(FontNetworkTimingHandler { task_source }),
519        }
520    }
521
522    pub(crate) fn font_context(&self) -> Arc<FontContext> {
523        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
524            worker.font_context()
525        } else if let Some(window) = self.downcast::<Window>() {
526            window.font_context()
527        } else {
528            unreachable!("Unsupported global type retrieving font context")
529        }
530    }
531
532    /// <https://w3c.github.io/ServiceWorker/#get-the-service-worker-registration-object>
533    #[allow(clippy::too_many_arguments)]
534    pub(crate) fn get_serviceworker_registration(
535        &self,
536        cx: &mut JSContext,
537        script_url: &ServoUrl,
538        scope: &ServoUrl,
539        registration_id: ServiceWorkerRegistrationId,
540        installing_worker: Option<ServiceWorkerId>,
541        _waiting_worker: Option<ServiceWorkerId>,
542        _active_worker: Option<ServiceWorkerId>,
543    ) -> DomRoot<ServiceWorkerRegistration> {
544        // Step 1
545        {
546            let registrations = self.registration_map.borrow_mut();
547
548            if let Some(registration) = registrations.get(&registration_id) {
549                // Step 3
550                return DomRoot::from_ref(&**registration);
551            }
552        }
553
554        // Step 2.1 -> 2.5
555        let new_registration =
556            ServiceWorkerRegistration::new(cx, self, scope.clone(), registration_id);
557
558        // Step 2.6
559        if let Some(worker_id) = installing_worker {
560            let worker = self.get_serviceworker(cx, script_url, scope, worker_id);
561            new_registration.set_installing(&worker);
562        }
563
564        // TODO: 2.7 (waiting worker)
565
566        // TODO: 2.8 (active worker)
567
568        // Step 2.9
569        self.registration_map
570            .borrow_mut()
571            .insert(registration_id, Dom::from_ref(&*new_registration));
572
573        // Step 3
574        new_registration
575    }
576
577    fn send_service_worker_state_update_done(&self, worker_id: ServiceWorkerId) {
578        let res = self.script_to_constellation_chan().send(
579            ScriptToConstellationMessage::ServiceWorkerStateUpdateDone(
580                worker_id,
581                self.pipeline_id(),
582            ),
583        );
584        if res.is_err() {
585            error!("Sending ServiceWorkerStateUpdateDone failed");
586        }
587    }
588
589    /// <https://w3c.github.io/ServiceWorker/#update-state-algorithm>
590    pub(crate) fn update_service_worker_state(
591        &self,
592        cx: &mut js::context::JSContext,
593        state: ServiceWorkerState,
594        worker_id: ServiceWorkerId,
595    ) {
596        // Step 4.1: Let objectMap be settingsObject’s service worker object map.
597        let object_map = self.worker_map.borrow();
598
599        // Step 4.3: Let workerObj be objectMap[worker].
600        let Some(worker) = object_map.get(&worker_id) else {
601            // Step 4.2: If objectMap[worker] does not exist, then abort these steps.
602            self.send_service_worker_state_update_done(worker_id);
603            return;
604        };
605
606        // Step 4.4: Set workerObj’s state to state.
607        worker.set_state(state);
608
609        // Step 4.5: Fire an event named statechange at workerObj.
610        worker.upcast().fire_event(cx, atom!("statechange"));
611
612        self.send_service_worker_state_update_done(worker_id);
613    }
614
615    /// <https://w3c.github.io/ServiceWorker/#get-the-service-worker-object>
616    pub(crate) fn get_serviceworker(
617        &self,
618        cx: &mut JSContext,
619        script_url: &ServoUrl,
620        scope: &ServoUrl,
621        worker_id: ServiceWorkerId,
622    ) -> DomRoot<ServiceWorker> {
623        // Step 1
624        {
625            let workers = self.worker_map.borrow_mut();
626
627            if let Some(worker) = workers.get(&worker_id) {
628                // Step 3
629                return DomRoot::from_ref(&**worker);
630            }
631        }
632
633        // Step 2.1
634        // TODO: step 2.2, worker state.
635        let new_worker = ServiceWorker::new(cx, self, script_url.clone(), scope.clone(), worker_id);
636
637        // Step 2.3
638        self.worker_map
639            .borrow_mut()
640            .insert(worker_id, Dom::from_ref(&*new_worker));
641
642        // Step 3
643        new_worker
644    }
645
646    /// Complete the transfer of a message-port.
647    pub(super) fn complete_port_transfer(
648        &self,
649        cx: &mut JSContext,
650        port_id: MessagePortId,
651        tasks: VecDeque<PortMessageTask>,
652        disentangled: bool,
653    ) {
654        let should_start = if let MessagePortState::Managed(_id, message_ports) =
655            &mut *self.message_port_state.borrow_mut()
656        {
657            match message_ports.get_mut(&port_id) {
658                None => {
659                    panic!("complete_port_transfer called for an unknown port.");
660                },
661                Some(managed_port) => {
662                    if managed_port.pending {
663                        panic!("CompleteTransfer msg received for a pending port.");
664                    }
665                    if let Some(port_impl) = managed_port.port_impl.as_mut() {
666                        port_impl.complete_transfer(tasks);
667                        if disentangled {
668                            port_impl.disentangle();
669                            managed_port.dom_port.disentangle();
670                        }
671                        port_impl.enabled()
672                    } else {
673                        panic!("managed-port has no port-impl.");
674                    }
675                },
676            }
677        } else {
678            panic!("complete_port_transfer called for an unknown port.");
679        };
680        if should_start {
681            self.start_message_port(cx, &port_id);
682        }
683    }
684
685    /// The closing of `otherPort`, if it is in a different global.
686    /// <https://html.spec.whatwg.org/multipage/#disentangle>
687    pub(super) fn try_complete_disentanglement(&self, cx: &mut JSContext, port_id: MessagePortId) {
688        let dom_port = if let MessagePortState::Managed(_id, message_ports) =
689            &mut *self.message_port_state.borrow_mut()
690        {
691            if let Some(managed_port) = message_ports.get_mut(&port_id) {
692                if managed_port.pending {
693                    unreachable!("CompleteDisentanglement msg received for a pending port.");
694                }
695                let port_impl = managed_port
696                    .port_impl
697                    .as_mut()
698                    .expect("managed-port has no port-impl.");
699                port_impl.disentangle();
700                managed_port.dom_port.as_rooted()
701            } else {
702                // Note: this, and the other return below,
703                // can happen if the port has already been transferred out of this global,
704                // in which case the disentanglement will complete along with the transfer.
705                return;
706            }
707        } else {
708            return;
709        };
710
711        // Fire an event named close at otherPort.
712        dom_port.upcast().fire_event(cx, atom!("close"));
713
714        let res = self.script_to_constellation_chan().send(
715            ScriptToConstellationMessage::DisentanglePorts(port_id, None),
716        );
717        if res.is_err() {
718            warn!("Sending DisentanglePorts failed");
719        }
720    }
721
722    /// Clean-up DOM related resources
723    pub(crate) fn perform_a_dom_garbage_collection_checkpoint(&self) {
724        self.perform_a_message_port_garbage_collection_checkpoint();
725        self.perform_a_blob_garbage_collection_checkpoint();
726        self.perform_a_broadcast_channel_garbage_collection_checkpoint();
727        self.perform_an_abort_signal_garbage_collection_checkpoint();
728    }
729
730    /// Remove the routers for ports and broadcast-channels.
731    /// Drain the list of workers.
732    pub(crate) fn remove_web_messaging_and_dedicated_workers_infra(&self) {
733        self.remove_message_ports_router();
734        self.remove_broadcast_channel_router();
735
736        // Drop each ref to a worker explicitly now,
737        // which will send a shutdown signal,
738        // and join on the worker thread.
739        self.list_auto_close_worker
740            .borrow_mut()
741            .drain(0..)
742            .for_each(drop);
743    }
744
745    /// Update our state to un-managed,
746    /// and tell the constellation to drop the sender to our message-port router.
747    fn remove_message_ports_router(&self) {
748        if let MessagePortState::Managed(router_id, _message_ports) =
749            &*self.message_port_state.borrow()
750        {
751            let _ = self.script_to_constellation_chan().send(
752                ScriptToConstellationMessage::RemoveMessagePortRouter(*router_id),
753            );
754        }
755        *self.message_port_state.borrow_mut() = MessagePortState::UnManaged;
756    }
757
758    /// Update our state to un-managed,
759    /// and tell the constellation to drop the sender to our broadcast router.
760    fn remove_broadcast_channel_router(&self) {
761        if let BroadcastChannelState::Managed(router_id, _channels) =
762            &*self.broadcast_channel_state.borrow()
763        {
764            let _ = self.script_to_constellation_chan().send(
765                ScriptToConstellationMessage::RemoveBroadcastChannelRouter(
766                    *router_id,
767                    self.origin().immutable().clone(),
768                ),
769            );
770        }
771        *self.broadcast_channel_state.borrow_mut() = BroadcastChannelState::UnManaged;
772    }
773
774    /// <https://html.spec.whatwg.org/multipage/#disentangle>
775    pub(crate) fn disentangle_port(&self, cx: &mut JSContext, port: &MessagePort) {
776        let initiator_port = port.message_port_id();
777        // Let otherPort be the MessagePort which initiatorPort was entangled with.
778        let Some(other_port) = port.disentangle() else {
779            // Assert: otherPort exists.
780            // Note: ignoring the assert,
781            // because the streams spec seems to disentangle ports that are disentangled already.
782            return;
783        };
784
785        // Disentangle initiatorPort and otherPort, so that they are no longer entangled or associated with each other.
786        // Note: this is done in part here, and in part at the constellation(if otherPort is in another global).
787        let dom_port = if let MessagePortState::Managed(_id, message_ports) =
788            &mut *self.message_port_state.borrow_mut()
789        {
790            let mut dom_port = None;
791            for port_id in &[initiator_port, &other_port] {
792                match message_ports.get_mut(port_id) {
793                    None => {
794                        continue;
795                    },
796                    Some(managed_port) => {
797                        let port_impl = managed_port
798                            .port_impl
799                            .as_mut()
800                            .expect("managed-port has no port-impl.");
801                        managed_port.dom_port.disentangle();
802                        port_impl.disentangle();
803
804                        if **port_id == other_port {
805                            dom_port = Some(managed_port.dom_port.as_rooted())
806                        }
807                    },
808                }
809            }
810            dom_port
811        } else {
812            panic!("disentangle_port called on a global not managing any ports.");
813        };
814
815        // Fire an event named close at `otherPort`.
816        // Note: done here if the port is managed by the same global as `initialPort`.
817        if let Some(dom_port) = dom_port {
818            dom_port.upcast().fire_event(cx, atom!("close"));
819        }
820
821        let chan = self.script_to_constellation_chan();
822        let initiator_port = *initiator_port;
823        self.task_manager()
824            .port_message_queue()
825            .queue(task!(post_message: move || {
826                // Note: we do this in a task to ensure it doesn't affect messages that are still to be routed,
827                // see the task queueing in `post_messageport_msg`.
828                let res = chan.send(ScriptToConstellationMessage::DisentanglePorts(initiator_port, Some(other_port)));
829                if res.is_err() {
830                    warn!("Sending DisentanglePorts failed");
831                }
832            }));
833    }
834
835    /// <https://html.spec.whatwg.org/multipage/#entangle>
836    pub(crate) fn entangle_ports(&self, port1: MessagePortId, port2: MessagePortId) {
837        if let MessagePortState::Managed(_id, message_ports) =
838            &mut *self.message_port_state.borrow_mut()
839        {
840            for (port_id, entangled_id) in &[(port1, port2), (port2, port1)] {
841                match message_ports.get_mut(port_id) {
842                    None => {
843                        return warn!("entangled_ports called on a global not managing the port.");
844                    },
845                    Some(managed_port) => {
846                        if let Some(port_impl) = managed_port.port_impl.as_mut() {
847                            managed_port.dom_port.entangle(*entangled_id);
848                            port_impl.entangle(*entangled_id);
849                        } else {
850                            panic!("managed-port has no port-impl.");
851                        }
852                    },
853                }
854            }
855        } else {
856            panic!("entangled_ports called on a global not managing any ports.");
857        }
858
859        let _ = self
860            .script_to_constellation_chan()
861            .send(ScriptToConstellationMessage::EntanglePorts(port1, port2));
862    }
863
864    /// Handle the transfer of a port in the current task.
865    pub(crate) fn mark_port_as_transferred(&self, port_id: &MessagePortId) -> MessagePortImpl {
866        if let MessagePortState::Managed(_id, message_ports) =
867            &mut *self.message_port_state.borrow_mut()
868        {
869            let mut port_impl = message_ports
870                .remove(port_id)
871                .map(|ref mut managed_port| {
872                    managed_port
873                        .port_impl
874                        .take()
875                        .expect("Managed port doesn't have a port-impl.")
876                })
877                .expect("mark_port_as_transferred called on a global not managing the port.");
878            port_impl.set_has_been_shipped();
879            let _ = self
880                .script_to_constellation_chan()
881                .send(ScriptToConstellationMessage::MessagePortShipped(*port_id));
882            port_impl
883        } else {
884            panic!("mark_port_as_transferred called on a global not managing any ports.");
885        }
886    }
887
888    /// <https://html.spec.whatwg.org/multipage/#dom-messageport-start>
889    pub(crate) fn start_message_port(&self, cx: &mut JSContext, port_id: &MessagePortId) {
890        let (message_buffer, dom_port) = if let MessagePortState::Managed(_id, message_ports) =
891            &mut *self.message_port_state.borrow_mut()
892        {
893            let (message_buffer, dom_port) = match message_ports.get_mut(port_id) {
894                None => panic!("start_message_port called on a unknown port."),
895                Some(managed_port) => {
896                    if let Some(port_impl) = managed_port.port_impl.as_mut() {
897                        (port_impl.start(), managed_port.dom_port.as_rooted())
898                    } else {
899                        panic!("managed-port has no port-impl.");
900                    }
901                },
902            };
903            (message_buffer, dom_port)
904        } else {
905            return warn!("start_message_port called on a global not managing any ports.");
906        };
907        if let Some(message_buffer) = message_buffer {
908            for task in message_buffer {
909                self.route_task_to_port(cx, *port_id, task);
910            }
911            if dom_port.disentangled() {
912                // <https://html.spec.whatwg.org/multipage/#disentangle>
913                // Fire an event named close at otherPort.
914                dom_port.upcast().fire_event(cx, atom!("close"));
915
916                let res = self.script_to_constellation_chan().send(
917                    ScriptToConstellationMessage::DisentanglePorts(*port_id, None),
918                );
919                if res.is_err() {
920                    warn!("Sending DisentanglePorts failed");
921                }
922            }
923        }
924    }
925
926    /// <https://html.spec.whatwg.org/multipage/#dom-messageport-close>
927    pub(crate) fn close_message_port(&self, port_id: &MessagePortId) {
928        if let MessagePortState::Managed(_id, message_ports) =
929            &mut *self.message_port_state.borrow_mut() &&
930            let Some(managed_port) = message_ports.get_mut(port_id)
931        {
932            if let Some(port_impl) = managed_port.port_impl.as_mut() {
933                port_impl.close();
934                managed_port.explicitly_closed = true;
935            } else {
936                panic!("managed-port has no port-impl.");
937            }
938        } else {
939            warn!("close_message_port called on a global not managing any ports.")
940        }
941    }
942
943    /// <https://html.spec.whatwg.org/multipage/#message-port-post-message-steps>
944    // Steps 6 and 7
945    pub(crate) fn post_messageport_msg(&self, port_id: MessagePortId, task: PortMessageTask) {
946        if let MessagePortState::Managed(_id, message_ports) =
947            &mut *self.message_port_state.borrow_mut()
948        {
949            let entangled_port = match message_ports.get_mut(&port_id) {
950                None => panic!("post_messageport_msg called on an unknown port."),
951                Some(managed_port) => {
952                    if let Some(port_impl) = managed_port.port_impl.as_mut() {
953                        port_impl.entangled_port_id()
954                    } else {
955                        panic!("managed-port has no port-impl.");
956                    }
957                },
958            };
959            if let Some(entangled_id) = entangled_port {
960                // Step 7
961                let this = Trusted::new(self);
962                self.task_manager()
963                    .port_message_queue()
964                    .queue(task!(post_message: move |cx| {
965                        let global = this.root();
966                        // Note: we do this in a task, as this will ensure the global and constellation
967                        // are aware of any transfer that might still take place in the current task.
968                        global.route_task_to_port(cx, entangled_id, task);
969                    }));
970            }
971        } else {
972            warn!("post_messageport_msg called on a global not managing any ports.");
973        }
974    }
975
976    /// If we don't know about the port,
977    /// send the message to the constellation for routing.
978    fn re_route_port_task(&self, port_id: MessagePortId, task: PortMessageTask) {
979        let _ = self.script_to_constellation_chan().send(
980            ScriptToConstellationMessage::RerouteMessagePort(port_id, task),
981        );
982    }
983
984    /// <https://html.spec.whatwg.org/multipage/#dom-broadcastchannel-postmessage>
985    /// Step 7 and following steps.
986    pub(crate) fn schedule_broadcast(&self, msg: BroadcastChannelMsg, channel_id: &Uuid) {
987        // First, broadcast locally.
988        self.broadcast_message_event(msg.clone(), Some(channel_id));
989
990        if let BroadcastChannelState::Managed(router_id, _) =
991            &*self.broadcast_channel_state.borrow()
992        {
993            // Second, broadcast to other globals via the constellation.
994            //
995            // Note: for globals in the same script-thread,
996            // we could skip the hop to the constellation.
997            let _ = self.script_to_constellation_chan().send(
998                ScriptToConstellationMessage::ScheduleBroadcast(*router_id, msg),
999            );
1000        } else {
1001            panic!("Attemps to broadcast a message via global not managing any channels.");
1002        }
1003    }
1004
1005    /// <https://html.spec.whatwg.org/multipage/#dom-broadcastchannel-postmessage>
1006    /// Step 7 and following steps.
1007    pub(crate) fn broadcast_message_event(
1008        &self,
1009        event: BroadcastChannelMsg,
1010        channel_id: Option<&Uuid>,
1011    ) {
1012        let BroadcastChannelState::Managed(_, channels) = &*self.broadcast_channel_state.borrow()
1013        else {
1014            return;
1015        };
1016
1017        let BroadcastChannelMsg {
1018            data,
1019            origin,
1020            channel_name,
1021        } = event;
1022
1023        // Step 7, a few preliminary steps.
1024
1025        // - Check the worker is not closing.
1026        if let Some(worker) = self.downcast::<WorkerGlobalScope>() &&
1027            worker.is_closing()
1028        {
1029            return;
1030        }
1031
1032        // - Check the associated document is fully-active.
1033        if let Some(window) = self.downcast::<Window>() &&
1034            !window.Document().is_fully_active()
1035        {
1036            return;
1037        }
1038
1039        // - Check for a case-sensitive match for the name of the channel.
1040        let Some(channels) = channels.get(&channel_name.into()) else {
1041            return;
1042        };
1043        channels
1044            .iter()
1045            .filter(|channel| {
1046                // Step 8.
1047                // Filter out the sender.
1048                if let Some(id) = channel_id {
1049                    channel.id() != id
1050                } else {
1051                    true
1052                }
1053            })
1054            .map(|channel| DomRoot::from_ref(&**channel))
1055            // Step 9, sort by creation order,
1056            // done by using a queue to store channels in creation order.
1057            .for_each(|channel| {
1058                let data = data.clone_for_broadcast();
1059                let origin = origin.clone();
1060
1061                // Step 10: Queue a task on the DOM manipulation task-source,
1062                // to fire the message event
1063                let channel = Trusted::new(&*channel);
1064                let global = Trusted::new(self);
1065                self.task_manager().dom_manipulation_task_source().queue(
1066                    task!(process_pending_port_messages: move |cx| {
1067                        let destination = channel.root();
1068                        let global = global.root();
1069
1070                        // 10.1 Check for closed flag.
1071                        if destination.closed() {
1072                            return;
1073                        }
1074
1075                        rooted!(&in(cx) let mut message = UndefinedValue());
1076
1077                        // Step 10.3 StructuredDeserialize(serialized, targetRealm).
1078                        if let Ok(ports) = structuredclone::read(cx, &global, data, message.handle_mut()) {
1079                            // Step 10.4, Fire an event named message at destination.
1080                            MessageEvent::dispatch_jsval(
1081                                cx,
1082                                destination.upcast(),
1083                                &global,
1084                                message.handle(),
1085                                Some(origin.ascii_serialization().as_ref()),
1086                                None,
1087                                ports,
1088                            );
1089                        } else {
1090                            // Step 10.3, fire an event named messageerror at destination.
1091                            MessageEvent::dispatch_error(cx, destination.upcast(), &global);
1092                        }
1093                    })
1094                );
1095            });
1096    }
1097
1098    /// <https://html.spec.whatwg.org/multipage/#encoding-parsing-a-url>
1099    pub(crate) fn encoding_parse_a_url(&self, url: &str) -> Result<ServoUrl, url::ParseError> {
1100        if let Some(window) = self.downcast::<Window>() {
1101            return window.Document().encoding_parse_a_url(url);
1102        }
1103
1104        // encoding parsing for worker environments.
1105        let base = self.api_base_url();
1106        base.join(url)
1107    }
1108
1109    /// <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformreadable>
1110    /// The "Add a handler for port’s message event with the following steps:"
1111    /// and "Add a handler for port’s messageerror event with the following steps:" part.
1112    pub(crate) fn note_cross_realm_transform_readable(
1113        &self,
1114        cross_realm_transform_readable: &CrossRealmTransformReadable,
1115        port_id: &MessagePortId,
1116    ) {
1117        let MessagePortState::Managed(_id, message_ports) =
1118            &mut *self.message_port_state.borrow_mut()
1119        else {
1120            unreachable!(
1121                "Cross realm transform readable must be called on a global managing ports"
1122            );
1123        };
1124
1125        let Some(managed_port) = message_ports.get_mut(port_id) else {
1126            unreachable!("Cross realm transform readable must match a managed port");
1127        };
1128
1129        managed_port.cross_realm_transform = Some(CrossRealmTransform::Readable(
1130            cross_realm_transform_readable.clone(),
1131        ));
1132    }
1133
1134    /// <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformwritable>
1135    /// The "Add a handler for port’s message event with the following steps:"
1136    /// and "Add a handler for port’s messageerror event with the following steps:" part.
1137    pub(crate) fn note_cross_realm_transform_writable(
1138        &self,
1139        cross_realm_transform_writable: &CrossRealmTransformWritable,
1140        port_id: &MessagePortId,
1141    ) {
1142        let MessagePortState::Managed(_id, message_ports) =
1143            &mut *self.message_port_state.borrow_mut()
1144        else {
1145            unreachable!(
1146                "Cross realm transform writable must be called on a global managing ports"
1147            );
1148        };
1149
1150        let Some(managed_port) = message_ports.get_mut(port_id) else {
1151            unreachable!("Cross realm transform writable must match a managed port");
1152        };
1153
1154        managed_port.cross_realm_transform = Some(CrossRealmTransform::Writable(
1155            cross_realm_transform_writable.clone(),
1156        ));
1157    }
1158
1159    /// Custom routing logic, followed by the task steps of
1160    /// <https://html.spec.whatwg.org/multipage/#message-port-post-message-steps>
1161    pub(super) fn route_task_to_port(
1162        &self,
1163        cx: &mut JSContext,
1164        port_id: MessagePortId,
1165        task: PortMessageTask,
1166    ) {
1167        rooted!(&in(cx) let mut cross_realm_transform = None);
1168
1169        let should_dispatch = if let MessagePortState::Managed(_id, message_ports) =
1170            &mut *self.message_port_state.borrow_mut()
1171        {
1172            if !message_ports.contains_key(&port_id) {
1173                self.re_route_port_task(port_id, task);
1174                return;
1175            }
1176            match message_ports.get_mut(&port_id) {
1177                None => panic!("route_task_to_port called for an unknown port."),
1178                Some(managed_port) => {
1179                    // If the port is not enabled yet, or if is awaiting the completion of it's transfer,
1180                    // the task will be buffered and dispatched upon enablement or completion of the transfer.
1181                    if let Some(port_impl) = managed_port.port_impl.as_mut() {
1182                        let to_dispatch = port_impl.handle_incoming(task).map(|to_dispatch| {
1183                            (DomRoot::from_ref(&*managed_port.dom_port), to_dispatch)
1184                        });
1185                        cross_realm_transform.set(managed_port.cross_realm_transform.clone());
1186                        to_dispatch
1187                    } else {
1188                        panic!("managed-port has no port-impl.");
1189                    }
1190                },
1191            }
1192        } else {
1193            self.re_route_port_task(port_id, task);
1194            return;
1195        };
1196
1197        // Add a task that runs the following steps to the port message queue of targetPort:
1198        // Note: we are in the task, and running the relevant steps.
1199
1200        // Let finalTargetPort be the MessagePort in whose port message queue the task now finds itself.
1201        if let Some((dom_port, PortMessageTask { origin, data })) = should_dispatch {
1202            // Let messageEventTarget be finalTargetPort's message event target.
1203            let message_event_target = dom_port.upcast();
1204
1205            // Let targetRealm be finalTargetPort's relevant realm.
1206            // Done via the routing logic here and in the constellation: `self` is the target realm.
1207
1208            // Let messageClone be deserializeRecord.[[Deserialized]].
1209            // Re-ordered because we need to pass it to `structuredclone::read`.
1210            rooted!(&in(cx) let mut message_clone = UndefinedValue());
1211
1212            let mut realm = enter_auto_realm(cx, self);
1213            let cx = &mut realm.current_realm();
1214
1215            // Note: this is necessary, on top of entering the realm above,
1216            // for the call to `GlobalScope::incumbent`,
1217            // in `MessagePort::post_message_impl` to succeed.
1218            run_a_script::<DomTypeHolder, _, _>(cx, self, |cx| {
1219                // Let deserializeRecord be StructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm).
1220                // Let newPorts be a new frozen array
1221                // consisting of all MessagePort objects in deserializeRecord.[[TransferredValues]],
1222                // if any, maintaining their relative order.
1223                // Note: both done in `structuredclone::read`.
1224                if let Ok(ports) = structuredclone::read(cx, self, data, message_clone.handle_mut())
1225                {
1226                    // Note: if this port is used to transfer a stream, we handle the events in Rust.
1227                    if let Some(transform) = cross_realm_transform.deref().as_ref() {
1228                        match transform {
1229                            // Add a handler for port’s message event with the following steps:
1230                            // from <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformreadable>
1231                            CrossRealmTransform::Readable(readable) => {
1232                                readable.handle_message(
1233                                    cx,
1234                                    self,
1235                                    &dom_port,
1236                                    message_clone.handle(),
1237                                );
1238                            },
1239                            // Add a handler for port’s message event with the following steps:
1240                            // from <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformwritable>
1241                            CrossRealmTransform::Writable(writable) => {
1242                                writable.handle_message(cx, self, message_clone.handle());
1243                            },
1244                        }
1245                    } else {
1246                        // Fire an event named message at messageEventTarget,
1247                        // using MessageEvent,
1248                        // with the data attribute initialized to messageClone
1249                        // and the ports attribute initialized to newPorts.
1250                        MessageEvent::dispatch_jsval(
1251                            cx,
1252                            message_event_target,
1253                            self,
1254                            message_clone.handle(),
1255                            Some(origin.ascii_serialization().as_ref()),
1256                            None,
1257                            ports,
1258                        );
1259                    }
1260                } else if let Some(transform) = cross_realm_transform.deref().as_ref() {
1261                    match transform {
1262                        // Add a handler for port’s messageerror event with the following steps:
1263                        // from <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformreadable>
1264                        CrossRealmTransform::Readable(readable) => {
1265                            readable.handle_error(cx, self, &dom_port);
1266                        },
1267                        // Add a handler for port’s messageerror event with the following steps:
1268                        // from <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformwritable>
1269                        CrossRealmTransform::Writable(writable) => {
1270                            writable.handle_error(cx, self, &dom_port);
1271                        },
1272                    }
1273                } else {
1274                    // If this throws an exception, catch it,
1275                    // fire an event named messageerror at messageEventTarget,
1276                    // using MessageEvent, and then return.
1277                    MessageEvent::dispatch_error(cx, message_event_target, self);
1278                }
1279            });
1280        }
1281    }
1282
1283    /// Check all ports that have been transfer-received in the previous task,
1284    /// and complete their transfer if they haven't been re-transferred.
1285    pub(crate) fn maybe_add_pending_ports(&self) {
1286        if let MessagePortState::Managed(router_id, message_ports) =
1287            &mut *self.message_port_state.borrow_mut()
1288        {
1289            let to_be_added: Vec<MessagePortId> = message_ports
1290                .iter()
1291                .filter_map(|(id, managed_port)| {
1292                    if managed_port.pending {
1293                        Some(*id)
1294                    } else {
1295                        None
1296                    }
1297                })
1298                .collect();
1299            for id in to_be_added.iter() {
1300                let managed_port = message_ports
1301                    .get_mut(id)
1302                    .expect("Collected port-id to match an entry");
1303                if !managed_port.pending {
1304                    panic!("Only pending ports should be found in to_be_added")
1305                }
1306                managed_port.pending = false;
1307            }
1308            let _ = self.script_to_constellation_chan().send(
1309                ScriptToConstellationMessage::CompleteMessagePortTransfer(*router_id, to_be_added),
1310            );
1311        } else {
1312            warn!("maybe_add_pending_ports called on a global not managing any ports.");
1313        }
1314    }
1315
1316    /// <https://html.spec.whatwg.org/multipage/#ports-and-garbage-collection>
1317    pub(crate) fn perform_a_message_port_garbage_collection_checkpoint(&self) {
1318        let is_empty = if let MessagePortState::Managed(_id, message_ports) =
1319            &mut *self.message_port_state.borrow_mut()
1320        {
1321            let to_be_removed: Vec<MessagePortId> = message_ports
1322                .iter()
1323                .filter_map(|(id, managed_port)| {
1324                    if managed_port.explicitly_closed {
1325                        Some(*id)
1326                    } else {
1327                        None
1328                    }
1329                })
1330                .collect();
1331            for id in to_be_removed {
1332                message_ports.remove(&id);
1333            }
1334            // Note: ports are only removed throught explicit closure by script in this global.
1335            // TODO: #25772
1336            // TODO: remove ports when we can be sure their port message queue is empty(via the constellation).
1337            message_ports.is_empty()
1338        } else {
1339            false
1340        };
1341        if is_empty {
1342            self.remove_message_ports_router();
1343        }
1344    }
1345
1346    /// Remove broadcast-channels that are closed.
1347    /// TODO: Also remove them if they do not have an event-listener.
1348    /// see <https://github.com/servo/servo/issues/25772>
1349    pub(crate) fn perform_a_broadcast_channel_garbage_collection_checkpoint(&self) {
1350        let is_empty = if let BroadcastChannelState::Managed(router_id, channels) =
1351            &mut *self.broadcast_channel_state.borrow_mut()
1352        {
1353            channels.retain(|name, ref mut channels| {
1354                channels.retain(|chan| !chan.closed());
1355                if channels.is_empty() {
1356                    let _ = self.script_to_constellation_chan().send(
1357                        ScriptToConstellationMessage::RemoveBroadcastChannelNameInRouter(
1358                            *router_id,
1359                            name.to_string(),
1360                            self.origin().immutable().clone(),
1361                        ),
1362                    );
1363                    false
1364                } else {
1365                    true
1366                }
1367            });
1368            channels.is_empty()
1369        } else {
1370            false
1371        };
1372        if is_empty {
1373            self.remove_broadcast_channel_router();
1374        }
1375    }
1376
1377    /// Register a dependent AbortSignal that may need to be kept alive
1378    /// <https://dom.spec.whatwg.org/#abort-signal-garbage-collection>
1379    pub(crate) fn register_dependent_abort_signal(&self, signal: &AbortSignal) {
1380        self.abort_signal_dependents
1381            .borrow_mut()
1382            .insert(Dom::from_ref(signal));
1383    }
1384
1385    /// Clean up dependent AbortSignals that no longer satisfy the GC predicate.
1386    pub(crate) fn perform_an_abort_signal_garbage_collection_checkpoint(&self) {
1387        let mut set = self.abort_signal_dependents.borrow_mut();
1388
1389        set.retain(|dom_signal| dom_signal.must_keep_alive_for_gc());
1390    }
1391
1392    /// Start tracking a broadcast-channel.
1393    pub(crate) fn track_broadcast_channel(&self, dom_channel: &BroadcastChannel) {
1394        let mut current_state = self.broadcast_channel_state.borrow_mut();
1395
1396        if let BroadcastChannelState::UnManaged = &*current_state {
1397            let context = Trusted::new(self);
1398            let listener = BroadcastListener {
1399                task_source: self.task_manager().dom_manipulation_task_source().into(),
1400                context,
1401            };
1402            let broadcast_control_callback = GenericCallback::new(move |message| match message {
1403                Ok(msg) => listener.handle(msg),
1404                Err(err) => warn!("Error receiving a BroadcastChannelMsg: {:?}", err),
1405            })
1406            .expect("Could not generate callback");
1407            let router_id = BroadcastChannelRouterId::new();
1408            *current_state = BroadcastChannelState::Managed(router_id, HashMap::new());
1409            let _ = self.script_to_constellation_chan().send(
1410                ScriptToConstellationMessage::NewBroadcastChannelRouter(
1411                    router_id,
1412                    broadcast_control_callback,
1413                    self.origin().immutable().clone(),
1414                ),
1415            );
1416        }
1417
1418        if let BroadcastChannelState::Managed(router_id, channels) = &mut *current_state {
1419            let entry = channels
1420                .entry(dom_channel.Name().traced())
1421                .or_insert_with(|| {
1422                    let _ = self.script_to_constellation_chan().send(
1423                        ScriptToConstellationMessage::NewBroadcastChannelNameInRouter(
1424                            *router_id,
1425                            String::from(dom_channel.Name()),
1426                            self.origin().immutable().clone(),
1427                        ),
1428                    );
1429                    VecDeque::new()
1430                });
1431            entry.push_back(Dom::from_ref(dom_channel));
1432        } else {
1433            panic!("track_broadcast_channel should have first switched the state to managed.");
1434        }
1435    }
1436
1437    /// Start tracking a message-port
1438    pub(crate) fn track_message_port(
1439        &self,
1440        dom_port: &MessagePort,
1441        port_impl: Option<MessagePortImpl>,
1442    ) {
1443        let mut current_state = self.message_port_state.borrow_mut();
1444
1445        if let MessagePortState::UnManaged = &*current_state {
1446            // Setup a route for IPC, for messages from the constellation to our ports.
1447            let context = Trusted::new(self);
1448            let listener = MessageListener {
1449                task_source: self.task_manager().port_message_queue().into(),
1450                context,
1451            };
1452
1453            let port_control_callback = GenericCallback::new(move |message| match message {
1454                Ok(msg) => listener.notify(msg),
1455                Err(err) => warn!("Error receiving a MessagePortMsg: {:?}", err),
1456            })
1457            .expect("Could not create callback");
1458            let router_id = MessagePortRouterId::new();
1459            *current_state = MessagePortState::Managed(router_id, HashMapTracedValues::new_fx());
1460            let _ = self.script_to_constellation_chan().send(
1461                ScriptToConstellationMessage::NewMessagePortRouter(
1462                    router_id,
1463                    port_control_callback,
1464                ),
1465            );
1466        }
1467
1468        if let MessagePortState::Managed(router_id, message_ports) = &mut *current_state {
1469            if let Some(port_impl) = port_impl {
1470                // We keep transfer-received ports as "pending",
1471                // and only ask the constellation to complete the transfer
1472                // if they're not re-shipped in the current task.
1473                message_ports.insert(
1474                    *dom_port.message_port_id(),
1475                    ManagedMessagePort {
1476                        port_impl: Some(port_impl),
1477                        dom_port: Dom::from_ref(dom_port),
1478                        pending: true,
1479                        explicitly_closed: false,
1480                        cross_realm_transform: None,
1481                    },
1482                );
1483
1484                // Queue a task to complete the transfer,
1485                // unless the port is re-transferred in the current task.
1486                let this = Trusted::new(self);
1487                self.task_manager().port_message_queue().queue(
1488                    task!(process_pending_port_messages: move || {
1489                        let target_global = this.root();
1490                        target_global.maybe_add_pending_ports();
1491                    }),
1492                );
1493            } else {
1494                // If this is a newly-created port, let the constellation immediately know.
1495                let port_impl = MessagePortImpl::new(*dom_port.message_port_id());
1496                message_ports.insert(
1497                    *dom_port.message_port_id(),
1498                    ManagedMessagePort {
1499                        port_impl: Some(port_impl),
1500                        dom_port: Dom::from_ref(dom_port),
1501                        pending: false,
1502                        explicitly_closed: false,
1503                        cross_realm_transform: None,
1504                    },
1505                );
1506                let _ = self.script_to_constellation_chan().send(
1507                    ScriptToConstellationMessage::NewMessagePort(
1508                        *router_id,
1509                        *dom_port.message_port_id(),
1510                    ),
1511                );
1512            };
1513        } else {
1514            panic!("track_message_port should have first switched the state to managed.");
1515        }
1516    }
1517
1518    /// <https://html.spec.whatwg.org/multipage/#serialization-steps>
1519    /// defined at <https://w3c.github.io/FileAPI/#blob-section>.
1520    /// Get the snapshot state and underlying bytes of the blob.
1521    pub(crate) fn serialize_blob(&self, blob_id: &BlobId) -> BlobImpl {
1522        // Note: we combine the snapshot state and underlying bytes into one call,
1523        // which seems spec compliant.
1524        // See https://w3c.github.io/FileAPI/#snapshot-state
1525        let bytes = self
1526            .get_blob_bytes(blob_id)
1527            .expect("Could not read bytes from blob as part of serialization steps.");
1528        let type_string = self.get_blob_type_string(blob_id);
1529
1530        // Note: the new BlobImpl is a clone, but with it's own BlobId.
1531        BlobImpl::new_from_bytes(bytes, type_string)
1532    }
1533
1534    fn track_blob_info(&self, blob_info: BlobInfo, blob_id: BlobId) {
1535        self.blob_state.borrow_mut().insert(blob_id, blob_info);
1536    }
1537
1538    /// Start tracking a blob
1539    pub(crate) fn track_blob(&self, dom_blob: &Blob, blob_impl: BlobImpl) {
1540        let blob_id = blob_impl.blob_id();
1541
1542        let blob_info = BlobInfo {
1543            blob_impl,
1544            tracker: BlobTracker::Blob(WeakRef::new(dom_blob)),
1545            has_url: false,
1546        };
1547
1548        self.track_blob_info(blob_info, blob_id);
1549    }
1550
1551    /// Start tracking a file
1552    pub(crate) fn track_file(&self, file: &File, blob_impl: BlobImpl) {
1553        let blob_id = blob_impl.blob_id();
1554
1555        let blob_info = BlobInfo {
1556            blob_impl,
1557            tracker: BlobTracker::File(WeakRef::new(file)),
1558            has_url: false,
1559        };
1560
1561        self.track_blob_info(blob_info, blob_id);
1562    }
1563
1564    /// Clean-up any file or blob that is unreachable from script,
1565    /// unless it has an oustanding blob url.
1566    /// <https://w3c.github.io/FileAPI/#lifeTime>
1567    fn perform_a_blob_garbage_collection_checkpoint(&self) {
1568        let mut blob_state = self.blob_state.borrow_mut();
1569        blob_state.0.retain(|_id, blob_info| {
1570            let garbage_collected = match &blob_info.tracker {
1571                BlobTracker::File(weak) => weak.root().is_none(),
1572                BlobTracker::Blob(weak) => weak.root().is_none(),
1573            };
1574            if garbage_collected && !blob_info.has_url {
1575                if let BlobData::File(f) = blob_info.blob_impl.blob_data() {
1576                    self.decrement_file_ref(f.get_id());
1577                }
1578                false
1579            } else {
1580                true
1581            }
1582        });
1583    }
1584
1585    /// Clean-up all file related resources on document unload.
1586    /// <https://w3c.github.io/FileAPI/#lifeTime>
1587    pub(crate) fn clean_up_all_file_resources(&self) {
1588        self.blob_state
1589            .borrow_mut()
1590            .drain()
1591            .for_each(|(_id, blob_info)| {
1592                if let BlobData::File(f) = blob_info.blob_impl.blob_data() {
1593                    self.decrement_file_ref(f.get_id());
1594                }
1595            });
1596    }
1597
1598    fn decrement_file_ref(&self, id: Uuid) {
1599        let origin = self.origin().immutable().clone();
1600
1601        let (tx, rx) = profile_generic_channel::channel(self.time_profiler_chan().clone()).unwrap();
1602
1603        let msg = FileManagerThreadMsg::DecRef(id, origin, tx);
1604        self.send_to_file_manager(msg);
1605        let _ = rx.recv();
1606    }
1607
1608    /// Get a slice to the inner data of a Blob,
1609    /// In the case of a File-backed blob, this might incur synchronous read and caching.
1610    pub(crate) fn get_blob_bytes(&self, blob_id: &BlobId) -> Result<Vec<u8>, ()> {
1611        let parent = {
1612            match *self.get_blob_data(blob_id) {
1613                BlobData::Sliced(parent, rel_pos) => Some((parent, rel_pos)),
1614                _ => None,
1615            }
1616        };
1617
1618        match parent {
1619            Some((parent_id, rel_pos)) => self.get_blob_bytes_non_sliced(&parent_id).map(|v| {
1620                let range = rel_pos.to_abs_range(v.len());
1621                v.index(range).to_vec()
1622            }),
1623            None => self.get_blob_bytes_non_sliced(blob_id),
1624        }
1625    }
1626
1627    /// Retrieve information about a specific blob from the blob store
1628    ///
1629    /// # Panics
1630    /// This function panics if there is no blob with the given ID.
1631    pub(crate) fn get_blob_data<'a>(&'a self, blob_id: &BlobId) -> Ref<'a, BlobData> {
1632        Ref::map(self.blob_state.borrow(), |blob_state| {
1633            blob_state
1634                .get(blob_id)
1635                .expect("get_blob_impl called for a unknown blob")
1636                .blob_impl
1637                .blob_data()
1638        })
1639    }
1640
1641    /// Get bytes from a non-sliced blob
1642    fn get_blob_bytes_non_sliced(&self, blob_id: &BlobId) -> Result<Vec<u8>, ()> {
1643        match *self.get_blob_data(blob_id) {
1644            BlobData::File(ref f) => {
1645                let (buffer, is_new_buffer) = match f.get_cache() {
1646                    Some(bytes) => (bytes, false),
1647                    None => {
1648                        let bytes = self.read_file(f.get_id())?;
1649                        (bytes, true)
1650                    },
1651                };
1652
1653                // Cache
1654                if is_new_buffer {
1655                    f.cache_bytes(buffer.clone());
1656                }
1657
1658                Ok(buffer)
1659            },
1660            BlobData::Memory(ref s) => Ok(s.clone()),
1661            BlobData::Sliced(_, _) => panic!("This blob doesn't have a parent."),
1662        }
1663    }
1664
1665    /// Get a slice to the inner data of a Blob,
1666    /// if it's a memory blob, or it's file-id and file-size otherwise.
1667    ///
1668    /// Note: this is almost a duplicate of `get_blob_bytes`,
1669    /// tweaked for integration with streams.
1670    /// TODO: merge with `get_blob_bytes` by way of broader integration with blob streams.
1671    fn get_blob_bytes_or_file_id(&self, blob_id: &BlobId) -> BlobResult {
1672        let parent = {
1673            match *self.get_blob_data(blob_id) {
1674                BlobData::Sliced(parent, rel_pos) => Some((parent, rel_pos)),
1675                _ => None,
1676            }
1677        };
1678
1679        match parent {
1680            Some((parent_id, rel_pos)) => {
1681                match self.get_blob_bytes_non_sliced_or_file_id(&parent_id) {
1682                    BlobResult::Bytes(bytes) => {
1683                        let range = rel_pos.to_abs_range(bytes.len());
1684                        BlobResult::Bytes(bytes.index(range).to_vec())
1685                    },
1686                    res => res,
1687                }
1688            },
1689            None => self.get_blob_bytes_non_sliced_or_file_id(blob_id),
1690        }
1691    }
1692
1693    /// Get bytes from a non-sliced blob if in memory, or it's file-id and file-size.
1694    ///
1695    /// Note: this is almost a duplicate of `get_blob_bytes_non_sliced`,
1696    /// tweaked for integration with streams.
1697    /// TODO: merge with `get_blob_bytes` by way of broader integration with blob streams.
1698    fn get_blob_bytes_non_sliced_or_file_id(&self, blob_id: &BlobId) -> BlobResult {
1699        match *self.get_blob_data(blob_id) {
1700            BlobData::File(ref f) => match f.get_cache() {
1701                Some(bytes) => BlobResult::Bytes(bytes),
1702                None => BlobResult::File(f.get_id(), f.get_size() as usize),
1703            },
1704            BlobData::Memory(ref s) => BlobResult::Bytes(s.clone()),
1705            BlobData::Sliced(_, _) => panic!("This blob doesn't have a parent."),
1706        }
1707    }
1708
1709    /// Get a copy of the type_string of a blob.
1710    pub(crate) fn get_blob_type_string(&self, blob_id: &BlobId) -> String {
1711        let blob_state = self.blob_state.borrow();
1712        let blob_info = blob_state
1713            .get(blob_id)
1714            .expect("get_blob_type_string called for a unknown blob.");
1715        blob_info.blob_impl.type_string()
1716    }
1717
1718    /// <https://w3c.github.io/FileAPI/#dfn-size>
1719    pub(crate) fn get_blob_size(&self, blob_id: &BlobId) -> u64 {
1720        let parent = {
1721            match *self.get_blob_data(blob_id) {
1722                BlobData::Sliced(parent, rel_pos) => Some((parent, rel_pos)),
1723                _ => None,
1724            }
1725        };
1726        match parent {
1727            Some((parent_id, rel_pos)) => {
1728                let parent_size = match *self.get_blob_data(&parent_id) {
1729                    BlobData::File(ref f) => f.get_size(),
1730                    BlobData::Memory(ref v) => v.len() as u64,
1731                    BlobData::Sliced(_, _) => panic!("Blob ancestry should be only one level."),
1732                };
1733                rel_pos.to_abs_range(parent_size as usize).len() as u64
1734            },
1735            None => match *self.get_blob_data(blob_id) {
1736                BlobData::File(ref f) => f.get_size(),
1737                BlobData::Memory(ref v) => v.len() as u64,
1738                BlobData::Sliced(_, _) => {
1739                    panic!("It was previously checked that this blob does not have a parent.")
1740                },
1741            },
1742        }
1743    }
1744
1745    pub(crate) fn get_blob_url_id(&self, blob_id: &BlobId) -> Uuid {
1746        let mut blob_state = self.blob_state.borrow_mut();
1747        let parent = {
1748            let blob_info = blob_state
1749                .get_mut(blob_id)
1750                .expect("get_blob_url_id called for a unknown blob.");
1751
1752            // Keep track of blobs with outstanding URLs.
1753            blob_info.has_url = true;
1754
1755            match blob_info.blob_impl.blob_data() {
1756                BlobData::Sliced(parent, rel_pos) => Some((*parent, *rel_pos)),
1757                _ => None,
1758            }
1759        };
1760        match parent {
1761            Some((parent_id, rel_pos)) => {
1762                let parent_info = blob_state
1763                    .get_mut(&parent_id)
1764                    .expect("Parent of blob whose url is requested is unknown.");
1765                let parent_file_id = self.promote(parent_info, /* set_valid is */ false);
1766                let parent_size = match parent_info.blob_impl.blob_data() {
1767                    BlobData::File(f) => f.get_size(),
1768                    BlobData::Memory(v) => v.len() as u64,
1769                    BlobData::Sliced(_, _) => panic!("Blob ancestry should be only one level."),
1770                };
1771                let parent_size = rel_pos.to_abs_range(parent_size as usize).len() as u64;
1772                let blob_info = blob_state
1773                    .get_mut(blob_id)
1774                    .expect("Blob whose url is requested is unknown.");
1775                self.create_sliced_url_id(blob_info, &parent_file_id, &rel_pos, parent_size)
1776            },
1777            None => {
1778                let blob_info = blob_state
1779                    .get_mut(blob_id)
1780                    .expect("Blob whose url is requested is unknown.");
1781                self.promote(blob_info, /* set_valid is */ true)
1782            },
1783        }
1784    }
1785
1786    /// Get a FileID representing sliced parent-blob content
1787    fn create_sliced_url_id(
1788        &self,
1789        blob_info: &mut BlobInfo,
1790        parent_file_id: &Uuid,
1791        rel_pos: &RelativePos,
1792        parent_len: u64,
1793    ) -> Uuid {
1794        let origin = self.origin().immutable().clone();
1795
1796        let (tx, rx) = profile_generic_channel::channel(self.time_profiler_chan().clone()).unwrap();
1797        let msg = FileManagerThreadMsg::AddSlicedURLEntry(*parent_file_id, *rel_pos, tx, origin);
1798        self.send_to_file_manager(msg);
1799        match rx.recv().expect("File manager thread is down.") {
1800            Ok(new_id) => {
1801                *blob_info.blob_impl.blob_data_mut() = BlobData::File(FileBlob::new(
1802                    new_id,
1803                    None,
1804                    None,
1805                    rel_pos.to_abs_range(parent_len as usize).len() as u64,
1806                ));
1807
1808                // Return the indirect id reference
1809                new_id
1810            },
1811            Err(_) => {
1812                // Return dummy id
1813                Uuid::new_v4()
1814            },
1815        }
1816    }
1817
1818    /// Send a PromoteMemory message to register a new blob URL entry
1819    /// with the file manager for the given byte data.
1820    /// Return the generated UUID.
1821    fn promote_memory_entry(
1822        &self,
1823        blob_info: &BlobInfo,
1824        blob_bytes: &[u8],
1825        set_valid: bool,
1826    ) -> Uuid {
1827        let origin = self.origin().immutable().clone();
1828        let blob_buf = BlobBuf {
1829            filename: None,
1830            type_string: blob_info.blob_impl.type_string(),
1831            size: blob_bytes.len() as u64,
1832            bytes: blob_bytes.to_vec(),
1833        };
1834        let id = Uuid::new_v4();
1835        let msg = FileManagerThreadMsg::PromoteMemory(id, blob_buf, set_valid, origin);
1836        self.send_to_file_manager(msg);
1837        id
1838    }
1839
1840    /// Promote non-Slice blob:
1841    /// 1. Memory-based: The bytes in data slice will be transferred to file manager thread.
1842    /// 2. File-based: If set_valid, then activate the FileID so it can serve as URL
1843    ///    Depending on set_valid, the returned FileID can be part of
1844    ///    valid or invalid Blob URL.
1845    pub(crate) fn promote(&self, blob_info: &mut BlobInfo, set_valid: bool) -> Uuid {
1846        let mut bytes = vec![];
1847
1848        match blob_info.blob_impl.blob_data_mut() {
1849            BlobData::Sliced(_, _) => {
1850                panic!("Sliced blobs should use create_sliced_url_id instead of promote.");
1851            },
1852            BlobData::File(f) => {
1853                if set_valid {
1854                    // File blobs with cached byte data (converted from Memory)
1855                    // need a unique UUID per URL.createObjectURL call.
1856                    if let Some(cached_bytes) = f.get_cache() {
1857                        return self.promote_memory_entry(blob_info, &cached_bytes, true);
1858                    }
1859
1860                    let origin = self.origin().immutable().clone();
1861                    let (tx, rx) =
1862                        profile_generic_channel::channel(self.time_profiler_chan().clone())
1863                            .unwrap();
1864
1865                    let msg = FileManagerThreadMsg::ActivateBlobURL(f.get_id(), tx, origin);
1866                    self.send_to_file_manager(msg);
1867
1868                    match rx.recv().unwrap() {
1869                        Ok(_) => return f.get_id(),
1870                        // Return a dummy id on error
1871                        Err(_) => return Uuid::new_v4(),
1872                    }
1873                } else {
1874                    // no need to activate
1875                    return f.get_id();
1876                }
1877            },
1878            BlobData::Memory(bytes_in) => mem::swap(bytes_in, &mut bytes),
1879        };
1880
1881        let id = self.promote_memory_entry(blob_info, &bytes, set_valid);
1882
1883        *blob_info.blob_impl.blob_data_mut() = BlobData::File(FileBlob::new(
1884            id,
1885            None,
1886            Some(bytes.to_vec()),
1887            bytes.len() as u64,
1888        ));
1889
1890        id
1891    }
1892
1893    fn send_to_file_manager(&self, msg: FileManagerThreadMsg) {
1894        let resource_threads = self.resource_threads();
1895        let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg));
1896    }
1897
1898    fn read_file(&self, id: Uuid) -> Result<Vec<u8>, ()> {
1899        let (chan, recv) = profile_generic_callback::GenericCallback::new_blocking(
1900            self.time_profiler_chan().clone(),
1901        )
1902        .expect("Couldn't create read_file callback");
1903
1904        self.send_msg(id, chan);
1905
1906        GlobalScope::read_msg(recv)
1907    }
1908
1909    /// <https://w3c.github.io/FileAPI/#blob-get-stream>
1910    pub(crate) fn get_blob_stream(
1911        &self,
1912        cx: &mut JSContext,
1913        blob_id: &BlobId,
1914    ) -> Fallible<DomRoot<ReadableStream>> {
1915        let (file_id, size) = match self.get_blob_bytes_or_file_id(blob_id) {
1916            BlobResult::Bytes(bytes) => {
1917                // If we have all the bytes in memory, queue them and close the stream.
1918                return ReadableStream::new_from_bytes_with_byte_reading_support(cx, self, bytes);
1919            },
1920            BlobResult::File(id, size) => (id, size),
1921        };
1922
1923        let stream = ReadableStream::new_with_external_underlying_byte_source(
1924            cx,
1925            self,
1926            UnderlyingSourceType::Blob(size),
1927        )?;
1928
1929        let trusted_stream = Trusted::new(&*stream);
1930        let mut file_listener = FileListener {
1931            state: Some(FileListenerState::Empty(FileListenerTarget::Stream(
1932                trusted_stream,
1933            ))),
1934            task_source: self.task_manager().file_reading_task_source().into(),
1935        };
1936
1937        let chan = profile_generic_callback::GenericCallback::new(move |msg| {
1938            file_listener.handle(msg.expect("Deserialization of file listener msg failed."));
1939        })
1940        .expect("Couldn't create get_blob_stream callback");
1941
1942        self.send_msg(file_id, chan);
1943
1944        Ok(stream)
1945    }
1946
1947    pub(crate) fn read_file_async(
1948        &self,
1949        id: Uuid,
1950        promise: &RootedPromise,
1951        callback: FileListenerCallback,
1952    ) {
1953        let trusted_promise = TrustedPromise::from(promise);
1954        let mut file_listener = FileListener {
1955            state: Some(FileListenerState::Empty(FileListenerTarget::Promise(
1956                trusted_promise,
1957                callback,
1958            ))),
1959            task_source: self.task_manager().file_reading_task_source().into(),
1960        };
1961
1962        let chan = profile_generic_callback::GenericCallback::new(move |msg| {
1963            file_listener.handle(msg.expect("Deserialization of file listener msg failed."));
1964        })
1965        .expect("Couldn't create read_file_async callback");
1966
1967        self.send_msg(id, chan);
1968    }
1969
1970    fn send_msg(
1971        &self,
1972        id: Uuid,
1973        chan: profile_generic_callback::GenericCallback<FileManagerResult<ReadFileProgress>>,
1974    ) {
1975        let resource_threads = self.resource_threads();
1976        let origin = self.origin().immutable().clone();
1977        let msg = FileManagerThreadMsg::ReadFile(chan, id, origin);
1978        let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg));
1979    }
1980
1981    fn read_msg(
1982        receiver: profile_generic_channel::GenericReceiver<FileManagerResult<ReadFileProgress>>,
1983    ) -> Result<Vec<u8>, ()> {
1984        let mut bytes = vec![];
1985
1986        loop {
1987            match receiver.recv().unwrap() {
1988                Ok(ReadFileProgress::Meta(mut blob_buf)) => {
1989                    bytes.append(&mut blob_buf.bytes);
1990                },
1991                Ok(ReadFileProgress::Partial(mut bytes_in)) => {
1992                    bytes.append(&mut bytes_in);
1993                },
1994                Ok(ReadFileProgress::EOF) => {
1995                    return Ok(bytes);
1996                },
1997                Err(_) => return Err(()),
1998            }
1999        }
2000    }
2001
2002    pub(crate) fn permission_state_invocation_results(
2003        &self,
2004    ) -> &DomRefCell<HashMap<PermissionName, PermissionState>> {
2005        &self.permission_state_invocation_results
2006    }
2007
2008    pub(crate) fn track_worker(
2009        &self,
2010        closing: Arc<AtomicBool>,
2011        animation_frame_provider_supported: Arc<AtomicBool>,
2012        join_handle: JoinHandle<()>,
2013        control_sender: Sender<DedicatedWorkerControlMsg>,
2014        context: ThreadSafeJSContext,
2015    ) {
2016        self.list_auto_close_worker
2017            .borrow_mut()
2018            .push(AutoCloseWorker {
2019                closing,
2020                animation_frame_provider_supported,
2021                join_handle: Some(join_handle),
2022                control_sender,
2023                context,
2024            });
2025    }
2026
2027    pub(crate) fn disable_owned_worker_animation_frame_providers(&self) {
2028        for worker in &*self.list_auto_close_worker.borrow() {
2029            worker
2030                .animation_frame_provider_supported
2031                .store(false, Ordering::SeqCst);
2032            let _ = worker
2033                .control_sender
2034                .send(DedicatedWorkerControlMsg::AnimationFrameProviderUnsupported);
2035        }
2036    }
2037
2038    pub(crate) fn track_event_source(&self, event_source: &EventSource) {
2039        self.event_source_tracker.track(event_source);
2040    }
2041
2042    pub(crate) fn close_event_sources(&self) -> bool {
2043        let mut canceled_any_fetch = false;
2044        self.event_source_tracker
2045            .for_each(
2046                |event_source: DomRoot<EventSource>| match event_source.ReadyState() {
2047                    2 => {},
2048                    _ => {
2049                        event_source.cancel();
2050                        canceled_any_fetch = true;
2051                    },
2052                },
2053            );
2054        canceled_any_fetch
2055    }
2056
2057    /// Returns the global scope of the realm that the given DOM object's reflector
2058    /// was created in.
2059    #[expect(unsafe_code)]
2060    pub(crate) fn from_reflector<T: DomObject>(reflector: &T) -> DomRoot<Self> {
2061        unsafe { GlobalScope::from_object(*reflector.reflector().get_jsobject()) }
2062    }
2063
2064    /// Returns the global scope of the realm that the given JS object was created in.
2065    #[expect(unsafe_code)]
2066    pub(crate) unsafe fn from_object(obj: *mut JSObject) -> DomRoot<Self> {
2067        assert!(!obj.is_null());
2068        let global = unsafe { GetNonCCWObjectGlobal(obj) };
2069        unsafe { global_scope_from_global_static(global) }
2070    }
2071
2072    /// Return global scope asociated with current realm
2073    ///
2074    /// Eventually we could return Handle here as global is already rooted by realm.
2075    #[expect(unsafe_code)]
2076    pub(crate) fn from_current_realm(realm: &'_ mut CurrentRealm) -> DomRoot<Self> {
2077        let global = realm.global().get();
2078        unsafe { global_scope_from_global(realm, global) }
2079    }
2080
2081    pub(crate) fn add_uncaught_rejection(&self, rejection: HandleObject) {
2082        self.uncaught_rejections
2083            .borrow_mut()
2084            .push(Heap::boxed(rejection.get()));
2085    }
2086
2087    pub(crate) fn remove_uncaught_rejection(&self, rejection: HandleObject) {
2088        let mut uncaught_rejections = self.uncaught_rejections.borrow_mut();
2089
2090        if let Some(index) = uncaught_rejections
2091            .iter()
2092            .position(|promise| *promise == Heap::boxed(rejection.get()))
2093        {
2094            uncaught_rejections.remove(index);
2095        }
2096    }
2097
2098    // `Heap` values must stay boxed, as they need semantics like `Pin`
2099    // (that is, they cannot be moved).
2100    #[allow(clippy::vec_box)]
2101    /// <https://html.spec.whatwg.org/multipage/#about-to-be-notified-rejected-promises-list>
2102    pub(crate) fn get_uncaught_rejections(&self) -> &DomRefCell<Vec<Box<Heap<*mut JSObject>>>> {
2103        &self.uncaught_rejections
2104    }
2105
2106    pub(crate) fn add_consumed_rejection(&self, rejection: HandleObject) {
2107        self.consumed_rejections
2108            .borrow_mut()
2109            .push(Heap::boxed(rejection.get()));
2110    }
2111
2112    pub(crate) fn remove_consumed_rejection(&self, rejection: HandleObject) {
2113        let mut consumed_rejections = self.consumed_rejections.borrow_mut();
2114
2115        if let Some(index) = consumed_rejections
2116            .iter()
2117            .position(|promise| *promise == Heap::boxed(rejection.get()))
2118        {
2119            consumed_rejections.remove(index);
2120        }
2121    }
2122
2123    // `Heap` values must stay boxed, as they need semantics like `Pin`
2124    // (that is, they cannot be moved).
2125    #[allow(clippy::vec_box)]
2126    pub(crate) fn get_consumed_rejections(&self) -> &DomRefCell<Vec<Box<Heap<*mut JSObject>>>> {
2127        &self.consumed_rejections
2128    }
2129
2130    pub(crate) fn with_module_map<T>(
2131        &self,
2132        f: impl FnOnce(&DomRefCell<HashMapTracedValues<ModuleRequest, ModuleStatus>>) -> T,
2133    ) -> T {
2134        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2135            f(worker.module_map())
2136        } else if let Some(worklet) = self.downcast::<WorkletGlobalScope>() {
2137            f(worklet.module_map())
2138        } else if let Some(window) = self.downcast::<Window>() {
2139            f(window.Document().module_map())
2140        } else {
2141            unreachable!("Unsupported global type retrieving module map")
2142        }
2143    }
2144
2145    pub(crate) fn time(&self, label: DOMString) -> Result<(), ()> {
2146        let mut timers = self.console_timers.borrow_mut();
2147        if timers.len() >= 10000 {
2148            return Err(());
2149        }
2150        match timers.entry(label.traced()) {
2151            Entry::Vacant(entry) => {
2152                entry.insert(Instant::now());
2153                Ok(())
2154            },
2155            Entry::Occupied(_) => Err(()),
2156        }
2157    }
2158
2159    /// Computes the delta time since a label has been created
2160    ///
2161    /// Returns an error if the label does not exist.
2162    pub(crate) fn time_log(&self, label: &DOMString) -> Result<u64, ()> {
2163        self.console_timers
2164            .borrow()
2165            .get(label)
2166            .ok_or(())
2167            .map(|&start| (Instant::now() - start).as_millis() as u64)
2168    }
2169
2170    /// Computes the delta time since a label has been created and stops
2171    /// tracking the label.
2172    ///
2173    /// Returns an error if the label does not exist.
2174    pub(crate) fn time_end(&self, label: &DOMString) -> Result<u64, ()> {
2175        self.console_timers
2176            .borrow_mut()
2177            .remove(label)
2178            .ok_or(())
2179            .map(|start| (Instant::now() - start).as_millis() as u64)
2180    }
2181
2182    /// Get an `&IpcSender<ScriptToDevtoolsControlMsg>` to send messages
2183    /// to the devtools thread when available.
2184    #[cfg(feature = "devtools")]
2185    pub(crate) fn devtools_chan(&self) -> Option<&GenericCallback<ScriptToDevtoolsControlMsg>> {
2186        self.devtools_chan.as_ref()
2187    }
2188
2189    /// The debugger global that has this global as a debuggee, if any.
2190    #[cfg(feature = "devtools")]
2191    pub(crate) fn debugger_global(
2192        &self,
2193        cx: &mut JSContext,
2194    ) -> Option<DomRoot<DebuggerGlobalScope>> {
2195        if self.is::<Window>() {
2196            return with_script_thread(|script_thread| script_thread.debugger_global());
2197        }
2198        self.downcast::<WorkerGlobalScope>()?.debugger_global(cx)
2199    }
2200
2201    /// Get a sender to the memory profiler thread.
2202    pub(crate) fn mem_profiler_chan(&self) -> &profile_mem::ProfilerChan {
2203        &self.mem_profiler_chan
2204    }
2205
2206    /// Get a sender to the time profiler thread.
2207    pub(crate) fn time_profiler_chan(&self) -> &profile_time::ProfilerChan {
2208        &self.time_profiler_chan
2209    }
2210
2211    /// Get a sender to the constellation thread.
2212    pub(crate) fn script_to_constellation_chan(&self) -> ScriptToConstellationChan {
2213        ScriptToConstellationChan {
2214            sender: self.script_to_constellation_sender.clone(),
2215            webview_id: self.webview_id().unwrap_or(TEST_WEBVIEW_ID),
2216            pipeline_id: self.pipeline_id(),
2217        }
2218    }
2219
2220    pub(crate) fn script_to_embedder_chan(&self) -> &ScriptToEmbedderChan {
2221        &self.script_to_embedder_chan
2222    }
2223
2224    pub(crate) fn send_to_embedder(&self, msg: EmbedderMsg) {
2225        self.script_to_embedder_chan().send(msg).unwrap();
2226    }
2227
2228    /// Get the `PipelineId` for this global scope.
2229    pub(crate) fn pipeline_id(&self) -> PipelineId {
2230        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2231            worker.pipeline_id()
2232        } else if let Some(window) = self.downcast::<Window>() {
2233            window.pipeline_id()
2234        } else if let Some(worklet) = self.downcast::<WorkletGlobalScope>() {
2235            worklet.pipeline_id()
2236        } else if let Some(dissimilar) = self.downcast::<DissimilarOriginWindow>() {
2237            dissimilar.pipeline_id()
2238        } else {
2239            #[cfg(feature = "devtools")]
2240            if let Some(debugger) = self.downcast::<DebuggerGlobalScope>() {
2241                return debugger.pipeline_id();
2242            }
2243            unreachable!("Unsupported global type for pipeline id")
2244        }
2245    }
2246
2247    /// Register interest in a notification category. Sends a `RegisterInterest`
2248    /// message to the constellation when the first listener is registered.
2249    pub(crate) fn register_interest(&self, interest: ConstellationInterest) {
2250        let mut counts = self.constellation_interest_counts.borrow_mut();
2251        let count = counts.entry(interest).or_insert(0);
2252        *count += 1;
2253        if *count == 1 {
2254            let _ = self
2255                .script_to_constellation_chan()
2256                .send(ScriptToConstellationMessage::RegisterInterest(interest));
2257        }
2258    }
2259
2260    /// Unregister interest in a notification category. Sends an `UnregisterInterest`
2261    /// message to the constellation when the last listener is removed.
2262    pub(crate) fn unregister_interest(&self, interest: ConstellationInterest) {
2263        let mut counts = self.constellation_interest_counts.borrow_mut();
2264        if let Some(count) = counts.get_mut(&interest) {
2265            *count = count.saturating_sub(1);
2266            if *count == 0 {
2267                counts.remove(&interest);
2268                let _ = self
2269                    .script_to_constellation_chan()
2270                    .send(ScriptToConstellationMessage::UnregisterInterest(interest));
2271            }
2272        }
2273    }
2274
2275    /// Get the origin for this global scope
2276    pub(crate) fn origin(&self) -> MutableOrigin {
2277        if let Some(window) = self.downcast::<Window>() {
2278            window.origin()
2279        } else if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2280            worker.origin()
2281        } else if let Some(worklet) = self.downcast::<WorkletGlobalScope>() {
2282            worklet.origin()
2283        } else if let Some(dissimilar_window) = self.downcast::<DissimilarOriginWindow>() {
2284            dissimilar_window.origin()
2285        } else {
2286            #[cfg(feature = "devtools")]
2287            if let Some(debugger) = self.downcast::<DebuggerGlobalScope>() {
2288                return debugger.origin();
2289            }
2290            unreachable!("Unexpected origin check against global")
2291        }
2292    }
2293
2294    /// Get the creation_url for this global scope
2295    pub(crate) fn creation_url(&self) -> ServoUrl {
2296        self.creation_url.borrow().clone()
2297    }
2298
2299    pub(crate) fn set_creation_url(&self, creation_url: ServoUrl) {
2300        *self.creation_url.borrow_mut() = creation_url;
2301    }
2302
2303    /// Get the top_level_creation_url for this global scope
2304    pub(crate) fn top_level_creation_url(&self) -> Option<ServoUrl> {
2305        self.top_level_creation_url.borrow().clone()
2306    }
2307
2308    /// TODO: This value should be immutable after we fix #37417.
2309    pub(crate) fn set_top_level_creation_url(&self, url: ServoUrl) {
2310        *self.top_level_creation_url.borrow_mut() = Some(url);
2311    }
2312
2313    pub(crate) fn image_cache(&self) -> Arc<dyn ImageCache> {
2314        if let Some(window) = self.downcast::<Window>() {
2315            return window.image_cache();
2316        }
2317        if let Some(worker) = self.downcast::<DedicatedWorkerGlobalScope>() {
2318            return worker.image_cache();
2319        }
2320        if let Some(worker) = self.downcast::<SharedWorkerGlobalScope>() {
2321            return worker.image_cache();
2322        }
2323        if let Some(worker) = self.downcast::<PaintWorkletGlobalScope>() {
2324            return worker.image_cache();
2325        }
2326        unreachable!();
2327    }
2328
2329    /// Schedule a [`TimerEventRequest`] on this [`GlobalScope`]'s [`timers::TimerScheduler`].
2330    /// Every Worker has its own scheduler, which handles events in the Worker event loop,
2331    /// but `Window`s use a shared scheduler associated with their [`ScriptThread`].
2332    pub(crate) fn schedule_timer(&self, request: TimerEventRequest) -> Option<TimerId> {
2333        match self.downcast::<WorkerGlobalScope>() {
2334            Some(worker_global) => Some(worker_global.timer_scheduler().schedule_timer(request)),
2335            _ => with_script_thread(|script_thread| Some(script_thread.schedule_timer(request))),
2336        }
2337    }
2338
2339    /// <https://html.spec.whatwg.org/multipage/#nested-browsing-context>
2340    pub(crate) fn is_nested_browsing_context(&self) -> bool {
2341        self.downcast::<Window>()
2342            .is_some_and(|window| !window.is_top_level())
2343    }
2344
2345    /// Obtain the size of in flight keep alive records from the resource thread.
2346    /// If we can't communicate with the thread, we return u64::MAX to ensure
2347    /// the limit is higher than what is allowed. This ensures that whenever
2348    /// we want to initiate a keep alive request and the thread doesn't communicate,
2349    /// we block additional keep alive requests.
2350    pub(crate) fn total_size_of_in_flight_keep_alive_records(&self) -> u64 {
2351        let (sender, receiver) = generic_channel::channel().unwrap();
2352        if self
2353            .core_resource_thread()
2354            .send(CoreResourceMsg::TotalSizeOfInFlightKeepAliveRecords(
2355                self.pipeline_id(),
2356                sender,
2357            ))
2358            .is_err()
2359        {
2360            return u64::MAX;
2361        }
2362        receiver.recv().unwrap_or(u64::MAX)
2363    }
2364
2365    /// Part of <https://fetch.spec.whatwg.org/#populate-request-from-client>
2366    pub(crate) fn request_client(&self, no_gc: Option<&NoGC>) -> RequestClient {
2367        if let Some(window) = self.downcast::<Window>() {
2368            return window.request_client(no_gc);
2369        }
2370        RequestClient {
2371            preloaded_resources: Default::default(),
2372            policy_container: self.policy_container(),
2373            origin: RequestOrigin::Origin(self.origin().immutable().clone()),
2374            is_nested_browsing_context: false,
2375            insecure_requests_policy: self.insecure_requests_policy(),
2376            upgrade_insecure_navigations_set: self.upgrade_insecure_navigations_set().clone(),
2377            has_trustworthy_ancestor_origin: false,
2378            network_partition_key: None,
2379        }
2380    }
2381
2382    /// <https://html.spec.whatwg.org/multipage/#concept-settings-object-policy-container>
2383    pub(crate) fn policy_container(&self) -> Arc<PolicyContainer> {
2384        if let Some(window) = self.downcast::<Window>() {
2385            return window.Document().policy_container().clone();
2386        }
2387        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2388            return worker.policy_container().clone();
2389        }
2390        unreachable!();
2391    }
2392
2393    /// Get the [base url](https://html.spec.whatwg.org/multipage/#api-base-url)
2394    /// for this global scope.
2395    pub(crate) fn api_base_url(&self) -> ServoUrl {
2396        if let Some(window) = self.downcast::<Window>() {
2397            // https://html.spec.whatwg.org/multipage/#script-settings-for-browsing-contexts:api-base-url
2398            return window.Document().base_url();
2399        }
2400        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2401            // https://html.spec.whatwg.org/multipage/#script-settings-for-workers:api-base-url
2402            return worker.get_url().clone();
2403        }
2404        if let Some(worklet) = self.downcast::<WorkletGlobalScope>() {
2405            // https://drafts.css-houdini.org/worklets/#script-settings-for-worklets
2406            return worklet.base_url();
2407        }
2408        #[cfg(feature = "devtools")]
2409        if let Some(_debugger_global) = self.downcast::<DebuggerGlobalScope>() {
2410            return self.creation_url();
2411        }
2412        unreachable!();
2413    }
2414
2415    /// Get the URL for this global scope.
2416    pub(crate) fn get_url(&self) -> ServoUrl {
2417        if let Some(window) = self.downcast::<Window>() {
2418            return window.get_url();
2419        }
2420        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2421            return worker.get_url().clone();
2422        }
2423        if let Some(worklet) = self.downcast::<WorkletGlobalScope>() {
2424            // TODO: is this the right URL to return?
2425            return worklet.base_url();
2426        }
2427        if self.is::<DissimilarOriginWindow>() {
2428            return self.creation_url();
2429        }
2430        #[cfg(feature = "devtools")]
2431        if self.downcast::<DebuggerGlobalScope>().is_some() {
2432            return self.creation_url();
2433        }
2434        unreachable!();
2435    }
2436
2437    /// Get the Referrer Policy for this global scope.
2438    pub(crate) fn get_referrer_policy(&self) -> ReferrerPolicy {
2439        if let Some(window) = self.downcast::<Window>() {
2440            let document = window.Document();
2441
2442            return document.get_referrer_policy();
2443        }
2444        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2445            return worker.policy_container().get_referrer_policy();
2446        }
2447        unreachable!();
2448    }
2449
2450    /// Step 3."client" of <https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer>
2451    /// Determine the Referrer for a request whose Referrer is "client"
2452    pub(crate) fn get_referrer(&self) -> Referrer {
2453        // Substep 3."client".2. If environment’s global object is a Window object, then
2454        if let Some(window) = self.downcast::<Window>() {
2455            // Substep 3."client".2.1. Let document be the associated Document of environment’s global object.
2456            let mut document = window.Document();
2457
2458            // Substep 3."client".2.2. If document’s origin is an opaque origin, return no referrer.
2459            if let ImmutableOrigin::Opaque(_) = document.origin().immutable() {
2460                return Referrer::NoReferrer;
2461            }
2462
2463            let mut url = document.url();
2464
2465            // Substep 3."client".2.3. While document is an iframe srcdoc document,
2466            // let document be document’s browsing context’s browsing context container’s node document.
2467            while url.as_str() == "about:srcdoc" {
2468                // Return early if we cannot get a parent document. This might happen if
2469                // this iframe was already removed from the parent page.
2470                let Some(parent_document) =
2471                    document.browsing_context().and_then(|browsing_context| {
2472                        browsing_context
2473                            .parent()
2474                            .and_then(|parent| parent.document())
2475                    })
2476                else {
2477                    return Referrer::NoReferrer;
2478                };
2479                document = parent_document;
2480                url = document.url();
2481            }
2482
2483            // Substep 3."client".2.4. Let referrerSource be document’s URL.
2484            Referrer::Client(url)
2485        } else {
2486            // Substep 3."client".3. Otherwise, let referrerSource be environment’s creation URL.
2487            Referrer::Client(self.creation_url())
2488        }
2489    }
2490
2491    /// Extract a `Window`, panic if the global object is not a `Window`.
2492    pub(crate) fn as_window(&self) -> &Window {
2493        self.downcast::<Window>().expect("expected a Window scope")
2494    }
2495
2496    /// Returns a policy that should be used for fetches initiated from this global.
2497    pub(crate) fn insecure_requests_policy(&self) -> InsecureRequestsPolicy {
2498        if let Some(window) = self.downcast::<Window>() {
2499            return window.Document().insecure_requests_policy();
2500        }
2501        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2502            return worker.insecure_requests_policy();
2503        }
2504        debug!("unsupported global, defaulting insecure requests policy to DoNotUpgrade");
2505        InsecureRequestsPolicy::DoNotUpgrade
2506    }
2507
2508    /// <https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-insecure-navigations-set>
2509    pub(crate) fn upgrade_insecure_navigations_set(
2510        &self,
2511    ) -> Ref<'_, HashSet<UpgradeInsecureNavigations>> {
2512        self.inherited_upgrade_insecure_navigations_set.borrow()
2513    }
2514
2515    /// <https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-insecure-navigations-set>
2516    pub(crate) fn upgrade_insecure_navigations_set_mut(
2517        &self,
2518    ) -> RefMut<'_, HashSet<UpgradeInsecureNavigations>> {
2519        self.inherited_upgrade_insecure_navigations_set.borrow_mut()
2520    }
2521
2522    /// Whether this document has ancestor navigables that are trustworthy
2523    pub(crate) fn has_trustworthy_ancestor_origin(&self) -> bool {
2524        self.downcast::<Window>()
2525            .is_some_and(|window| window.Document().has_trustworthy_ancestor_origin())
2526    }
2527
2528    /// <https://html.spec.whatwg.org/multipage/#report-an-exception>
2529    pub(crate) fn report_an_exception(&self, cx: &mut JSContext, error: HandleValue) {
2530        // Step 2. Let errorInfo be the result of extracting error information from exception.
2531        let error_info = ErrorInfo::from_value(cx, error);
2532
2533        // Step 3. Let script be a script found in an implementation-defined way, or null.
2534        // This should usually be the running script (most notably during run a classic script).
2535        // Step 4. If script is a classic script and script's muted errors is true, then set
2536        // errorInfo[error] to null, errorInfo[message] to "Script error.", errorInfo[filename]
2537        // to the empty string, errorInfo[lineno] to 0, and errorInfo[colno] to 0.
2538        // Note: This is handled in 'run_a_classic_script'.
2539
2540        // Step 5. If omitError is true, then set errorInfo[error] to null.
2541        //
2542        // `omitError` defaults to `false`
2543
2544        // Steps 6-7
2545        self.report_an_error(cx, error_info, error);
2546    }
2547
2548    /// Steps 6-7 of <https://html.spec.whatwg.org/multipage/#report-an-exception>
2549    pub(crate) fn report_an_error(
2550        &self,
2551        cx: &mut JSContext,
2552        error_info: ErrorInfo,
2553        value: HandleValue,
2554    ) {
2555        self.send_to_embedder(EmbedderMsg::ShowConsoleApiMessage(
2556            self.webview_id(),
2557            ConsoleLogLevel::Error,
2558            format!(
2559                "Error at {}:{}:{} {}",
2560                error_info.filename, error_info.lineno, error_info.column, error_info.message
2561            ),
2562        ));
2563
2564        #[cfg(feature = "js_backtrace")]
2565        LAST_EXCEPTION_BACKTRACE.with(|backtrace| {
2566            if let Some((js_backtrace, rust_backtrace)) = backtrace.borrow_mut().take() {
2567                if let Some(stack) = js_backtrace {
2568                    error!("JS backtrace:\n{}", stack);
2569                }
2570                error!("Rust backtrace:\n{}", rust_backtrace);
2571            }
2572        });
2573
2574        // Step 1. Let notHandled be true.
2575        let mut not_handled = true;
2576
2577        // Step 6. If global is not in error reporting mode:
2578        if !self.in_error_reporting_mode.get() {
2579            // Step 6.1. Set global's in error reporting mode to true.
2580            self.in_error_reporting_mode.set(true);
2581
2582            // Step 6.2 If global implements EventTarget, then set notHandled to the result of
2583            // firing an event named error at global, using ErrorEvent, with the cancelable
2584            // attribute initialized to true, and additional attributes initialized according to
2585            // errorInfo.
2586            let event = ErrorEvent::new(
2587                cx,
2588                self,
2589                atom!("error"),
2590                EventBubbles::DoesNotBubble,
2591                EventCancelable::Cancelable,
2592                error_info.message.as_str().into(),
2593                error_info.filename.as_str().into(),
2594                error_info.lineno,
2595                error_info.column,
2596                value,
2597            );
2598            not_handled = event
2599                .upcast::<Event>()
2600                .fire(cx, self.upcast::<EventTarget>());
2601
2602            // Step 6.3. Set global's in error reporting mode to false.
2603            self.in_error_reporting_mode.set(false);
2604        }
2605
2606        // Step 7. If notHandled is true, then:
2607        if not_handled {
2608            // Step 7.2. If global implements DedicatedWorkerGlobalScope,
2609            // queue a global task on the DOM manipulation task source with the
2610            // global's associated Worker's relevant global object to run these steps:
2611            //
2612            // https://html.spec.whatwg.org/multipage/#runtime-script-errors-2
2613            if let Some(dedicated) = self.downcast::<DedicatedWorkerGlobalScope>() {
2614                dedicated.forward_error_to_worker_object(error_info);
2615            } else if self.is::<Window>() {
2616                // Step 7.3. Otherwise, the user agent may report exception to a developer console.
2617                #[cfg(feature = "devtools")]
2618                if let Some(ref chan) = self.devtools_chan {
2619                    let _ = chan.send(ScriptToDevtoolsControlMsg::ReportPageError(
2620                        self.pipeline_id(),
2621                        PageError {
2622                            error_message: error_info.message.clone(),
2623                            source_name: error_info.filename.clone(),
2624                            line_number: error_info.lineno,
2625                            column_number: error_info.column,
2626                            time_stamp: get_time_stamp(),
2627                        },
2628                    ));
2629                }
2630            }
2631        }
2632    }
2633
2634    /// Get the `&ResourceThreads` for this global scope.
2635    pub(crate) fn resource_threads(&self) -> &ResourceThreads {
2636        &self.resource_threads
2637    }
2638
2639    /// Get the `CoreResourceThread` for this global scope.
2640    pub(crate) fn core_resource_thread(&self) -> CoreResourceThread {
2641        self.resource_threads().sender()
2642    }
2643
2644    /// Get a reference to the [`StorageThreads`] for this [`GlobalScope`].
2645    pub(crate) fn storage_threads(&self) -> &StorageThreads {
2646        &self.storage_threads
2647    }
2648
2649    /// A sender to the event loop of this global scope. This either sends to the Worker event loop
2650    /// or the ScriptThread event loop in the case of a `Window`. This can be `None` for dedicated
2651    /// workers that are not currently handling a message.
2652    pub(crate) fn event_loop_sender(&self) -> Option<ScriptEventLoopSender> {
2653        if let Some(window) = self.downcast::<Window>() {
2654            Some(window.event_loop_sender())
2655        } else if let Some(dedicated) = self.downcast::<DedicatedWorkerGlobalScope>() {
2656            dedicated.event_loop_sender()
2657        } else if let Some(shared_worker) = self.downcast::<SharedWorkerGlobalScope>() {
2658            Some(shared_worker.event_loop_sender())
2659        } else if let Some(service_worker) = self.downcast::<ServiceWorkerGlobalScope>() {
2660            Some(service_worker.event_loop_sender())
2661        } else {
2662            unreachable!(
2663                "Tried to access event loop sender for incompatible \
2664                 GlobalScope (PaintWorklet or DissimilarOriginWindow)"
2665            );
2666        }
2667    }
2668
2669    /// A reference to the [`TaskManager`] used to schedule tasks for this [`GlobalScope`].
2670    pub(crate) fn task_manager(&self) -> Rc<TaskManager> {
2671        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2672            worker.task_manager()
2673        } else if let Some(window) = self.downcast::<Window>() {
2674            window.task_manager()
2675        } else if let Some(worklet) = self.downcast::<WorkletGlobalScope>() {
2676            worklet.task_manager()
2677        } else {
2678            unreachable!("Attempted to use task manager with unsupported global");
2679        }
2680    }
2681
2682    /// Evaluate JS code on this global scope.
2683    #[expect(unsafe_code)]
2684    pub(crate) fn evaluate_js_on_global(
2685        &self,
2686        cx: &mut CurrentRealm,
2687        code: Cow<'_, str>,
2688        filename: &str,
2689        introduction_type: Option<&'static CStr>,
2690        rval: Option<MutableHandleValue>,
2691    ) -> Result<(), JavaScriptEvaluationError> {
2692        run_a_script::<DomTypeHolder, _, _>(cx, self, |cx| {
2693            let url = self.api_base_url();
2694            let fetch_options = ScriptFetchOptions::default_classic_script();
2695
2696            let mut script_options = ScriptOptions::empty();
2697            script_options.set(ScriptOptions::ReturnsAValue, rval.is_some());
2698
2699            let options = fill_compile_options(
2700                cx,
2701                filename,
2702                script_options,
2703                introduction_type,
2704                1, // line_number
2705            );
2706
2707            let mut source = transform_str_to_source_text(&code);
2708            rooted!(&in(cx) let compiled_script = unsafe { Compile1(cx, options.ptr, &mut source) });
2709
2710            if compiled_script.is_null() {
2711                debug!("error compiling Dom string");
2712                report_pending_exception(cx);
2713                return Err(JavaScriptEvaluationError::CompilationFailure);
2714            }
2715
2716            rooted!(&in(cx) let mut value = UndefinedValue());
2717            let rval = rval.unwrap_or_else(|| value.handle_mut());
2718
2719            maybe_associate_with_script(cx, compiled_script.handle(), url, fetch_options);
2720
2721            if unsafe { !JS_ExecuteScript(cx, compiled_script.handle(), rval) } {
2722                let error_info = take_and_report_pending_exception_for_api(cx);
2723                return Err(JavaScriptEvaluationError::EvaluationFailure(error_info));
2724            }
2725
2726            maybe_resume_unwind();
2727            Ok(())
2728        })
2729    }
2730
2731    /// <https://html.spec.whatwg.org/multipage/#timer-initialisation-steps>
2732    pub(crate) fn schedule_js_callback(
2733        &self,
2734        callback: RootedInternalTimerCallback,
2735        data: JsTimerTaskData,
2736        duration: Duration,
2737    ) -> OneshotTimerHandle {
2738        self.with_timers(|timers| {
2739            timers.schedule_js_callback(callback, data, duration, self.timer_source())
2740        })
2741    }
2742
2743    /// <https://html.spec.whatwg.org/multipage/#timer-initialisation-steps>
2744    pub(crate) fn schedule_callback(
2745        &self,
2746        callback: OneshotTimerCallback,
2747        duration: Duration,
2748    ) -> OneshotTimerHandle {
2749        self.with_timers(|timers| timers.schedule_callback(callback, duration, self.timer_source()))
2750    }
2751
2752    pub(crate) fn unschedule_callback(&self, handle: OneshotTimerHandle) {
2753        self.with_timers(|timers| timers.unschedule_callback(handle));
2754    }
2755
2756    /// <https://html.spec.whatwg.org/multipage/#timer-initialisation-steps>
2757    pub(crate) fn set_timeout_or_interval(
2758        &self,
2759        cx: &mut JSContext,
2760        callback: TimerCallback,
2761        arguments: Vec<HandleValue>,
2762        timeout: Duration,
2763        is_interval: IsInterval,
2764    ) -> Fallible<i32> {
2765        self.with_timers(|timers| {
2766            timers.set_timeout_or_interval(
2767                cx,
2768                self,
2769                callback,
2770                arguments,
2771                timeout,
2772                is_interval,
2773                self.timer_source(),
2774            )
2775        })
2776    }
2777
2778    pub(crate) fn clear_timeout_or_interval(&self, handle: i32) {
2779        self.with_timers(|timers| timers.clear_timeout_or_interval(self, handle));
2780    }
2781
2782    pub(crate) fn fire_timer(&self, cx: &mut JSContext, handle: TimerEventId) {
2783        self.with_timers(|timers| timers.fire_timer(cx, handle));
2784    }
2785
2786    pub(crate) fn resume(&self) {
2787        self.with_timers(|timers| timers.resume());
2788    }
2789
2790    pub(crate) fn suspend(&self) {
2791        self.with_timers(|timers| timers.suspend());
2792    }
2793
2794    pub(crate) fn slow_down_timers(&self) {
2795        self.with_timers(|timers| timers.slow_down());
2796    }
2797
2798    pub(crate) fn speed_up_timers(&self) {
2799        self.with_timers(|timers| timers.speed_up());
2800    }
2801
2802    fn timer_source(&self) -> TimerSource {
2803        if self.is::<Window>() {
2804            return TimerSource::FromWindow(self.pipeline_id());
2805        }
2806        if self.is::<WorkerGlobalScope>() {
2807            return TimerSource::FromWorker;
2808        }
2809        unreachable!();
2810    }
2811
2812    /// Returns a boolean indicating whether the event-loop
2813    /// where this global is running on can continue running JS.
2814    pub(crate) fn can_continue_running(&self) -> bool {
2815        if self.is::<Window>() {
2816            return ScriptThread::can_continue_running();
2817        }
2818        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2819            return !worker.is_closing();
2820        }
2821
2822        // TODO: plug worklets into this.
2823        true
2824    }
2825
2826    /// Potentially instantiate and return this [`GlobalScope`]'s [`IDBFactory`].
2827    pub(crate) fn ensure_indexeddb_factory(&self, cx: &mut JSContext) -> DomRoot<IDBFactory> {
2828        self.indexeddb.or_init(|| IDBFactory::new(cx, self))
2829    }
2830
2831    /// Return this [`GlobalScope`]'s [`IDBFactory`] if it has previously been instantiated.
2832    pub(crate) fn indexeddb_factory(&self) -> Option<DomRoot<IDBFactory>> {
2833        self.indexeddb.get()
2834    }
2835
2836    /// Perform a microtask checkpoint.
2837    pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut JSContext) {
2838        if let Some(window) = self.downcast::<Window>() {
2839            window.perform_a_microtask_checkpoint(cx);
2840        } else if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2841            worker.perform_a_microtask_checkpoint(cx);
2842        } else if let Some(worklet) = self.downcast::<WorkletGlobalScope>() {
2843            worklet.perform_a_microtask_checkpoint(cx);
2844        }
2845    }
2846
2847    /// Enqueue a microtask for subsequent execution.
2848    pub(crate) fn enqueue_microtask(
2849        &self,
2850        cx: &js::context::JSContext,
2851        job: Box<dyn MicrotaskRunnable>,
2852    ) {
2853        if self.is::<Window>() {
2854            ScriptThread::enqueue_microtask(cx, job);
2855        } else if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2856            worker.enqueue_microtask(cx, job);
2857        }
2858    }
2859
2860    /// Create a new sender/receiver pair that can be used to implement an on-demand
2861    /// event loop. Used for implementing web APIs that require blocking semantics
2862    /// without resorting to nested event loops.
2863    pub(crate) fn new_script_pair(&self) -> (ScriptEventLoopSender, ScriptEventLoopReceiver) {
2864        if let Some(window) = self.downcast::<Window>() {
2865            return window.new_script_pair();
2866        }
2867        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2868            return worker.new_script_pair();
2869        }
2870        unreachable!();
2871    }
2872
2873    /// Process a single event as if it were the next event
2874    /// in the queue for the event-loop where this global scope is running on.
2875    /// Returns a boolean indicating whether further events should be processed.
2876    pub(crate) fn process_event(&self, cx: &mut JSContext, msg: CommonScriptMsg) -> bool {
2877        if self.is::<Window>() {
2878            return ScriptThread::process_event(cx, msg);
2879        }
2880        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2881            return worker.process_event(msg, cx);
2882        }
2883        unreachable!();
2884    }
2885
2886    pub(crate) fn runtime_handle(&self) -> ParentRuntime {
2887        if self.is::<Window>() {
2888            ScriptThread::runtime_handle()
2889        } else if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2890            worker.runtime_handle()
2891        } else {
2892            unreachable!()
2893        }
2894    }
2895
2896    /// Returns the ["current"] global object.
2897    ///
2898    /// ["current"]: https://html.spec.whatwg.org/multipage/#current
2899    #[expect(unsafe_code)]
2900    pub(crate) fn current() -> Option<DomRoot<Self>> {
2901        let mut cx = unsafe { JSContext::get_from_thread()? };
2902        unsafe {
2903            let global = CurrentGlobalOrNull(&cx);
2904            if global.is_null() {
2905                None
2906            } else {
2907                Some(global_scope_from_global(&mut cx, global))
2908            }
2909        }
2910    }
2911
2912    /// Returns the ["entry"] global object.
2913    ///
2914    /// ["entry"]: https://html.spec.whatwg.org/multipage/#entry
2915    pub(crate) fn entry() -> DomRoot<Self> {
2916        entry_global()
2917    }
2918
2919    /// Returns the ["incumbent"] global object.
2920    ///
2921    /// ["incumbent"]: https://html.spec.whatwg.org/multipage/#incumbent
2922    pub(crate) fn incumbent() -> Option<DomRoot<Self>> {
2923        incumbent_global()
2924    }
2925
2926    pub(crate) fn performance(&self, cx: &mut JSContext) -> DomRoot<Performance> {
2927        if let Some(window) = self.downcast::<Window>() {
2928            return window.Performance(cx);
2929        }
2930        if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
2931            return worker.Performance(cx);
2932        }
2933        unreachable!();
2934    }
2935
2936    /// <https://w3c.github.io/performance-timeline/#supportedentrytypes-attribute>
2937    pub(crate) fn supported_performance_entry_types(
2938        &self,
2939        cx: &mut JSContext,
2940        retval: MutableHandleValue,
2941    ) {
2942        self.frozen_supported_performance_entry_types.get_or_init(
2943            cx,
2944            || {
2945                EntryType::VARIANTS
2946                    .iter()
2947                    .map(|t| DOMString::from(t.as_str()))
2948                    .collect()
2949            },
2950            retval,
2951        );
2952    }
2953
2954    pub(crate) fn inherited_secure_context(&self) -> Option<bool> {
2955        self.inherited_secure_context
2956    }
2957
2958    /// <https://html.spec.whatwg.org/multipage/#secure-context>
2959    pub(crate) fn is_secure_context(&self) -> bool {
2960        // This differs from the specification, but it seems that
2961        // `inherited_secure_context` implements more-or-less the exact same logic, in a
2962        // different manner. Workers inherit whether or not their in a secure context and
2963        // worklets do as well (they can only be created in secure contexts).
2964        if Some(false) == self.inherited_secure_context {
2965            return false;
2966        }
2967        // Step 1. If environment is an environment settings object, then:
2968        // Step 1.1. Let global be environment's global object.
2969        match self.top_level_creation_url() {
2970            None => {
2971                // Workers and worklets don't have a top-level creation URL
2972                assert!(self.is::<WorkerGlobalScope>() || self.is::<WorkletGlobalScope>());
2973                true
2974            },
2975            Some(top_level_creation_url) => {
2976                assert!(self.is::<Window>());
2977                // Step 2. If the result of Is url potentially trustworthy?
2978                // given environment's top-level creation URL is "Potentially Trustworthy", then return true.
2979                // Step 3. Return false.
2980                if top_level_creation_url.scheme() == "blob" &&
2981                    Some(true) == self.inherited_secure_context
2982                {
2983                    return true;
2984                }
2985                top_level_creation_url.is_potentially_trustworthy()
2986            },
2987        }
2988    }
2989
2990    /// <https://www.w3.org/TR/CSP/#get-csp-of-object>
2991    pub(crate) fn call_on_csp_list<T, F: FnOnce(&Option<CspList>) -> T>(&self, f: F) -> T {
2992        if self.is::<Window>() || self.is::<WorkerGlobalScope>() {
2993            return f(&self.policy_container().as_ref().csp_list);
2994        }
2995        // TODO: Worklet global scopes.
2996        f(&None)
2997    }
2998
2999    pub(crate) fn status_code(&self) -> Option<u16> {
3000        if let Some(window) = self.downcast::<Window>() {
3001            return window.Document().status_code();
3002        }
3003        None
3004    }
3005
3006    pub(crate) fn online(&self) -> bool {
3007        if let Some(worker_global_scope) = self.downcast::<WorkerGlobalScope>() {
3008            return worker_global_scope.online();
3009        }
3010        ScriptThread::online()
3011    }
3012
3013    #[cfg(feature = "webgpu")]
3014    pub(crate) fn wgpu_id_hub(&self) -> Arc<IdentityHub> {
3015        self.gpu_id_hub.clone()
3016    }
3017
3018    #[cfg(feature = "webgpu")]
3019    pub(crate) fn add_gpu_device(&self, device: &GPUDevice) {
3020        self.gpu_devices
3021            .borrow_mut()
3022            .insert(device.id(), WeakRef::new(device));
3023    }
3024
3025    #[cfg(feature = "webgpu")]
3026    pub(crate) fn remove_gpu_device(&self, device: WebGPUDevice) {
3027        let device = self
3028            .gpu_devices
3029            .borrow_mut()
3030            .remove(&device)
3031            .expect("GPUDevice should still be in devices hashmap");
3032        assert!(device.root().is_none())
3033    }
3034
3035    #[cfg(feature = "webgpu")]
3036    pub(crate) fn gpu_device_lost(
3037        &self,
3038        device: WebGPUDevice,
3039        reason: DeviceLostReason,
3040        msg: String,
3041    ) {
3042        let reason = match reason {
3043            DeviceLostReason::Unknown => GPUDeviceLostReason::Unknown,
3044            DeviceLostReason::Destroyed => GPUDeviceLostReason::Destroyed,
3045        };
3046        if let Some(device) = self
3047            .gpu_devices
3048            .borrow_mut()
3049            .get_mut(&device)
3050            .expect("GPUDevice should still be in devices hashmap")
3051            .root()
3052        {
3053            device.lose(reason, msg);
3054        }
3055    }
3056
3057    #[cfg(feature = "webgpu")]
3058    pub(crate) fn handle_uncaptured_gpu_error(
3059        &self,
3060        device: WebGPUDevice,
3061        error: webgpu_traits::Error,
3062    ) {
3063        if let Some(gpu_device) = self
3064            .gpu_devices
3065            .borrow()
3066            .get(&device)
3067            .and_then(|device| device.root())
3068        {
3069            gpu_device.fire_uncaptured_error(error);
3070        } else {
3071            warn!("Recived error for lost GPUDevice!")
3072        }
3073    }
3074
3075    pub(crate) fn current_group_label(&self) -> Option<DOMString> {
3076        self.console_group_stack
3077            .borrow()
3078            .last()
3079            .map(|label| DOMString::from(format!("[{}]", label)))
3080    }
3081
3082    pub(crate) fn push_console_group(&self, group: DOMString) {
3083        self.console_group_stack.borrow_mut().push(group.traced());
3084    }
3085
3086    pub(crate) fn pop_console_group(&self) {
3087        let _ = self.console_group_stack.borrow_mut().pop();
3088    }
3089
3090    pub(crate) fn increment_console_count(&self, label: &DOMString) -> usize {
3091        *self
3092            .console_count_map
3093            .borrow_mut()
3094            .entry(label.clone().traced())
3095            .and_modify(|e| *e += 1)
3096            .or_insert(1)
3097    }
3098
3099    pub(crate) fn reset_console_count(&self, label: &DOMString) -> Result<(), ()> {
3100        match self.console_count_map.borrow_mut().get_mut(label) {
3101            Some(value) => {
3102                *value = 0;
3103                Ok(())
3104            },
3105            None => Err(()),
3106        }
3107    }
3108
3109    pub(crate) fn structured_clone(
3110        &self,
3111        cx: &mut JSContext,
3112        value: HandleValue,
3113        options: &StructuredSerializeOptions,
3114        retval: MutableHandleValue,
3115    ) -> Fallible<()> {
3116        auto_root!(&in(cx) let guard =
3117            options
3118                .transfer
3119                .iter()
3120                .map(|js| js.get())
3121                .collect::<Vec<_>>());
3122
3123        let data = structuredclone::write(cx, value, Some(guard))?;
3124
3125        structuredclone::read(cx, self, data, retval)?;
3126
3127        Ok(())
3128    }
3129
3130    pub(crate) fn fetch<Listener: FetchResponseListener>(
3131        &self,
3132        request_builder: RequestBuilder,
3133        context: Listener,
3134        task_source: SendableTaskSource,
3135    ) {
3136        self.fetch_group_mut().fetch(
3137            request_builder,
3138            NetworkListener::new(context, task_source),
3139            None, /* state */
3140        );
3141    }
3142
3143    pub(crate) fn fetch_favicon<Listener: FetchResponseListener>(
3144        &self,
3145        request_builder: RequestBuilder,
3146        context: Listener,
3147        task_source: SendableTaskSource,
3148    ) {
3149        self.fetch_group_mut().fetch_with_options(
3150            request_builder,
3151            NetworkListener::new(context, task_source),
3152            None, /* state */
3153            false,
3154        );
3155    }
3156
3157    pub(crate) fn unminify_js(&self) -> bool {
3158        self.unminified_js_dir.is_some()
3159    }
3160
3161    pub(crate) fn unminified_js_dir(&self) -> Option<String> {
3162        self.unminified_js_dir.clone()
3163    }
3164
3165    pub(crate) fn set_byte_length_queuing_strategy_size(&self, function: RootedCallback<Function>) {
3166        if self
3167            .byte_length_queuing_strategy_size_function
3168            .set(function.to_traced())
3169            .is_err()
3170        {
3171            warn!("byte length queuing strategy size function is set twice.");
3172        };
3173    }
3174
3175    pub(crate) fn get_byte_length_queuing_strategy_size(
3176        &self,
3177        cx: &JSContext,
3178    ) -> Option<RootedCallback<Function>> {
3179        self.byte_length_queuing_strategy_size_function
3180            .get()
3181            .cloned()
3182            .map(|f| f.root(cx))
3183    }
3184
3185    pub(crate) fn set_count_queuing_strategy_size(&self, function: RootedCallback<Function>) {
3186        if self
3187            .count_queuing_strategy_size_function
3188            .set(function.to_traced())
3189            .is_err()
3190        {
3191            warn!("count queuing strategy size function is set twice.");
3192        };
3193    }
3194
3195    pub(crate) fn get_count_queuing_strategy_size(
3196        &self,
3197        cx: &JSContext,
3198    ) -> Option<RootedCallback<Function>> {
3199        self.count_queuing_strategy_size_function
3200            .get()
3201            .cloned()
3202            .map(|f| f.root(cx))
3203    }
3204
3205    pub(crate) fn add_notification_permission_request_callback(
3206        &self,
3207        callback_id: String,
3208        callback: RootedCallback<NotificationPermissionCallback>,
3209    ) {
3210        self.notification_permission_request_callback_map
3211            .borrow_mut()
3212            .insert(callback_id, callback.to_traced());
3213    }
3214
3215    pub(crate) fn remove_notification_permission_request_callback(
3216        &self,
3217        callback_id: String,
3218    ) -> Option<TracedCallback<NotificationPermissionCallback>> {
3219        self.notification_permission_request_callback_map
3220            .borrow_mut()
3221            .remove(&callback_id)
3222    }
3223
3224    pub(crate) fn fetch_group(&self) -> Ref<'_, FetchGroup> {
3225        self.fetch_group.borrow()
3226    }
3227
3228    pub(crate) fn fetch_group_mut(&self) -> RefMut<'_, FetchGroup> {
3229        self.fetch_group.borrow_mut()
3230    }
3231
3232    pub(crate) fn import_map(&self) -> Ref<'_, ImportMap> {
3233        self.import_map.borrow()
3234    }
3235
3236    pub(crate) fn import_map_mut(&self) -> RefMut<'_, ImportMap> {
3237        self.import_map.borrow_mut()
3238    }
3239
3240    pub(crate) fn resolved_module_set(&self) -> Ref<'_, HashSet<ResolvedModule>> {
3241        self.resolved_module_set.borrow()
3242    }
3243
3244    /// <https://html.spec.whatwg.org/multipage/#add-module-to-resolved-module-set>
3245    pub(crate) fn add_module_to_resolved_module_set(
3246        &self,
3247        base_url: &str,
3248        specifier: &str,
3249        specifier_url: Option<ServoUrl>,
3250    ) {
3251        // Step 1. Let global be settingsObject's global object.
3252        // Step 2. If global does not implement Window, then return.
3253        if self.is::<Window>() {
3254            // Step 3. Let record be a new specifier resolution record, with serialized base URL
3255            // set to serializedBaseURL, specifier set to normalizedSpecifier, and specifier as
3256            // a URL set to asURL.
3257            let record =
3258                ResolvedModule::new(base_url.to_owned(), specifier.to_owned(), specifier_url);
3259            // Step 4. Append record to global's resolved module set.
3260            self.resolved_module_set.borrow_mut().insert(record);
3261        }
3262    }
3263
3264    /// <https://html.spec.whatwg.org/multipage/#run-steps-after-a-timeout>
3265    /// TODO: This should end-up being used in the other timer mechanism
3266    /// integrate as per <https://html.spec.whatwg.org/multipage/#timers:run-steps-after-a-timeout?
3267    pub(crate) fn run_steps_after_a_timeout<F>(
3268        &self,
3269        ordering_identifier: DOMString,
3270        milliseconds: i64,
3271        completion_steps: F,
3272    ) -> i32
3273    where
3274        F: 'static + FnOnce(&mut JSContext, &GlobalScope),
3275    {
3276        let ms = milliseconds.max(0) as u64;
3277        let delay = std::time::Duration::from_millis(ms);
3278
3279        let (callback, timer_key) = self.with_timers(|timers| {
3280            // Step 1. Let timerKey be a new unique internal value.
3281            let timer_key = timers.fresh_runsteps_key();
3282
3283            // Step 2. Let startTime be the current high resolution time given global.
3284            let start_time = timers.now_for_runsteps();
3285
3286            // Step 3. Set global's map of active timers[timerKey] to startTime plus milliseconds.
3287            let deadline = start_time + delay;
3288            timers.runsteps_set_active(timer_key, deadline);
3289
3290            // Step 4. Run the following steps in parallel:
3291            //   (We schedule a oneshot that will enforce the sub-steps when it fires.)
3292            let callback = OneshotTimerCallback::RunStepsAfterTimeout {
3293                // Step 1. timerKey
3294                timer_key,
3295                // Step 4. orderingIdentifier
3296                ordering_id: ordering_identifier,
3297                // Spec: milliseconds
3298                milliseconds: ms,
3299                // Step 4.4 Perform completionSteps.
3300                completion: Box::new(completion_steps),
3301            };
3302            (callback, timer_key)
3303        });
3304        let _ = self.schedule_callback(callback, delay);
3305
3306        // Step 5. Return timerKey.
3307        timer_key
3308    }
3309
3310    pub(crate) fn set_network_online_state_on_dedicated_workers(&self, online: bool) {
3311        for worker in &*self.list_auto_close_worker.borrow() {
3312            _ = worker
3313                .control_sender
3314                .send(DedicatedWorkerControlMsg::SetNetworkOnlineState(online));
3315        }
3316    }
3317}
3318
3319/// Returns the Rust global scope from a JS global object.
3320#[expect(unsafe_code)]
3321unsafe fn global_scope_from_global(
3322    cx: &mut JSContext,
3323    global: *mut JSObject,
3324) -> DomRoot<GlobalScope> {
3325    unsafe {
3326        assert!(!global.is_null());
3327        let clasp = get_object_class(global);
3328        assert_ne!(
3329            ((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)),
3330            0
3331        );
3332        root_from_object(cx, global).unwrap()
3333    }
3334}
3335
3336/// Returns the Rust global scope from a JS global object.
3337#[expect(unsafe_code)]
3338unsafe fn global_scope_from_global_static(global: *mut JSObject) -> DomRoot<GlobalScope> {
3339    assert!(!global.is_null());
3340    let clasp = unsafe { get_object_class(global) };
3341
3342    unsafe {
3343        assert_ne!(
3344            ((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)),
3345            0
3346        );
3347    }
3348
3349    root_from_object_static(global).unwrap()
3350}
3351
3352#[expect(unsafe_code)]
3353impl GlobalScopeHelpers<crate::DomTypeHolder> for GlobalScope {
3354    fn from_current_realm(realm: &'_ mut CurrentRealm) -> DomRoot<Self> {
3355        GlobalScope::from_current_realm(realm)
3356    }
3357
3358    unsafe fn from_object(obj: *mut JSObject) -> DomRoot<Self> {
3359        unsafe { GlobalScope::from_object(obj) }
3360    }
3361
3362    fn from_reflector(reflector: &impl DomObject) -> DomRoot<Self> {
3363        GlobalScope::from_reflector(reflector)
3364    }
3365
3366    fn origin(&self) -> MutableOrigin {
3367        GlobalScope::origin(self)
3368    }
3369
3370    fn incumbent() -> Option<DomRoot<Self>> {
3371        GlobalScope::incumbent()
3372    }
3373
3374    fn perform_a_microtask_checkpoint(&self, cx: &mut JSContext) {
3375        GlobalScope::perform_a_microtask_checkpoint(self, cx)
3376    }
3377
3378    fn get_url(&self) -> ServoUrl {
3379        self.get_url()
3380    }
3381
3382    fn is_secure_context(&self) -> bool {
3383        self.is_secure_context()
3384    }
3385
3386    fn pipeline_id(&self) -> PipelineId {
3387        self.pipeline_id()
3388    }
3389
3390    fn script_to_constellation_chan(&self) -> ScriptToConstellationChan {
3391        self.script_to_constellation_chan()
3392    }
3393
3394    fn entry() -> DomRoot<Self> {
3395        GlobalScope::entry()
3396    }
3397}
3398
3399impl OwnerWindow<DomTypeHolder> for GlobalScope {}