/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! The script thread is the thread that owns the DOM in memory, runs JavaScript, and triggers //! layout. It's in charge of processing events for all same-origin pages in a frame //! tree, and manages the entire lifetime of pages in the frame tree from initial request to //! teardown. //! //! Page loads follow a two-step process. When a request for a new page load is received, the //! network request is initiated and the relevant data pertaining to the new page is stashed. //! While the non-blocking request is ongoing, the script thread is free to process further events, //! noting when they pertain to ongoing loads (such as resizes/viewport adjustments). When the //! initial response is received for an ongoing load, the second phase starts - the frame tree //! entry is created, along with the Window and Document objects, and the appropriate parser //! takes over the response body. Once parsing is complete, the document lifecycle for loading //! a page runs its course and the script thread returns to processing events in the main event //! loop. use std::borrow::Cow; use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::default::Default; use std::option::Option; use std::rc::Rc; use std::result::Result; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; use std::time::{Duration, Instant, SystemTime}; use background_hang_monitor_api::{ BackgroundHangMonitor, BackgroundHangMonitorExitSignal, HangAnnotation, MonitoredComponentId, MonitoredComponentType, ScriptHangAnnotation, }; use base::cross_process_instant::CrossProcessInstant; use base::id::{ BrowsingContextId, HistoryStateId, PipelineId, PipelineNamespace, TopLevelBrowsingContextId, }; use base::Epoch; use bluetooth_traits::BluetoothRequest; use canvas_traits::webgl::WebGLPipeline; use chrono::{DateTime, Local}; use crossbeam_channel::{select, unbounded, Receiver, Sender}; use devtools_traits::{ CSSError, DevtoolScriptControlMsg, DevtoolsPageInfo, NavigationState, ScriptToDevtoolsControlMsg, WorkerId, }; use embedder_traits::EmbedderMsg; use euclid::default::{Point2D, Rect}; use fonts::SystemFontServiceProxy; use headers::{HeaderMapExt, LastModified, ReferrerPolicy as ReferrerPolicyHeader}; use html5ever::{local_name, namespace_url, ns}; use hyper_serde::Serde; use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::router::ROUTER; use js::glue::GetWindowProxyClass; use js::jsapi::{ JSContext as UnsafeJSContext, JSTracer, JS_AddInterruptCallback, SetWindowProxyClass, }; use js::jsval::UndefinedValue; use js::rust::ParentRuntime; use media::WindowGLContext; use metrics::{PaintTimeMetrics, MAX_TASK_NS}; use mime::{self, Mime}; use net_traits::image_cache::{ImageCache, PendingImageResponse}; use net_traits::request::{ CredentialsMode, Destination, RedirectMode, RequestBuilder, RequestId, RequestMode, }; use net_traits::storage_thread::StorageType; use net_traits::{ FetchMetadata, FetchResponseListener, FetchResponseMsg, Metadata, NetworkError, ResourceFetchTiming, ResourceThreads, ResourceTimingType, }; use percent_encoding::percent_decode; use profile_traits::mem::{self as profile_mem, OpaqueSender, ReportsChan}; use profile_traits::time::{self as profile_time, ProfilerCategory}; use profile_traits::time_profile; use script_layout_interface::{ node_id_from_scroll_id, LayoutConfig, LayoutFactory, ReflowGoal, ScriptThreadFactory, }; use script_traits::webdriver_msg::WebDriverScriptCommand; use script_traits::{ CompositorEvent, ConstellationControlMsg, DiscardBrowsingContext, DocumentActivity, EventResult, InitialScriptState, JsEvalResult, LayoutMsg, LoadData, LoadOrigin, MediaSessionActionType, MouseButton, MouseEventType, NavigationHistoryBehavior, NewLayoutInfo, Painter, ProgressiveWebMetricType, ScriptMsg, ScriptToConstellationChan, ScrollState, StructuredSerializedData, Theme, TimerSchedulerMsg, TouchEventType, TouchId, UntrustedNodeAddress, UpdatePipelineIdReason, WheelDelta, WindowSizeData, WindowSizeType, }; use servo_atoms::Atom; use servo_config::opts; use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl}; use style::dom::OpaqueNode; use style::thread_state::{self, ThreadState}; use url::Position; #[cfg(feature = "webgpu")] use webgpu::{WebGPUDevice, WebGPUMsg}; use webrender_api::DocumentId; use webrender_traits::CrossProcessCompositorApi; use crate::document_collection::DocumentCollection; use crate::document_loader::DocumentLoader; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::DocumentBinding::{ DocumentMethods, DocumentReadyState, }; use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::conversions::{ ConversionResult, FromJSValConvertible, StringificationBehavior, }; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::{ Dom, DomRoot, MutNullableDom, RootCollection, ThreadLocalStackRoots, }; use crate::dom::bindings::settings_stack::AutoEntryScript; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::{HashMapTracedValues, JSTraceable}; use crate::dom::customelementregistry::{ CallbackReaction, CustomElementDefinition, CustomElementReactionStack, }; use crate::dom::document::{ Document, DocumentSource, FocusType, HasBrowsingContext, IsHTMLDocument, TouchEventResult, }; use crate::dom::element::Element; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlanchorelement::HTMLAnchorElement; use crate::dom::htmliframeelement::HTMLIFrameElement; use crate::dom::mutationobserver::MutationObserver; use crate::dom::node::{window_from_node, Node, ShadowIncluding}; use crate::dom::performanceentry::PerformanceEntry; use crate::dom::performancepainttiming::PerformancePaintTiming; use crate::dom::serviceworker::TrustedServiceWorkerAddress; use crate::dom::servoparser::{ParserContext, ServoParser}; #[cfg(feature = "webgpu")] use crate::dom::webgpu::identityhub::IdentityHub; use crate::dom::window::Window; use crate::dom::windowproxy::{CreatorBrowsingContextInfo, WindowProxy}; use crate::dom::worker::TrustedWorkerAddress; use crate::dom::worklet::WorkletThreadPool; use crate::dom::workletglobalscope::WorkletGlobalScopeInit; use crate::fetch::FetchCanceller; use crate::microtask::{Microtask, MicrotaskQueue}; use crate::realms::enter_realm; use crate::script_module::ScriptFetchOptions; use crate::script_runtime::{ CanGc, CommonScriptMsg, JSContext, Runtime, ScriptChan, ScriptPort, ScriptThreadEventCategory, ThreadSafeJSContext, }; use crate::task_manager::TaskManager; use crate::task_queue::{QueuedTask, QueuedTaskConversion, TaskQueue}; use crate::task_source::dom_manipulation::DOMManipulationTaskSource; use crate::task_source::file_reading::FileReadingTaskSource; use crate::task_source::gamepad::GamepadTaskSource; use crate::task_source::history_traversal::HistoryTraversalTaskSource; use crate::task_source::media_element::MediaElementTaskSource; use crate::task_source::networking::NetworkingTaskSource; use crate::task_source::performance_timeline::PerformanceTimelineTaskSource; use crate::task_source::port_message::PortMessageQueue; use crate::task_source::remote_event::RemoteEventTaskSource; use crate::task_source::rendering::RenderingTaskSource; use crate::task_source::timer::TimerTaskSource; use crate::task_source::user_interaction::UserInteractionTaskSource; use crate::task_source::websocket::WebsocketTaskSource; use crate::task_source::{TaskSource, TaskSourceName}; use crate::{devtools, webdriver_handlers}; pub type ImageCacheMsg = (PipelineId, PendingImageResponse); thread_local!(static SCRIPT_THREAD_ROOT: Cell> = const { Cell::new(None) }); fn with_optional_script_thread(f: impl FnOnce(Option<&ScriptThread>) -> R) -> R { SCRIPT_THREAD_ROOT.with(|root| { f(root .get() .and_then(|script_thread| unsafe { script_thread.as_ref() })) }) } pub(crate) fn with_script_thread(f: impl FnOnce(&ScriptThread) -> R) -> R { with_optional_script_thread(|script_thread| script_thread.map(f).unwrap_or_default()) } /// # Safety /// /// The `JSTracer` argument must point to a valid `JSTracer` in memory. In addition, /// implementors of this method must ensure that all active objects are properly traced /// or else the garbage collector may end up collecting objects that are still reachable. pub unsafe fn trace_thread(tr: *mut JSTracer) { with_script_thread(|script_thread| { debug!("tracing fields of ScriptThread"); script_thread.trace(tr); }) } /// A document load that is in the process of fetching the requested resource. Contains /// data that will need to be present when the document and frame tree entry are created, /// but is only easily available at initiation of the load and on a push basis (so some /// data will be updated according to future resize events, viewport changes, etc.) #[derive(JSTraceable)] struct InProgressLoad { /// The pipeline which requested this load. #[no_trace] pipeline_id: PipelineId, /// The browsing context being loaded into. #[no_trace] browsing_context_id: BrowsingContextId, /// The top level ancestor browsing context. #[no_trace] top_level_browsing_context_id: TopLevelBrowsingContextId, /// The parent pipeline and frame type associated with this load, if any. #[no_trace] parent_info: Option, /// The opener, if this is an auxiliary. #[no_trace] opener: Option, /// The current window size associated with this pipeline. #[no_trace] window_size: WindowSizeData, /// The activity level of the document (inactive, active or fully active). #[no_trace] activity: DocumentActivity, /// Window is throttled, running timers at a heavily limited rate. throttled: bool, /// The requested URL of the load. #[no_trace] url: ServoUrl, /// The origin for the document #[no_trace] origin: MutableOrigin, /// Timestamp reporting the time when the browser started this load. #[no_trace] navigation_start: CrossProcessInstant, /// For cancelling the fetch canceller: FetchCanceller, /// If inheriting the security context inherited_secure_context: Option, } impl InProgressLoad { /// Create a new InProgressLoad object. #[allow(clippy::too_many_arguments)] fn new( id: PipelineId, browsing_context_id: BrowsingContextId, top_level_browsing_context_id: TopLevelBrowsingContextId, parent_info: Option, opener: Option, window_size: WindowSizeData, url: ServoUrl, origin: MutableOrigin, inherited_secure_context: Option, ) -> InProgressLoad { let navigation_start = CrossProcessInstant::now(); InProgressLoad { pipeline_id: id, browsing_context_id, top_level_browsing_context_id, parent_info, opener, window_size, activity: DocumentActivity::FullyActive, throttled: false, url, origin, navigation_start, canceller: Default::default(), inherited_secure_context, } } } #[derive(Debug)] #[allow(clippy::enum_variant_names)] enum MixedMessage { FromConstellation(ConstellationControlMsg), FromScript(MainThreadScriptMsg), FromDevtools(DevtoolScriptControlMsg), FromImageCache((PipelineId, PendingImageResponse)), #[cfg(feature = "webgpu")] FromWebGPUServer(WebGPUMsg), } /// Messages used to control the script event loop. #[derive(Debug)] pub enum MainThreadScriptMsg { /// Common variants associated with the script messages Common(CommonScriptMsg), /// Notifies the script thread that a new worklet has been loaded, and thus the page should be /// reflowed. WorkletLoaded(PipelineId), /// Notifies the script thread that a new paint worklet has been registered. RegisterPaintWorklet { pipeline_id: PipelineId, name: Atom, properties: Vec, painter: Box, }, /// A task related to a not fully-active document has been throttled. Inactive, /// Wake-up call from the task queue. WakeUp, } impl QueuedTaskConversion for MainThreadScriptMsg { fn task_source_name(&self) -> Option<&TaskSourceName> { let script_msg = match self { MainThreadScriptMsg::Common(script_msg) => script_msg, _ => return None, }; match script_msg { CommonScriptMsg::Task(_category, _boxed, _pipeline_id, task_source) => { Some(task_source) }, _ => None, } } fn pipeline_id(&self) -> Option { let script_msg = match self { MainThreadScriptMsg::Common(script_msg) => script_msg, _ => return None, }; match script_msg { CommonScriptMsg::Task(_category, _boxed, pipeline_id, _task_source) => *pipeline_id, _ => None, } } fn into_queued_task(self) -> Option { let script_msg = match self { MainThreadScriptMsg::Common(script_msg) => script_msg, _ => return None, }; let (category, boxed, pipeline_id, task_source) = match script_msg { CommonScriptMsg::Task(category, boxed, pipeline_id, task_source) => { (category, boxed, pipeline_id, task_source) }, _ => return None, }; Some((None, category, boxed, pipeline_id, task_source)) } fn from_queued_task(queued_task: QueuedTask) -> Self { let (_worker, category, boxed, pipeline_id, task_source) = queued_task; let script_msg = CommonScriptMsg::Task(category, boxed, pipeline_id, task_source); MainThreadScriptMsg::Common(script_msg) } fn inactive_msg() -> Self { MainThreadScriptMsg::Inactive } fn wake_up_msg() -> Self { MainThreadScriptMsg::WakeUp } fn is_wake_up(&self) -> bool { matches!(self, MainThreadScriptMsg::WakeUp) } } impl OpaqueSender for Box { fn send(&self, msg: CommonScriptMsg) { ScriptChan::send(&**self, msg).unwrap(); } } impl ScriptPort for Receiver { fn recv(&self) -> Result { self.recv().map_err(|_| ()) } } impl ScriptPort for Receiver { fn recv(&self) -> Result { match self.recv() { Ok(MainThreadScriptMsg::Common(script_msg)) => Ok(script_msg), Ok(_) => panic!("unexpected main thread event message!"), Err(_) => Err(()), } } } impl ScriptPort for Receiver<(TrustedWorkerAddress, CommonScriptMsg)> { fn recv(&self) -> Result { self.recv().map(|(_, msg)| msg).map_err(|_| ()) } } impl ScriptPort for Receiver<(TrustedWorkerAddress, MainThreadScriptMsg)> { fn recv(&self) -> Result { match self.recv().map(|(_, msg)| msg) { Ok(MainThreadScriptMsg::Common(script_msg)) => Ok(script_msg), Ok(_) => panic!("unexpected main thread event message!"), Err(_) => Err(()), } } } impl ScriptPort for Receiver<(TrustedServiceWorkerAddress, CommonScriptMsg)> { fn recv(&self) -> Result { self.recv().map(|(_, msg)| msg).map_err(|_| ()) } } /// Encapsulates internal communication of shared messages within the script thread. #[derive(JSTraceable)] pub struct SendableMainThreadScriptChan(#[no_trace] pub Sender); impl ScriptChan for SendableMainThreadScriptChan { fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> { self.0.send(msg).map_err(|_| ()) } fn clone(&self) -> Box { Box::new(SendableMainThreadScriptChan((self.0).clone())) } } /// Encapsulates internal communication of main thread messages within the script thread. #[derive(JSTraceable)] pub struct MainThreadScriptChan(#[no_trace] pub Sender); impl ScriptChan for MainThreadScriptChan { fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> { self.0 .send(MainThreadScriptMsg::Common(msg)) .map_err(|_| ()) } fn clone(&self) -> Box { Box::new(MainThreadScriptChan((self.0).clone())) } } impl OpaqueSender for Sender { fn send(&self, msg: CommonScriptMsg) { self.send(MainThreadScriptMsg::Common(msg)).unwrap() } } // We borrow the incomplete parser contexts mutably during parsing, // which is fine except that parsing can trigger evaluation, // which can trigger GC, and so we can end up tracing the script // thread during parsing. For this reason, we don't trace the // incomplete parser contexts during GC. pub struct IncompleteParserContexts(RefCell>); unsafe_no_jsmanaged_fields!(TaskQueue); #[derive(JSTraceable)] // ScriptThread instances are rooted on creation, so this is okay #[allow(crown::unrooted_must_root)] pub struct ScriptThread { /// last_render_opportunity_time: DomRefCell>, /// The documents for pipelines managed by this thread documents: DomRefCell, /// The window proxies known by this thread /// TODO: this map grows, but never shrinks. Issue #15258. window_proxies: DomRefCell>>, /// A list of data pertaining to loads that have not yet received a network response incomplete_loads: DomRefCell>, /// A vector containing parser contexts which have not yet been fully processed incomplete_parser_contexts: IncompleteParserContexts, /// Image cache for this script thread. #[no_trace] image_cache: Arc, /// A handle to the resource thread. This is an `Arc` to avoid running out of file descriptors if /// there are many iframes. #[no_trace] resource_threads: ResourceThreads, /// A handle to the bluetooth thread. #[no_trace] bluetooth_thread: IpcSender, /// A queue of tasks to be executed in this script-thread. task_queue: TaskQueue, /// The dedicated means of communication with the background-hang-monitor for this script-thread. #[no_trace] background_hang_monitor: Box, /// A flag set to `true` by the BHM on exit, and checked from within the interrupt handler. closing: Arc, /// A channel to hand out to script thread-based entities that need to be able to enqueue /// events in the event queue. chan: MainThreadScriptChan, dom_manipulation_task_sender: Box, gamepad_task_sender: Box, #[no_trace] media_element_task_sender: Sender, #[no_trace] user_interaction_task_sender: Sender, networking_task_sender: Box, #[no_trace] history_traversal_task_sender: Sender, file_reading_task_sender: Box, performance_timeline_task_sender: Box, port_message_sender: Box, timer_task_sender: Box, remote_event_task_sender: Box, rendering_task_sender: Box, /// A channel to hand out to threads that need to respond to a message from the script thread. #[no_trace] control_chan: IpcSender, /// The port on which the constellation and layout can communicate with the /// script thread. #[no_trace] control_port: Receiver, /// For communicating load url messages to the constellation #[no_trace] script_sender: IpcSender<(PipelineId, ScriptMsg)>, /// A sender for layout to communicate to the constellation. #[no_trace] layout_to_constellation_chan: IpcSender, /// A proxy to the `SystemFontService` to use for accessing system font lists. #[no_trace] system_font_service: Arc, /// The port on which we receive messages from the image cache #[no_trace] image_cache_port: Receiver, /// The channel on which the image cache can send messages to ourself. #[no_trace] image_cache_channel: Sender, /// For providing contact with the time profiler. #[no_trace] time_profiler_chan: profile_time::ProfilerChan, /// For providing contact with the memory profiler. #[no_trace] mem_profiler_chan: profile_mem::ProfilerChan, /// For providing instructions to an optional devtools server. #[no_trace] devtools_chan: Option>, /// For receiving commands from an optional devtools server. Will be ignored if /// no such server exists. #[no_trace] devtools_port: Receiver, #[no_trace] devtools_sender: IpcSender, /// The JavaScript runtime. js_runtime: Rc, /// The topmost element over the mouse. topmost_mouse_over_target: MutNullableDom, /// List of pipelines that have been owned and closed by this script thread. #[no_trace] closed_pipelines: DomRefCell>, #[no_trace] scheduler_chan: IpcSender, #[no_trace] content_process_shutdown_chan: Sender<()>, /// microtask_queue: Rc, /// Microtask Queue for adding support for mutation observer microtasks mutation_observer_microtask_queued: Cell, /// The unit of related similar-origin browsing contexts' list of MutationObserver objects mutation_observers: DomRefCell>>, /// A handle to the WebGL thread #[no_trace] webgl_chan: Option, /// The WebXR device registry #[no_trace] #[cfg(feature = "webxr")] webxr_registry: Option, /// The worklet thread pool worklet_thread_pool: DomRefCell>>, /// A list of pipelines containing documents that finished loading all their blocking /// resources during a turn of the event loop. docs_with_no_blocking_loads: DomRefCell>>, /// custom_element_reaction_stack: CustomElementReactionStack, /// The Webrender Document ID associated with this thread. #[no_trace] webrender_document: DocumentId, /// Cross-process access to the compositor's API. #[no_trace] compositor_api: CrossProcessCompositorApi, /// Periodically print out on which events script threads spend their processing time. profile_script_events: bool, /// Print Progressive Web Metrics to console. print_pwm: bool, /// Emits notifications when there is a relayout. relayout_event: bool, /// True if it is safe to write to the image. prepare_for_screenshot: bool, /// Unminify Javascript. unminify_js: bool, /// Directory with stored unminified scripts local_script_source: Option, /// Unminify Css. unminify_css: bool, /// Where to load userscripts from, if any. An empty string will load from /// the resources/user-agent-js directory, and if the option isn't passed userscripts /// won't be loaded userscripts_path: Option, /// True if headless mode. headless: bool, /// Replace unpaired surrogates in DOM strings with U+FFFD. /// See replace_surrogates: bool, /// An optional string allowing the user agent to be set for testing. user_agent: Cow<'static, str>, /// Application window's GL Context for Media player #[no_trace] player_context: WindowGLContext, /// A set of all nodes ever created in this script thread node_ids: DomRefCell>, /// Code is running as a consequence of a user interaction is_user_interacting: Cell, /// Identity manager for WebGPU resources #[no_trace] #[cfg(feature = "webgpu")] gpu_id_hub: Arc, /// Receiver to receive commands from optional WebGPU server. #[no_trace] #[cfg(feature = "webgpu")] webgpu_port: RefCell>>, // Secure context inherited_secure_context: Option, /// A factory for making new layouts. This allows layout to depend on script. #[no_trace] layout_factory: Arc, } struct BHMExitSignal { closing: Arc, js_context: ThreadSafeJSContext, } impl BackgroundHangMonitorExitSignal for BHMExitSignal { fn signal_to_exit(&self) { self.closing.store(true, Ordering::SeqCst); self.js_context.request_interrupt_callback(); } } #[allow(unsafe_code)] unsafe extern "C" fn interrupt_callback(_cx: *mut UnsafeJSContext) -> bool { let res = ScriptThread::can_continue_running(); if !res { ScriptThread::prepare_for_shutdown(); } res } /// In the event of thread panic, all data on the stack runs its destructor. However, there /// are no reachable, owning pointers to the DOM memory, so it never gets freed by default /// when the script thread fails. The ScriptMemoryFailsafe uses the destructor bomb pattern /// to forcibly tear down the JS realms for pages associated with the failing ScriptThread. struct ScriptMemoryFailsafe<'a> { owner: Option<&'a ScriptThread>, } impl<'a> ScriptMemoryFailsafe<'a> { fn neuter(&mut self) { self.owner = None; } fn new(owner: &'a ScriptThread) -> ScriptMemoryFailsafe<'a> { ScriptMemoryFailsafe { owner: Some(owner) } } } impl<'a> Drop for ScriptMemoryFailsafe<'a> { #[allow(crown::unrooted_must_root)] fn drop(&mut self) { if let Some(owner) = self.owner { for (_, document) in owner.documents.borrow().iter() { document.window().clear_js_runtime_for_script_deallocation(); } } } } impl ScriptThreadFactory for ScriptThread { fn create( state: InitialScriptState, layout_factory: Arc, system_font_service: Arc, load_data: LoadData, user_agent: Cow<'static, str>, ) { let (script_chan, script_port) = unbounded(); thread::Builder::new() .name(format!("Script{:?}", state.id)) .spawn(move || { thread_state::initialize(ThreadState::SCRIPT | ThreadState::LAYOUT); PipelineNamespace::install(state.pipeline_namespace_id); TopLevelBrowsingContextId::install(state.top_level_browsing_context_id); let roots = RootCollection::new(); let _stack_roots = ThreadLocalStackRoots::new(&roots); let id = state.id; let browsing_context_id = state.browsing_context_id; let top_level_browsing_context_id = state.top_level_browsing_context_id; let parent_info = state.parent_info; let opener = state.opener; let secure = load_data.inherited_secure_context; let mem_profiler_chan = state.mem_profiler_chan.clone(); let window_size = state.window_size; let script_thread = ScriptThread::new( state, script_port, script_chan.clone(), layout_factory, system_font_service, user_agent, ); SCRIPT_THREAD_ROOT.with(|root| { root.set(Some(&script_thread as *const _)); }); let mut failsafe = ScriptMemoryFailsafe::new(&script_thread); let origin = MutableOrigin::new(load_data.url.origin()); let new_load = InProgressLoad::new( id, browsing_context_id, top_level_browsing_context_id, parent_info, opener, window_size, load_data.url.clone(), origin, secure, ); script_thread.pre_page_load(new_load, load_data); let reporter_name = format!("script-reporter-{:?}", id); mem_profiler_chan.run_with_memory_reporting( || { script_thread.start(CanGc::note()); let _ = script_thread.content_process_shutdown_chan.send(()); }, reporter_name, script_chan, CommonScriptMsg::CollectReports, ); // This must always be the very last operation performed before the thread completes failsafe.neuter(); }) .expect("Thread spawning failed"); } } impl ScriptThread { pub fn runtime_handle() -> ParentRuntime { with_optional_script_thread(|script_thread| { script_thread.unwrap().js_runtime.prepare_for_new_child() }) } pub fn can_continue_running() -> bool { with_script_thread(|script_thread| script_thread.can_continue_running_inner()) } pub fn prepare_for_shutdown() { with_script_thread(|script_thread| { script_thread.prepare_for_shutdown_inner(); }) } pub fn set_mutation_observer_microtask_queued(value: bool) { with_script_thread(|script_thread| { script_thread.mutation_observer_microtask_queued.set(value); }) } pub fn is_mutation_observer_microtask_queued() -> bool { with_script_thread(|script_thread| script_thread.mutation_observer_microtask_queued.get()) } pub fn add_mutation_observer(observer: &MutationObserver) { with_script_thread(|script_thread| { script_thread .mutation_observers .borrow_mut() .push(Dom::from_ref(observer)); }) } pub fn get_mutation_observers() -> Vec> { with_script_thread(|script_thread| { script_thread .mutation_observers .borrow() .iter() .map(|o| DomRoot::from_ref(&**o)) .collect() }) } pub fn mark_document_with_no_blocked_loads(doc: &Document) { with_script_thread(|script_thread| { script_thread .docs_with_no_blocking_loads .borrow_mut() .insert(Dom::from_ref(doc)); }) } pub fn page_headers_available( id: &PipelineId, metadata: Option, can_gc: CanGc, ) -> Option> { with_script_thread(|script_thread| { script_thread.handle_page_headers_available(id, metadata, can_gc) }) } /// Process a single event as if it were the next event /// in the queue for this window event-loop. /// Returns a boolean indicating whether further events should be processed. pub fn process_event(msg: CommonScriptMsg) -> bool { with_script_thread(|script_thread| { if !script_thread.can_continue_running_inner() { return false; } script_thread.handle_msg_from_script(MainThreadScriptMsg::Common(msg)); true }) } // https://html.spec.whatwg.org/multipage/#await-a-stable-state pub fn await_stable_state(task: Microtask) { with_script_thread(|script_thread| { script_thread .microtask_queue .enqueue(task, script_thread.get_cx()); }); } /// Check that two origins are "similar enough", /// for now only used to prevent cross-origin JS url evaluation. /// /// pub fn check_load_origin(source: &LoadOrigin, target: &ImmutableOrigin) -> bool { match (source, target) { (LoadOrigin::Constellation, _) | (LoadOrigin::WebDriver, _) => { // Always allow loads initiated by the constellation or webdriver. true }, (_, ImmutableOrigin::Opaque(_)) => { // If the target is opaque, allow. // This covers newly created about:blank auxiliaries, and iframe with no src. // TODO: https://github.com/servo/servo/issues/22879 true }, (LoadOrigin::Script(source_origin), _) => source_origin == target, } } /// Step 13 of pub fn navigate( browsing_context: BrowsingContextId, pipeline_id: PipelineId, mut load_data: LoadData, history_handling: NavigationHistoryBehavior, ) { with_script_thread(|script_thread| { let is_javascript = load_data.url.scheme() == "javascript"; // If resource is a request whose url's scheme is "javascript" // https://html.spec.whatwg.org/multipage/#javascript-protocol if is_javascript { let window = match script_thread.documents.borrow().find_window(pipeline_id) { None => return, Some(window) => window, }; let global = window.upcast::(); let trusted_global = Trusted::new(global); let sender = script_thread.script_sender.clone(); let task = task!(navigate_javascript: move || { // Important re security. See https://github.com/servo/servo/issues/23373 // TODO: check according to https://w3c.github.io/webappsec-csp/#should-block-navigation-request if let Some(window) = trusted_global.root().downcast::() { if ScriptThread::check_load_origin(&load_data.load_origin, &window.get_url().origin()) { ScriptThread::eval_js_url(&trusted_global.root(), &mut load_data, CanGc::note()); sender .send((pipeline_id, ScriptMsg::LoadUrl(load_data, history_handling))) .unwrap(); } } }); global .dom_manipulation_task_source() .queue(task, global.upcast()) .expect("Enqueing navigate js task on the DOM manipulation task source failed"); } else { if let Some(ref sender) = script_thread.devtools_chan { let _ = sender.send(ScriptToDevtoolsControlMsg::Navigate( browsing_context, NavigationState::Start(load_data.url.clone()), )); } script_thread .script_sender .send((pipeline_id, ScriptMsg::LoadUrl(load_data, history_handling))) .expect("Sending a LoadUrl message to the constellation failed"); } }); } pub fn process_attach_layout(new_layout_info: NewLayoutInfo, origin: MutableOrigin) { with_script_thread(|script_thread| { let pipeline_id = Some(new_layout_info.new_pipeline_id); script_thread.profile_event( ScriptThreadEventCategory::AttachLayout, pipeline_id, || { script_thread.handle_new_layout(new_layout_info, origin); }, ) }); } pub fn get_top_level_for_browsing_context( sender_pipeline: PipelineId, browsing_context_id: BrowsingContextId, ) -> Option { with_script_thread(|script_thread| { script_thread.ask_constellation_for_top_level_info(sender_pipeline, browsing_context_id) }) } pub fn find_document(id: PipelineId) -> Option> { with_script_thread(|script_thread| script_thread.documents.borrow().find_document(id)) } pub fn set_user_interacting(interacting: bool) { with_script_thread(|script_thread| { script_thread.is_user_interacting.set(interacting); }); } pub fn is_user_interacting() -> bool { with_script_thread(|script_thread| script_thread.is_user_interacting.get()) } pub fn get_fully_active_document_ids() -> HashSet { with_script_thread(|script_thread| { script_thread .documents .borrow() .iter() .filter_map(|(id, document)| { if document.is_fully_active() { Some(id) } else { None } }) .fold(HashSet::new(), |mut set, id| { let _ = set.insert(id); set }) }) } pub fn find_window_proxy(id: BrowsingContextId) -> Option> { with_script_thread(|script_thread| { script_thread .window_proxies .borrow() .get(&id) .map(|context| DomRoot::from_ref(&**context)) }) } pub fn find_window_proxy_by_name(name: &DOMString) -> Option> { with_script_thread(|script_thread| { for (_, proxy) in script_thread.window_proxies.borrow().iter() { if proxy.get_name() == *name { return Some(DomRoot::from_ref(&**proxy)); } } None }) } pub fn worklet_thread_pool() -> Rc { with_optional_script_thread(|script_thread| { let script_thread = script_thread.unwrap(); script_thread .worklet_thread_pool .borrow_mut() .get_or_insert_with(|| { let init = WorkletGlobalScopeInit { to_script_thread_sender: script_thread.chan.0.clone(), resource_threads: script_thread.resource_threads.clone(), mem_profiler_chan: script_thread.mem_profiler_chan.clone(), time_profiler_chan: script_thread.time_profiler_chan.clone(), devtools_chan: script_thread.devtools_chan.clone(), to_constellation_sender: script_thread.script_sender.clone(), scheduler_chan: script_thread.scheduler_chan.clone(), image_cache: script_thread.image_cache.clone(), is_headless: script_thread.headless, user_agent: script_thread.user_agent.clone(), #[cfg(feature = "webgpu")] gpu_id_hub: script_thread.gpu_id_hub.clone(), inherited_secure_context: script_thread.inherited_secure_context, }; Rc::new(WorkletThreadPool::spawn(init)) }) .clone() }) } fn handle_register_paint_worklet( &self, pipeline_id: PipelineId, name: Atom, properties: Vec, painter: Box, ) { let Some(window) = self.documents.borrow().find_window(pipeline_id) else { warn!("Paint worklet registered after pipeline {pipeline_id} closed."); return; }; window .layout_mut() .register_paint_worklet_modules(name, properties, painter); } pub fn push_new_element_queue() { with_script_thread(|script_thread| { script_thread .custom_element_reaction_stack .push_new_element_queue(); }) } pub fn pop_current_element_queue(can_gc: CanGc) { with_script_thread(|script_thread| { script_thread .custom_element_reaction_stack .pop_current_element_queue(can_gc); }) } pub fn enqueue_callback_reaction( element: &Element, reaction: CallbackReaction, definition: Option>, ) { with_script_thread(|script_thread| { script_thread .custom_element_reaction_stack .enqueue_callback_reaction(element, reaction, definition); }) } pub fn enqueue_upgrade_reaction(element: &Element, definition: Rc) { with_script_thread(|script_thread| { script_thread .custom_element_reaction_stack .enqueue_upgrade_reaction(element, definition); }) } pub fn invoke_backup_element_queue(can_gc: CanGc) { with_script_thread(|script_thread| { script_thread .custom_element_reaction_stack .invoke_backup_element_queue(can_gc); }) } pub fn save_node_id(node_id: String) { with_script_thread(|script_thread| { script_thread.node_ids.borrow_mut().insert(node_id); }) } pub fn has_node_id(node_id: &str) -> bool { with_script_thread(|script_thread| script_thread.node_ids.borrow().contains(node_id)) } /// Creates a new script thread. pub fn new( state: InitialScriptState, port: Receiver, chan: Sender, layout_factory: Arc, system_font_service: Arc, user_agent: Cow<'static, str>, ) -> ScriptThread { let opts = opts::get(); let prepare_for_screenshot = opts.output_file.is_some() || opts.exit_after_load || opts.webdriver_port.is_some(); let boxed_script_sender = Box::new(MainThreadScriptChan(chan.clone())); let runtime = Runtime::new(Some(NetworkingTaskSource( boxed_script_sender.clone(), state.id, ))); let cx = runtime.cx(); unsafe { SetWindowProxyClass(cx, GetWindowProxyClass()); JS_AddInterruptCallback(cx, Some(interrupt_callback)); } // Ask the router to proxy IPC messages from the devtools to us. let (ipc_devtools_sender, ipc_devtools_receiver) = ipc::channel().unwrap(); let devtools_port = ROUTER.route_ipc_receiver_to_new_crossbeam_receiver(ipc_devtools_receiver); let (image_cache_channel, image_cache_port) = unbounded(); let task_queue = TaskQueue::new(port, chan.clone()); let closing = Arc::new(AtomicBool::new(false)); let background_hang_monitor_exit_signal = BHMExitSignal { closing: closing.clone(), js_context: runtime.thread_safe_js_context(), }; let background_hang_monitor = state.background_hang_monitor_register.register_component( MonitoredComponentId(state.id, MonitoredComponentType::Script), Duration::from_millis(1000), Duration::from_millis(5000), Some(Box::new(background_hang_monitor_exit_signal)), ); // Ask the router to proxy IPC messages from the control port to us. let control_port = ROUTER.route_ipc_receiver_to_new_crossbeam_receiver(state.control_port); ScriptThread { documents: DomRefCell::new(DocumentCollection::default()), last_render_opportunity_time: Default::default(), window_proxies: DomRefCell::new(HashMapTracedValues::new()), incomplete_loads: DomRefCell::new(vec![]), incomplete_parser_contexts: IncompleteParserContexts(RefCell::new(vec![])), image_cache: state.image_cache.clone(), image_cache_channel, image_cache_port, resource_threads: state.resource_threads, bluetooth_thread: state.bluetooth_thread, task_queue, background_hang_monitor, closing, chan: MainThreadScriptChan(chan.clone()), dom_manipulation_task_sender: boxed_script_sender.clone(), gamepad_task_sender: boxed_script_sender.clone(), media_element_task_sender: chan.clone(), user_interaction_task_sender: chan.clone(), networking_task_sender: boxed_script_sender.clone(), port_message_sender: boxed_script_sender.clone(), file_reading_task_sender: boxed_script_sender.clone(), performance_timeline_task_sender: boxed_script_sender.clone(), timer_task_sender: boxed_script_sender.clone(), remote_event_task_sender: boxed_script_sender.clone(), rendering_task_sender: boxed_script_sender.clone(), history_traversal_task_sender: chan.clone(), control_chan: state.control_chan, control_port, script_sender: state.script_to_constellation_chan.sender.clone(), time_profiler_chan: state.time_profiler_chan.clone(), mem_profiler_chan: state.mem_profiler_chan, devtools_chan: state.devtools_chan, devtools_port, devtools_sender: ipc_devtools_sender, microtask_queue: runtime.microtask_queue.clone(), js_runtime: Rc::new(runtime), topmost_mouse_over_target: MutNullableDom::new(Default::default()), closed_pipelines: DomRefCell::new(HashSet::new()), scheduler_chan: state.scheduler_chan, content_process_shutdown_chan: state.content_process_shutdown_chan, mutation_observer_microtask_queued: Default::default(), mutation_observers: Default::default(), layout_to_constellation_chan: state.layout_to_constellation_chan, system_font_service, webgl_chan: state.webgl_chan, #[cfg(feature = "webxr")] webxr_registry: state.webxr_registry, worklet_thread_pool: Default::default(), docs_with_no_blocking_loads: Default::default(), custom_element_reaction_stack: CustomElementReactionStack::new(), webrender_document: state.webrender_document, compositor_api: state.compositor_api, profile_script_events: opts.debug.profile_script_events, print_pwm: opts.print_pwm, relayout_event: opts.debug.relayout_event, prepare_for_screenshot, unminify_js: opts.unminify_js, local_script_source: opts.local_script_source.clone(), unminify_css: opts.unminify_css, userscripts_path: opts.userscripts.clone(), headless: opts.headless, replace_surrogates: opts.debug.replace_surrogates, user_agent, player_context: state.player_context, node_ids: Default::default(), is_user_interacting: Cell::new(false), #[cfg(feature = "webgpu")] gpu_id_hub: Arc::new(IdentityHub::default()), #[cfg(feature = "webgpu")] webgpu_port: RefCell::new(None), inherited_secure_context: state.inherited_secure_context, layout_factory, } } #[allow(unsafe_code)] pub fn get_cx(&self) -> JSContext { unsafe { JSContext::from_ptr(self.js_runtime.cx()) } } /// Check if we are closing. fn can_continue_running_inner(&self) -> bool { if self.closing.load(Ordering::SeqCst) { return false; } true } /// We are closing, ensure no script can run and potentially hang. fn prepare_for_shutdown_inner(&self) { let docs = self.documents.borrow(); for (_, document) in docs.iter() { let window = document.window(); window.ignore_all_tasks(); } } /// Starts the script thread. After calling this method, the script thread will loop receiving /// messages on its port. pub fn start(&self, can_gc: CanGc) { debug!("Starting script thread."); while self.handle_msgs(can_gc) { // Go on... debug!("Running script thread."); } debug!("Stopped script thread."); } /// Process a compositor mouse move event. fn process_mouse_move_event( &self, document: &Document, window: &Window, point: Point2D, node_address: Option, pressed_mouse_buttons: u16, can_gc: CanGc, ) { // Get the previous target temporarily let prev_mouse_over_target = self.topmost_mouse_over_target.get(); unsafe { document.handle_mouse_move_event( point, &self.topmost_mouse_over_target, node_address, pressed_mouse_buttons, can_gc, ) } // Short-circuit if nothing changed if self.topmost_mouse_over_target.get() == prev_mouse_over_target { return; } let mut state_already_changed = false; // Notify Constellation about the topmost anchor mouse over target. if let Some(target) = self.topmost_mouse_over_target.get() { if let Some(anchor) = target .upcast::() .inclusive_ancestors(ShadowIncluding::No) .filter_map(DomRoot::downcast::) .next() { let status = anchor .upcast::() .get_attribute(&ns!(), &local_name!("href")) .and_then(|href| { let value = href.value(); let url = document.url(); url.join(&value).map(|url| url.to_string()).ok() }); let event = EmbedderMsg::Status(status); window.send_to_embedder(event); state_already_changed = true; } } // We might have to reset the anchor state if !state_already_changed { if let Some(target) = prev_mouse_over_target { if target .upcast::() .inclusive_ancestors(ShadowIncluding::No) .filter_map(DomRoot::downcast::) .next() .is_some() { let event = EmbedderMsg::Status(None); window.send_to_embedder(event); } } } } /// Process compositor events as part of a "update the rendering task". fn process_pending_compositor_events(&self, pipeline_id: PipelineId, can_gc: CanGc) { let Some(document) = self.documents.borrow().find_document(pipeline_id) else { warn!("Processing pending compositor events for closed pipeline {pipeline_id}."); return; }; // Do not handle events if the BC has been, or is being, discarded if document.window().Closed() { warn!("Compositor event sent to a pipeline with a closed window {pipeline_id}."); return; } ScriptThread::set_user_interacting(true); let window = document.window(); let _realm = enter_realm(document.window()); for event in document.take_pending_compositor_events().into_iter() { match event { CompositorEvent::ResizeEvent(new_size, size_type) => { window.add_resize_event(new_size, size_type); }, CompositorEvent::MouseButtonEvent( event_type, button, point, node_address, point_in_node, pressed_mouse_buttons, ) => { self.handle_mouse_button_event( pipeline_id, event_type, button, point, node_address, point_in_node, pressed_mouse_buttons, can_gc, ); }, CompositorEvent::MouseMoveEvent(point, node_address, pressed_mouse_buttons) => { self.process_mouse_move_event( &document, window, point, node_address, pressed_mouse_buttons, can_gc, ); }, CompositorEvent::TouchEvent(event_type, identifier, point, node_address) => { let touch_result = self.handle_touch_event( pipeline_id, event_type, identifier, point, node_address, can_gc, ); match (event_type, touch_result) { (TouchEventType::Down, TouchEventResult::Processed(handled)) => { let result = if handled { // TODO: Wait to see if preventDefault is called on the first touchmove event. EventResult::DefaultAllowed } else { EventResult::DefaultPrevented }; let message = ScriptMsg::TouchEventProcessed(result); self.script_sender.send((pipeline_id, message)).unwrap(); }, _ => { // TODO: Calling preventDefault on a touchup event should prevent clicks. }, } }, CompositorEvent::WheelEvent(delta, point, node_address) => { self.handle_wheel_event(pipeline_id, delta, point, node_address, can_gc); }, CompositorEvent::KeyboardEvent(key_event) => { document.dispatch_key_event(key_event, can_gc); }, CompositorEvent::IMEDismissedEvent => { document.ime_dismissed(can_gc); }, CompositorEvent::CompositionEvent(composition_event) => { document.dispatch_composition_event(composition_event, can_gc); }, CompositorEvent::GamepadEvent(gamepad_event) => { let global = window.upcast::(); global.handle_gamepad_event(gamepad_event); }, } } ScriptThread::set_user_interacting(false); } /// /// /// Attempt to update the rendering and then do a microtask checkpoint if rendering was actually /// updated. pub(crate) fn update_the_rendering(&self, requested_by_compositor: bool, can_gc: CanGc) { *self.last_render_opportunity_time.borrow_mut() = Some(Instant::now()); if !self.can_continue_running_inner() { return; } // Run rafs for all pipeline, if a raf tick was received for any. // This ensures relative ordering of rafs between parent doc and iframes. let should_run_rafs = self .documents .borrow() .iter() .any(|(_, doc)| doc.has_received_raf_tick()); let any_animations_running = self .documents .borrow() .iter() .any(|(_, document)| document.animations().running_animation_count() != 0); // TODO: The specification says to filter out non-renderable documents, // as well as those for which a rendering update would be unnecessary, // but this isn't happening here. // If we aren't explicitly running rAFs, this update wasn't requested by the compositor, // and we are running animations, then wait until the compositor tells us it is time to // update the rendering via a TickAllAnimations message. if !requested_by_compositor && any_animations_running { return; } // > 2. Let docs be all fully active Document objects whose relevant agent's event loop // > is eventLoop, sorted arbitrarily except that the following conditions must be // > met: // // > Any Document B whose container document is A must be listed after A in the // > list. // // > If there are two documents A and B that both have the same non-null container // > document C, then the order of A and B in the list must match the // > shadow-including tree order of their respective navigable containers in C's // > node tree. // // > In the steps below that iterate over docs, each Document must be processed in // > the order it is found in the list. let documents_in_order = self.documents.borrow().documents_in_order(); // TODO: The specification reads: "for doc in docs" at each step whereas this runs all // steps per doc in docs. Currently `