/
script_thread.rs
3737 lines (3375 loc) · 147 KB
/
script_thread.rs
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 spawns parsing
//! and layout threads. 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 crate::compartments::enter_realm;
use crate::devtools;
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::EventBinding::EventInit;
use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods;
use crate::dom::bindings::codegen::Bindings::TransitionEventBinding::TransitionEventInit;
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::num::Finite;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::ThreadLocalStackRoots;
use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom, RootCollection};
use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::structuredclone::StructuredCloneData;
use crate::dom::bindings::trace::JSTraceable;
use crate::dom::bindings::utils::WRAP_CALLBACKS;
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::event::{Event, EventBubbles, EventCancelable};
use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlanchorelement::HTMLAnchorElement;
use crate::dom::htmliframeelement::{HTMLIFrameElement, NavigationType};
use crate::dom::mutationobserver::MutationObserver;
use crate::dom::node::{
from_untrusted_node_address, window_from_node, Node, NodeDamage, ShadowIncluding,
};
use crate::dom::performanceentry::PerformanceEntry;
use crate::dom::performancepainttiming::PerformancePaintTiming;
use crate::dom::serviceworker::TrustedServiceWorkerAddress;
use crate::dom::serviceworkerregistration::ServiceWorkerRegistration;
use crate::dom::servoparser::{ParserContext, ServoParser};
use crate::dom::transitionevent::TransitionEvent;
use crate::dom::uievent::UIEvent;
use crate::dom::window::{ReflowReason, Window};
use crate::dom::windowproxy::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::script_runtime::{get_reports, new_rt_and_cx, Runtime, ScriptPort};
use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptThreadEventCategory};
use crate::serviceworkerjob::{Job, JobQueue};
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::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::remote_event::RemoteEventTaskSource;
use crate::task_source::user_interaction::UserInteractionTaskSource;
use crate::task_source::websocket::WebsocketTaskSource;
use crate::task_source::TaskSource;
use crate::task_source::TaskSourceName;
use crate::webdriver_handlers;
use bluetooth_traits::BluetoothRequest;
use canvas_traits::webgl::WebGLPipeline;
use crossbeam_channel::{unbounded, Receiver, Sender};
use devtools_traits::CSSError;
use devtools_traits::{DevtoolScriptControlMsg, DevtoolsPageInfo};
use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId};
use embedder_traits::EmbedderMsg;
use euclid::{Point2D, Rect, Vector2D};
use headers::ReferrerPolicy as ReferrerPolicyHeader;
use headers::{HeaderMapExt, LastModified};
use hyper_serde::Serde;
use ipc_channel::ipc::{self, IpcSender};
use ipc_channel::router::ROUTER;
use js::glue::GetWindowProxyClass;
use js::jsapi::{JSContext, JS_SetWrapObjectCallbacks};
use js::jsapi::{JSTracer, SetWindowProxyClass};
use js::jsval::UndefinedValue;
use js::rust::ParentRuntime;
use media::WindowGLContext;
use metrics::{PaintTimeMetrics, MAX_TASK_NS};
use mime::{self, Mime};
use msg::constellation_msg::{
BackgroundHangMonitor, BackgroundHangMonitorRegister, ScriptHangAnnotation,
};
use msg::constellation_msg::{BrowsingContextId, HistoryStateId, PipelineId};
use msg::constellation_msg::{HangAnnotation, MonitoredComponentId, MonitoredComponentType};
use msg::constellation_msg::{PipelineNamespace, TopLevelBrowsingContextId};
use net_traits::image_cache::{ImageCache, PendingImageResponse};
use net_traits::request::{CredentialsMode, Destination, RedirectMode, RequestBuilder};
use net_traits::storage_thread::StorageType;
use net_traits::{FetchMetadata, FetchResponseListener, FetchResponseMsg};
use net_traits::{
Metadata, NetworkError, ReferrerPolicy, ResourceFetchTiming, ResourceThreads,
ResourceTimingType,
};
use profile_traits::mem::{self as profile_mem, OpaqueSender, ReportsChan};
use profile_traits::time::{self as profile_time, profile, ProfilerCategory};
use script_layout_interface::message::{self, LayoutThreadInit, Msg, ReflowGoal};
use script_traits::webdriver_msg::WebDriverScriptCommand;
use script_traits::CompositorEvent::{
CompositionEvent, KeyboardEvent, MouseButtonEvent, MouseMoveEvent, ResizeEvent, TouchEvent,
WheelEvent,
};
use script_traits::{CompositorEvent, ConstellationControlMsg};
use script_traits::{
DiscardBrowsingContext, DocumentActivity, EventResult, HistoryEntryReplacement,
};
use script_traits::{InitialScriptState, JsEvalResult, LayoutMsg, LoadData, LoadOrigin};
use script_traits::{MouseButton, MouseEventType, NewLayoutInfo};
use script_traits::{Painter, ProgressiveWebMetricType, ScriptMsg, ScriptThreadFactory};
use script_traits::{ScriptToConstellationChan, TimerEvent, TimerSchedulerMsg};
use script_traits::{TimerSource, TouchEventType, TouchId, UntrustedNodeAddress, WheelDelta};
use script_traits::{UpdatePipelineIdReason, WindowSizeData, WindowSizeType};
use servo_atoms::Atom;
use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
use std::borrow::Cow;
use std::cell::Cell;
use std::cell::RefCell;
use std::collections::{hash_map, HashMap, HashSet};
use std::default::Default;
use std::ops::Deref;
use std::option::Option;
use std::ptr;
use std::rc::Rc;
use std::result::Result;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::thread;
use std::time::{Duration, SystemTime};
use style::dom::OpaqueNode;
use style::thread_state::{self, ThreadState};
use time::{at_utc, get_time, precise_time_ns, Timespec};
use url::percent_encoding::percent_decode;
use url::Position;
use webrender_api::{DocumentId, RenderApiSender};
use webvr_traits::{WebVREvent, WebVRMsg};
pub type ImageCacheMsg = (PipelineId, PendingImageResponse);
thread_local!(static SCRIPT_THREAD_ROOT: Cell<Option<*const ScriptThread>> = Cell::new(None));
pub unsafe fn trace_thread(tr: *mut JSTracer) {
SCRIPT_THREAD_ROOT.with(|root| {
if let Some(script_thread) = root.get() {
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.
pipeline_id: PipelineId,
/// The browsing context being loaded into.
browsing_context_id: BrowsingContextId,
/// The top level ancestor browsing context.
top_level_browsing_context_id: TopLevelBrowsingContextId,
/// The parent pipeline and frame type associated with this load, if any.
parent_info: Option<PipelineId>,
/// The opener, if this is an auxiliary.
opener: Option<BrowsingContextId>,
/// The current window size associated with this pipeline.
window_size: WindowSizeData,
/// Channel to the layout thread associated with this pipeline.
layout_chan: Sender<message::Msg>,
/// The activity level of the document (inactive, active or fully active).
activity: DocumentActivity,
/// Window is visible.
is_visible: bool,
/// The requested URL of the load.
url: ServoUrl,
/// The origin for the document
origin: MutableOrigin,
/// Timestamp reporting the time when the browser started this load.
navigation_start: u64,
/// High res timestamp reporting the time when the browser started this load.
navigation_start_precise: u64,
/// For cancelling the fetch
canceller: FetchCanceller,
/// Flag for sharing with the layout thread that is not yet created.
layout_is_busy: Arc<AtomicBool>,
}
impl InProgressLoad {
/// Create a new InProgressLoad object.
fn new(
id: PipelineId,
browsing_context_id: BrowsingContextId,
top_level_browsing_context_id: TopLevelBrowsingContextId,
parent_info: Option<PipelineId>,
opener: Option<BrowsingContextId>,
layout_chan: Sender<message::Msg>,
window_size: WindowSizeData,
url: ServoUrl,
origin: MutableOrigin,
layout_is_busy: Arc<AtomicBool>,
) -> InProgressLoad {
let current_time = get_time();
let navigation_start_precise = precise_time_ns();
layout_chan
.send(message::Msg::SetNavigationStart(navigation_start_precise))
.unwrap();
InProgressLoad {
pipeline_id: id,
browsing_context_id: browsing_context_id,
top_level_browsing_context_id: top_level_browsing_context_id,
parent_info: parent_info,
opener: opener,
layout_chan: layout_chan,
window_size: window_size,
activity: DocumentActivity::FullyActive,
is_visible: true,
url: url,
origin: origin,
navigation_start: (current_time.sec * 1000 + current_time.nsec as i64 / 1000000) as u64,
navigation_start_precise: navigation_start_precise,
canceller: Default::default(),
layout_is_busy: layout_is_busy,
}
}
}
#[derive(Debug)]
enum MixedMessage {
FromConstellation(ConstellationControlMsg),
FromScript(MainThreadScriptMsg),
FromDevtools(DevtoolScriptControlMsg),
FromImageCache((PipelineId, PendingImageResponse)),
FromScheduler(TimerEvent),
}
/// 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<Atom>,
painter: Box<dyn Painter>,
},
/// Dispatches a job queue.
DispatchJobQueue { scope_url: ServoUrl },
/// 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<PipelineId> {
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.clone()
},
_ => None,
}
}
fn into_queued_task(self) -> Option<QueuedTask> {
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 {
match self {
MainThreadScriptMsg::WakeUp => true,
_ => false,
}
}
}
impl OpaqueSender<CommonScriptMsg> for Box<dyn ScriptChan + Send> {
fn send(&self, msg: CommonScriptMsg) {
ScriptChan::send(&**self, msg).unwrap();
}
}
impl ScriptPort for Receiver<CommonScriptMsg> {
fn recv(&self) -> Result<CommonScriptMsg, ()> {
self.recv().map_err(|_| ())
}
}
impl ScriptPort for Receiver<MainThreadScriptMsg> {
fn recv(&self) -> Result<CommonScriptMsg, ()> {
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<CommonScriptMsg, ()> {
self.recv().map(|(_, msg)| msg).map_err(|_| ())
}
}
impl ScriptPort for Receiver<(TrustedWorkerAddress, MainThreadScriptMsg)> {
fn recv(&self) -> Result<CommonScriptMsg, ()> {
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<CommonScriptMsg, ()> {
self.recv().map(|(_, msg)| msg).map_err(|_| ())
}
}
/// Encapsulates internal communication of shared messages within the script thread.
#[derive(JSTraceable)]
pub struct SendableMainThreadScriptChan(pub Sender<CommonScriptMsg>);
impl ScriptChan for SendableMainThreadScriptChan {
fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> {
self.0.send(msg).map_err(|_| ())
}
fn clone(&self) -> Box<dyn ScriptChan + Send> {
Box::new(SendableMainThreadScriptChan((&self.0).clone()))
}
}
/// Encapsulates internal communication of main thread messages within the script thread.
#[derive(JSTraceable)]
pub struct MainThreadScriptChan(pub Sender<MainThreadScriptMsg>);
impl ScriptChan for MainThreadScriptChan {
fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> {
self.0
.send(MainThreadScriptMsg::Common(msg))
.map_err(|_| ())
}
fn clone(&self) -> Box<dyn ScriptChan + Send> {
Box::new(MainThreadScriptChan((&self.0).clone()))
}
}
impl OpaqueSender<CommonScriptMsg> for Sender<MainThreadScriptMsg> {
fn send(&self, msg: CommonScriptMsg) {
self.send(MainThreadScriptMsg::Common(msg)).unwrap()
}
}
/// The set of all documents managed by this script thread.
#[derive(JSTraceable)]
#[must_root]
pub struct Documents {
map: HashMap<PipelineId, Dom<Document>>,
}
impl Documents {
pub fn new() -> Documents {
Documents {
map: HashMap::new(),
}
}
pub fn insert(&mut self, pipeline_id: PipelineId, doc: &Document) {
self.map.insert(pipeline_id, Dom::from_ref(doc));
}
pub fn remove(&mut self, pipeline_id: PipelineId) -> Option<DomRoot<Document>> {
self.map
.remove(&pipeline_id)
.map(|ref doc| DomRoot::from_ref(&**doc))
}
pub fn find_document(&self, pipeline_id: PipelineId) -> Option<DomRoot<Document>> {
self.map
.get(&pipeline_id)
.map(|doc| DomRoot::from_ref(&**doc))
}
pub fn find_window(&self, pipeline_id: PipelineId) -> Option<DomRoot<Window>> {
self.find_document(pipeline_id)
.map(|doc| DomRoot::from_ref(doc.window()))
}
pub fn find_global(&self, pipeline_id: PipelineId) -> Option<DomRoot<GlobalScope>> {
self.find_window(pipeline_id)
.map(|window| DomRoot::from_ref(window.upcast()))
}
pub fn find_iframe(
&self,
pipeline_id: PipelineId,
browsing_context_id: BrowsingContextId,
) -> Option<DomRoot<HTMLIFrameElement>> {
self.find_document(pipeline_id)
.and_then(|doc| doc.find_iframe(browsing_context_id))
}
pub fn iter<'a>(&'a self) -> DocumentsIter<'a> {
DocumentsIter {
iter: self.map.iter(),
}
}
}
#[allow(unrooted_must_root)]
pub struct DocumentsIter<'a> {
iter: hash_map::Iter<'a, PipelineId, Dom<Document>>,
}
impl<'a> Iterator for DocumentsIter<'a> {
type Item = (PipelineId, DomRoot<Document>);
fn next(&mut self) -> Option<(PipelineId, DomRoot<Document>)> {
self.iter
.next()
.map(|(id, doc)| (*id, DomRoot::from_ref(&**doc)))
}
}
// 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.
type IncompleteParserContexts = Vec<(PipelineId, ParserContext)>;
unsafe_no_jsmanaged_fields!(RefCell<IncompleteParserContexts>);
unsafe_no_jsmanaged_fields!(TaskQueue<MainThreadScriptMsg>);
unsafe_no_jsmanaged_fields!(dyn BackgroundHangMonitorRegister);
unsafe_no_jsmanaged_fields!(dyn BackgroundHangMonitor);
#[derive(JSTraceable)]
// ScriptThread instances are rooted on creation, so this is okay
#[allow(unrooted_must_root)]
pub struct ScriptThread {
/// The documents for pipelines managed by this thread
documents: DomRefCell<Documents>,
/// The window proxies known by this thread
/// TODO: this map grows, but never shrinks. Issue #15258.
window_proxies: DomRefCell<HashMap<BrowsingContextId, Dom<WindowProxy>>>,
/// 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: RefCell<IncompleteParserContexts>,
/// A map to store service worker registrations for a given origin
registration_map: DomRefCell<HashMap<ServoUrl, Dom<ServiceWorkerRegistration>>>,
/// A job queue for Service Workers keyed by their scope url
job_queue_map: Rc<JobQueue>,
/// Image cache for this script thread.
image_cache: Arc<dyn ImageCache>,
/// A handle to the resource thread. This is an `Arc` to avoid running out of file descriptors if
/// there are many iframes.
resource_threads: ResourceThreads,
/// A handle to the bluetooth thread.
bluetooth_thread: IpcSender<BluetoothRequest>,
/// A queue of tasks to be executed in this script-thread.
task_queue: TaskQueue<MainThreadScriptMsg>,
/// A handle to register associated layout threads for hang-monitoring.
background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
/// The dedicated means of communication with the background-hang-monitor for this script-thread.
background_hang_monitor: Box<dyn BackgroundHangMonitor>,
/// 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<dyn ScriptChan>,
media_element_task_sender: Sender<MainThreadScriptMsg>,
user_interaction_task_sender: Sender<MainThreadScriptMsg>,
networking_task_sender: Box<dyn ScriptChan>,
history_traversal_task_sender: Sender<MainThreadScriptMsg>,
file_reading_task_sender: Box<dyn ScriptChan>,
performance_timeline_task_sender: Box<dyn ScriptChan>,
remote_event_task_sender: Box<dyn ScriptChan>,
/// A channel to hand out to threads that need to respond to a message from the script thread.
control_chan: IpcSender<ConstellationControlMsg>,
/// The port on which the constellation and layout threads can communicate with the
/// script thread.
control_port: Receiver<ConstellationControlMsg>,
/// For communicating load url messages to the constellation
script_sender: IpcSender<(PipelineId, ScriptMsg)>,
/// A sender for new layout threads to communicate to the constellation.
layout_to_constellation_chan: IpcSender<LayoutMsg>,
/// The port on which we receive messages from the image cache
image_cache_port: Receiver<ImageCacheMsg>,
/// The channel on which the image cache can send messages to ourself.
image_cache_channel: Sender<ImageCacheMsg>,
/// For providing contact with the time profiler.
time_profiler_chan: profile_time::ProfilerChan,
/// For providing contact with the memory profiler.
mem_profiler_chan: profile_mem::ProfilerChan,
/// For providing instructions to an optional devtools server.
devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// For receiving commands from an optional devtools server. Will be ignored if
/// no such server exists.
devtools_port: Receiver<DevtoolScriptControlMsg>,
devtools_sender: IpcSender<DevtoolScriptControlMsg>,
/// The JavaScript runtime.
js_runtime: Rc<Runtime>,
/// The topmost element over the mouse.
topmost_mouse_over_target: MutNullableDom<Element>,
/// List of pipelines that have been owned and closed by this script thread.
closed_pipelines: DomRefCell<HashSet<PipelineId>>,
scheduler_chan: IpcSender<TimerSchedulerMsg>,
timer_event_chan: Sender<TimerEvent>,
timer_event_port: Receiver<TimerEvent>,
content_process_shutdown_chan: IpcSender<()>,
/// <https://html.spec.whatwg.org/multipage/#microtask-queue>
microtask_queue: Rc<MicrotaskQueue>,
/// Microtask Queue for adding support for mutation observer microtasks
mutation_observer_microtask_queued: Cell<bool>,
/// The unit of related similar-origin browsing contexts' list of MutationObserver objects
mutation_observers: DomRefCell<Vec<Dom<MutationObserver>>>,
/// A handle to the WebGL thread
webgl_chan: Option<WebGLPipeline>,
/// A handle to the webvr thread, if available
webvr_chan: Option<IpcSender<WebVRMsg>>,
/// The WebXR device registry
webxr_registry: 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<HashSet<Dom<Document>>>,
/// A list of nodes with in-progress CSS transitions, which roots them for the duration
/// of the transition.
transitioning_nodes: DomRefCell<Vec<Dom<Node>>>,
/// <https://html.spec.whatwg.org/multipage/#custom-element-reactions-stack>
custom_element_reaction_stack: CustomElementReactionStack,
/// The Webrender Document ID associated with this thread.
webrender_document: DocumentId,
/// Webrender API sender.
webrender_api_sender: RenderApiSender,
/// 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,
/// 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<String>,
/// True if headless mode.
headless: bool,
/// Replace unpaired surrogates in DOM strings with U+FFFD.
/// See <https://github.com/servo/servo/issues/6564>
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
player_context: WindowGLContext,
}
/// 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 compartments 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(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 {
type Message = message::Msg;
fn create(
state: InitialScriptState,
load_data: LoadData,
profile_script_events: bool,
print_pwm: bool,
relayout_event: bool,
prepare_for_screenshot: bool,
unminify_js: bool,
userscripts_path: Option<String>,
headless: bool,
replace_surrogates: bool,
user_agent: Cow<'static, str>,
) -> (Sender<message::Msg>, Receiver<message::Msg>) {
let (script_chan, script_port) = unbounded();
let (sender, receiver) = unbounded();
let layout_chan = sender.clone();
thread::Builder::new()
.name(format!("ScriptThread {:?}", state.id))
.spawn(move || {
thread_state::initialize(ThreadState::SCRIPT);
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 mem_profiler_chan = state.mem_profiler_chan.clone();
let window_size = state.window_size;
let layout_is_busy = state.layout_is_busy.clone();
let script_thread = ScriptThread::new(
state,
script_port,
script_chan.clone(),
profile_script_events,
print_pwm,
relayout_event,
prepare_for_screenshot,
unminify_js,
userscripts_path,
headless,
replace_surrogates,
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,
layout_chan,
window_size,
load_data.url.clone(),
origin,
layout_is_busy,
);
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();
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");
(sender, receiver)
}
}
impl ScriptThread {
pub fn runtime_handle() -> ParentRuntime {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread.js_runtime.prepare_for_new_child()
})
}
pub unsafe fn note_newly_transitioning_nodes(nodes: Vec<UntrustedNodeAddress>) {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = &*root.get().unwrap();
let js_runtime = script_thread.js_runtime.rt();
let new_nodes = nodes
.into_iter()
.map(|n| Dom::from_ref(&*from_untrusted_node_address(js_runtime, n)));
script_thread
.transitioning_nodes
.borrow_mut()
.extend(new_nodes);
})
}
pub fn set_mutation_observer_microtask_queued(value: bool) {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread.mutation_observer_microtask_queued.set(value);
})
}
pub fn is_mutation_observer_microtask_queued() -> bool {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
return script_thread.mutation_observer_microtask_queued.get();
})
}
pub fn add_mutation_observer(observer: &MutationObserver) {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread
.mutation_observers
.borrow_mut()
.push(Dom::from_ref(observer));
})
}
pub fn get_mutation_observers() -> Vec<DomRoot<MutationObserver>> {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread
.mutation_observers
.borrow()
.iter()
.map(|o| DomRoot::from_ref(&**o))
.collect()
})
}
pub fn mark_document_with_no_blocked_loads(doc: &Document) {
SCRIPT_THREAD_ROOT.with(|root| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*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<Metadata>,
) -> Option<DomRoot<ServoParser>> {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread.handle_page_headers_available(id, metadata)
})
}
#[allow(unrooted_must_root)]
pub fn schedule_job(job: Job) {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
let job_queue = &*script_thread.job_queue_map;
job_queue.schedule_job(job, &script_thread);
});
}
pub fn process_event(msg: CommonScriptMsg) {
SCRIPT_THREAD_ROOT.with(|root| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread.handle_msg_from_script(MainThreadScriptMsg::Common(msg));
}
});
}
// https://html.spec.whatwg.org/multipage/#await-a-stable-state
#[allow(unsafe_code)]
pub fn await_stable_state(task: Microtask) {
SCRIPT_THREAD_ROOT.with(|root| {
if let Some(script_thread) = root.get() {
unsafe {
let 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
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 https://html.spec.whatwg.org/multipage/#navigate
pub fn navigate(
pipeline_id: PipelineId,
mut load_data: LoadData,
replace: HistoryEntryReplacement,
) {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = match root.get() {
None => return,
Some(script) => script,
};
let script_thread = unsafe { &*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::<GlobalScope>();
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::<Window>() {
if ScriptThread::check_load_origin(&load_data.load_origin, &window.get_url().origin()) {
ScriptThread::eval_js_url(&trusted_global.root(), &mut load_data);
sender
.send((pipeline_id, ScriptMsg::LoadUrl(load_data, replace)))
.unwrap();
}
}
});
global
.dom_manipulation_task_source()
.queue(task, global.upcast())
.expect("Enqueing navigate js task on the DOM manipulation task source failed");
} else {
script_thread
.script_sender
.send((pipeline_id, ScriptMsg::LoadUrl(load_data, replace)))
.expect("Sending a LoadUrl message to the constellation failed");
}
});
}
pub fn process_attach_layout(new_layout_info: NewLayoutInfo, origin: MutableOrigin) {
SCRIPT_THREAD_ROOT.with(|root| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*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);
},