-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathscript_thread.rs
More file actions
4380 lines (4023 loc) · 173 KB
/
script_thread.rs
File metadata and controls
4380 lines (4023 loc) · 173 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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::cell::{Cell, RefCell};
use std::collections::HashSet;
use std::default::Default;
use std::option::Option;
use std::rc::{Rc, Weak};
use std::result::Result;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant, SystemTime};
use background_hang_monitor_api::{
BackgroundHangMonitor, BackgroundHangMonitorExitSignal, BackgroundHangMonitorRegister,
HangAnnotation, MonitoredComponentId, MonitoredComponentType,
};
use chrono::{DateTime, Local};
use crossbeam_channel::unbounded;
use data_url::mime::Mime;
use devtools_traits::{
CSSError, DevtoolScriptControlMsg, DevtoolsPageInfo, NavigationState,
ScriptToDevtoolsControlMsg, WorkerId,
};
use embedder_traits::user_contents::{UserContentManagerId, UserContents, UserScript};
use embedder_traits::{
EmbedderControlId, EmbedderControlResponse, EmbedderMsg, FocusSequenceNumber,
InputEventOutcome, JavaScriptEvaluationError, JavaScriptEvaluationId, MediaSessionActionType,
Theme, ViewportDetails, WebDriverScriptCommand,
};
use encoding_rs::Encoding;
use fonts::{FontContext, SystemFontServiceProxy};
use headers::{HeaderMapExt, LastModified, ReferrerPolicy as ReferrerPolicyHeader};
use http::header::REFRESH;
use hyper_serde::Serde;
use ipc_channel::router::ROUTER;
use js::glue::GetWindowProxyClass;
use js::jsapi::{GCReason, JS_GC, JSContext as UnsafeJSContext};
use js::jsval::UndefinedValue;
use js::rust::ParentRuntime;
use js::rust::wrappers2::{JS_AddInterruptCallback, SetWindowProxyClass};
use layout_api::{LayoutConfig, LayoutFactory, RestyleReason, ScriptThreadFactory};
use media::WindowGLContext;
use metrics::MAX_TASK_NS;
use net_traits::image_cache::{ImageCache, ImageCacheFactory, ImageCacheResponseMessage};
use net_traits::request::{Referrer, RequestId};
use net_traits::response::ResponseInit;
use net_traits::{
FetchMetadata, FetchResponseMsg, Metadata, NetworkError, ResourceFetchTiming, ResourceThreads,
ResourceTimingType,
};
use paint_api::{CrossProcessPaintApi, PinchZoomInfos, PipelineExitSource};
use percent_encoding::percent_decode;
use profile_traits::mem::{ProcessReports, ReportsChan, perform_memory_report};
use profile_traits::time::ProfilerCategory;
use profile_traits::time_profile;
use rustc_hash::{FxHashMap, FxHashSet};
use script_bindings::script_runtime::{JSContext, temp_cx};
use script_traits::{
ConstellationInputEvent, DiscardBrowsingContext, DocumentActivity, InitialScriptState,
NewPipelineInfo, Painter, ProgressiveWebMetricType, ScriptThreadMessage,
UpdatePipelineIdReason,
};
use servo_arc::Arc as ServoArc;
use servo_base::cross_process_instant::CrossProcessInstant;
use servo_base::generic_channel;
use servo_base::generic_channel::GenericSender;
use servo_base::id::{
BrowsingContextId, HistoryStateId, PipelineId, PipelineNamespace, ScriptEventLoopId,
TEST_WEBVIEW_ID, WebViewId,
};
use servo_canvas_traits::webgl::WebGLPipeline;
use servo_config::{opts, pref, prefs};
use servo_constellation_traits::{
LoadData, LoadOrigin, NavigationHistoryBehavior, ScreenshotReadinessResponse,
ScriptToConstellationChan, ScriptToConstellationMessage, ScrollStateUpdate,
StructuredSerializedData, TargetSnapshotParams, TraversalDirection, WindowSizeType,
};
use servo_url::{ImmutableOrigin, MutableOrigin, OriginSnapshot, ServoUrl};
use storage_traits::StorageThreads;
use storage_traits::webstorage_thread::WebStorageType;
use style::context::QuirksMode;
use style::error_reporting::RustLogReporter;
use style::global_style_data::GLOBAL_STYLE_DATA;
use style::media_queries::MediaList;
use style::stylesheets::{AllowImportRules, DocumentStyleSheet, Origin, Stylesheet};
use style::thread_state::{self, ThreadState};
use stylo_atoms::Atom;
use timers::{TimerEventRequest, TimerId, TimerScheduler};
use url::Position;
#[cfg(feature = "webgpu")]
use webgpu_traits::{WebGPUDevice, WebGPUMsg};
use crate::devtools::DevtoolsState;
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, SafeFromJSValConvertible, StringificationBehavior,
};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::DomGlobal;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::csp::{CspReporting, GlobalCspReporting, Violation};
use crate::dom::customelementregistry::{
CallbackReaction, CustomElementDefinition, CustomElementReactionStack,
};
use crate::dom::document::focus::{FocusInitiator, FocusOperation, FocusableArea};
use crate::dom::document::{
Document, DocumentSource, HasBrowsingContext, IsHTMLDocument, RenderingUpdateReason,
};
use crate::dom::element::Element;
use crate::dom::globalscope::GlobalScope;
use crate::dom::html::htmliframeelement::{HTMLIFrameElement, IframeContext, ProcessingMode};
use crate::dom::node::{Node, NodeTraits};
use crate::dom::servoparser::{ParserContext, ServoParser};
use crate::dom::types::DebuggerGlobalScope;
#[cfg(feature = "webgpu")]
use crate::dom::webgpu::identityhub::IdentityHub;
use crate::dom::window::Window;
use crate::dom::windowproxy::{CreatorBrowsingContextInfo, WindowProxy};
use crate::dom::worklet::WorkletThreadPool;
use crate::dom::workletglobalscope::WorkletGlobalScopeInit;
use crate::fetch::FetchCanceller;
use crate::messaging::{
CommonScriptMsg, MainThreadScriptMsg, MixedMessage, ScriptEventLoopSender,
ScriptThreadReceivers, ScriptThreadSenders,
};
use crate::microtask::{Microtask, MicrotaskQueue};
use crate::mime::{APPLICATION, CHARSET, MimeExt, TEXT, XML};
use crate::navigation::{InProgressLoad, NavigationListener};
use crate::network_listener::{FetchResponseListener, submit_timing};
use crate::realms::{enter_auto_realm, enter_realm};
use crate::script_mutation_observers::ScriptMutationObservers;
use crate::script_runtime::{
CanGc, IntroductionType, JSContextHelper, Runtime, ScriptThreadEventCategory,
ThreadSafeJSContext,
};
use crate::script_window_proxies::ScriptWindowProxies;
use crate::task_queue::TaskQueue;
use crate::webdriver_handlers::jsval_to_webdriver;
use crate::{devtools, webdriver_handlers};
thread_local!(static SCRIPT_THREAD_ROOT: Cell<Option<*const ScriptThread>> = const { Cell::new(None) });
fn with_optional_script_thread<R>(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<R: Default>(f: impl FnOnce(&ScriptThread) -> R) -> R {
with_optional_script_thread(|script_thread| script_thread.map(f).unwrap_or_default())
}
// 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(crate) struct IncompleteParserContexts(RefCell<Vec<(PipelineId, ParserContext)>>);
unsafe_no_jsmanaged_fields!(TaskQueue<MainThreadScriptMsg>);
type NodeIdSet = HashSet<String>;
/// A simple guard structure that restore the user interacting state when dropped
#[derive(Default)]
pub(crate) struct ScriptUserInteractingGuard {
was_interacting: bool,
user_interaction_cell: Rc<Cell<bool>>,
}
impl ScriptUserInteractingGuard {
fn new(user_interaction_cell: Rc<Cell<bool>>) -> Self {
let was_interacting = user_interaction_cell.get();
user_interaction_cell.set(true);
Self {
was_interacting,
user_interaction_cell,
}
}
}
impl Drop for ScriptUserInteractingGuard {
fn drop(&mut self) {
self.user_interaction_cell.set(self.was_interacting)
}
}
/// This is the `ScriptThread`'s version of [`UserContents`] with the difference that user
/// stylesheets are represented as parsed `DocumentStyleSheet`s instead of simple source strings.
struct ScriptThreadUserContents {
user_scripts: Rc<Vec<UserScript>>,
user_stylesheets: Rc<Vec<DocumentStyleSheet>>,
}
impl From<UserContents> for ScriptThreadUserContents {
fn from(user_contents: UserContents) -> Self {
let shared_lock = &GLOBAL_STYLE_DATA.shared_lock;
let user_stylesheets = user_contents
.stylesheets
.iter()
.map(|user_stylesheet| {
DocumentStyleSheet(ServoArc::new(Stylesheet::from_str(
user_stylesheet.source(),
user_stylesheet.url().into(),
Origin::User,
ServoArc::new(shared_lock.wrap(MediaList::empty())),
shared_lock.clone(),
None,
Some(&RustLogReporter),
QuirksMode::NoQuirks,
AllowImportRules::Yes,
)))
})
.collect();
Self {
user_scripts: Rc::new(user_contents.scripts),
user_stylesheets: Rc::new(user_stylesheets),
}
}
}
#[derive(JSTraceable)]
// ScriptThread instances are rooted on creation, so this is okay
#[cfg_attr(crown, expect(crown::unrooted_must_root))]
pub struct ScriptThread {
/// A reference to the currently operating `ScriptThread`. This should always be
/// upgradable to an `Rc` as long as the `ScriptThread` is running.
#[no_trace]
this: Weak<ScriptThread>,
/// <https://html.spec.whatwg.org/multipage/#last-render-opportunity-time>
last_render_opportunity_time: Cell<Option<Instant>>,
/// The documents for pipelines managed by this thread
documents: DomRefCell<DocumentCollection>,
/// The window proxies known by this thread
window_proxies: Rc<ScriptWindowProxies>,
/// A list of data pertaining to loads that have not yet received a network response
incomplete_loads: DomRefCell<Vec<InProgressLoad>>,
/// A vector containing parser contexts which have not yet been fully processed
incomplete_parser_contexts: IncompleteParserContexts,
/// An [`ImageCacheFactory`] to use for creating [`ImageCache`]s for all of the
/// child `Pipeline`s.
#[no_trace]
image_cache_factory: Arc<dyn ImageCacheFactory>,
/// A [`ScriptThreadReceivers`] holding all of the incoming `Receiver`s for messages
/// to this [`ScriptThread`].
receivers: ScriptThreadReceivers,
/// A [`ScriptThreadSenders`] that holds all outgoing sending channels necessary to communicate
/// to other parts of Servo.
senders: ScriptThreadSenders,
/// 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,
#[no_trace]
storage_threads: StorageThreads,
/// A queue of tasks to be executed in this script-thread.
task_queue: TaskQueue<MainThreadScriptMsg>,
/// The dedicated means of communication with the background-hang-monitor for this script-thread.
#[no_trace]
background_hang_monitor: Box<dyn BackgroundHangMonitor>,
/// A flag set to `true` by the BHM on exit, and checked from within the interrupt handler.
closing: Arc<AtomicBool>,
/// A [`TimerScheduler`] used to schedule timers for this [`ScriptThread`]. Timers are handled
/// in the [`ScriptThread`] event loop.
#[no_trace]
timer_scheduler: RefCell<TimerScheduler>,
/// A proxy to the `SystemFontService` to use for accessing system font lists.
#[no_trace]
system_font_service: Arc<SystemFontServiceProxy>,
/// The JavaScript runtime.
js_runtime: Rc<Runtime>,
/// List of pipelines that have been owned and closed by this script thread.
#[no_trace]
closed_pipelines: DomRefCell<FxHashSet<PipelineId>>,
/// <https://html.spec.whatwg.org/multipage/#microtask-queue>
microtask_queue: Rc<MicrotaskQueue>,
mutation_observers: Rc<ScriptMutationObservers>,
/// A handle to the WebGL thread
#[no_trace]
webgl_chan: Option<WebGLPipeline>,
/// The WebXR device registry
#[no_trace]
#[cfg(feature = "webxr")]
webxr_registry: Option<webxr_api::Registry>,
/// The worklet thread pool
worklet_thread_pool: DomRefCell<Option<Rc<WorkletThreadPool>>>,
/// 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<FxHashSet<Dom<Document>>>,
/// <https://html.spec.whatwg.org/multipage/#custom-element-reactions-stack>
custom_element_reaction_stack: Rc<CustomElementReactionStack>,
/// Cross-process access to `Paint`'s API.
#[no_trace]
paint_api: CrossProcessPaintApi,
/// Periodically print out on which events script threads spend their processing time.
profile_script_events: bool,
/// Unminify Javascript.
unminify_js: bool,
/// Directory with stored unminified scripts
local_script_source: Option<String>,
/// Unminify Css.
unminify_css: bool,
/// A map from [`UserContentManagerId`] to its [`UserContents`]. This is initialized
/// with a copy of the map in constellation (via the `InitialScriptState`). After that,
/// the constellation forwards any mutations to this `ScriptThread` using messages.
#[no_trace]
user_contents_for_manager_id:
RefCell<FxHashMap<UserContentManagerId, ScriptThreadUserContents>>,
/// Application window's GL Context for Media player
#[no_trace]
player_context: WindowGLContext,
/// A map from pipelines to all owned nodes ever created in this script thread
#[no_trace]
pipeline_to_node_ids: DomRefCell<FxHashMap<PipelineId, NodeIdSet>>,
/// Code is running as a consequence of a user interaction
is_user_interacting: Rc<Cell<bool>>,
/// Identity manager for WebGPU resources
#[no_trace]
#[cfg(feature = "webgpu")]
gpu_id_hub: Arc<IdentityHub>,
/// A factory for making new layouts. This allows layout to depend on script.
#[no_trace]
layout_factory: Arc<dyn LayoutFactory>,
/// The [`TimerId`] of a ScriptThread-scheduled "update the rendering" call, if any.
/// The ScriptThread schedules calls to "update the rendering," but the renderer can
/// also do this when animating. Renderer-based calls always take precedence.
#[no_trace]
scheduled_update_the_rendering: RefCell<Option<TimerId>>,
/// Whether an animation tick or ScriptThread-triggered rendering update is pending. This might
/// either be because the Servo renderer is managing animations and the [`ScriptThread`] has
/// received a [`ScriptThreadMessage::TickAllAnimations`] message, because the [`ScriptThread`]
/// itself is managing animations the timer fired triggering a [`ScriptThread`]-based
/// animation tick, or if there are no animations running and the [`ScriptThread`] has noticed a
/// change that requires a rendering update.
needs_rendering_update: Arc<AtomicBool>,
debugger_global: Dom<DebuggerGlobalScope>,
debugger_paused: Cell<bool>,
/// A list of URLs that can access privileged internal APIs.
#[no_trace]
privileged_urls: Vec<ServoUrl>,
devtools_state: DevtoolsState,
}
struct BHMExitSignal {
closing: Arc<AtomicBool>,
js_context: ThreadSafeJSContext,
}
impl BackgroundHangMonitorExitSignal for BHMExitSignal {
fn signal_to_exit(&self) {
self.closing.store(true, Ordering::SeqCst);
self.js_context.request_interrupt_callback();
}
}
#[expect(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 Drop for ScriptMemoryFailsafe<'_> {
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<dyn LayoutFactory>,
image_cache_factory: Arc<dyn ImageCacheFactory>,
background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
) -> JoinHandle<()> {
// Setup pipeline-namespace-installing for all threads in this process.
// Idempotent in single-process mode.
PipelineNamespace::set_installer_sender(state.namespace_request_sender.clone());
let script_thread_id = state.id;
thread::Builder::new()
.name(format!("Script#{script_thread_id}"))
.spawn(move || {
thread_state::initialize(ThreadState::SCRIPT);
PipelineNamespace::install(state.pipeline_namespace_id);
ScriptEventLoopId::install(state.id);
let memory_profiler_sender = state.memory_profiler_sender.clone();
let reporter_name = format!("script-reporter-{script_thread_id:?}");
let (script_thread, mut cx) = ScriptThread::new(
state,
layout_factory,
image_cache_factory,
background_hang_monitor_register,
);
SCRIPT_THREAD_ROOT.with(|root| {
root.set(Some(Rc::as_ptr(&script_thread)));
});
let mut failsafe = ScriptMemoryFailsafe::new(&script_thread);
memory_profiler_sender.run_with_memory_reporting(
|| script_thread.start(&mut cx),
reporter_name,
ScriptEventLoopSender::MainThread(script_thread.senders.self_sender.clone()),
CommonScriptMsg::CollectReports,
);
// This must always be the very last operation performed before the thread completes
failsafe.neuter();
})
.expect("Thread spawning failed")
}
}
impl ScriptThread {
pub(crate) fn runtime_handle() -> ParentRuntime {
with_optional_script_thread(|script_thread| {
script_thread.unwrap().js_runtime.prepare_for_new_child()
})
}
pub(crate) fn can_continue_running() -> bool {
with_script_thread(|script_thread| script_thread.can_continue_running_inner())
}
pub(crate) fn prepare_for_shutdown() {
with_script_thread(|script_thread| {
script_thread.prepare_for_shutdown_inner();
})
}
pub(crate) fn mutation_observers() -> Rc<ScriptMutationObservers> {
with_script_thread(|script_thread| script_thread.mutation_observers.clone())
}
pub(crate) fn microtask_queue() -> Rc<MicrotaskQueue> {
with_script_thread(|script_thread| script_thread.microtask_queue.clone())
}
pub(crate) 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(crate) fn page_headers_available(
webview_id: WebViewId,
pipeline_id: PipelineId,
metadata: Option<&Metadata>,
origin: MutableOrigin,
cx: &mut js::context::JSContext,
) -> Option<DomRoot<ServoParser>> {
with_script_thread(|script_thread| {
script_thread.handle_page_headers_available(
webview_id,
pipeline_id,
metadata,
origin,
cx,
)
})
}
/// 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(crate) fn process_event(msg: CommonScriptMsg, cx: &mut js::context::JSContext) -> bool {
with_script_thread(|script_thread| {
if !script_thread.can_continue_running_inner() {
return false;
}
script_thread.handle_msg_from_script(MainThreadScriptMsg::Common(msg), cx);
true
})
}
/// Schedule a [`TimerEventRequest`] on this [`ScriptThread`]'s [`TimerScheduler`].
pub(crate) fn schedule_timer(&self, request: TimerEventRequest) -> TimerId {
self.timer_scheduler.borrow_mut().schedule_timer(request)
}
/// Cancel a the [`TimerEventRequest`] for the given [`TimerId`] on this
/// [`ScriptThread`]'s [`TimerScheduler`].
pub(crate) fn cancel_timer(&self, timer_id: TimerId) {
self.timer_scheduler.borrow_mut().cancel_timer(timer_id)
}
// https://html.spec.whatwg.org/multipage/#await-a-stable-state
pub(crate) 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.
///
/// <https://github.com/whatwg/html/issues/2591>
fn check_load_origin(source: &LoadOrigin, target: &OriginSnapshot) -> bool {
match (source, target.immutable()) {
(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.same_origin_domain(target),
}
}
/// Inform the `ScriptThread` that it should make a call to
/// [`ScriptThread::update_the_rendering`] as soon as possible, as the rendering
/// update timer has fired or the renderer has asked us for a new rendering update.
pub(crate) fn set_needs_rendering_update(&self) {
self.needs_rendering_update.store(true, Ordering::Relaxed);
}
/// <https://html.spec.whatwg.org/multipage/#navigate-to-a-javascript:-url>
pub(crate) fn can_navigate_to_javascript_url(
cx: &mut js::context::JSContext,
initiator_global: &GlobalScope,
target_global: &GlobalScope,
load_data: &mut LoadData,
container: Option<&Element>,
) -> bool {
// Step 3. If initiatorOrigin is not same origin-domain with targetNavigable's active document's origin, then return.
//
// Important re security. See https://github.com/servo/servo/issues/23373
if !Self::check_load_origin(&load_data.load_origin, &target_global.origin().snapshot()) {
return false;
}
// Step 5: If the result of should navigation request of type be blocked by
// Content Security Policy? given request and cspNavigationType is "Blocked", then return. [CSP]
if initiator_global
.get_csp_list()
.should_navigation_request_be_blocked(cx, initiator_global, load_data, container)
{
return false;
}
true
}
/// Attempt to navigate a global to a javascript: URL. Returns true if a new document is created.
/// <https://html.spec.whatwg.org/multipage/#navigate-to-a-javascript:-url>
pub(crate) fn navigate_to_javascript_url(
cx: &mut js::context::JSContext,
initiator_global: &GlobalScope,
target_global: &GlobalScope,
load_data: &mut LoadData,
container: Option<&Element>,
initial_insertion: Option<bool>,
) -> bool {
// Step 6. If the result of should navigation request of type be blocked by Content Security Policy? given request and cspNavigationType is "Blocked", then return.
if !Self::can_navigate_to_javascript_url(
cx,
initiator_global,
target_global,
load_data,
container,
) {
return false;
}
// Step 7. Let newDocument be the result of evaluating a javascript: URL given targetNavigable,
// url, initiatorOrigin, and userInvolvement.
let Some(body) = Self::eval_js_url(cx, target_global, &load_data.url) else {
// Step 8. If newDocument is null:
let window_proxy = target_global.as_window().window_proxy();
if let Some(frame_element) = window_proxy
.frame_element()
.and_then(Castable::downcast::<HTMLIFrameElement>)
{
// Step 8.1 If initialInsertion is true and targetNavigable's active document's is initial about:blank is true, then run the iframe load event steps given targetNavigable's container.
if initial_insertion == Some(true) && frame_element.is_initial_blank_document() {
frame_element.run_iframe_load_event_steps(cx);
}
}
// Step 8.2. Return.
return false;
};
// Step 11. of <https://html.spec.whatwg.org/multipage/#evaluate-a-javascript:-url>.
// Let response be a new response with
// URL targetNavigable's active document's URL
// header list « (`Content-Type`, `text/html;charset=utf-8`) »
// body the UTF-8 encoding of result, as a body
load_data.js_eval_result = Some(body);
load_data.url = target_global.get_url();
load_data
.headers
.typed_insert(headers::ContentType::from(mime::TEXT_HTML_UTF_8));
true
}
pub(crate) fn get_top_level_for_browsing_context(
sender_webview_id: WebViewId,
sender_pipeline_id: PipelineId,
browsing_context_id: BrowsingContextId,
) -> Option<WebViewId> {
with_script_thread(|script_thread| {
script_thread.ask_constellation_for_top_level_info(
sender_webview_id,
sender_pipeline_id,
browsing_context_id,
)
})
}
pub(crate) fn find_document(id: PipelineId) -> Option<DomRoot<Document>> {
with_script_thread(|script_thread| script_thread.documents.borrow().find_document(id))
}
/// Creates a guard that sets user_is_interacting to true and returns the
/// state of user_is_interacting on drop of the guard.
/// Notice that you need to use `let _guard = ...` as `let _ = ...` is not enough
#[must_use]
pub(crate) fn user_interacting_guard() -> ScriptUserInteractingGuard {
with_script_thread(|script_thread| {
ScriptUserInteractingGuard::new(script_thread.is_user_interacting.clone())
})
}
pub(crate) fn is_user_interacting() -> bool {
with_script_thread(|script_thread| script_thread.is_user_interacting.get())
}
pub(crate) fn get_fully_active_document_ids(&self) -> FxHashSet<PipelineId> {
self.documents
.borrow()
.iter()
.filter_map(|(id, document)| {
if document.is_fully_active() {
Some(id)
} else {
None
}
})
.fold(FxHashSet::default(), |mut set, id| {
let _ = set.insert(id);
set
})
}
pub(crate) fn window_proxies() -> Rc<ScriptWindowProxies> {
with_script_thread(|script_thread| script_thread.window_proxies.clone())
}
pub(crate) fn find_window_proxy_by_name(name: &DOMString) -> Option<DomRoot<WindowProxy>> {
with_script_thread(|script_thread| {
script_thread.window_proxies.find_window_proxy_by_name(name)
})
}
/// The worklet will use the given `ImageCache`.
pub(crate) fn worklet_thread_pool(image_cache: Arc<dyn ImageCache>) -> Rc<WorkletThreadPool> {
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.senders.self_sender.clone(),
resource_threads: script_thread.resource_threads.clone(),
storage_threads: script_thread.storage_threads.clone(),
mem_profiler_chan: script_thread.senders.memory_profiler_sender.clone(),
time_profiler_chan: script_thread.senders.time_profiler_sender.clone(),
devtools_chan: script_thread.senders.devtools_server_sender.clone(),
to_constellation_sender: script_thread
.senders
.pipeline_to_constellation_sender
.clone(),
to_embedder_sender: script_thread
.senders
.pipeline_to_embedder_sender
.clone(),
image_cache,
#[cfg(feature = "webgpu")]
gpu_id_hub: script_thread.gpu_id_hub.clone(),
};
Rc::new(WorkletThreadPool::spawn(init))
})
.clone()
})
}
fn handle_register_paint_worklet(
&self,
pipeline_id: PipelineId,
name: Atom,
properties: Vec<Atom>,
painter: Box<dyn Painter>,
) {
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(crate) fn custom_element_reaction_stack() -> Rc<CustomElementReactionStack> {
with_optional_script_thread(|script_thread| {
script_thread
.as_ref()
.unwrap()
.custom_element_reaction_stack
.clone()
})
}
pub(crate) fn enqueue_callback_reaction(
element: &Element,
reaction: CallbackReaction,
definition: Option<Rc<CustomElementDefinition>>,
) {
with_script_thread(|script_thread| {
script_thread
.custom_element_reaction_stack
.enqueue_callback_reaction(element, reaction, definition);
})
}
pub(crate) fn enqueue_upgrade_reaction(
element: &Element,
definition: Rc<CustomElementDefinition>,
) {
with_script_thread(|script_thread| {
script_thread
.custom_element_reaction_stack
.enqueue_upgrade_reaction(element, definition);
})
}
pub(crate) fn invoke_backup_element_queue(cx: &mut js::context::JSContext) {
with_script_thread(|script_thread| {
script_thread
.custom_element_reaction_stack
.invoke_backup_element_queue(cx);
})
}
pub(crate) fn save_node_id(pipeline: PipelineId, node_id: String) {
with_script_thread(|script_thread| {
script_thread
.pipeline_to_node_ids
.borrow_mut()
.entry(pipeline)
.or_default()
.insert(node_id);
})
}
pub(crate) fn has_node_id(pipeline: PipelineId, node_id: &str) -> bool {
with_script_thread(|script_thread| {
script_thread
.pipeline_to_node_ids
.borrow()
.get(&pipeline)
.is_some_and(|node_ids| node_ids.contains(node_id))
})
}
/// Creates a new script thread.
pub(crate) fn new(
state: InitialScriptState,
layout_factory: Arc<dyn LayoutFactory>,
image_cache_factory: Arc<dyn ImageCacheFactory>,
background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
) -> (Rc<ScriptThread>, js::context::JSContext) {
let (self_sender, self_receiver) = unbounded();
let mut runtime =
Runtime::new(Some(ScriptEventLoopSender::MainThread(self_sender.clone())));
// SAFETY: We ensure that only one JSContext exists in this thread.
// This is the first one and the only one
let mut cx = unsafe { runtime.cx() };
unsafe {
SetWindowProxyClass(&cx, GetWindowProxyClass());
JS_AddInterruptCallback(&cx, Some(interrupt_callback));
}
let constellation_receiver = state
.constellation_to_script_receiver
.route_preserving_errors();
// Ask the router to proxy IPC messages from the devtools to us.
let devtools_server_sender = state.devtools_server_sender;
let (ipc_devtools_sender, ipc_devtools_receiver) = generic_channel::channel().unwrap();
let devtools_server_receiver = ipc_devtools_receiver.route_preserving_errors();
let task_queue = TaskQueue::new(self_receiver, self_sender.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 = background_hang_monitor_register.register_component(
// TODO: We shouldn't rely on this PipelineId as a ScriptThread can have multiple
// Pipelines and any of them might disappear at any time.
MonitoredComponentId(state.id, MonitoredComponentType::Script),
Duration::from_millis(1000),
Duration::from_millis(5000),
Box::new(background_hang_monitor_exit_signal),
);
let (image_cache_sender, image_cache_receiver) = unbounded();
let receivers = ScriptThreadReceivers {
constellation_receiver,
image_cache_receiver,
devtools_server_receiver,
// Initialized to `never` until WebGPU is initialized.
#[cfg(feature = "webgpu")]
webgpu_receiver: RefCell::new(crossbeam_channel::never()),
};
let opts = opts::get();
let senders = ScriptThreadSenders {
self_sender,
#[cfg(feature = "bluetooth")]
bluetooth_sender: state.bluetooth_sender,
constellation_sender: state.constellation_to_script_sender,
pipeline_to_constellation_sender: state.script_to_constellation_sender,
pipeline_to_embedder_sender: state.script_to_embedder_sender.clone(),
image_cache_sender,
time_profiler_sender: state.time_profiler_sender,
memory_profiler_sender: state.memory_profiler_sender,
devtools_server_sender,
devtools_client_to_script_thread_sender: ipc_devtools_sender,
};
let microtask_queue = runtime.microtask_queue.clone();
#[cfg(feature = "webgpu")]
let gpu_id_hub = Arc::new(IdentityHub::default());
let debugger_pipeline_id = PipelineId::new();
let script_to_constellation_chan = ScriptToConstellationChan {
sender: senders.pipeline_to_constellation_sender.clone(),
// This channel is not expected to be used, so the `WebViewId` that we set here
// does not matter.
// TODO: Look at ways of removing the channel entirely for debugger globals.
webview_id: TEST_WEBVIEW_ID,
pipeline_id: debugger_pipeline_id,
};
let debugger_global = DebuggerGlobalScope::new(
PipelineId::new(),
senders.devtools_server_sender.clone(),
senders.devtools_client_to_script_thread_sender.clone(),
senders.memory_profiler_sender.clone(),
senders.time_profiler_sender.clone(),
script_to_constellation_chan,
senders.pipeline_to_embedder_sender.clone(),
state.resource_threads.clone(),
state.storage_threads.clone(),
#[cfg(feature = "webgpu")]
gpu_id_hub.clone(),
&mut cx,
);
debugger_global.execute(&mut cx);
let user_contents_for_manager_id =
FxHashMap::from_iter(state.user_contents_for_manager_id.into_iter().map(
|(user_content_manager_id, user_contents)| {
(user_content_manager_id, user_contents.into())
},
));
(
Rc::new_cyclic(|weak_script_thread| {
runtime.set_script_thread(weak_script_thread.clone());
Self {
documents: DomRefCell::new(DocumentCollection::default()),
last_render_opportunity_time: Default::default(),
window_proxies: Default::default(),
incomplete_loads: DomRefCell::new(vec![]),
incomplete_parser_contexts: IncompleteParserContexts(RefCell::new(vec![])),
senders,
receivers,
image_cache_factory,
resource_threads: state.resource_threads,
storage_threads: state.storage_threads,
task_queue,
background_hang_monitor,
closing,
timer_scheduler: Default::default(),
microtask_queue,
js_runtime: Rc::new(runtime),
closed_pipelines: DomRefCell::new(FxHashSet::default()),
mutation_observers: Default::default(),
system_font_service: Arc::new(state.system_font_service.to_proxy()),
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(),