Skip to main content

script/runtime/
script_runtime.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! The script runtime contains common traits and structs commonly used by the
6//! script thread, the dom, and the worker threads.
7
8#![expect(dead_code)]
9
10use core::ffi::c_char;
11use std::cell::{Cell, LazyCell, RefCell};
12use std::collections::{HashMap, HashSet};
13use std::ffi::{CStr, CString};
14use std::io::{Write, stdout};
15use std::ops::{Deref, DerefMut};
16use std::os::raw::c_void;
17use std::ptr::NonNull;
18use std::rc::{Rc, Weak};
19use std::time::Instant;
20use std::{os, ptr};
21
22use background_hang_monitor_api::ScriptHangAnnotation;
23use js::context::JSContext;
24use js::gc::StackGCVector;
25use js::glue::{
26    DispatchablePointer, RUST_js_GetErrorMessage, RegisterScriptEnvironmentPreparer,
27    RunScriptEnvironmentPreparerClosure, SetBuildId, StreamConsumerConsumeChunk,
28    StreamConsumerNoteResponseURLs, StreamConsumerStreamEnd, StreamConsumerStreamError,
29};
30use js::jsapi::{
31    AsmJSOption, BuildIdCharVector, CompilationType, Dispatchable_MaybeShuttingDown, GCDescription,
32    GCOptions, GCProgress, GCReason, Handle as RawHandle, HandleObject, HandleString,
33    HandleValue as RawHandleValue, Heap, JSContext as RawJSContext, JSErrNum, JSGCParamKey,
34    JSGCStatus, JSJitCompilerOption, JSObject, JSSecurityCallbacks, JSString, JSTracer, MimeType,
35    MutableHandleString, PromiseRejectionHandlingState, RuntimeCode,
36    ScriptEnvironmentPreparer_Closure, SetProcessBuildIdOp, StreamConsumer as JSStreamConsumer,
37};
38use js::jsval::{JSVal, UndefinedValue};
39use js::panic::wrap_panic;
40use js::realm::CurrentRealm;
41pub(crate) use js::rust::ThreadSafeJSContext;
42use js::rust::wrappers2::{
43    CollectServoSizes, ContextOptionsRef, DispatchableRun, InitConsumeStreamCallback,
44    JS_AddExtraGCRootsTracer, JS_GetPromiseResult, JS_InitDestroyPrincipalsCallback,
45    JS_InitReadPrincipalsCallback, JS_NewStringCopyUTF8N, JS_SetGCCallback, JS_SetGCParameter,
46    JS_SetGlobalJitCompilerOption, JS_SetOffthreadIonCompilationEnabled, JS_SetSecurityCallbacks,
47    SetDOMCallbacks, SetGCSliceCallback, SetPreserveWrapperCallbacks,
48    SetPromiseRejectionTrackerCallback, SetUpEventLoopDispatch,
49};
50use js::rust::{
51    Handle, HandleObject as RustHandleObject, HandleValue, IntoHandle, ParentRuntime,
52    Runtime as RustRuntime, Trace,
53};
54use malloc_size_of::MallocSizeOfOps;
55use malloc_size_of_derive::MallocSizeOf;
56use profile_traits::mem::{Report, ReportKind};
57use profile_traits::path;
58use profile_traits::time::ProfilerCategory;
59use script_bindings::reflector::DomObject;
60use script_bindings::script_runtime::{mark_runtime_dead, runtime_is_alive, temp_cx};
61use script_bindings::settings_stack::run_a_script;
62use servo_config::opts::{self, DiagnosticsLoggingOption};
63use servo_config::pref;
64use servo_url::ServoUrl;
65use style::thread_state::{self, ThreadState};
66
67use crate::dom::bindings::codegen::Bindings::ResponseBinding::Response_Binding::ResponseMethods;
68use crate::dom::bindings::codegen::Bindings::ResponseBinding::ResponseType as DOMResponseType;
69use crate::dom::bindings::codegen::UnionTypes::TrustedScriptOrString;
70use crate::dom::bindings::conversions::{
71    get_dom_class, private_from_object, root_from_handleobject, root_from_object,
72};
73use crate::dom::bindings::error::{Error, report_pending_exception, throw_dom_exception};
74use crate::dom::bindings::inheritance::Castable;
75use crate::dom::bindings::refcounted::{
76    LivePromiseReferences, Trusted, TrustedPromise, trace_refcounted_objects,
77};
78use crate::dom::bindings::reflector::DomGlobal;
79use crate::dom::bindings::root::trace_roots;
80use crate::dom::bindings::str::DOMString;
81use crate::dom::bindings::utils::DOM_CALLBACKS;
82use crate::dom::bindings::{principals, settings_stack};
83use crate::dom::console::{Console, stringify_handle_value};
84use crate::dom::csp::CspReporting;
85use crate::dom::event::{Event, EventBubbles, EventCancelable};
86use crate::dom::eventtarget::EventTarget;
87use crate::dom::globalscope::GlobalScope;
88use crate::dom::promise::Promise;
89use crate::dom::promiserejectionevent::PromiseRejectionEvent;
90use crate::dom::response::Response;
91use crate::dom::trustedtypes::trustedscript::TrustedScript;
92use crate::dom::window::Window;
93use crate::engine::handle::current_js_engine_handle;
94use crate::fetch::body::BodyMixin;
95use crate::messaging::{CommonScriptMsg, ScriptEventLoopSender};
96use crate::realms::enter_auto_realm;
97use crate::runtime::job_queue::{JobQueue, job_queue_clear};
98use crate::scripting::script_module::EnsureModuleHooksInitialized;
99use crate::tasks::task_source::TaskSourceName;
100use crate::{DomTypeHolder, ScriptThread};
101
102static SECURITY_CALLBACKS: JSSecurityCallbacks = JSSecurityCallbacks {
103    contentSecurityPolicyAllows: Some(content_security_policy_allows),
104    codeForEvalGets: Some(code_for_eval_gets),
105    subsumes: Some(principals::subsumes),
106};
107
108#[derive(Clone, Copy, Debug, Eq, Hash, JSTraceable, MallocSizeOf, PartialEq)]
109pub(crate) enum ScriptThreadEventCategory {
110    SpawnPipeline,
111    ConstellationMsg,
112    DatabaseAccessEvent,
113    DevtoolsMsg,
114    DocumentEvent,
115    FileRead,
116    FontLoading,
117    FormPlannedNavigation,
118    GeolocationEvent,
119    ImageCacheMsg,
120    InputEvent,
121    NavigationAndTraversalEvent,
122    NetworkEvent,
123    PortMessage,
124    Rendering,
125    Resize,
126    ScriptEvent,
127    SetScrollState,
128    SetViewport,
129    StylesheetLoad,
130    TimerEvent,
131    UpdateReplacedElement,
132    WebSocketEvent,
133    WorkerEvent,
134    WorkletEvent,
135    ServiceWorkerEvent,
136    EnterFullscreen,
137    ExitFullscreen,
138    PerformanceTimelineTask,
139    #[cfg(feature = "webgpu")]
140    WebGPUMsg,
141}
142
143impl From<ScriptThreadEventCategory> for ProfilerCategory {
144    fn from(category: ScriptThreadEventCategory) -> Self {
145        match category {
146            ScriptThreadEventCategory::SpawnPipeline => ProfilerCategory::ScriptSpawnPipeline,
147            ScriptThreadEventCategory::ConstellationMsg => ProfilerCategory::ScriptConstellationMsg,
148            ScriptThreadEventCategory::DatabaseAccessEvent => {
149                ProfilerCategory::ScriptDatabaseAccessEvent
150            },
151            ScriptThreadEventCategory::DevtoolsMsg => ProfilerCategory::ScriptDevtoolsMsg,
152            ScriptThreadEventCategory::DocumentEvent => ProfilerCategory::ScriptDocumentEvent,
153            ScriptThreadEventCategory::EnterFullscreen => ProfilerCategory::ScriptEnterFullscreen,
154            ScriptThreadEventCategory::ExitFullscreen => ProfilerCategory::ScriptExitFullscreen,
155            ScriptThreadEventCategory::FileRead => ProfilerCategory::ScriptFileRead,
156            ScriptThreadEventCategory::FontLoading => ProfilerCategory::ScriptFontLoading,
157            ScriptThreadEventCategory::FormPlannedNavigation => {
158                ProfilerCategory::ScriptPlannedNavigation
159            },
160            ScriptThreadEventCategory::GeolocationEvent => ProfilerCategory::ScriptGeolocationEvent,
161            ScriptThreadEventCategory::NavigationAndTraversalEvent => {
162                ProfilerCategory::ScriptNavigationAndTraversalEvent
163            },
164            ScriptThreadEventCategory::ImageCacheMsg => ProfilerCategory::ScriptImageCacheMsg,
165            ScriptThreadEventCategory::InputEvent => ProfilerCategory::ScriptInputEvent,
166            ScriptThreadEventCategory::NetworkEvent => ProfilerCategory::ScriptNetworkEvent,
167            ScriptThreadEventCategory::PerformanceTimelineTask => {
168                ProfilerCategory::ScriptPerformanceEvent
169            },
170            ScriptThreadEventCategory::PortMessage => ProfilerCategory::ScriptPortMessage,
171            ScriptThreadEventCategory::Resize => ProfilerCategory::ScriptResize,
172            ScriptThreadEventCategory::Rendering => ProfilerCategory::ScriptRendering,
173            ScriptThreadEventCategory::ScriptEvent => ProfilerCategory::ScriptEvent,
174            ScriptThreadEventCategory::ServiceWorkerEvent => {
175                ProfilerCategory::ScriptServiceWorkerEvent
176            },
177            ScriptThreadEventCategory::SetScrollState => ProfilerCategory::ScriptSetScrollState,
178            ScriptThreadEventCategory::SetViewport => ProfilerCategory::ScriptSetViewport,
179            ScriptThreadEventCategory::StylesheetLoad => ProfilerCategory::ScriptStylesheetLoad,
180            ScriptThreadEventCategory::TimerEvent => ProfilerCategory::ScriptTimerEvent,
181            ScriptThreadEventCategory::UpdateReplacedElement => {
182                ProfilerCategory::ScriptUpdateReplacedElement
183            },
184            ScriptThreadEventCategory::WebSocketEvent => ProfilerCategory::ScriptWebSocketEvent,
185            ScriptThreadEventCategory::WorkerEvent => ProfilerCategory::ScriptWorkerEvent,
186            ScriptThreadEventCategory::WorkletEvent => ProfilerCategory::ScriptWorkletEvent,
187            #[cfg(feature = "webgpu")]
188            ScriptThreadEventCategory::WebGPUMsg => ProfilerCategory::ScriptWebGPUMsg,
189        }
190    }
191}
192
193impl From<ScriptThreadEventCategory> for ScriptHangAnnotation {
194    fn from(category: ScriptThreadEventCategory) -> Self {
195        match category {
196            ScriptThreadEventCategory::SpawnPipeline => ScriptHangAnnotation::SpawnPipeline,
197            ScriptThreadEventCategory::ConstellationMsg => ScriptHangAnnotation::ConstellationMsg,
198            ScriptThreadEventCategory::DatabaseAccessEvent => {
199                ScriptHangAnnotation::DatabaseAccessEvent
200            },
201            ScriptThreadEventCategory::DevtoolsMsg => ScriptHangAnnotation::DevtoolsMsg,
202            ScriptThreadEventCategory::DocumentEvent => ScriptHangAnnotation::DocumentEvent,
203            ScriptThreadEventCategory::InputEvent => ScriptHangAnnotation::InputEvent,
204            ScriptThreadEventCategory::FileRead => ScriptHangAnnotation::FileRead,
205            ScriptThreadEventCategory::FontLoading => ScriptHangAnnotation::FontLoading,
206            ScriptThreadEventCategory::FormPlannedNavigation => {
207                ScriptHangAnnotation::FormPlannedNavigation
208            },
209            ScriptThreadEventCategory::GeolocationEvent => ScriptHangAnnotation::GeolocationEvent,
210            ScriptThreadEventCategory::NavigationAndTraversalEvent => {
211                ScriptHangAnnotation::NavigationAndTraversalEvent
212            },
213            ScriptThreadEventCategory::ImageCacheMsg => ScriptHangAnnotation::ImageCacheMsg,
214            ScriptThreadEventCategory::NetworkEvent => ScriptHangAnnotation::NetworkEvent,
215            ScriptThreadEventCategory::Rendering => ScriptHangAnnotation::Rendering,
216            ScriptThreadEventCategory::Resize => ScriptHangAnnotation::Resize,
217            ScriptThreadEventCategory::ScriptEvent => ScriptHangAnnotation::ScriptEvent,
218            ScriptThreadEventCategory::SetScrollState => ScriptHangAnnotation::SetScrollState,
219            ScriptThreadEventCategory::SetViewport => ScriptHangAnnotation::SetViewport,
220            ScriptThreadEventCategory::StylesheetLoad => ScriptHangAnnotation::StylesheetLoad,
221            ScriptThreadEventCategory::TimerEvent => ScriptHangAnnotation::TimerEvent,
222            ScriptThreadEventCategory::UpdateReplacedElement => {
223                ScriptHangAnnotation::UpdateReplacedElement
224            },
225            ScriptThreadEventCategory::WebSocketEvent => ScriptHangAnnotation::WebSocketEvent,
226            ScriptThreadEventCategory::WorkerEvent => ScriptHangAnnotation::WorkerEvent,
227            ScriptThreadEventCategory::WorkletEvent => ScriptHangAnnotation::WorkletEvent,
228            ScriptThreadEventCategory::ServiceWorkerEvent => {
229                ScriptHangAnnotation::ServiceWorkerEvent
230            },
231            ScriptThreadEventCategory::EnterFullscreen => ScriptHangAnnotation::EnterFullscreen,
232            ScriptThreadEventCategory::ExitFullscreen => ScriptHangAnnotation::ExitFullscreen,
233            ScriptThreadEventCategory::PerformanceTimelineTask => {
234                ScriptHangAnnotation::PerformanceTimelineTask
235            },
236            ScriptThreadEventCategory::PortMessage => ScriptHangAnnotation::PortMessage,
237            #[cfg(feature = "webgpu")]
238            ScriptThreadEventCategory::WebGPUMsg => ScriptHangAnnotation::WebGPUMsg,
239        }
240    }
241}
242
243#[expect(unsafe_code)]
244/// <https://html.spec.whatwg.org/multipage/#the-hostpromiserejectiontracker-implementation>
245unsafe extern "C" fn promise_rejection_tracker(
246    cx: *mut RawJSContext,
247    muted_errors: bool,
248    promise: HandleObject,
249    state: PromiseRejectionHandlingState,
250    _data: *mut c_void,
251) {
252    // Step 1. Let script be the running script.
253    // Step 2. If script is a classic script and script's muted errors is true, then return.
254    if muted_errors {
255        return;
256    }
257
258    // Step 3.
259    // SAFETY: it is safe to construct a JSContext from engine hook.
260    let mut cx = unsafe { JSContext::from_ptr(NonNull::new(cx).unwrap()) };
261    let mut realm = CurrentRealm::assert(&mut cx);
262
263    let global = GlobalScope::from_current_realm(&mut realm);
264    let cx = &mut realm;
265
266    wrap_panic(&mut || {
267        match state {
268            // Step 4.
269            PromiseRejectionHandlingState::Unhandled => {
270                global.add_uncaught_rejection(promise);
271            },
272            // Step 5.
273            PromiseRejectionHandlingState::Handled => {
274                // Step 5-1.
275                if global
276                    .get_uncaught_rejections()
277                    .borrow()
278                    .contains(&Heap::boxed(promise.get()))
279                {
280                    global.remove_uncaught_rejection(promise);
281                    return;
282                }
283
284                // Step 5-2.
285                if !global
286                    .get_consumed_rejections()
287                    .borrow()
288                    .contains(&Heap::boxed(promise.get()))
289                {
290                    return;
291                }
292
293                // Step 5-3.
294                global.remove_consumed_rejection(promise);
295
296                let target = Trusted::new(global.upcast::<EventTarget>());
297                let promise =
298                    Promise::new_with_js_promise(cx, unsafe { Handle::from_raw(promise) });
299                let trusted_promise = TrustedPromise::from(&promise);
300
301                // Step 5-4.
302                global.task_manager().dom_manipulation_task_source().queue(
303                task!(rejection_handled_event: move |cx| {
304                    let target = target.root();
305                    let root_promise = trusted_promise.root(cx);
306
307                    rooted!(&in(cx) let mut reason = UndefinedValue());
308                    unsafe {
309                        JS_GetPromiseResult(root_promise.reflector().get_jsobject(), reason.handle_mut());
310                    }
311
312                    let event = PromiseRejectionEvent::new(
313                        cx,
314                        &target.global(),
315                        atom!("rejectionhandled"),
316                        EventBubbles::DoesNotBubble,
317                        EventCancelable::Cancelable,
318                        &root_promise,
319                        reason.handle(),
320                    );
321
322                    event.upcast::<Event>().fire(cx, &target);
323                })
324                );
325            },
326        };
327    })
328}
329
330#[expect(unsafe_code)]
331fn safely_convert_null_to_string(cx: &JSContext, str_: HandleString) -> DOMString {
332    unsafe {
333        // Non null string is a valid string.
334        DOMString::from_raw_js_string(cx, *str_)
335    }
336    .unwrap_or_default()
337}
338
339#[expect(unsafe_code)]
340unsafe extern "C" fn code_for_eval_gets(
341    cx: *mut RawJSContext,
342    code: HandleObject,
343    code_for_eval: MutableHandleString,
344) -> bool {
345    // SAFETY: We are in SM hook
346    let (mut cx, code) = unsafe {
347        (
348            JSContext::from_ptr(NonNull::new(cx).unwrap()),
349            RustHandleObject::from_raw(code),
350        )
351    };
352    let cx = &mut cx;
353    if let Ok(trusted_script) = root_from_handleobject::<TrustedScript>(cx, code) {
354        let script_str = trusted_script.data().str();
355        let s = js::conversions::Utf8Chars::from(&*script_str);
356        let new_string = unsafe { JS_NewStringCopyUTF8N(cx, &*s as *const _) };
357        code_for_eval.set(new_string);
358    }
359    true
360}
361
362#[expect(unsafe_code)]
363unsafe extern "C" fn content_security_policy_allows(
364    cx: *mut RawJSContext,
365    runtime_code: RuntimeCode,
366    code_string: HandleString,
367    compilation_type: CompilationType,
368    parameter_strings: RawHandle<StackGCVector<*mut JSString>>,
369    body_string: HandleString,
370    parameter_args: RawHandle<StackGCVector<JSVal>>,
371    body_arg: RawHandleValue,
372    can_compile_strings: *mut bool,
373) -> bool {
374    let mut allowed = false;
375    // SAFETY: We are in SM hook
376    let mut cx = unsafe { JSContext::from_ptr(NonNull::new(cx).unwrap()) };
377    let cx = &mut cx;
378    wrap_panic(&mut || {
379        // SpiderMonkey provides null pointer when executing webassembly.
380        let mut realm = CurrentRealm::assert(cx);
381        let global = GlobalScope::from_current_realm(&mut realm);
382        // If we don't have any CSP checks to run, short-circuit all logic here
383        allowed = global.call_on_csp_list(|csp_list| csp_list.is_none()) ||
384            match runtime_code {
385                RuntimeCode::JS => {
386                    let parameter_strings = unsafe { Handle::from_raw(parameter_strings) };
387                    let parameter_strings_length = parameter_strings.len();
388                    let mut parameter_strings_vec =
389                        Vec::with_capacity(parameter_strings_length as usize);
390
391                    for i in 0..parameter_strings_length {
392                        let Some(str_) = parameter_strings.at(i) else {
393                            unreachable!();
394                        };
395                        parameter_strings_vec.push(safely_convert_null_to_string(cx, str_.into()));
396                    }
397
398                    let parameter_args = unsafe { Handle::from_raw(parameter_args) };
399                    let parameter_args_length = parameter_args.len();
400                    let mut parameter_args_vec = Vec::with_capacity(parameter_args_length as usize);
401
402                    for i in 0..parameter_args_length {
403                        let Some(arg) = parameter_args.at(i) else {
404                            unreachable!();
405                        };
406                        let value = arg.into_handle().get();
407                        if value.is_object() {
408                            if let Ok(trusted_script) =
409                                unsafe { root_from_object::<TrustedScript>(cx, value.to_object()) }
410                            {
411                                parameter_args_vec
412                                    .push(TrustedScriptOrString::TrustedScript(trusted_script));
413                            } else {
414                                // It's not a trusted script but a different object. Treat it
415                                // as if it is a string, since we don't need the actual contents
416                                // of the object.
417                                parameter_args_vec
418                                    .push(TrustedScriptOrString::String(DOMString::new()));
419                            }
420                        } else if value.is_string() {
421                            // We don't need to know the specific string, only that it is untrusted
422                            parameter_args_vec
423                                .push(TrustedScriptOrString::String(DOMString::new()));
424                        } else {
425                            unreachable!();
426                        }
427                    }
428
429                    let code_string = safely_convert_null_to_string(cx, code_string);
430                    let body_string = safely_convert_null_to_string(cx, body_string);
431
432                    TrustedScript::can_compile_string_with_trusted_type(
433                        cx,
434                        &global,
435                        code_string,
436                        compilation_type,
437                        parameter_strings_vec,
438                        body_string,
439                        parameter_args_vec,
440                        unsafe { HandleValue::from_raw(body_arg) },
441                    )
442                },
443                RuntimeCode::WASM => global
444                    .call_on_csp_list(|csp_list| csp_list.is_wasm_evaluation_allowed(cx, &global)),
445            };
446    });
447    unsafe { *can_compile_strings = allowed };
448    true
449}
450
451#[expect(unsafe_code)]
452/// <https://html.spec.whatwg.org/multipage/#notify-about-rejected-promises>
453pub(crate) fn notify_about_rejected_promises(cx: &mut JSContext, global: &GlobalScope) {
454    // Step 1. Let list be a clone of global's about-to-be-notified rejected promises list.
455    let uncaught_rejections: Vec<TrustedPromise> = {
456        global
457            .get_uncaught_rejections()
458            .borrow()
459            .iter()
460            .map(|promise| {
461                let promise =
462                    Promise::new_with_js_promise(cx, unsafe { Handle::from_raw(promise.handle()) });
463
464                TrustedPromise::from(&promise)
465            })
466            .collect()
467    };
468    global.get_uncaught_rejections().safe_borrow_mut(cx).clear();
469
470    // Step 2. If list is empty, then return.
471    if uncaught_rejections.is_empty() {
472        return;
473    }
474
475    // Step 3. Empty global's about-to-be-notified rejected promises list.
476    // NOTE: We did this as part of Step 1. using the "drain(..)" call.
477
478    // Step 4. Queue a global task on the DOM manipulation task source given global to run the following step:
479    let target = Trusted::new(global.upcast::<EventTarget>());
480    global.task_manager().dom_manipulation_task_source().queue(
481        task!(unhandled_rejection_event: move |cx| {
482            let target = target.root();
483
484            // Step 4.1 For each promise p of list:
485            for promise in uncaught_rejections {
486                let promise = promise.root(cx);
487
488                // 4.1.1 If p.[[PromiseIsHandled]] is true, then continue.
489                if promise.get_promise_is_handled() {
490                    continue;
491                }
492
493                // Step 4.1.2 Let notCanceled be the result of firing an event named unhandledrejection at global,
494                // using PromiseRejectionEvent, with the cancelable attribute initialized to true,
495                // the promise attribute initialized to p, and the reason attribute initialized to p.[[PromiseResult]].
496                rooted!(&in(cx) let mut reason = UndefinedValue());
497                unsafe {
498                    JS_GetPromiseResult(promise.reflector().get_jsobject(), reason.handle_mut());
499                }
500
501                let event = PromiseRejectionEvent::new(
502                    cx,
503                    &target.global(),
504                    atom!("unhandledrejection"),
505                    EventBubbles::DoesNotBubble,
506                    EventCancelable::Cancelable,
507                    &promise,
508                    reason.handle(),
509                );
510                let not_canceled = event.upcast::<Event>().fire(cx, &target);
511
512                // Step 4.1.3 If notCanceled is true, then the user agent may report
513                // p.[[PromiseResult]] to a developer console.
514                if not_canceled {
515                    let global = target.global();
516                    let reason_string = run_a_script::<DomTypeHolder, _, _>(
517                        cx,
518                        &global,
519                        |cx: &mut JSContext| stringify_handle_value(cx, reason.handle()),
520                    );
521                    Console::internal_error(
522                        cx,
523                        &global,
524                        format!("Unhandled promise rejection: {reason_string}")
525                    );
526                }
527
528                // Step 4.1.4 If p.[[PromiseIsHandled]] is false, then append p to global's outstanding
529                // rejected promises weak set.
530                if !promise.get_promise_is_handled() {
531                    target.global().add_consumed_rejection(promise.reflector().get_jsobject().into_handle());
532                }
533            }
534        })
535    );
536}
537
538/// Data that is sent to SpiderMonkey runtime callbacks as a pointer, which allows access
539/// to the `Runtime` state.
540#[derive(Default, JSTraceable, MallocSizeOf)]
541struct RuntimeCallbackData {
542    script_event_loop_sender: Option<ScriptEventLoopSender>,
543    #[no_trace]
544    #[ignore_malloc_size_of = "ScriptThread measures its own memory itself."]
545    script_thread: Option<Weak<ScriptThread>>,
546}
547
548#[derive(JSTraceable, MallocSizeOf)]
549pub(crate) struct Runtime {
550    #[ignore_malloc_size_of = "Type from mozjs"]
551    rt: RustRuntime,
552    job_queue: JobQueue,
553    /// The data that is set on the SpiderMonkey runtime callbacks as a pointer.
554    runtime_callback_data: Box<RuntimeCallbackData>,
555}
556
557impl Runtime {
558    /// Create a new runtime, optionally with the given [`SendableTaskSource`] for networking.
559    ///
560    /// # Safety
561    ///
562    /// If panicking does not abort the program, any threads with child runtimes will continue
563    /// executing after the thread with the parent runtime panics, but they will be in an
564    /// invalid and undefined state.
565    ///
566    /// This, like many calls to SpiderMoney API, is unsafe.
567    #[expect(unsafe_code)]
568    pub(crate) fn new(main_thread_sender: Option<ScriptEventLoopSender>) -> Runtime {
569        unsafe { Self::new_with_parent(None, main_thread_sender) }
570    }
571
572    #[allow(unsafe_code)]
573    /// ## Safety
574    /// - only one `JSContext` can exist on the thread at a time (see note in [JSContext::from_ptr])
575    /// - the `JSContext` must not outlive the `Runtime`
576    pub(crate) unsafe fn cx(&self) -> JSContext {
577        unsafe { JSContext::from_ptr(RustRuntime::get().unwrap()) }
578    }
579
580    /// Create a new runtime, optionally with the given [`ParentRuntime`] and [`SendableTaskSource`]
581    /// for networking.
582    ///
583    /// # Safety
584    ///
585    /// If panicking does not abort the program, any threads with child runtimes will continue
586    /// executing after the thread with the parent runtime panics, but they will be in an
587    /// invalid and undefined state.
588    ///
589    /// The `parent` pointer in the [`ParentRuntime`] argument must point to a valid object in memory.
590    ///
591    /// This, like many calls to the SpiderMoney API, is unsafe.
592    #[expect(unsafe_code)]
593    pub(crate) unsafe fn new_with_parent(
594        parent: Option<ParentRuntime>,
595        script_event_loop_sender: Option<ScriptEventLoopSender>,
596    ) -> Runtime {
597        let mut runtime = if let Some(parent) = parent {
598            unsafe { RustRuntime::create_with_parent(parent) }
599        } else {
600            RustRuntime::new(current_js_engine_handle())
601        };
602        let cx = runtime.cx();
603
604        let have_event_loop_sender = script_event_loop_sender.is_some();
605        let runtime_callback_data = Box::new(RuntimeCallbackData {
606            script_event_loop_sender,
607            script_thread: None,
608        });
609        let runtime_callback_data = Box::into_raw(runtime_callback_data);
610
611        unsafe {
612            JS_AddExtraGCRootsTracer(
613                cx,
614                Some(trace_rust_roots),
615                runtime_callback_data as *mut c_void,
616            );
617
618            JS_SetSecurityCallbacks(cx, &SECURITY_CALLBACKS);
619
620            JS_InitDestroyPrincipalsCallback(cx, Some(principals::destroy_servo_jsprincipal));
621            JS_InitReadPrincipalsCallback(cx, Some(principals::read_jsprincipal));
622
623            // Needed for debug assertions about whether GC is running.
624            if cfg!(debug_assertions) {
625                JS_SetGCCallback(cx, Some(debug_gc_callback), ptr::null_mut());
626            }
627
628            if opts::get()
629                .debug
630                .is_enabled(DiagnosticsLoggingOption::GcProfile)
631            {
632                SetGCSliceCallback(cx, Some(gc_slice_callback));
633            }
634        }
635
636        unsafe extern "C" fn empty_wrapper_callback(_: *mut RawJSContext, _: HandleObject) -> bool {
637            true
638        }
639        unsafe extern "C" fn empty_has_released_callback(_: HandleObject) -> bool {
640            // fixme: return true when the Drop impl for a DOM object has been invoked
641            false
642        }
643
644        unsafe {
645            SetDOMCallbacks(cx, &DOM_CALLBACKS);
646            SetPreserveWrapperCallbacks(
647                cx,
648                Some(empty_wrapper_callback),
649                Some(empty_has_released_callback),
650            );
651        }
652
653        unsafe extern "C" fn dispatch_to_event_loop(
654            data: *mut c_void,
655            dispatchable: *mut DispatchablePointer,
656        ) -> bool {
657            let runtime_callback_data: &RuntimeCallbackData =
658                unsafe { &*(data as *mut RuntimeCallbackData) };
659            let Some(script_event_loop_sender) =
660                runtime_callback_data.script_event_loop_sender.as_ref()
661            else {
662                return false;
663            };
664
665            let runnable = Runnable(dispatchable);
666            let task = task!(dispatch_to_event_loop_message: move |cx| {
667                runnable.run(cx, Dispatchable_MaybeShuttingDown::NotShuttingDown);
668            });
669
670            script_event_loop_sender
671                .send(CommonScriptMsg::Task(
672                    ScriptThreadEventCategory::NetworkEvent,
673                    Box::new(task),
674                    None, /* pipeline_id */
675                    TaskSourceName::Networking,
676                ))
677                .is_ok()
678        }
679
680        if have_event_loop_sender {
681            unsafe {
682                SetUpEventLoopDispatch(
683                    cx,
684                    Some(dispatch_to_event_loop),
685                    None,
686                    None,
687                    runtime_callback_data as *mut c_void,
688                );
689            }
690        }
691
692        unsafe {
693            InitConsumeStreamCallback(cx, Some(consume_stream), Some(report_stream_error));
694        }
695
696        let cx_opts;
697        let job_queue;
698        unsafe {
699            let cx = runtime.cx();
700            job_queue = JobQueue::new();
701            job_queue.set_on_context(cx);
702            SetPromiseRejectionTrackerCallback(
703                cx,
704                Some(promise_rejection_tracker),
705                ptr::null_mut(),
706            );
707
708            RegisterScriptEnvironmentPreparer(
709                cx.raw_cx(),
710                Some(invoke_script_environment_preparer),
711            );
712
713            EnsureModuleHooksInitialized(runtime.rt());
714
715            let cx = runtime.cx();
716
717            set_gc_zeal_options(cx.raw_cx());
718
719            // Enable or disable the JITs.
720            cx_opts = &mut *ContextOptionsRef(cx);
721            JS_SetGlobalJitCompilerOption(
722                cx,
723                JSJitCompilerOption::JSJITCOMPILER_BASELINE_INTERPRETER_ENABLE,
724                pref!(js_baseline_interpreter_enabled) as u32,
725            );
726            JS_SetGlobalJitCompilerOption(
727                cx,
728                JSJitCompilerOption::JSJITCOMPILER_BASELINE_ENABLE,
729                pref!(js_baseline_jit_enabled) as u32,
730            );
731            JS_SetGlobalJitCompilerOption(
732                cx,
733                JSJitCompilerOption::JSJITCOMPILER_ION_ENABLE,
734                pref!(js_ion_enabled) as u32,
735            );
736        }
737        cx_opts.compileOptions_.asmJSOption_ = if pref!(js_asmjs_enabled) {
738            AsmJSOption::Enabled
739        } else {
740            AsmJSOption::DisabledByAsmJSPref
741        };
742        let wasm_enabled = pref!(js_wasm_enabled);
743        cx_opts.set_wasm_(wasm_enabled);
744        if wasm_enabled {
745            // If WASM is enabled without setting the buildIdOp,
746            // initializing a module will report an out of memory error.
747            // https://dxr.mozilla.org/mozilla-central/source/js/src/wasm/WasmTypes.cpp#458
748            unsafe { SetProcessBuildIdOp(Some(servo_build_id)) };
749        }
750        cx_opts.set_wasmBaseline_(pref!(js_wasm_baseline_enabled));
751        cx_opts.set_wasmIon_(pref!(js_wasm_ion_enabled));
752
753        unsafe {
754            let cx = runtime.cx();
755            // TODO: handle js.throw_on_asmjs_validation_failure (needs new Spidermonkey)
756            JS_SetGlobalJitCompilerOption(
757                cx,
758                JSJitCompilerOption::JSJITCOMPILER_NATIVE_REGEXP_ENABLE,
759                pref!(js_native_regex_enabled) as u32,
760            );
761            JS_SetOffthreadIonCompilationEnabled(cx, pref!(js_offthread_compilation_enabled));
762            JS_SetGlobalJitCompilerOption(
763                cx,
764                JSJitCompilerOption::JSJITCOMPILER_BASELINE_WARMUP_TRIGGER,
765                if pref!(js_baseline_jit_unsafe_eager_compilation_enabled) {
766                    0
767                } else {
768                    u32::MAX
769                },
770            );
771            JS_SetGlobalJitCompilerOption(
772                cx,
773                JSJitCompilerOption::JSJITCOMPILER_ION_NORMAL_WARMUP_TRIGGER,
774                if pref!(js_ion_unsafe_eager_compilation_enabled) {
775                    0
776                } else {
777                    u32::MAX
778                },
779            );
780            // TODO: handle js.discard_system_source.enabled
781            // TODO: handle js.asyncstack.enabled (needs new Spidermonkey)
782            // TODO: handle js.throw_on_debugee_would_run (needs new Spidermonkey)
783            // TODO: handle js.dump_stack_on_debugee_would_run (needs new Spidermonkey)
784            // TODO: handle js.shared_memory.enabled
785            JS_SetGCParameter(
786                cx,
787                JSGCParamKey::JSGC_MAX_BYTES,
788                in_range(pref!(js_mem_max), 1, 0x100)
789                    .map(|val| (val * 1024 * 1024) as u32)
790                    .unwrap_or(u32::MAX),
791            );
792
793            // Pre-barriers aren't implemented correctly at the moment, so this preference
794            // defaults to false.
795            JS_SetGCParameter(
796                cx,
797                JSGCParamKey::JSGC_INCREMENTAL_GC_ENABLED,
798                pref!(js_mem_gc_incremental_enabled) as u32,
799            );
800
801            JS_SetGCParameter(
802                cx,
803                JSGCParamKey::JSGC_PER_ZONE_GC_ENABLED,
804                pref!(js_mem_gc_per_zone_enabled) as u32,
805            );
806            if let Some(val) = in_range(pref!(js_mem_gc_incremental_slice_ms), 0, 100_000) {
807                JS_SetGCParameter(cx, JSGCParamKey::JSGC_SLICE_TIME_BUDGET_MS, val as u32);
808            }
809            JS_SetGCParameter(
810                cx,
811                JSGCParamKey::JSGC_COMPACTING_ENABLED,
812                pref!(js_mem_gc_compacting_enabled) as u32,
813            );
814
815            if let Some(val) = in_range(pref!(js_mem_gc_high_frequency_time_limit_ms), 0, 10_000) {
816                JS_SetGCParameter(cx, JSGCParamKey::JSGC_HIGH_FREQUENCY_TIME_LIMIT, val as u32);
817            }
818            if let Some(val) = in_range(pref!(js_mem_gc_low_frequency_heap_growth), 0, 10_000) {
819                JS_SetGCParameter(cx, JSGCParamKey::JSGC_LOW_FREQUENCY_HEAP_GROWTH, val as u32);
820            }
821            if let Some(val) = in_range(pref!(js_mem_gc_high_frequency_heap_growth_min), 0, 10_000)
822            {
823                JS_SetGCParameter(
824                    cx,
825                    JSGCParamKey::JSGC_HIGH_FREQUENCY_LARGE_HEAP_GROWTH,
826                    val as u32,
827                );
828            }
829            if let Some(val) = in_range(pref!(js_mem_gc_high_frequency_heap_growth_max), 0, 10_000)
830            {
831                JS_SetGCParameter(
832                    cx,
833                    JSGCParamKey::JSGC_HIGH_FREQUENCY_SMALL_HEAP_GROWTH,
834                    val as u32,
835                );
836            }
837            if let Some(val) = in_range(pref!(js_mem_gc_high_frequency_low_limit_mb), 0, 10_000) {
838                JS_SetGCParameter(cx, JSGCParamKey::JSGC_SMALL_HEAP_SIZE_MAX, val as u32);
839            }
840            if let Some(val) = in_range(pref!(js_mem_gc_high_frequency_high_limit_mb), 0, 10_000) {
841                JS_SetGCParameter(cx, JSGCParamKey::JSGC_LARGE_HEAP_SIZE_MIN, val as u32);
842            }
843            if let Some(val) = in_range(pref!(js_mem_gc_empty_chunk_count_min), 0, 10_000) {
844                JS_SetGCParameter(cx, JSGCParamKey::JSGC_MIN_EMPTY_CHUNK_COUNT, val as u32);
845            }
846            if let Some(val) = in_range(pref!(js_mem_gc_malloc_threshold_base_mb), 0, 10_000) {
847                JS_SetGCParameter(cx, JSGCParamKey::JSGC_MALLOC_THRESHOLD_BASE, val as u32);
848            }
849            if let Some(val) = in_range(pref!(js_mem_gc_urgent_threshold_mb), 0, 10_000) {
850                JS_SetGCParameter(cx, JSGCParamKey::JSGC_URGENT_THRESHOLD_MB, val as u32);
851            }
852        }
853        Runtime {
854            rt: runtime,
855            job_queue,
856            runtime_callback_data: unsafe { Box::from_raw(runtime_callback_data) },
857        }
858    }
859
860    pub(crate) fn set_script_thread(&mut self, script_thread: Weak<ScriptThread>) {
861        self.runtime_callback_data
862            .script_thread
863            .replace(script_thread);
864    }
865
866    pub(crate) fn thread_safe_js_context(&self) -> ThreadSafeJSContext {
867        self.rt.thread_safe_js_context()
868    }
869}
870
871impl Drop for Runtime {
872    fn drop(&mut self) {
873        // Clear our main microtask_queue.
874        job_queue_clear(self.rt.cx_no_gc());
875
876        LivePromiseReferences::destruct();
877        script_bindings::refcounted::LiveDOMReferences::destruct();
878        mark_runtime_dead();
879    }
880}
881
882impl Deref for Runtime {
883    type Target = RustRuntime;
884    fn deref(&self) -> &RustRuntime {
885        &self.rt
886    }
887}
888
889impl DerefMut for Runtime {
890    fn deref_mut(&mut self) -> &mut RustRuntime {
891        &mut self.rt
892    }
893}
894
895fn in_range<T: PartialOrd + Copy>(val: T, min: T, max: T) -> Option<T> {
896    if val < min || val >= max {
897        None
898    } else {
899        Some(val)
900    }
901}
902
903thread_local!(static MALLOC_SIZE_OF_OPS: Cell<*mut MallocSizeOfOps> = const { Cell::new(ptr::null_mut()) });
904
905#[derive(Default)]
906struct InterfaceSizeData {
907    /// How many live instances of this interface exist.
908    count: usize,
909    /// The total number of bytes allocated for instances of this interface.
910    bytes: usize,
911}
912
913struct GlobalSizeData {
914    /// The URL associated with this global.
915    url: ServoUrl,
916    /// A map of WebIDL interface names to size information.
917    interface_sizes: HashMap<&'static str, InterfaceSizeData>,
918    /// Is this global considered dead?
919    is_zombie: bool,
920}
921
922#[derive(Default)]
923/// A map of globals to size information for those globals.
924/// The key is the global's JS reflector pointer as an integer.
925pub(crate) struct PerGlobalInterfaceSizes(HashMap<usize, GlobalSizeData>);
926
927thread_local!(
928    static DOM_OBJECT_SIZES: LazyCell<RefCell<PerGlobalInterfaceSizes>> = const {
929        LazyCell::new(Default::default)
930    }
931);
932
933#[expect(unsafe_code)]
934unsafe extern "C" fn get_size(obj: *mut JSObject) -> usize {
935    let ops = MALLOC_SIZE_OF_OPS.get();
936    ALREADY_COMPUTED_OBJECTS.with(|objects| {
937        let ignored = objects.borrow();
938        DOM_OBJECT_SIZES.with(|dom_sizes| {
939            let mut per_global_interface_sizes = dom_sizes.borrow_mut();
940            compute_size(
941                obj,
942                unsafe { &mut *ops },
943                &ignored,
944                Some(&mut per_global_interface_sizes),
945            )
946        })
947    })
948}
949
950thread_local!(static GC_CYCLE_START: Cell<Option<Instant>> = const { Cell::new(None) });
951thread_local!(static GC_SLICE_START: Cell<Option<Instant>> = const { Cell::new(None) });
952
953#[expect(unsafe_code)]
954unsafe extern "C" fn gc_slice_callback(
955    _cx: *mut RawJSContext,
956    progress: GCProgress,
957    desc: *const GCDescription,
958) {
959    match progress {
960        GCProgress::GC_CYCLE_BEGIN => GC_CYCLE_START.with(|start| {
961            start.set(Some(Instant::now()));
962            println!("GC cycle began");
963        }),
964        GCProgress::GC_SLICE_BEGIN => GC_SLICE_START.with(|start| {
965            start.set(Some(Instant::now()));
966            println!("GC slice began");
967        }),
968        GCProgress::GC_SLICE_END => GC_SLICE_START.with(|start| {
969            let duration = start.get().unwrap().elapsed();
970            start.set(None);
971            println!("GC slice ended: duration={:?}", duration);
972        }),
973        GCProgress::GC_CYCLE_END => GC_CYCLE_START.with(|start| {
974            let duration = start.get().unwrap().elapsed();
975            start.set(None);
976            println!("GC cycle ended: duration={:?}", duration);
977        }),
978    };
979    if !desc.is_null() {
980        let desc: &GCDescription = unsafe { &*desc };
981        let options = match desc.options_ {
982            GCOptions::Normal => "Normal",
983            GCOptions::Shrink => "Shrink",
984            GCOptions::Shutdown => "Shutdown",
985        };
986        println!("  isZone={}, options={}", desc.isZone_, options);
987    }
988    let _ = stdout().flush();
989}
990
991#[expect(unsafe_code)]
992unsafe extern "C" fn debug_gc_callback(
993    _cx: *mut RawJSContext,
994    status: JSGCStatus,
995    _reason: GCReason,
996    _data: *mut os::raw::c_void,
997) {
998    match status {
999        JSGCStatus::JSGC_BEGIN => thread_state::enter(ThreadState::IN_GC),
1000        JSGCStatus::JSGC_END => thread_state::exit(ThreadState::IN_GC),
1001    }
1002}
1003
1004#[expect(unsafe_code)]
1005unsafe extern "C" fn trace_rust_roots(tr: *mut JSTracer, data: *mut os::raw::c_void) {
1006    if !runtime_is_alive() {
1007        return;
1008    }
1009    trace!("starting custom root handler");
1010
1011    let runtime_callback_data = unsafe { &*(data as *const RuntimeCallbackData) };
1012    if let Some(script_thread) = runtime_callback_data
1013        .script_thread
1014        .as_ref()
1015        .and_then(Weak::upgrade)
1016    {
1017        trace!("tracing fields of ScriptThread");
1018        unsafe { script_thread.trace(tr) };
1019    };
1020
1021    unsafe {
1022        trace_roots(tr);
1023        trace_refcounted_objects(tr);
1024        settings_stack::trace(tr);
1025    }
1026    trace!("done custom root handler");
1027}
1028
1029#[expect(unsafe_code)]
1030unsafe extern "C" fn servo_build_id(build_id: *mut BuildIdCharVector) -> bool {
1031    let servo_id = b"Servo\0";
1032    unsafe { SetBuildId(build_id, servo_id[0] as *const c_char, servo_id.len()) }
1033}
1034
1035#[expect(unsafe_code)]
1036#[cfg(feature = "debugmozjs")]
1037unsafe fn set_gc_zeal_options(cx: *mut RawJSContext) {
1038    use js::jsapi::SetGCZeal;
1039
1040    let level = match pref!(js_mem_gc_zeal_level) {
1041        level @ 0..=14 => level as u8,
1042        _ => return,
1043    };
1044    let frequency = match pref!(js_mem_gc_zeal_frequency) {
1045        frequency if frequency >= 0 => frequency as u32,
1046        // https://searchfox.org/mozilla-esr128/source/js/public/GCAPI.h#1392
1047        _ => 5000,
1048    };
1049    unsafe {
1050        SetGCZeal(cx, level, frequency);
1051    }
1052}
1053
1054#[expect(unsafe_code)]
1055#[cfg(not(feature = "debugmozjs"))]
1056unsafe fn set_gc_zeal_options(_: *mut RawJSContext) {}
1057
1058thread_local!(static ALREADY_COMPUTED_OBJECTS: LazyCell<RefCell<HashSet<*const JSObject>>> = const {
1059    LazyCell::new(Default::default)
1060});
1061
1062#[expect(unsafe_code)]
1063pub(crate) fn compute_size(
1064    obj: *mut JSObject,
1065    ops: &mut MallocSizeOfOps,
1066    ignored: &HashSet<*const JSObject>,
1067    per_global_interface_sizes: Option<&mut PerGlobalInterfaceSizes>,
1068) -> usize {
1069    if ignored.contains(&(obj as *const JSObject)) {
1070        return 0;
1071    }
1072
1073    match unsafe { get_dom_class(obj) } {
1074        Ok(v) => {
1075            let dom_object = unsafe { private_from_object(obj) as *const c_void };
1076
1077            if dom_object.is_null() {
1078                return 0;
1079            }
1080            let size = unsafe { (v.malloc_size_of)(&mut *ops, dom_object) };
1081
1082            let Some(per_global_interface_sizes) = per_global_interface_sizes else {
1083                return size;
1084            };
1085
1086            let global = unsafe { js::jsapi::GetNonCCWObjectGlobal(obj) };
1087            let interface = v.interface_chain[v.depth as usize];
1088            let interface_size = per_global_interface_sizes
1089                .0
1090                .entry(global as usize)
1091                .or_insert_with(|| {
1092                    let global = unsafe { GlobalScope::from_object(obj) };
1093                    GlobalSizeData {
1094                        url: global.get_url(),
1095                        interface_sizes: HashMap::new(),
1096                        is_zombie: global
1097                            .downcast::<Window>()
1098                            .is_some_and(|window| !window.is_alive()),
1099                    }
1100                })
1101                .interface_sizes
1102                .entry(interface.into())
1103                .or_default();
1104            interface_size.count += 1;
1105            interface_size.bytes += size;
1106            // Always report a size of zero, since we report this value
1107            // in a separate tree from the main JS heap.
1108            0
1109        },
1110        Err(_e) => 0,
1111    }
1112}
1113
1114#[expect(unsafe_code)]
1115pub(crate) fn get_reports(
1116    cx: &mut JSContext,
1117    path_seg: String,
1118    ops: &mut MallocSizeOfOps,
1119    already_computed_objects: HashSet<*const JSObject>,
1120) -> Vec<Report> {
1121    MALLOC_SIZE_OF_OPS.with(|ops_tls| ops_tls.set(ops));
1122    ALREADY_COMPUTED_OBJECTS.with(|objects| {
1123        *objects.borrow_mut() = already_computed_objects;
1124    });
1125
1126    let stats = unsafe {
1127        let mut stats = ::std::mem::zeroed();
1128        if !CollectServoSizes(cx, &mut stats, Some(get_size)) {
1129            return vec![];
1130        }
1131        stats
1132    };
1133    MALLOC_SIZE_OF_OPS.with(|ops| ops.set(ptr::null_mut()));
1134    ALREADY_COMPUTED_OBJECTS.with(|objects| {
1135        let mut objects = objects.borrow_mut();
1136        objects.clear();
1137        objects.shrink_to_fit();
1138    });
1139
1140    let mut reports = vec![];
1141    let mut report = |mut path_suffix, kind, size| {
1142        let mut path = path![path_seg, "js"];
1143        path.append(&mut path_suffix);
1144        reports.push(Report { path, kind, size })
1145    };
1146
1147    DOM_OBJECT_SIZES.with(|sizes| {
1148        let mut sizes = sizes.borrow_mut();
1149        let mut known_globals = HashMap::new();
1150        for global_size_data in sizes.0.values() {
1151            let url = global_size_data.url.as_str();
1152            let suffix = if global_size_data.is_zombie {
1153                "-zombie"
1154            } else {
1155                ""
1156            };
1157            let index = known_globals.entry(url).or_insert(0);
1158            *index += 1;
1159            for (interface, interface_data) in &global_size_data.interface_sizes {
1160                report(
1161                    path![
1162                        "dom",
1163                        "out-of-tree",
1164                        format!("url({url}){suffix}-{}", *index),
1165                        format!("{interface} [{}]", interface_data.count)
1166                    ],
1167                    ReportKind::ExplicitJemallocHeapSize,
1168                    interface_data.bytes,
1169                );
1170            }
1171        }
1172        sizes.0.clear();
1173    });
1174
1175    // A note about possibly confusing terminology: the JS GC "heap" is allocated via
1176    // mmap/VirtualAlloc, which means it's not on the malloc "heap", so we use
1177    // `ExplicitNonHeapSize` as its kind.
1178    report(
1179        path!["gc-heap", "used"],
1180        ReportKind::ExplicitNonHeapSize,
1181        stats.gcHeapUsed,
1182    );
1183
1184    report(
1185        path!["gc-heap", "unused"],
1186        ReportKind::ExplicitNonHeapSize,
1187        stats.gcHeapUnused,
1188    );
1189
1190    report(
1191        path!["gc-heap", "admin"],
1192        ReportKind::ExplicitNonHeapSize,
1193        stats.gcHeapAdmin,
1194    );
1195
1196    report(
1197        path!["gc-heap", "decommitted"],
1198        ReportKind::ExplicitNonHeapSize,
1199        stats.gcHeapDecommitted,
1200    );
1201
1202    // SpiderMonkey uses the system heap, not jemalloc.
1203    report(
1204        path!["malloc-heap"],
1205        ReportKind::ExplicitSystemHeapSize,
1206        stats.mallocHeap,
1207    );
1208
1209    report(
1210        path!["non-heap"],
1211        ReportKind::ExplicitNonHeapSize,
1212        stats.nonHeap,
1213    );
1214    reports
1215}
1216
1217pub(crate) struct StreamConsumer(*mut JSStreamConsumer);
1218
1219#[expect(unsafe_code)]
1220impl StreamConsumer {
1221    pub(crate) fn consume_chunk(&self, stream: &[u8]) -> bool {
1222        unsafe {
1223            let stream_ptr = stream.as_ptr();
1224            StreamConsumerConsumeChunk(self.0, stream_ptr, stream.len())
1225        }
1226    }
1227
1228    pub(crate) fn stream_end(&self) {
1229        unsafe {
1230            StreamConsumerStreamEnd(self.0);
1231        }
1232    }
1233
1234    pub(crate) fn stream_error(&self, error_code: JSErrNum) {
1235        unsafe {
1236            StreamConsumerStreamError(self.0, error_code as usize);
1237        }
1238    }
1239
1240    pub(crate) fn note_response_urls(
1241        &self,
1242        maybe_url: Option<String>,
1243        maybe_source_map_url: Option<String>,
1244    ) {
1245        unsafe {
1246            let maybe_url = maybe_url.map(|url| CString::new(url).unwrap());
1247            let maybe_source_map_url = maybe_source_map_url.map(|url| CString::new(url).unwrap());
1248
1249            let maybe_url_param = match maybe_url.as_ref() {
1250                Some(url) => url.as_ptr(),
1251                None => ptr::null(),
1252            };
1253            let maybe_source_map_url_param = match maybe_source_map_url.as_ref() {
1254                Some(url) => url.as_ptr(),
1255                None => ptr::null(),
1256            };
1257
1258            StreamConsumerNoteResponseURLs(self.0, maybe_url_param, maybe_source_map_url_param);
1259        }
1260    }
1261}
1262
1263/// Implements the steps to compile webassembly response mentioned here
1264/// <https://webassembly.github.io/spec/web-api/#compile-a-potential-webassembly-response>
1265#[expect(unsafe_code)]
1266unsafe extern "C" fn consume_stream(
1267    cx: *mut RawJSContext,
1268    obj: HandleObject,
1269    _mime_type: MimeType,
1270    consumer: *mut JSStreamConsumer,
1271) -> bool {
1272    let mut cx = unsafe {
1273        // SAFETY: We are in SM hook
1274        JSContext::from_ptr(NonNull::new(cx).expect("JSContext should not be null in SM hook"))
1275    };
1276    let cx = &mut cx;
1277    let mut realm = CurrentRealm::assert(cx);
1278    let global = GlobalScope::from_current_realm(&mut realm);
1279
1280    // Step 2.1 Upon fulfillment of source, store the Response with value unwrappedSource.
1281    if let Ok(unwrapped_source) =
1282        unsafe { root_from_handleobject::<Response>(cx, RustHandleObject::from_raw(obj)) }
1283    {
1284        // Step 2.2 Let mimeType be the result of extracting a MIME type from response’s header list.
1285        let mimetype = unwrapped_source.Headers(cx).extract_mime_type();
1286
1287        // Step 2.3 If mimeType is not `application/wasm`, return with a TypeError and abort these substeps.
1288        if !&mimetype[..].eq_ignore_ascii_case(b"application/wasm") {
1289            throw_dom_exception(
1290                cx,
1291                &global,
1292                Error::Type(c"Response has unsupported MIME type".to_owned()),
1293            );
1294            return false;
1295        }
1296
1297        // Step 2.4 If response is not CORS-same-origin, return with a TypeError and abort these substeps.
1298        match unwrapped_source.Type() {
1299            DOMResponseType::Basic | DOMResponseType::Cors | DOMResponseType::Default => {},
1300            _ => {
1301                throw_dom_exception(
1302                    cx,
1303                    &global,
1304                    Error::Type(c"Response.type must be 'basic', 'cors' or 'default'".to_owned()),
1305                );
1306                return false;
1307            },
1308        }
1309
1310        // Step 2.5 If response’s status is not an ok status, return with a TypeError and abort these substeps.
1311        if !unwrapped_source.Ok() {
1312            throw_dom_exception(
1313                cx,
1314                &global,
1315                Error::Type(c"Response does not have ok status".to_owned()),
1316            );
1317            return false;
1318        }
1319
1320        // Step 2.6.1 If response body is locked, return with a TypeError and abort these substeps.
1321        if unwrapped_source.is_locked() {
1322            throw_dom_exception(
1323                cx,
1324                &global,
1325                Error::Type(c"There was an error consuming the Response".to_owned()),
1326            );
1327            return false;
1328        }
1329
1330        // Step 2.6.2 If response body is alreaady consumed, return with a TypeError and abort these substeps.
1331        if unwrapped_source.is_disturbed() {
1332            throw_dom_exception(
1333                cx,
1334                &global,
1335                Error::Type(c"Response already consumed".to_owned()),
1336            );
1337            return false;
1338        }
1339
1340        let consumer1 = StreamConsumer(consumer);
1341        let Some(body_stream) = unwrapped_source.body() else {
1342            consumer1.stream_end();
1343            return true;
1344        };
1345        let consumer2 = StreamConsumer(consumer);
1346        let aborted = Rc::new(Cell::new(false));
1347        let aborted2 = aborted.clone();
1348        let reader = match body_stream.acquire_default_reader(cx) {
1349            Ok(reader) => reader,
1350            Err(error) => {
1351                throw_dom_exception(cx, &global, error);
1352                return false;
1353            },
1354        };
1355
1356        reader.read_all_bytes(
1357            cx,
1358            Rc::new(move |_cx, bytes| {
1359                if !consumer1.consume_chunk(&bytes) {
1360                    aborted.set(true);
1361                } else {
1362                    consumer1.stream_end();
1363                }
1364            }),
1365            Rc::new(move |_cx, _v| {
1366                if aborted2.get() {
1367                    return;
1368                }
1369                consumer2.stream_error(JSErrNum::JSMSG_WASM_ERROR_CONSUMING_RESPONSE);
1370            }),
1371        );
1372    } else {
1373        // Step 3 Upon rejection of source, return with reason.
1374        throw_dom_exception(
1375            cx,
1376            &global,
1377            Error::Type(c"expected Response or Promise resolving to Response".to_owned()),
1378        );
1379        return false;
1380    }
1381    true
1382}
1383
1384#[expect(unsafe_code)]
1385unsafe extern "C" fn report_stream_error(cx: *mut RawJSContext, error_code: usize) {
1386    let mut cx = unsafe {
1387        // SAFETY: We are in SM hook
1388        JSContext::from_ptr(NonNull::new(cx).expect("JSContext should not be null in SM hook"))
1389    };
1390    let cx = &mut cx;
1391
1392    let mut realm = CurrentRealm::assert(cx);
1393    let global = GlobalScope::from_current_realm(&mut realm);
1394
1395    warn!("Error streaming to StreamConsumer: {:?}", unsafe {
1396        RUST_js_GetErrorMessage(ptr::null_mut(), error_code as u32)
1397    });
1398
1399    throw_dom_exception(
1400        cx,
1401        &global,
1402        Error::Abort(Some("The operation was aborted.".to_owned())),
1403    );
1404}
1405
1406#[expect(unsafe_code)]
1407unsafe extern "C" fn invoke_script_environment_preparer(
1408    global: HandleObject,
1409    closure: *mut ScriptEnvironmentPreparer_Closure,
1410) {
1411    // SAFETY: always safe from a JS engine hook.
1412    let mut cx = unsafe { temp_cx() };
1413    let global = unsafe { GlobalScope::from_object(global.get()) };
1414    let mut realm = enter_auto_realm(&mut cx, &*global);
1415    let cx = &mut realm.current_realm();
1416
1417    run_a_script::<DomTypeHolder, _, _>(cx, &global, |cx| {
1418        if unsafe { !RunScriptEnvironmentPreparerClosure(cx.raw_cx(), closure) } {
1419            report_pending_exception(cx);
1420        };
1421    });
1422}
1423
1424pub(crate) struct Runnable(*mut DispatchablePointer);
1425
1426#[expect(unsafe_code)]
1427unsafe impl Sync for Runnable {}
1428#[expect(unsafe_code)]
1429unsafe impl Send for Runnable {}
1430
1431#[expect(unsafe_code)]
1432impl Runnable {
1433    fn run(&self, cx: &mut JSContext, maybe_shutting_down: Dispatchable_MaybeShuttingDown) {
1434        unsafe {
1435            DispatchableRun(cx, self.0, maybe_shutting_down);
1436        }
1437    }
1438}
1439
1440/// `introductionType` values in SpiderMonkey TransitiveCompileOptions.
1441///
1442/// Value definitions are based on the SpiderMonkey Debugger API docs:
1443/// <https://firefox-source-docs.mozilla.org/js/Debugger/Debugger.Source.html#introductiontype>
1444// TODO: squish `scriptElement` <https://searchfox.org/mozilla-central/rev/202069c4c5113a1a9052d84fa4679d4c1b22113e/devtools/server/actors/source.js#199-201>
1445pub(crate) struct IntroductionType;
1446impl IntroductionType {
1447    /// `introductionType` for code passed to `eval`.
1448    pub const EVAL: &CStr = c"eval";
1449    pub const EVAL_STR: &str = "eval";
1450
1451    /// `introductionType` for code evaluated by debugger.
1452    /// This includes code run via the devtools repl, even if the thread is not paused.
1453    pub const DEBUGGER_EVAL: &CStr = c"debugger eval";
1454    pub const DEBUGGER_EVAL_STR: &str = "debugger eval";
1455
1456    /// `introductionType` for code passed to the `Function` constructor.
1457    pub const FUNCTION: &CStr = c"Function";
1458    pub const FUNCTION_STR: &str = "Function";
1459
1460    /// `introductionType` for code loaded by worklet.
1461    pub const WORKLET: &CStr = c"Worklet";
1462    pub const WORKLET_STR: &str = "Worklet";
1463
1464    /// `introductionType` for code assigned to DOM elements’ event handler IDL attributes as a string.
1465    pub const EVENT_HANDLER: &CStr = c"eventHandler";
1466    pub const EVENT_HANDLER_STR: &str = "eventHandler";
1467
1468    /// `introductionType` for code belonging to `<script src="file.js">` elements.
1469    /// This includes `<script type="module" src="...">`.
1470    pub const SRC_SCRIPT: &CStr = c"srcScript";
1471    pub const SRC_SCRIPT_STR: &str = "srcScript";
1472
1473    /// `introductionType` for code belonging to `<script>code;</script>` elements.
1474    /// This includes `<script type="module" src="...">`.
1475    pub const INLINE_SCRIPT: &CStr = c"inlineScript";
1476    pub const INLINE_SCRIPT_STR: &str = "inlineScript";
1477
1478    /// `introductionType` for code belonging to scripts that *would* be `"inlineScript"` except that they were not
1479    /// part of the initial file itself.
1480    /// For example, scripts created via:
1481    /// - `document.write("<script>code;</script>")`
1482    /// - `var s = document.createElement("script"); s.text = "code";`
1483    pub const INJECTED_SCRIPT: &CStr = c"injectedScript";
1484    pub const INJECTED_SCRIPT_STR: &str = "injectedScript";
1485
1486    /// `introductionType` for code that was loaded indirectly by being imported by another script
1487    /// using ESM static or dynamic imports.
1488    pub const IMPORTED_MODULE: &CStr = c"importedModule";
1489    pub const IMPORTED_MODULE_STR: &str = "importedModule";
1490
1491    /// `introductionType` for code presented in `javascript:` URLs.
1492    pub const JAVASCRIPT_URL: &CStr = c"javascriptURL";
1493    pub const JAVASCRIPT_URL_STR: &str = "javascriptURL";
1494
1495    /// `introductionType` for code passed to `setTimeout`/`setInterval` as a string.
1496    pub const DOM_TIMER: &CStr = c"domTimer";
1497    pub const DOM_TIMER_STR: &str = "domTimer";
1498
1499    /// `introductionType` for web workers.
1500    /// FIXME: only documented in older(?) devtools user docs
1501    /// <https://firefox-source-docs.mozilla.org/devtools-user/debugger-api/debugger.source/index.html>
1502    pub const WORKER: &CStr = c"Worker";
1503    pub const WORKER_STR: &str = "Worker";
1504}