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