1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 
5 use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId};
6 use dom::bindings::cell::DomRefCell;
7 use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
8 use dom::bindings::codegen::Bindings::WorkerGlobalScopeBinding::WorkerGlobalScopeMethods;
9 use dom::bindings::conversions::root_from_object;
10 use dom::bindings::error::{ErrorInfo, report_pending_exception};
11 use dom::bindings::inheritance::Castable;
12 use dom::bindings::reflector::DomObject;
13 use dom::bindings::root::{DomRoot, MutNullableDom};
14 use dom::bindings::settings_stack::{AutoEntryScript, entry_global, incumbent_global};
15 use dom::bindings::str::DOMString;
16 use dom::crypto::Crypto;
17 use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope;
18 use dom::errorevent::ErrorEvent;
19 use dom::event::{Event, EventBubbles, EventCancelable, EventStatus};
20 use dom::eventtarget::EventTarget;
21 use dom::performance::Performance;
22 use dom::window::Window;
23 use dom::workerglobalscope::WorkerGlobalScope;
24 use dom::workletglobalscope::WorkletGlobalScope;
25 use dom_struct::dom_struct;
26 use ipc_channel::ipc::IpcSender;
27 use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL};
28 use js::glue::{IsWrapper, UnwrapObject};
29 use js::jsapi::{CurrentGlobalOrNull, GetGlobalForObjectCrossCompartment};
30 use js::jsapi::{HandleValue, Evaluate2, JSAutoCompartment, JSContext};
31 use js::jsapi::{JSObject, JS_GetContext};
32 use js::jsapi::{JS_GetObjectRuntime, MutableHandleValue};
33 use js::panic::maybe_resume_unwind;
34 use js::rust::{CompileOptionsWrapper, Runtime, get_object_class};
35 use libc;
36 use microtask::{Microtask, MicrotaskQueue};
37 use msg::constellation_msg::PipelineId;
38 use net_traits::{CoreResourceThread, ResourceThreads, IpcSend};
39 use profile_traits::{mem, time};
40 use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort};
41 use script_thread::{MainThreadScriptChan, ScriptThread};
42 use script_traits::{MsDuration, ScriptToConstellationChan, TimerEvent};
43 use script_traits::{TimerEventId, TimerSchedulerMsg, TimerSource};
44 use servo_url::{MutableOrigin, ServoUrl};
45 use std::cell::Cell;
46 use std::collections::HashMap;
47 use std::collections::hash_map::Entry;
48 use std::ffi::CString;
49 use std::rc::Rc;
50 use std::sync::Arc;
51 use std::sync::atomic::{AtomicBool, Ordering};
52 use task::TaskCanceller;
53 use task_source::file_reading::FileReadingTaskSource;
54 use task_source::networking::NetworkingTaskSource;
55 use task_source::performance_timeline::PerformanceTimelineTaskSource;
56 use time::{Timespec, get_time};
57 use timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle};
58 use timers::{OneshotTimers, TimerCallback};
59 
60 #[derive(JSTraceable)]
61 pub struct AutoCloseWorker(
62     Arc<AtomicBool>,
63 );
64 
65 impl Drop for AutoCloseWorker {
drop(&mut self)66     fn drop(&mut self) {
67         self.0.store(true, Ordering::SeqCst);
68     }
69 }
70 
71 #[dom_struct]
72 pub struct GlobalScope {
73     eventtarget: EventTarget,
74     crypto: MutNullableDom<Crypto>,
75     next_worker_id: Cell<WorkerId>,
76 
77     /// Pipeline id associated with this global.
78     pipeline_id: PipelineId,
79 
80     /// A flag to indicate whether the developer tools has requested
81     /// live updates from the worker.
82     devtools_wants_updates: Cell<bool>,
83 
84     /// Timers used by the Console API.
85     console_timers: DomRefCell<HashMap<DOMString, u64>>,
86 
87     /// For providing instructions to an optional devtools server.
88     #[ignore_malloc_size_of = "channels are hard"]
89     devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
90 
91     /// For sending messages to the memory profiler.
92     #[ignore_malloc_size_of = "channels are hard"]
93     mem_profiler_chan: mem::ProfilerChan,
94 
95     /// For sending messages to the time profiler.
96     #[ignore_malloc_size_of = "channels are hard"]
97     time_profiler_chan: time::ProfilerChan,
98 
99     /// A handle for communicating messages to the constellation thread.
100     #[ignore_malloc_size_of = "channels are hard"]
101     script_to_constellation_chan: ScriptToConstellationChan,
102 
103     #[ignore_malloc_size_of = "channels are hard"]
104     scheduler_chan: IpcSender<TimerSchedulerMsg>,
105 
106     /// <https://html.spec.whatwg.org/multipage/#in-error-reporting-mode>
107     in_error_reporting_mode: Cell<bool>,
108 
109     /// Associated resource threads for use by DOM objects like XMLHttpRequest,
110     /// including resource_thread, filemanager_thread and storage_thread
111     resource_threads: ResourceThreads,
112 
113     timers: OneshotTimers,
114 
115     /// The origin of the globalscope
116     origin: MutableOrigin,
117 
118     /// The microtask queue associated with this global.
119     ///
120     /// It is refcounted because windows in the same script thread share the
121     /// same microtask queue.
122     ///
123     /// <https://html.spec.whatwg.org/multipage/#microtask-queue>
124     #[ignore_malloc_size_of = "Rc<T> is hard"]
125     microtask_queue: Rc<MicrotaskQueue>,
126 
127     /// Vector storing closing references of all workers
128     #[ignore_malloc_size_of = "Arc"]
129     list_auto_close_worker: DomRefCell<Vec<AutoCloseWorker>>,
130 }
131 
132 impl GlobalScope {
new_inherited( pipeline_id: PipelineId, devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>, mem_profiler_chan: mem::ProfilerChan, time_profiler_chan: time::ProfilerChan, script_to_constellation_chan: ScriptToConstellationChan, scheduler_chan: IpcSender<TimerSchedulerMsg>, resource_threads: ResourceThreads, timer_event_chan: IpcSender<TimerEvent>, origin: MutableOrigin, microtask_queue: Rc<MicrotaskQueue>, ) -> Self133     pub fn new_inherited(
134         pipeline_id: PipelineId,
135         devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
136         mem_profiler_chan: mem::ProfilerChan,
137         time_profiler_chan: time::ProfilerChan,
138         script_to_constellation_chan: ScriptToConstellationChan,
139         scheduler_chan: IpcSender<TimerSchedulerMsg>,
140         resource_threads: ResourceThreads,
141         timer_event_chan: IpcSender<TimerEvent>,
142         origin: MutableOrigin,
143         microtask_queue: Rc<MicrotaskQueue>,
144     ) -> Self {
145         Self {
146             eventtarget: EventTarget::new_inherited(),
147             crypto: Default::default(),
148             next_worker_id: Cell::new(WorkerId(0)),
149             pipeline_id,
150             devtools_wants_updates: Default::default(),
151             console_timers: DomRefCell::new(Default::default()),
152             devtools_chan,
153             mem_profiler_chan,
154             time_profiler_chan,
155             script_to_constellation_chan,
156             scheduler_chan: scheduler_chan.clone(),
157             in_error_reporting_mode: Default::default(),
158             resource_threads,
159             timers: OneshotTimers::new(timer_event_chan, scheduler_chan),
160             origin,
161             microtask_queue,
162             list_auto_close_worker: Default::default(),
163         }
164     }
165 
track_worker(&self, closing_worker: Arc<AtomicBool>)166     pub fn track_worker(&self, closing_worker: Arc<AtomicBool>) {
167        self.list_auto_close_worker.borrow_mut().push(AutoCloseWorker(closing_worker));
168     }
169 
170     /// Returns the global scope of the realm that the given DOM object's reflector
171     /// was created in.
172     #[allow(unsafe_code)]
from_reflector<T: DomObject>(reflector: &T) -> DomRoot<Self>173     pub fn from_reflector<T: DomObject>(reflector: &T) -> DomRoot<Self> {
174         unsafe { GlobalScope::from_object(*reflector.reflector().get_jsobject()) }
175     }
176 
177     /// Returns the global scope of the realm that the given JS object was created in.
178     #[allow(unsafe_code)]
from_object(obj: *mut JSObject) -> DomRoot<Self>179     pub unsafe fn from_object(obj: *mut JSObject) -> DomRoot<Self> {
180         assert!(!obj.is_null());
181         let global = GetGlobalForObjectCrossCompartment(obj);
182         global_scope_from_global(global)
183     }
184 
185     /// Returns the global scope for the given JSContext
186     #[allow(unsafe_code)]
from_context(cx: *mut JSContext) -> DomRoot<Self>187     pub unsafe fn from_context(cx: *mut JSContext) -> DomRoot<Self> {
188         let global = CurrentGlobalOrNull(cx);
189         global_scope_from_global(global)
190     }
191 
192     /// Returns the global object of the realm that the given JS object
193     /// was created in, after unwrapping any wrappers.
194     #[allow(unsafe_code)]
from_object_maybe_wrapped(mut obj: *mut JSObject) -> DomRoot<Self>195     pub unsafe fn from_object_maybe_wrapped(mut obj: *mut JSObject) -> DomRoot<Self> {
196         if IsWrapper(obj) {
197             obj = UnwrapObject(obj, /* stopAtWindowProxy = */ 0);
198             assert!(!obj.is_null());
199         }
200         GlobalScope::from_object(obj)
201     }
202 
203     #[allow(unsafe_code)]
get_cx(&self) -> *mut JSContext204     pub fn get_cx(&self) -> *mut JSContext {
205         unsafe {
206             let runtime = JS_GetObjectRuntime(
207                 self.reflector().get_jsobject().get());
208             assert!(!runtime.is_null());
209             let context = JS_GetContext(runtime);
210             assert!(!context.is_null());
211             context
212         }
213     }
214 
crypto(&self) -> DomRoot<Crypto>215     pub fn crypto(&self) -> DomRoot<Crypto> {
216         self.crypto.or_init(|| Crypto::new(self))
217     }
218 
219     /// Get next worker id.
get_next_worker_id(&self) -> WorkerId220     pub fn get_next_worker_id(&self) -> WorkerId {
221         let worker_id = self.next_worker_id.get();
222         let WorkerId(id_num) = worker_id;
223         self.next_worker_id.set(WorkerId(id_num + 1));
224         worker_id
225     }
226 
live_devtools_updates(&self) -> bool227     pub fn live_devtools_updates(&self) -> bool {
228         self.devtools_wants_updates.get()
229     }
230 
set_devtools_wants_updates(&self, value: bool)231     pub fn set_devtools_wants_updates(&self, value: bool) {
232         self.devtools_wants_updates.set(value);
233     }
234 
time(&self, label: DOMString) -> Result<(), ()>235     pub fn time(&self, label: DOMString) -> Result<(), ()> {
236         let mut timers = self.console_timers.borrow_mut();
237         if timers.len() >= 10000 {
238             return Err(());
239         }
240         match timers.entry(label) {
241             Entry::Vacant(entry) => {
242                 entry.insert(timestamp_in_ms(get_time()));
243                 Ok(())
244             },
245             Entry::Occupied(_) => Err(()),
246         }
247     }
248 
time_end(&self, label: &str) -> Result<u64, ()>249     pub fn time_end(&self, label: &str) -> Result<u64, ()> {
250         self.console_timers.borrow_mut().remove(label).ok_or(()).map(|start| {
251             timestamp_in_ms(get_time()) - start
252         })
253     }
254 
255     /// Get an `&IpcSender<ScriptToDevtoolsControlMsg>` to send messages
256     /// to the devtools thread when available.
devtools_chan(&self) -> Option<&IpcSender<ScriptToDevtoolsControlMsg>>257     pub fn devtools_chan(&self) -> Option<&IpcSender<ScriptToDevtoolsControlMsg>> {
258         self.devtools_chan.as_ref()
259     }
260 
261     /// Get a sender to the memory profiler thread.
mem_profiler_chan(&self) -> &mem::ProfilerChan262     pub fn mem_profiler_chan(&self) -> &mem::ProfilerChan {
263         &self.mem_profiler_chan
264     }
265 
266     /// Get a sender to the time profiler thread.
time_profiler_chan(&self) -> &time::ProfilerChan267     pub fn time_profiler_chan(&self) -> &time::ProfilerChan {
268         &self.time_profiler_chan
269     }
270 
271     /// Get a sender to the constellation thread.
script_to_constellation_chan(&self) -> &ScriptToConstellationChan272     pub fn script_to_constellation_chan(&self) -> &ScriptToConstellationChan {
273         &self.script_to_constellation_chan
274     }
275 
scheduler_chan(&self) -> &IpcSender<TimerSchedulerMsg>276     pub fn scheduler_chan(&self) -> &IpcSender<TimerSchedulerMsg> {
277         &self.scheduler_chan
278     }
279 
280     /// Get the `PipelineId` for this global scope.
pipeline_id(&self) -> PipelineId281     pub fn pipeline_id(&self) -> PipelineId {
282         self.pipeline_id
283     }
284 
285     /// Get the origin for this global scope
origin(&self) -> &MutableOrigin286     pub fn origin(&self) -> &MutableOrigin {
287         &self.origin
288     }
289 
290     /// Get the [base url](https://html.spec.whatwg.org/multipage/#api-base-url)
291     /// for this global scope.
api_base_url(&self) -> ServoUrl292     pub fn api_base_url(&self) -> ServoUrl {
293         if let Some(window) = self.downcast::<Window>() {
294             // https://html.spec.whatwg.org/multipage/#script-settings-for-browsing-contexts:api-base-url
295             return window.Document().base_url();
296         }
297         if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
298             // https://html.spec.whatwg.org/multipage/#script-settings-for-workers:api-base-url
299             return worker.get_url().clone();
300         }
301         if let Some(worker) = self.downcast::<WorkletGlobalScope>() {
302             // https://drafts.css-houdini.org/worklets/#script-settings-for-worklets
303             return worker.base_url();
304         }
305         unreachable!();
306     }
307 
308     /// Get the URL for this global scope.
get_url(&self) -> ServoUrl309     pub fn get_url(&self) -> ServoUrl {
310         if let Some(window) = self.downcast::<Window>() {
311             return window.get_url();
312         }
313         if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
314             return worker.get_url().clone();
315         }
316         if let Some(worker) = self.downcast::<WorkletGlobalScope>() {
317             // TODO: is this the right URL to return?
318             return worker.base_url();
319         }
320         unreachable!();
321     }
322 
323     /// Extract a `Window`, panic if the global object is not a `Window`.
as_window(&self) -> &Window324     pub fn as_window(&self) -> &Window {
325         self.downcast::<Window>().expect("expected a Window scope")
326     }
327 
328     /// <https://html.spec.whatwg.org/multipage/#report-the-error>
report_an_error(&self, error_info: ErrorInfo, value: HandleValue)329     pub fn report_an_error(&self, error_info: ErrorInfo, value: HandleValue) {
330         // Step 1.
331         if self.in_error_reporting_mode.get() {
332             return;
333         }
334 
335         // Step 2.
336         self.in_error_reporting_mode.set(true);
337 
338         // Steps 3-6.
339         // FIXME(#13195): muted errors.
340         let event = ErrorEvent::new(
341             self,
342             atom!("error"),
343             EventBubbles::DoesNotBubble,
344             EventCancelable::Cancelable,
345             error_info.message.as_str().into(),
346             error_info.filename.as_str().into(),
347             error_info.lineno,
348             error_info.column,
349             value,
350         );
351 
352         // Step 7.
353         let event_status = event.upcast::<Event>().fire(self.upcast::<EventTarget>());
354 
355         // Step 8.
356         self.in_error_reporting_mode.set(false);
357 
358         // Step 9.
359         if event_status == EventStatus::NotCanceled {
360             // https://html.spec.whatwg.org/multipage/#runtime-script-errors-2
361             if let Some(dedicated) = self.downcast::<DedicatedWorkerGlobalScope>() {
362                 dedicated.forward_error_to_worker_object(error_info);
363             }
364         }
365 
366     }
367 
368     /// Get the `&ResourceThreads` for this global scope.
resource_threads(&self) -> &ResourceThreads369     pub fn resource_threads(&self) -> &ResourceThreads {
370         &self.resource_threads
371     }
372 
373     /// Get the `CoreResourceThread` for this global scope.
core_resource_thread(&self) -> CoreResourceThread374     pub fn core_resource_thread(&self) -> CoreResourceThread {
375         self.resource_threads().sender()
376     }
377 
378     /// `ScriptChan` to send messages to the event loop of this global scope.
script_chan(&self) -> Box<ScriptChan + Send>379     pub fn script_chan(&self) -> Box<ScriptChan + Send> {
380         if let Some(window) = self.downcast::<Window>() {
381             return MainThreadScriptChan(window.main_thread_script_chan().clone()).clone();
382         }
383         if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
384             return worker.script_chan();
385         }
386         unreachable!();
387     }
388 
389     /// `ScriptChan` to send messages to the networking task source of
390     /// this of this global scope.
networking_task_source(&self) -> NetworkingTaskSource391     pub fn networking_task_source(&self) -> NetworkingTaskSource {
392         if let Some(window) = self.downcast::<Window>() {
393             return window.networking_task_source();
394         }
395         if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
396             return worker.networking_task_source();
397         }
398         unreachable!();
399     }
400 
401     /// Evaluate JS code on this global scope.
evaluate_js_on_global_with_result( &self, code: &str, rval: MutableHandleValue) -> bool402     pub fn evaluate_js_on_global_with_result(
403             &self, code: &str, rval: MutableHandleValue) -> bool {
404         self.evaluate_script_on_global_with_result(code, "", rval, 1)
405     }
406 
407     /// Evaluate a JS script on this global scope.
408     #[allow(unsafe_code)]
evaluate_script_on_global_with_result( &self, code: &str, filename: &str, rval: MutableHandleValue, line_number: u32) -> bool409     pub fn evaluate_script_on_global_with_result(
410             &self, code: &str, filename: &str, rval: MutableHandleValue, line_number: u32) -> bool {
411         let metadata = time::TimerMetadata {
412             url: if filename.is_empty() {
413                 self.get_url().as_str().into()
414             } else {
415                 filename.into()
416             },
417             iframe: time::TimerMetadataFrameType::RootWindow,
418             incremental: time::TimerMetadataReflowType::FirstReflow,
419         };
420         time::profile(
421             time::ProfilerCategory::ScriptEvaluate,
422             Some(metadata),
423             self.time_profiler_chan().clone(),
424             || {
425                 let cx = self.get_cx();
426                 let globalhandle = self.reflector().get_jsobject();
427                 let code: Vec<u16> = code.encode_utf16().collect();
428                 let filename = CString::new(filename).unwrap();
429 
430                 let _ac = JSAutoCompartment::new(cx, globalhandle.get());
431                 let _aes = AutoEntryScript::new(self);
432                 let options = CompileOptionsWrapper::new(cx, filename.as_ptr(), line_number);
433 
434                 debug!("evaluating Dom string");
435                 let result = unsafe {
436                     Evaluate2(cx, options.ptr, code.as_ptr(),
437                               code.len() as libc::size_t,
438                               rval)
439                 };
440 
441                 if !result {
442                     debug!("error evaluating Dom string");
443                     unsafe { report_pending_exception(cx, true) };
444                 }
445 
446                 maybe_resume_unwind();
447                 result
448             }
449         )
450     }
451 
schedule_callback( &self, callback: OneshotTimerCallback, duration: MsDuration) -> OneshotTimerHandle452     pub fn schedule_callback(
453             &self, callback: OneshotTimerCallback, duration: MsDuration)
454             -> OneshotTimerHandle {
455         self.timers.schedule_callback(callback, duration, self.timer_source())
456     }
457 
unschedule_callback(&self, handle: OneshotTimerHandle)458     pub fn unschedule_callback(&self, handle: OneshotTimerHandle) {
459         self.timers.unschedule_callback(handle);
460     }
461 
set_timeout_or_interval( &self, callback: TimerCallback, arguments: Vec<HandleValue>, timeout: i32, is_interval: IsInterval) -> i32462     pub fn set_timeout_or_interval(
463             &self,
464             callback: TimerCallback,
465             arguments: Vec<HandleValue>,
466             timeout: i32,
467             is_interval: IsInterval)
468             -> i32 {
469         self.timers.set_timeout_or_interval(
470             self, callback, arguments, timeout, is_interval, self.timer_source())
471     }
472 
clear_timeout_or_interval(&self, handle: i32)473     pub fn clear_timeout_or_interval(&self, handle: i32) {
474         self.timers.clear_timeout_or_interval(self, handle)
475     }
476 
fire_timer(&self, handle: TimerEventId)477     pub fn fire_timer(&self, handle: TimerEventId) {
478         self.timers.fire_timer(handle, self)
479     }
480 
resume(&self)481     pub fn resume(&self) {
482         self.timers.resume()
483     }
484 
suspend(&self)485     pub fn suspend(&self) {
486         self.timers.suspend()
487     }
488 
slow_down_timers(&self)489     pub fn slow_down_timers(&self) {
490         self.timers.slow_down()
491     }
492 
speed_up_timers(&self)493     pub fn speed_up_timers(&self) {
494         self.timers.speed_up()
495     }
496 
timer_source(&self) -> TimerSource497     fn timer_source(&self) -> TimerSource {
498         if self.is::<Window>() {
499             return TimerSource::FromWindow(self.pipeline_id());
500         }
501         if self.is::<WorkerGlobalScope>() {
502             return TimerSource::FromWorker;
503         }
504         unreachable!();
505     }
506 
507     /// Returns the task canceller of this global to ensure that everything is
508     /// properly cancelled when the global scope is destroyed.
task_canceller(&self) -> TaskCanceller509     pub fn task_canceller(&self) -> TaskCanceller {
510         if let Some(window) = self.downcast::<Window>() {
511             return window.task_canceller();
512         }
513         if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
514             return worker.task_canceller();
515         }
516         unreachable!();
517     }
518 
519     /// Perform a microtask checkpoint.
perform_a_microtask_checkpoint(&self)520     pub fn perform_a_microtask_checkpoint(&self) {
521         self.microtask_queue.checkpoint(|_| Some(DomRoot::from_ref(self)));
522     }
523 
524     /// Enqueue a microtask for subsequent execution.
enqueue_microtask(&self, job: Microtask)525     pub fn enqueue_microtask(&self, job: Microtask) {
526         self.microtask_queue.enqueue(job);
527     }
528 
529     /// Create a new sender/receiver pair that can be used to implement an on-demand
530     /// event loop. Used for implementing web APIs that require blocking semantics
531     /// without resorting to nested event loops.
new_script_pair(&self) -> (Box<ScriptChan + Send>, Box<ScriptPort + Send>)532     pub fn new_script_pair(&self) -> (Box<ScriptChan + Send>, Box<ScriptPort + Send>) {
533         if let Some(window) = self.downcast::<Window>() {
534             return window.new_script_pair();
535         }
536         if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
537             return worker.new_script_pair();
538         }
539         unreachable!();
540     }
541 
542     /// Returns the microtask queue of this global.
microtask_queue(&self) -> &Rc<MicrotaskQueue>543     pub fn microtask_queue(&self) -> &Rc<MicrotaskQueue> {
544         &self.microtask_queue
545     }
546 
547     /// Process a single event as if it were the next event
548     /// in the thread queue for this global scope.
process_event(&self, msg: CommonScriptMsg)549     pub fn process_event(&self, msg: CommonScriptMsg) {
550         if self.is::<Window>() {
551             return ScriptThread::process_event(msg);
552         }
553         if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
554             return worker.process_event(msg);
555         }
556         unreachable!();
557     }
558 
559     /// Channel to send messages to the file reading task source of
560     /// this of this global scope.
file_reading_task_source(&self) -> FileReadingTaskSource561     pub fn file_reading_task_source(&self) -> FileReadingTaskSource {
562         if let Some(window) = self.downcast::<Window>() {
563             return window.file_reading_task_source();
564         }
565         if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
566             return worker.file_reading_task_source();
567         }
568         unreachable!();
569     }
570 
571     /// Returns the ["current"] global object.
572     ///
573     /// ["current"]: https://html.spec.whatwg.org/multipage/#current
574     #[allow(unsafe_code)]
current() -> Option<DomRoot<Self>>575     pub fn current() -> Option<DomRoot<Self>> {
576         unsafe {
577             let cx = Runtime::get();
578             assert!(!cx.is_null());
579             let global = CurrentGlobalOrNull(cx);
580             if global.is_null() {
581                 None
582             } else {
583                 Some(global_scope_from_global(global))
584             }
585         }
586     }
587 
588     /// Returns the ["entry"] global object.
589     ///
590     /// ["entry"]: https://html.spec.whatwg.org/multipage/#entry
entry() -> DomRoot<Self>591     pub fn entry() -> DomRoot<Self> {
592         entry_global()
593     }
594 
595     /// Returns the ["incumbent"] global object.
596     ///
597     /// ["incumbent"]: https://html.spec.whatwg.org/multipage/#incumbent
incumbent() -> Option<DomRoot<Self>>598     pub fn incumbent() -> Option<DomRoot<Self>> {
599         incumbent_global()
600     }
601 
performance(&self) -> DomRoot<Performance>602     pub fn performance(&self) -> DomRoot<Performance> {
603         if let Some(window) = self.downcast::<Window>() {
604             return window.Performance();
605         }
606         if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
607             return worker.Performance();
608         }
609         unreachable!();
610     }
611 
612     /// Channel to send messages to the performance timeline task source
613     /// of this global scope.
performance_timeline_task_source(&self) -> PerformanceTimelineTaskSource614     pub fn performance_timeline_task_source(&self) -> PerformanceTimelineTaskSource {
615         if let Some(window) = self.downcast::<Window>() {
616             return window.performance_timeline_task_source();
617         }
618         if let Some(worker) = self.downcast::<WorkerGlobalScope>() {
619             return worker.performance_timeline_task_source();
620         }
621         unreachable!();
622     }
623 
624 }
625 
timestamp_in_ms(time: Timespec) -> u64626 fn timestamp_in_ms(time: Timespec) -> u64 {
627     (time.sec * 1000 + (time.nsec / 1000000) as i64) as u64
628 }
629 
630 /// Returns the Rust global scope from a JS global object.
631 #[allow(unsafe_code)]
global_scope_from_global(global: *mut JSObject) -> DomRoot<GlobalScope>632 unsafe fn global_scope_from_global(global: *mut JSObject) -> DomRoot<GlobalScope> {
633     assert!(!global.is_null());
634     let clasp = get_object_class(global);
635     assert_ne!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)), 0);
636     root_from_object(global).unwrap()
637 }
638