/
script_thread.rs
2546 lines (2236 loc) · 115 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 http://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 bluetooth_traits::BluetoothRequest;
use canvas_traits::webgl::WebGLPipeline;
use devtools;
use devtools_traits::{DevtoolScriptControlMsg, DevtoolsPageInfo};
use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId};
use devtools_traits::CSSError;
use document_loader::DocumentLoader;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, DocumentReadyState};
use dom::bindings::codegen::Bindings::EventBinding::EventInit;
use dom::bindings::codegen::Bindings::TransitionEventBinding::TransitionEventInit;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, StringificationBehavior};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableJS, Root, RootCollection};
use dom::bindings::js::{RootCollectionPtr, RootedReference};
use dom::bindings::num::Finite;
use dom::bindings::reflector::DomObject;
use dom::bindings::str::DOMString;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::WRAP_CALLBACKS;
use dom::customelementregistry::{CallbackReaction, CustomElementDefinition, CustomElementReactionStack};
use dom::document::{Document, DocumentSource, FocusType, HasBrowsingContext, IsHTMLDocument, TouchEventResult};
use dom::element::Element;
use dom::event::{Event, EventBubbles, EventCancelable};
use dom::globalscope::GlobalScope;
use dom::htmlanchorelement::HTMLAnchorElement;
use dom::htmliframeelement::{HTMLIFrameElement, NavigationType};
use dom::mutationobserver::MutationObserver;
use dom::node::{Node, NodeDamage, window_from_node, from_untrusted_node_address};
use dom::serviceworker::TrustedServiceWorkerAddress;
use dom::serviceworkerregistration::ServiceWorkerRegistration;
use dom::servoparser::{ParserContext, ServoParser};
use dom::transitionevent::TransitionEvent;
use dom::uievent::UIEvent;
use dom::window::{ReflowReason, Window};
use dom::windowproxy::WindowProxy;
use dom::worker::TrustedWorkerAddress;
use dom::worklet::WorkletThreadPool;
use dom::workletglobalscope::WorkletGlobalScopeInit;
use euclid::{Point2D, Vector2D, Rect};
use hyper::header::{ContentType, HttpDate, Headers, LastModified};
use hyper::header::ReferrerPolicy as ReferrerPolicyHeader;
use hyper::mime::{Mime, SubLevel, TopLevel};
use hyper_serde::Serde;
use ipc_channel::ipc::{self, IpcSender};
use ipc_channel::router::ROUTER;
use js::glue::GetWindowProxyClass;
use js::jsapi::{JSAutoCompartment, JSContext, JS_SetWrapObjectCallbacks};
use js::jsapi::{JSTracer, SetWindowProxyClass};
use js::jsval::UndefinedValue;
use js::rust::Runtime;
use mem::heap_size_of_self_and_children;
use metrics::PaintTimeMetrics;
use microtask::{MicrotaskQueue, Microtask};
use msg::constellation_msg::{BrowsingContextId, FrameType, PipelineId, PipelineNamespace, TopLevelBrowsingContextId};
use net_traits::{FetchMetadata, FetchResponseListener, FetchResponseMsg};
use net_traits::{Metadata, NetworkError, ReferrerPolicy, ResourceThreads};
use net_traits::image_cache::{ImageCache, PendingImageResponse};
use net_traits::request::{CredentialsMode, Destination, RedirectMode, RequestInit};
use net_traits::storage_thread::StorageType;
use profile_traits::mem::{self, OpaqueSender, Report, ReportKind, ReportsChan};
use profile_traits::time::{self, ProfilerCategory, profile};
use script_layout_interface::message::{self, Msg, NewLayoutThreadInfo, ReflowQueryType};
use script_runtime::{CommonScriptMsg, ScriptChan, ScriptThreadEventCategory};
use script_runtime::{ScriptPort, StackRootTLS, get_reports, new_rt_and_cx};
use script_traits::{CompositorEvent, ConstellationControlMsg};
use script_traits::{DocumentActivity, DiscardBrowsingContext, EventResult};
use script_traits::{InitialScriptState, JsEvalResult, LayoutMsg, LoadData, MouseButton, MouseEventType};
use script_traits::{MozBrowserEvent, NewLayoutInfo, ScriptToConstellationChan, ScriptMsg, UpdatePipelineIdReason};
use script_traits::{ScriptThreadFactory, TimerEvent, TimerSchedulerMsg, TimerSource};
use script_traits::{TouchEventType, TouchId, UntrustedNodeAddress, WindowSizeData, WindowSizeType};
use script_traits::CompositorEvent::{KeyEvent, MouseButtonEvent, MouseMoveEvent, ResizeEvent};
use script_traits::CompositorEvent::{TouchEvent, TouchpadPressureEvent};
use script_traits::webdriver_msg::WebDriverScriptCommand;
use serviceworkerjob::{Job, JobQueue, AsyncJobHandler};
use servo_config::opts;
use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
use std::cell::Cell;
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::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Select, Sender, channel};
use std::thread;
use style::context::ReflowGoal;
use style::thread_state;
use task_source::dom_manipulation::{DOMManipulationTask, DOMManipulationTaskSource};
use task_source::file_reading::FileReadingTaskSource;
use task_source::history_traversal::HistoryTraversalTaskSource;
use task_source::networking::NetworkingTaskSource;
use task_source::performance_timeline::{PerformanceTimelineTask, PerformanceTimelineTaskSource};
use task_source::user_interaction::{UserInteractionTask, UserInteractionTaskSource};
use time::{get_time, precise_time_ns, Tm};
use url::Position;
use webdriver_handlers;
use webvr_traits::{WebVREvent, WebVRMsg};
pub type ImageCacheMsg = (PipelineId, PendingImageResponse);
thread_local!(pub static STACK_ROOTS: Cell<Option<RootCollectionPtr>> = Cell::new(None));
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, FrameType)>,
/// The current window size associated with this pipeline.
window_size: Option<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: f64,
}
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, FrameType)>,
layout_chan: Sender<message::Msg>,
window_size: Option<WindowSizeData>,
url: ServoUrl,
origin: MutableOrigin) -> InProgressLoad {
let current_time = get_time();
let navigation_start_precise = precise_time_ns() as f64;
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,
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,
}
}
}
/// Encapsulated state required to create cancellable runnables from non-script threads.
pub struct RunnableWrapper {
pub cancelled: Option<Arc<AtomicBool>>,
}
impl RunnableWrapper {
pub fn wrap_runnable<T: Runnable + Send + 'static>(&self, runnable: Box<T>) -> Box<Runnable + Send> {
box CancellableRunnable {
cancelled: self.cancelled.clone(),
inner: runnable,
}
}
}
/// A runnable that can be discarded by toggling a shared flag.
pub struct CancellableRunnable<T: Runnable + Send> {
cancelled: Option<Arc<AtomicBool>>,
inner: Box<T>,
}
impl<T: Runnable + Send> Runnable for CancellableRunnable<T> {
fn name(&self) -> &'static str { self.inner.name() }
fn is_cancelled(&self) -> bool {
self.cancelled.as_ref()
.map(|cancelled| cancelled.load(Ordering::SeqCst))
.unwrap_or(false)
}
fn main_thread_handler(self: Box<CancellableRunnable<T>>, script_thread: &ScriptThread) {
self.inner.main_thread_handler(script_thread);
}
fn handler(self: Box<CancellableRunnable<T>>) {
self.inner.handler()
}
}
pub trait Runnable {
fn is_cancelled(&self) -> bool { false }
fn name(&self) -> &'static str { "generic runnable" }
fn handler(self: Box<Self>) {}
fn main_thread_handler(self: Box<Self>, _script_thread: &ScriptThread) { self.handler(); }
}
#[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 that a window associated with a particular pipeline
/// should be closed (only dispatched to ScriptThread).
ExitWindow(PipelineId),
/// Begins a content-initiated load on the specified pipeline (only
/// dispatched to ScriptThread). Allows for a replace bool to be passed. If true,
/// the current entry will be replaced instead of a new entry being added.
Navigate(PipelineId, LoadData, bool),
/// Tasks that originate from the DOM manipulation task source
DOMManipulation(DOMManipulationTask),
/// Tasks that originate from the user interaction task source
UserInteraction(UserInteractionTask),
/// Notifies the script thread that a new worklet has been loaded, and thus the page should be
/// reflowed.
WorkletLoaded(PipelineId),
/// Tasks that originate from the performance timeline task source.
PerformanceTimeline(PerformanceTimelineTask),
}
impl OpaqueSender<CommonScriptMsg> for Box<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(()),
}
}
}
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(()),
}
}
}
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<ScriptChan + Send> {
box 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<ScriptChan + Send> {
box 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, JS<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, JS::from_ref(doc));
}
pub fn remove(&mut self, pipeline_id: PipelineId) -> Option<Root<Document>> {
self.map.remove(&pipeline_id).map(|ref doc| Root::from_ref(&**doc))
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn find_document(&self, pipeline_id: PipelineId) -> Option<Root<Document>> {
self.map.get(&pipeline_id).map(|doc| Root::from_ref(&**doc))
}
pub fn find_window(&self, pipeline_id: PipelineId) -> Option<Root<Window>> {
self.find_document(pipeline_id).map(|doc| Root::from_ref(doc.window()))
}
pub fn find_global(&self, pipeline_id: PipelineId) -> Option<Root<GlobalScope>> {
self.find_window(pipeline_id).map(|window| Root::from_ref(window.upcast()))
}
pub fn find_iframe(&self, pipeline_id: PipelineId, browsing_context_id: BrowsingContextId)
-> Option<Root<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, JS<Document>>,
}
impl<'a> Iterator for DocumentsIter<'a> {
type Item = (PipelineId, Root<Document>);
fn next(&mut self) -> Option<(PipelineId, Root<Document>)> {
self.iter.next().map(|(id, doc)| (*id, Root::from_ref(&**doc)))
}
}
#[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, JS<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: DOMRefCell<Vec<(PipelineId, ParserContext)>>,
/// A map to store service worker registrations for a given origin
registration_map: DOMRefCell<HashMap<ServoUrl, JS<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<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>,
/// The port on which the script thread receives messages (load URL, exit, etc.)
port: Receiver<MainThreadScriptMsg>,
/// 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_source: DOMManipulationTaskSource,
user_interaction_task_source: UserInteractionTaskSource,
networking_task_source: NetworkingTaskSource,
history_traversal_task_source: HistoryTraversalTaskSource,
file_reading_task_source: FileReadingTaskSource,
performance_timeline_task_source: PerformanceTimelineTaskSource,
/// 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: time::ProfilerChan,
/// For providing contact with the memory profiler.
mem_profiler_chan: 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: MutNullableJS<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<()>,
microtask_queue: MicrotaskQueue,
/// Microtask Queue for adding support for mutation observer microtasks
mutation_observer_compound_microtask_queued: Cell<bool>,
/// The unit of related similar-origin browsing contexts' list of MutationObserver objects
mutation_observers: DOMRefCell<Vec<JS<MutationObserver>>>,
/// A handle to the webgl thread
webgl_chan: WebGLPipeline,
/// A handle to the webvr thread, if available
webvr_chan: Option<IpcSender<WebVRMsg>>,
/// 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<JS<Document>>>,
/// A list of nodes with in-progress CSS transitions, which roots them for the duration
/// of the transition.
transitioning_nodes: DOMRefCell<Vec<JS<Node>>>,
/// https://html.spec.whatwg.org/multipage/#custom-element-reactions-stack
custom_element_reaction_stack: CustomElementReactionStack,
}
/// 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)
-> (Sender<message::Msg>, Receiver<message::Msg>) {
let (script_chan, script_port) = channel();
let (sender, receiver) = channel();
let layout_chan = sender.clone();
thread::Builder::new().name(format!("ScriptThread {:?}", state.id)).spawn(move || {
thread_state::initialize(thread_state::SCRIPT);
PipelineNamespace::install(state.pipeline_namespace_id);
TopLevelBrowsingContextId::install(state.top_level_browsing_context_id);
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::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 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());
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,
layout_chan, window_size, load_data.url.clone(), origin);
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 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| JS::from_ref(&*from_untrusted_node_address(js_runtime, n)));
script_thread.transitioning_nodes.borrow_mut().extend(new_nodes);
})
}
pub fn set_mutation_observer_compound_microtask_queued(value: bool) {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread.mutation_observer_compound_microtask_queued.set(value);
})
}
pub fn is_mutation_observer_compound_microtask_queued() -> bool {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
return script_thread.mutation_observer_compound_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(JS::from_ref(observer));
})
}
pub fn get_mutation_observers() -> Vec<Root<MutationObserver>> {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread.mutation_observers.borrow().iter().map(|o| Root::from_ref(&**o)).collect()
})
}
pub fn mark_document_with_no_blocked_loads(doc: &Document) {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread.docs_with_no_blocking_loads
.borrow_mut()
.insert(JS::from_ref(doc));
})
}
pub fn invoke_perform_a_microtask_checkpoint() {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread.perform_a_microtask_checkpoint()
})
}
pub fn page_headers_available(id: &PipelineId, metadata: Option<Metadata>)
-> Option<Root<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, global: &GlobalScope) {
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, global, &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
pub fn await_stable_state(task: Microtask) {
SCRIPT_THREAD_ROOT.with(|root| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread.microtask_queue.enqueue(task);
}
});
}
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 };
script_thread.profile_event(ScriptThreadEventCategory::AttachLayout, || {
script_thread.handle_new_layout(new_layout_info, origin);
})
}
});
}
pub fn find_document(id: PipelineId) -> Option<Root<Document>> {
SCRIPT_THREAD_ROOT.with(|root| root.get().and_then(|script_thread| {
let script_thread = unsafe { &*script_thread };
script_thread.documents.borrow().find_document(id)
}))
}
pub fn find_window_proxy(id: BrowsingContextId) -> Option<Root<WindowProxy>> {
SCRIPT_THREAD_ROOT.with(|root| root.get().and_then(|script_thread| {
let script_thread = unsafe { &*script_thread };
script_thread.window_proxies.borrow().get(&id)
.map(|context| Root::from_ref(&**context))
}))
}
pub fn worklet_thread_pool() -> Rc<WorkletThreadPool> {
SCRIPT_THREAD_ROOT.with(|root| {
let script_thread = unsafe { &*root.get().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(),
};
Rc::new(WorkletThreadPool::spawn(init))
}).clone()
})
}
pub fn send_to_layout(&self, pipeline_id: PipelineId, msg: Msg) {
let window = self.documents.borrow().find_window(pipeline_id);
let window = match window {
Some(window) => window,
None => return warn!("Message sent to layout after pipeline {} closed.", pipeline_id),
};
let _ = window.layout_chan().send(msg);
}
pub fn push_new_element_queue() {
SCRIPT_THREAD_ROOT.with(|root| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread.custom_element_reaction_stack.push_new_element_queue();
}
})
}
pub fn pop_current_element_queue() {
SCRIPT_THREAD_ROOT.with(|root| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread.custom_element_reaction_stack.pop_current_element_queue();
}
})
}
pub fn enqueue_callback_reaction(element: &Element,
reaction: CallbackReaction,
definition: Option<Rc<CustomElementDefinition>>) {
SCRIPT_THREAD_ROOT.with(|root| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread.custom_element_reaction_stack.enqueue_callback_reaction(element, reaction, definition);
}
})
}
pub fn enqueue_upgrade_reaction(element: &Element, definition: Rc<CustomElementDefinition>) {
SCRIPT_THREAD_ROOT.with(|root| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread.custom_element_reaction_stack.enqueue_upgrade_reaction(element, definition);
}
})
}
pub fn invoke_backup_element_queue() {
SCRIPT_THREAD_ROOT.with(|root| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread.custom_element_reaction_stack.invoke_backup_element_queue();
}
})
}
/// Creates a new script thread.
pub fn new(state: InitialScriptState,
port: Receiver<MainThreadScriptMsg>,
chan: Sender<MainThreadScriptMsg>)
-> ScriptThread {
let runtime = unsafe { new_rt_and_cx() };
unsafe {
JS_SetWrapObjectCallbacks(runtime.rt(),
&WRAP_CALLBACKS);
SetWindowProxyClass(runtime.rt(), GetWindowProxyClass());
}
// 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_mpsc_receiver(ipc_devtools_receiver);
let (timer_event_chan, timer_event_port) = channel();
// Ask the router to proxy IPC messages from the control port to us.
let control_port = ROUTER.route_ipc_receiver_to_new_mpsc_receiver(state.control_port);
let boxed_script_sender = MainThreadScriptChan(chan.clone()).clone();
let (image_cache_channel, image_cache_port) = channel();
ScriptThread {
documents: DOMRefCell::new(Documents::new()),
window_proxies: DOMRefCell::new(HashMap::new()),
incomplete_loads: DOMRefCell::new(vec!()),
incomplete_parser_contexts: DOMRefCell::new(vec!()),
registration_map: DOMRefCell::new(HashMap::new()),
job_queue_map: Rc::new(JobQueue::new()),
image_cache: state.image_cache.clone(),
image_cache_channel: image_cache_channel,
image_cache_port: image_cache_port,
resource_threads: state.resource_threads,
bluetooth_thread: state.bluetooth_thread,
port: port,
chan: MainThreadScriptChan(chan.clone()),
dom_manipulation_task_source: DOMManipulationTaskSource(chan.clone()),
user_interaction_task_source: UserInteractionTaskSource(chan.clone()),
networking_task_source: NetworkingTaskSource(boxed_script_sender.clone()),
history_traversal_task_source: HistoryTraversalTaskSource(chan.clone()),
file_reading_task_source: FileReadingTaskSource(boxed_script_sender),
performance_timeline_task_source: PerformanceTimelineTaskSource(chan),
control_chan: state.control_chan,
control_port: control_port,
script_sender: state.script_to_constellation_chan.sender.clone(),
time_profiler_chan: state.time_profiler_chan,
mem_profiler_chan: state.mem_profiler_chan,
devtools_chan: state.devtools_chan,
devtools_port: devtools_port,
devtools_sender: ipc_devtools_sender,
js_runtime: Rc::new(runtime),
topmost_mouse_over_target: MutNullableJS::new(Default::default()),
closed_pipelines: DOMRefCell::new(HashSet::new()),
scheduler_chan: state.scheduler_chan,
timer_event_chan: timer_event_chan,
timer_event_port: timer_event_port,
content_process_shutdown_chan: state.content_process_shutdown_chan,
microtask_queue: MicrotaskQueue::default(),
mutation_observer_compound_microtask_queued: Default::default(),
mutation_observers: Default::default(),
layout_to_constellation_chan: state.layout_to_constellation_chan,
webgl_chan: state.webgl_chan,
webvr_chan: state.webvr_chan,
worklet_thread_pool: Default::default(),
docs_with_no_blocking_loads: Default::default(),
transitioning_nodes: Default::default(),
custom_element_reaction_stack: CustomElementReactionStack::new(),
}
}
pub fn get_cx(&self) -> *mut JSContext {
self.js_runtime.cx()
}
/// Starts the script thread. After calling this method, the script thread will loop receiving
/// messages on its port.
pub fn start(&self) {
debug!("Starting script thread.");
while self.handle_msgs() {
// Go on...
debug!("Running script thread.");
}
debug!("Stopped script thread.");
}
/// Handle incoming control messages.
fn handle_msgs(&self) -> bool {
use self::MixedMessage::{FromConstellation, FromDevtools, FromImageCache};
use self::MixedMessage::{FromScheduler, FromScript};
// Handle pending resize events.
// Gather them first to avoid a double mut borrow on self.
let mut resizes = vec!();
for (id, document) in self.documents.borrow().iter() {
// Only process a resize if layout is idle.
if let Some((size, size_type)) = document.window().steal_resize_event() {
resizes.push((id, size, size_type));
}
}
for (id, size, size_type) in resizes {
self.handle_event(id, ResizeEvent(size, size_type));
}
// Store new resizes, and gather all other events.
let mut sequential = vec![];
// Receive at least one message so we don't spinloop.
debug!("Waiting for event.");
let mut event = {
let sel = Select::new();
let mut script_port = sel.handle(&self.port);
let mut control_port = sel.handle(&self.control_port);
let mut timer_event_port = sel.handle(&self.timer_event_port);
let mut devtools_port = sel.handle(&self.devtools_port);
let mut image_cache_port = sel.handle(&self.image_cache_port);
unsafe {
script_port.add();
control_port.add();
timer_event_port.add();
if self.devtools_chan.is_some() {
devtools_port.add();
}
image_cache_port.add();
}
let ret = sel.wait();
if ret == script_port.id() {
FromScript(self.port.recv().unwrap())
} else if ret == control_port.id() {
FromConstellation(self.control_port.recv().unwrap())
} else if ret == timer_event_port.id() {
FromScheduler(self.timer_event_port.recv().unwrap())
} else if ret == devtools_port.id() {
FromDevtools(self.devtools_port.recv().unwrap())
} else if ret == image_cache_port.id() {
FromImageCache(self.image_cache_port.recv().unwrap())
} else {
panic!("unexpected select result")
}
};
debug!("Got event.");
// Squash any pending resize, reflow, animation tick, and mouse-move events in the queue.
let mut mouse_move_event_index = None;
let mut animation_ticks = HashSet::new();
loop {
// https://html.spec.whatwg.org/multipage/#event-loop-processing-model step 7
match event {
// This has to be handled before the ResizeMsg below,
// otherwise the page may not have been added to the
// child list yet, causing the find() to fail.
FromConstellation(ConstellationControlMsg::AttachLayout(
new_layout_info)) => {
self.profile_event(ScriptThreadEventCategory::AttachLayout, || {
// If this is an about:blank load, it must share the creator's origin.
// This must match the logic in the constellation when creating a new pipeline
let origin = if new_layout_info.load_data.url.as_str() != "about:blank" {
MutableOrigin::new(new_layout_info.load_data.url.origin())
} else if let Some(parent) = new_layout_info.parent_info
.and_then(|(pipeline_id, _)| self.documents.borrow()
.find_document(pipeline_id)) {
parent.origin().clone()
} else if let Some(creator) = new_layout_info.load_data.creator_pipeline_id