servo: Merge #9255 - Remove global fields from DOM objects (from ckimes89:remove-globalfield); r=nox
authorChad Kimes <ckimes89@gmail.com>
Tue, 12 Jan 2016 18:03:07 +0500
changeset 337923 d6870f742170542d1b5ba2d7f3084ff9d13f3d4c
parent 337922 50d87d1008c69be802337bfaa9b0436a04f33b96
child 337924 5ee7d57f1f6c9870720bb2f95020f94fd7122192
push id31307
push usergszorc@mozilla.com
push dateSat, 04 Feb 2017 00:59:06 +0000
treeherdermozilla-central@94079d43835f [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersnox
servo: Merge #9255 - Remove global fields from DOM objects (from ckimes89:remove-globalfield); r=nox Fixes #9227 Source-Repo: https://github.com/servo/servo Source-Revision: 53c4a782a0906c487139d4b6f3c62d9eca3f9f17
servo/components/script/dom/bindings/global.rs
servo/components/script/dom/bindings/reflector.rs
servo/components/script/dom/blob.rs
servo/components/script/dom/canvasrenderingcontext2d.rs
servo/components/script/dom/console.rs
servo/components/script/dom/domquad.rs
servo/components/script/dom/eventdispatcher.rs
servo/components/script/dom/eventtarget.rs
servo/components/script/dom/file.rs
servo/components/script/dom/filereader.rs
servo/components/script/dom/formdata.rs
servo/components/script/dom/storage.rs
servo/components/script/dom/testbinding.rs
servo/components/script/dom/webglrenderingcontext.rs
servo/components/script/dom/websocket.rs
servo/components/script/dom/window.rs
servo/components/script/dom/worker.rs
servo/components/script/dom/xmlhttprequest.rs
servo/components/script/timers.rs
--- a/servo/components/script/dom/bindings/global.rs
+++ b/servo/components/script/dom/bindings/global.rs
@@ -39,27 +39,16 @@ pub enum GlobalRef<'a> {
 /// A stack-based rooted reference to a global object.
 pub enum GlobalRoot {
     /// A root for a `Window` object.
     Window(Root<window::Window>),
     /// A root for a `WorkerGlobalScope` object.
     Worker(Root<WorkerGlobalScope>),
 }
 
-/// A traced reference to a global object, for use in fields of traced Rust
-/// structures.
-#[derive(JSTraceable, HeapSizeOf)]
-#[must_root]
-pub enum GlobalField {
-    /// A field for a `Window` object.
-    Window(JS<window::Window>),
-    /// A field for a `WorkerGlobalScope` object.
-    Worker(JS<WorkerGlobalScope>),
-}
-
 impl<'a> GlobalRef<'a> {
     /// Get the `JSContext` for the `JSRuntime` associated with the thread
     /// this global object is on.
     pub fn get_cx(&self) -> *mut JSContext {
         match *self {
             GlobalRef::Window(ref window) => window.get_cx(),
             GlobalRef::Worker(ref worker) => worker.get_cx(),
         }
@@ -268,35 +257,16 @@ impl GlobalRoot {
     pub fn r(&self) -> GlobalRef {
         match *self {
             GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()),
             GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()),
         }
     }
 }
 
-impl GlobalField {
-    /// Create a new `GlobalField` from a rooted reference.
-    #[allow(unrooted_must_root)]
-    pub fn from_rooted(global: &GlobalRef) -> GlobalField {
-        match *global {
-            GlobalRef::Window(window) => GlobalField::Window(JS::from_ref(window)),
-            GlobalRef::Worker(worker) => GlobalField::Worker(JS::from_ref(worker)),
-        }
-    }
-
-    /// Create a stack-bounded root for this reference.
-    pub fn root(&self) -> GlobalRoot {
-        match *self {
-            GlobalField::Window(ref window) => GlobalRoot::Window(Root::from_ref(window)),
-            GlobalField::Worker(ref worker) => GlobalRoot::Worker(Root::from_ref(worker)),
-        }
-    }
-}
-
 /// Returns the global object of the realm that the given DOM object's reflector was created in.
 pub fn global_root_from_reflector<T: Reflectable>(reflector: &T) -> GlobalRoot {
     global_root_from_object(*reflector.reflector().get_jsobject())
 }
 
 /// Returns the global object of the realm that the given JS object was created in.
 #[allow(unrooted_must_root)]
 pub fn global_root_from_object(obj: *mut JSObject) -> GlobalRoot {
--- a/servo/components/script/dom/bindings/reflector.rs
+++ b/servo/components/script/dom/bindings/reflector.rs
@@ -1,15 +1,15 @@
 /* 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 `Reflector` struct.
 
-use dom::bindings::global::GlobalRef;
+use dom::bindings::global::{GlobalRef, GlobalRoot, global_root_from_reflector};
 use dom::bindings::js::Root;
 use js::jsapi::{HandleObject, JSContext, JSObject};
 use std::cell::UnsafeCell;
 use std::ptr;
 
 /// Create the reflector for a new DOM object and yield ownership to the
 /// reflector.
 pub fn reflect_dom_object<T: Reflectable>(obj: Box<T>,
@@ -70,9 +70,14 @@ impl Reflector {
 }
 
 /// A trait to provide access to the `Reflector` for a DOM object.
 pub trait Reflectable {
     /// Returns the receiver's reflector.
     fn reflector(&self) -> &Reflector;
     /// Initializes the Reflector
     fn init_reflector(&mut self, obj: *mut JSObject);
+
+    /// Returns the global object of the realm that the Reflectable was created in.
+    fn global(&self) -> GlobalRoot where Self: Sized {
+        global_root_from_reflector(self)
+    }
 }
--- a/servo/components/script/dom/blob.rs
+++ b/servo/components/script/dom/blob.rs
@@ -1,18 +1,18 @@
 /* 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/. */
 
 use dom::bindings::codegen::Bindings::BlobBinding;
 use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
 use dom::bindings::error::Fallible;
-use dom::bindings::global::{GlobalField, GlobalRef};
+use dom::bindings::global::GlobalRef;
 use dom::bindings::js::Root;
-use dom::bindings::reflector::{Reflector, reflect_dom_object};
+use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
 use dom::bindings::trace::JSTraceable;
 use num::ToPrimitive;
 use std::ascii::AsciiExt;
 use std::borrow::ToOwned;
 use std::cell::Cell;
 use std::cmp::{max, min};
 use std::sync::Arc;
 use util::str::DOMString;
@@ -71,53 +71,50 @@ impl DataSlice {
 
 // https://w3c.github.io/FileAPI/#blob
 #[dom_struct]
 pub struct Blob {
     reflector_: Reflector,
     #[ignore_heap_size_of = "No clear owner"]
     data: DataSlice,
     typeString: String,
-    global: GlobalField,
     isClosed_: Cell<bool>,
 }
 
 fn is_ascii_printable(string: &str) -> bool {
     // Step 5.1 in Sec 5.1 of File API spec
     // https://w3c.github.io/FileAPI/#constructorBlob
     string.chars().all(|c| c >= '\x20' && c <= '\x7E')
 }
 
 impl Blob {
-    pub fn new_inherited(global: GlobalRef,
-                         bytes: Arc<Vec<u8>>,
+    pub fn new_inherited(bytes: Arc<Vec<u8>>,
                          bytes_start: Option<i64>,
                          bytes_end: Option<i64>,
                          typeString: &str) -> Blob {
         Blob {
             reflector_: Reflector::new(),
             data: DataSlice::new(bytes, bytes_start, bytes_end),
             typeString: typeString.to_owned(),
-            global: GlobalField::from_rooted(&global),
             isClosed_: Cell::new(false),
         }
     }
 
     pub fn new(global: GlobalRef, bytes: Vec<u8>, typeString: &str) -> Root<Blob> {
-        let boxed_blob = box Blob::new_inherited(global, Arc::new(bytes), None, None, typeString);
+        let boxed_blob = box Blob::new_inherited(Arc::new(bytes), None, None, typeString);
         reflect_dom_object(boxed_blob, global, BlobBinding::Wrap)
     }
 
     fn new_sliced(global: GlobalRef,
                   bytes: Arc<Vec<u8>>,
                   bytes_start: Option<i64>,
                   bytes_end: Option<i64>,
                   typeString: &str) -> Root<Blob> {
 
-      let boxed_blob = box Blob::new_inherited(global, bytes, bytes_start, bytes_end, typeString);
+      let boxed_blob = box Blob::new_inherited(bytes, bytes_start, bytes_end, typeString);
       reflect_dom_object(boxed_blob, global, BlobBinding::Wrap)
     }
 
     // https://w3c.github.io/FileAPI/#constructorBlob
     pub fn Constructor(global: GlobalRef) -> Fallible<Root<Blob>> {
         Ok(Blob::new(global, Vec::new(), ""))
     }
 
@@ -166,17 +163,17 @@ impl BlobMethods for Blob {
                 if is_ascii_printable(&str) {
                     str.make_ascii_lowercase();
                     str
                 } else {
                     DOMString::new()
                 }
             }
         };
-        let global = self.global.root();
+        let global = self.global();
         let bytes = self.data.bytes.clone();
         Blob::new_sliced(global.r(), bytes, start, end, &relativeContentType)
     }
 
     // https://w3c.github.io/FileAPI/#dfn-isClosed
     fn IsClosed(&self) -> bool {
         self.isClosed_.get()
     }
--- a/servo/components/script/dom/canvasrenderingcontext2d.rs
+++ b/servo/components/script/dom/canvasrenderingcontext2d.rs
@@ -13,21 +13,21 @@ use dom::bindings::codegen::Bindings::CS
 use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding;
 use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasFillRule;
 use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasRenderingContext2DMethods;
 use dom::bindings::codegen::Bindings::ImageDataBinding::ImageDataMethods;
 use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
 use dom::bindings::codegen::UnionTypes::HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D;
 use dom::bindings::codegen::UnionTypes::StringOrCanvasGradientOrCanvasPattern;
 use dom::bindings::error::{Error, Fallible};
-use dom::bindings::global::{GlobalField, GlobalRef};
+use dom::bindings::global::GlobalRef;
 use dom::bindings::inheritance::Castable;
 use dom::bindings::js::{JS, LayoutJS, Root};
 use dom::bindings::num::Finite;
-use dom::bindings::reflector::{Reflector, reflect_dom_object};
+use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
 use dom::canvasgradient::{CanvasGradient, CanvasGradientStyle, ToFillOrStrokeStyle};
 use dom::canvaspattern::CanvasPattern;
 use dom::htmlcanvaselement::HTMLCanvasElement;
 use dom::htmlcanvaselement::utils as canvas_utils;
 use dom::htmlimageelement::HTMLImageElement;
 use dom::imagedata::ImageData;
 use dom::node::{Node, NodeDamage, window_from_node};
 use euclid::matrix2d::Matrix2D;
@@ -56,17 +56,16 @@ enum CanvasFillOrStrokeStyle {
     Gradient(JS<CanvasGradient>),
     Pattern(JS<CanvasPattern>),
 }
 
 // https://html.spec.whatwg.org/multipage/#canvasrenderingcontext2d
 #[dom_struct]
 pub struct CanvasRenderingContext2D {
     reflector_: Reflector,
-    global: GlobalField,
     renderer_id: usize,
     #[ignore_heap_size_of = "Defined in ipc-channel"]
     ipc_renderer: IpcSender<CanvasMsg>,
     canvas: JS<HTMLCanvasElement>,
     state: DOMRefCell<CanvasContextState>,
     saved_states: DOMRefCell<Vec<CanvasContextState>>,
     origin_clean: Cell<bool>,
 }
@@ -123,17 +122,16 @@ impl CanvasRenderingContext2D {
                      size: Size2D<i32>)
                      -> CanvasRenderingContext2D {
         let (sender, receiver) = ipc::channel().unwrap();
         let constellation_chan = global.constellation_chan();
         constellation_chan.0.send(ConstellationMsg::CreateCanvasPaintThread(size, sender)).unwrap();
         let (ipc_renderer, renderer_id) = receiver.recv().unwrap();
         CanvasRenderingContext2D {
             reflector_: Reflector::new(),
-            global: GlobalField::from_rooted(&global),
             renderer_id: renderer_id,
             ipc_renderer: ipc_renderer,
             canvas: JS::from_ref(canvas),
             state: DOMRefCell::new(CanvasContextState::new()),
             saved_states: DOMRefCell::new(Vec::new()),
             origin_clean: Cell::new(true),
         }
     }
@@ -1011,22 +1009,22 @@ impl CanvasRenderingContext2DMethods for
     // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata
     fn CreateImageData(&self, sw: Finite<f64>, sh: Finite<f64>) -> Fallible<Root<ImageData>> {
         if *sw == 0.0 || *sh == 0.0 {
             return Err(Error::IndexSize);
         }
 
         let sw = cmp::max(1, sw.abs().to_u32().unwrap());
         let sh = cmp::max(1, sh.abs().to_u32().unwrap());
-        Ok(ImageData::new(self.global.root().r(), sw, sh, None))
+        Ok(ImageData::new(self.global().r(), sw, sh, None))
     }
 
     // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata
     fn CreateImageData_(&self, imagedata: &ImageData) -> Fallible<Root<ImageData>> {
-        Ok(ImageData::new(self.global.root().r(),
+        Ok(ImageData::new(self.global().r(),
                           imagedata.Width(),
                           imagedata.Height(),
                           None))
     }
 
     // https://html.spec.whatwg.org/multipage/#dom-context-2d-getimagedata
     fn GetImageData(&self,
                     sx: Finite<f64>,
@@ -1073,17 +1071,17 @@ impl CanvasRenderingContext2DMethods for
         // Un-premultiply alpha
         for chunk in data.chunks_mut(4) {
             let alpha = chunk[3] as usize;
             chunk[0] = UNPREMULTIPLY_TABLE[256 * alpha + chunk[0] as usize];
             chunk[1] = UNPREMULTIPLY_TABLE[256 * alpha + chunk[1] as usize];
             chunk[2] = UNPREMULTIPLY_TABLE[256 * alpha + chunk[2] as usize];
         }
 
-        Ok(ImageData::new(self.global.root().r(), sw, sh, Some(data)))
+        Ok(ImageData::new(self.global().r(), sw, sh, Some(data)))
     }
 
     // https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata
     fn PutImageData(&self, imagedata: &ImageData, dx: Finite<f64>, dy: Finite<f64>) {
         self.PutImageData_(imagedata,
                            dx,
                            dy,
                            Finite::wrap(0f64),
@@ -1096,17 +1094,17 @@ impl CanvasRenderingContext2DMethods for
     fn PutImageData_(&self,
                      imagedata: &ImageData,
                      dx: Finite<f64>,
                      dy: Finite<f64>,
                      dirtyX: Finite<f64>,
                      dirtyY: Finite<f64>,
                      dirtyWidth: Finite<f64>,
                      dirtyHeight: Finite<f64>) {
-        let data = imagedata.get_data_array(&self.global.root().r());
+        let data = imagedata.get_data_array(&self.global().r());
         let offset = Point2D::new(*dx, *dy);
         let image_data_size = Size2D::new(imagedata.Width() as f64, imagedata.Height() as f64);
 
         let dirty_rect = Rect::new(Point2D::new(*dirtyX, *dirtyY),
                                    Size2D::new(*dirtyWidth, *dirtyHeight));
         let msg = CanvasMsg::Canvas2d(Canvas2dMsg::PutImageData(data,
                                                                 offset,
                                                                 image_data_size,
@@ -1117,17 +1115,17 @@ impl CanvasRenderingContext2DMethods for
 
     // https://html.spec.whatwg.org/multipage/#dom-context-2d-createlineargradient
     fn CreateLinearGradient(&self,
                             x0: Finite<f64>,
                             y0: Finite<f64>,
                             x1: Finite<f64>,
                             y1: Finite<f64>)
                             -> Root<CanvasGradient> {
-        CanvasGradient::new(self.global.root().r(),
+        CanvasGradient::new(self.global().r(),
                             CanvasGradientStyle::Linear(LinearGradientStyle::new(*x0,
                                                                                  *y0,
                                                                                  *x1,
                                                                                  *y1,
                                                                                  Vec::new())))
     }
 
     // https://html.spec.whatwg.org/multipage/#dom-context-2d-createradialgradient
@@ -1138,17 +1136,17 @@ impl CanvasRenderingContext2DMethods for
                             x1: Finite<f64>,
                             y1: Finite<f64>,
                             r1: Finite<f64>)
                             -> Fallible<Root<CanvasGradient>> {
         if *r0 < 0. || *r1 < 0. {
             return Err(Error::IndexSize);
         }
 
-        Ok(CanvasGradient::new(self.global.root().r(),
+        Ok(CanvasGradient::new(self.global().r(),
                                CanvasGradientStyle::Radial(RadialGradientStyle::new(*x0,
                                                                                     *y0,
                                                                                     *r0,
                                                                                     *x1,
                                                                                     *y1,
                                                                                     *r1,
                                                                                     Vec::new()))))
     }
@@ -1178,17 +1176,17 @@ impl CanvasRenderingContext2DMethods for
             }
         };
 
         if repetition.is_empty() {
             repetition.push_str("repeat");
         }
 
         if let Ok(rep) = RepetitionStyle::from_str(&repetition) {
-            Ok(CanvasPattern::new(self.global.root().r(),
+            Ok(CanvasPattern::new(self.global().r(),
                                   image_data,
                                   image_size,
                                   rep,
                                   self.is_origin_clean(image)))
         } else {
             Err(Error::Syntax)
         }
     }
--- a/servo/components/script/dom/console.rs
+++ b/servo/components/script/dom/console.rs
@@ -1,18 +1,18 @@
 /* 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/. */
 
 use devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg};
 use dom::bindings::codegen::Bindings::ConsoleBinding;
 use dom::bindings::codegen::Bindings::ConsoleBinding::ConsoleMethods;
-use dom::bindings::global::{GlobalRef, global_root_from_reflector};
+use dom::bindings::global::GlobalRef;
 use dom::bindings::js::Root;
-use dom::bindings::reflector::{Reflector, reflect_dom_object};
+use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
 use util::str::DOMString;
 
 // https://developer.mozilla.org/en-US/docs/Web/API/Console
 #[dom_struct]
 pub struct Console {
     reflector_: Reflector,
 }
 
@@ -25,17 +25,17 @@ impl Console {
 
     pub fn new(global: GlobalRef) -> Root<Console> {
         reflect_dom_object(box Console::new_inherited(),
                            global,
                            ConsoleBinding::Wrap)
     }
 
     fn send_to_devtools(&self, level: LogLevel, message: DOMString) {
-        let global = global_root_from_reflector(self);
+        let global = self.global();
         let global = global.r();
         if let Some(chan) = global.devtools_chan() {
             let console_message = prepare_message(level, message);
             let devtools_message = ScriptToDevtoolsControlMsg::ConsoleAPI(
                 global.pipeline(),
                 console_message,
                 global.get_worker_id());
             chan.send(devtools_message).unwrap();
--- a/servo/components/script/dom/domquad.rs
+++ b/servo/components/script/dom/domquad.rs
@@ -3,19 +3,19 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods};
 use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::DOMPointReadOnlyMethods;
 use dom::bindings::codegen::Bindings::DOMQuadBinding::{DOMQuadInit, DOMQuadMethods, Wrap};
 use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods;
 use dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::{DOMRectInit, DOMRectReadOnlyMethods};
 use dom::bindings::error::Fallible;
-use dom::bindings::global::{GlobalRef, global_root_from_reflector};
+use dom::bindings::global::GlobalRef;
 use dom::bindings::js::{Root, JS};
-use dom::bindings::reflector::{Reflector, reflect_dom_object};
+use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
 use dom::dompoint::DOMPoint;
 use dom::domrect::DOMRect;
 
 // https://drafts.fxtf.org/geometry/#DOMQuad
 #[dom_struct]
 pub struct DOMQuad {
     reflector_: Reflector,
     p1: JS<DOMPoint>,
@@ -105,15 +105,15 @@ impl DOMQuadMethods for DOMQuad {
 
     // https://drafts.fxtf.org/geometry/#dom-domquad-getbounds
     fn GetBounds(&self) -> Root<DOMRect> {
         let left = self.p1.X().min(self.p2.X()).min(self.p3.X()).min(self.p4.X());
         let top = self.p1.Y().min(self.p2.Y()).min(self.p3.Y()).min(self.p4.Y());
         let right = self.p1.X().max(self.p2.X()).max(self.p3.X()).max(self.p4.X());
         let bottom = self.p1.Y().max(self.p2.Y()).max(self.p3.Y()).max(self.p4.Y());
 
-        DOMRect::new(global_root_from_reflector(self).r(),
+        DOMRect::new(self.global().r(),
                      left,
                      top,
                      right - left,
                      bottom - top)
     }
 }
--- a/servo/components/script/dom/eventdispatcher.rs
+++ b/servo/components/script/dom/eventdispatcher.rs
@@ -1,18 +1,19 @@
 /* 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/. */
 
 use devtools_traits::{StartedTimelineMarker, TimelineMarker, TimelineMarkerType};
 use dom::bindings::callback::ExceptionHandling::Report;
 use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
-use dom::bindings::global::{GlobalRoot, global_root_from_reflector};
+use dom::bindings::global::GlobalRoot;
 use dom::bindings::inheritance::Castable;
 use dom::bindings::js::{JS, Root, RootedReference};
+use dom::bindings::reflector::Reflectable;
 use dom::bindings::trace::RootedVec;
 use dom::event::{Event, EventPhase};
 use dom::eventtarget::{EventListenerType, EventTarget, ListenerPhase};
 use dom::node::Node;
 use dom::virtualmethods::vtable_for;
 use dom::window::Window;
 
 struct AutoDOMEventMarker {
@@ -44,17 +45,17 @@ fn handle_event(window: Option<&Window>,
 
     listener.call_or_handle_event(current_target, event, Report);
 }
 
 fn dispatch_to_listeners(event: &Event, target: &EventTarget, chain: &[&EventTarget]) {
     assert!(!event.stop_propagation());
     assert!(!event.stop_immediate());
 
-    let window = match global_root_from_reflector(target) {
+    let window = match target.global() {
         GlobalRoot::Window(window) => {
             if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) {
                 Some(window)
             } else {
                 None
             }
         },
         _ => None,
--- a/servo/components/script/dom/eventtarget.rs
+++ b/servo/components/script/dom/eventtarget.rs
@@ -6,17 +6,17 @@ use dom::bindings::callback::{CallbackCo
 use dom::bindings::cell::DOMRefCell;
 use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods;
 use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
 use dom::bindings::codegen::Bindings::EventHandlerBinding::OnErrorEventHandlerNonNull;
 use dom::bindings::codegen::Bindings::EventListenerBinding::EventListener;
 use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods;
 use dom::bindings::codegen::UnionTypes::EventOrString;
 use dom::bindings::error::{Error, Fallible, report_pending_exception};
-use dom::bindings::global::{GlobalRef, global_root_from_reflector};
+use dom::bindings::global::GlobalRef;
 use dom::bindings::inheritance::{Castable, EventTargetTypeId};
 use dom::bindings::js::Root;
 use dom::bindings::reflector::{Reflectable, Reflector};
 use dom::errorevent::ErrorEvent;
 use dom::event::{Event, EventBubbles, EventCancelable};
 use dom::eventdispatcher::dispatch_event;
 use dom::virtualmethods::VirtualMethods;
 use dom::window::Window;
@@ -118,17 +118,17 @@ impl EventListenerType {
         match *self {
             EventListenerType::Additive(ref listener) => {
                 let _ = listener.HandleEvent_(object, event, exception_handle);
             },
             EventListenerType::Inline(ref handler) => {
                 match *handler {
                     CommonEventHandler::ErrorEventHandler(ref handler) => {
                         if let Some(event) = event.downcast::<ErrorEvent>() {
-                            let global = global_root_from_reflector(object);
+                            let global = object.global();
                             let cx = global.r().get_cx();
                             let error = RootedValue::new(cx, event.Error(cx));
                             let _ = handler.Call_(object,
                                                   EventOrString::eString(event.Message()),
                                                   Some(event.Filename()),
                                                   Some(event.Lineno()),
                                                   Some(event.Colno()),
                                                   Some(error.handle()),
--- a/servo/components/script/dom/file.rs
+++ b/servo/components/script/dom/file.rs
@@ -13,29 +13,28 @@ use util::str::DOMString;
 
 #[dom_struct]
 pub struct File {
     blob: Blob,
     name: DOMString,
 }
 
 impl File {
-    fn new_inherited(global: GlobalRef,
-                     _file_bits: &Blob, name: DOMString) -> File {
+    fn new_inherited(_file_bits: &Blob, name: DOMString) -> File {
         File {
             //TODO: get type from the underlying filesystem instead of "".to_string()
-            blob: Blob::new_inherited(global, Arc::new(Vec::new()), None, None, ""),
+            blob: Blob::new_inherited(Arc::new(Vec::new()), None, None, ""),
             name: name,
         }
         // XXXManishearth Once Blob is able to store data
         // the relevant subfields of file_bits should be copied over
     }
 
     pub fn new(global: GlobalRef, file_bits: &Blob, name: DOMString) -> Root<File> {
-        reflect_dom_object(box File::new_inherited(global, file_bits, name),
+        reflect_dom_object(box File::new_inherited(file_bits, name),
                            global,
                            FileBinding::Wrap)
     }
 
     pub fn name(&self) -> &DOMString {
         &self.name
     }
 }
--- a/servo/components/script/dom/filereader.rs
+++ b/servo/components/script/dom/filereader.rs
@@ -2,17 +2,17 @@
  * 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/. */
 
 use dom::bindings::cell::DOMRefCell;
 use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
 use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
 use dom::bindings::codegen::Bindings::FileReaderBinding::{self, FileReaderConstants, FileReaderMethods};
 use dom::bindings::error::{Error, ErrorResult, Fallible};
-use dom::bindings::global::{GlobalField, GlobalRef};
+use dom::bindings::global::GlobalRef;
 use dom::bindings::inheritance::Castable;
 use dom::bindings::js::{JS, MutNullableHeap, Root};
 use dom::bindings::refcounted::Trusted;
 use dom::bindings::reflector::{Reflectable, reflect_dom_object};
 use dom::blob::{Blob, DataSlice};
 use dom::domexception::{DOMErrorName, DOMException};
 use dom::event::{Event, EventBubbles, EventCancelable};
 use dom::eventtarget::EventTarget;
@@ -64,37 +64,35 @@ pub enum FileReaderReadyState {
     Empty = FileReaderConstants::EMPTY,
     Loading = FileReaderConstants::LOADING,
     Done = FileReaderConstants::DONE,
 }
 
 #[dom_struct]
 pub struct FileReader {
     eventtarget: EventTarget,
-    global: GlobalField,
     ready_state: Cell<FileReaderReadyState>,
     error: MutNullableHeap<JS<DOMException>>,
     result: DOMRefCell<Option<DOMString>>,
     generation_id: Cell<GenerationId>,
 }
 
 impl FileReader {
-    pub fn new_inherited(global: GlobalRef) -> FileReader {
+    pub fn new_inherited() -> FileReader {
         FileReader {
             eventtarget: EventTarget::new_inherited(),//?
-            global: GlobalField::from_rooted(&global),
             ready_state: Cell::new(FileReaderReadyState::Empty),
             error: MutNullableHeap::new(None),
             result: DOMRefCell::new(None),
             generation_id: Cell::new(GenerationId(0)),
         }
     }
 
     pub fn new(global: GlobalRef) -> Root<FileReader> {
-        reflect_dom_object(box FileReader::new_inherited(global),
+        reflect_dom_object(box FileReader::new_inherited(),
                            global, FileReaderBinding::Wrap)
     }
 
     pub fn Constructor(global: GlobalRef) -> Fallible<Root<FileReader>> {
         Ok(FileReader::new(global))
     }
 
     //https://w3c.github.io/FileAPI/#dfn-error-steps
@@ -109,17 +107,17 @@ impl FileReader {
             );
         );
 
         return_on_abort!();
         // Step 1
         fr.change_ready_state(FileReaderReadyState::Done);
         *fr.result.borrow_mut() = None;
 
-        let global = fr.global.root();
+        let global = fr.r().global();
         let exception = DOMException::new(global.r(), error);
         fr.error.set(Some(&exception));
 
         fr.dispatch_progress_event(atom!("error"), 0, None);
         return_on_abort!();
         // Step 3
         fr.dispatch_progress_event(atom!("loadend"), 0, None);
         return_on_abort!();
@@ -286,17 +284,17 @@ impl FileReaderMethods for FileReader {
     fn Abort(&self) {
         // Step 2
         if self.ready_state.get() == FileReaderReadyState::Loading {
             self.change_ready_state(FileReaderReadyState::Done);
         }
         // Steps 1 & 3
         *self.result.borrow_mut() = None;
 
-        let global = self.global.root();
+        let global = self.global();
         let exception = DOMException::new(global.r(), DOMErrorName::AbortError);
         self.error.set(Some(&exception));
 
         self.terminate_ongoing_reading();
         // Steps 5 & 6
         self.dispatch_progress_event(atom!("abort"), 0, None);
         self.dispatch_progress_event(atom!("loadend"), 0, None);
     }
@@ -316,38 +314,38 @@ impl FileReaderMethods for FileReader {
         self.ready_state.get() as u16
     }
 }
 
 
 impl FileReader {
     fn dispatch_progress_event(&self, type_: Atom, loaded: u64, total: Option<u64>) {
 
-        let global = self.global.root();
+        let global = self.global();
         let progressevent = ProgressEvent::new(global.r(),
             type_, EventBubbles::DoesNotBubble, EventCancelable::NotCancelable,
             total.is_some(), loaded, total.unwrap_or(0));
         progressevent.upcast::<Event>().fire(self.upcast());
     }
 
     fn terminate_ongoing_reading(&self) {
         let GenerationId(prev_id) = self.generation_id.get();
         self.generation_id.set(GenerationId(prev_id + 1));
     }
 
     fn read(&self, function: FileReaderFunction, blob: &Blob, label: Option<DOMString>) -> ErrorResult {
-        let root = self.global.root();
+        let root = self.global();
         let global = root.r();
         // Step 1
         if self.ready_state.get() == FileReaderReadyState::Loading {
             return Err(Error::InvalidState);
         }
         // Step 2
         if blob.IsClosed() {
-            let global = self.global.root();
+            let global = self.global();
             let exception = DOMException::new(global.r(), DOMErrorName::InvalidStateError);
             self.error.set(Some(&exception));
 
             self.dispatch_progress_event(atom!("error"), 0, None);
             return Ok(());
         }
 
         // Step 3
--- a/servo/components/script/dom/formdata.rs
+++ b/servo/components/script/dom/formdata.rs
@@ -2,20 +2,20 @@
  * 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/. */
 
 use dom::bindings::cell::DOMRefCell;
 use dom::bindings::codegen::Bindings::FormDataBinding;
 use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods;
 use dom::bindings::codegen::UnionTypes::BlobOrUSVString::{self, eBlob, eUSVString};
 use dom::bindings::error::{Fallible};
-use dom::bindings::global::{GlobalField, GlobalRef};
+use dom::bindings::global::GlobalRef;
 use dom::bindings::inheritance::Castable;
 use dom::bindings::js::{JS, Root};
-use dom::bindings::reflector::{Reflector, reflect_dom_object};
+use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
 use dom::bindings::str::USVString;
 use dom::blob::Blob;
 use dom::file::File;
 use dom::htmlformelement::HTMLFormElement;
 use std::collections::HashMap;
 use std::collections::hash_map::Entry::{Occupied, Vacant};
 use string_cache::Atom;
 use util::str::DOMString;
@@ -27,32 +27,30 @@ pub enum FormDatum {
     StringData(String),
     BlobData(JS<Blob>)
 }
 
 #[dom_struct]
 pub struct FormData {
     reflector_: Reflector,
     data: DOMRefCell<HashMap<Atom, Vec<FormDatum>>>,
-    global: GlobalField,
     form: Option<JS<HTMLFormElement>>
 }
 
 impl FormData {
-    fn new_inherited(form: Option<&HTMLFormElement>, global: GlobalRef) -> FormData {
+    fn new_inherited(form: Option<&HTMLFormElement>) -> FormData {
         FormData {
             reflector_: Reflector::new(),
             data: DOMRefCell::new(HashMap::new()),
-            global: GlobalField::from_rooted(&global),
             form: form.map(|f| JS::from_ref(f)),
         }
     }
 
     pub fn new(form: Option<&HTMLFormElement>, global: GlobalRef) -> Root<FormData> {
-        reflect_dom_object(box FormData::new_inherited(form, global),
+        reflect_dom_object(box FormData::new_inherited(form),
                            global, FormDataBinding::Wrap)
     }
 
     pub fn Constructor(global: GlobalRef, form: Option<&HTMLFormElement>) -> Fallible<Root<FormData>> {
         // TODO: Construct form data set for form if it is supplied
         Ok(FormData::new(form, global))
     }
 }
@@ -123,16 +121,16 @@ impl FormDataMethods for FormData {
     }
 }
 
 
 impl FormData {
     fn get_file_or_blob(&self, value: &Blob, filename: Option<USVString>) -> Root<Blob> {
         match filename {
             Some(fname) => {
-                let global = self.global.root();
+                let global = self.global();
                 let name = DOMString::from(fname.0);
                 Root::upcast(File::new(global.r(), value, name))
             }
             None => Root::from_ref(value)
         }
     }
 }
--- a/servo/components/script/dom/storage.rs
+++ b/servo/components/script/dom/storage.rs
@@ -1,59 +1,57 @@
 /* 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/. */
 
 use dom::bindings::codegen::Bindings::StorageBinding;
 use dom::bindings::codegen::Bindings::StorageBinding::StorageMethods;
 use dom::bindings::error::{Error, ErrorResult};
-use dom::bindings::global::{GlobalField, GlobalRef};
+use dom::bindings::global::GlobalRef;
 use dom::bindings::inheritance::Castable;
 use dom::bindings::js::{Root, RootedReference};
 use dom::bindings::refcounted::Trusted;
-use dom::bindings::reflector::{Reflector, reflect_dom_object};
+use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
 use dom::event::{Event, EventBubbles, EventCancelable};
 use dom::storageevent::StorageEvent;
 use dom::urlhelper::UrlHelper;
 use ipc_channel::ipc;
 use net_traits::storage_thread::{StorageThread, StorageThreadMsg, StorageType};
 use page::IterablePage;
 use script_thread::{MainThreadRunnable, MainThreadScriptMsg, ScriptThread};
 use std::sync::mpsc::channel;
 use url::Url;
 use util::str::DOMString;
 
 #[dom_struct]
 pub struct Storage {
     reflector_: Reflector,
-    global: GlobalField,
     storage_type: StorageType
 }
 
 impl Storage {
-    fn new_inherited(global: &GlobalRef, storage_type: StorageType) -> Storage {
+    fn new_inherited(storage_type: StorageType) -> Storage {
         Storage {
             reflector_: Reflector::new(),
-            global: GlobalField::from_rooted(global),
             storage_type: storage_type
         }
     }
 
     pub fn new(global: &GlobalRef, storage_type: StorageType) -> Root<Storage> {
-        reflect_dom_object(box Storage::new_inherited(global, storage_type), *global, StorageBinding::Wrap)
+        reflect_dom_object(box Storage::new_inherited(storage_type), *global, StorageBinding::Wrap)
     }
 
     fn get_url(&self) -> Url {
-        let global_root = self.global.root();
+        let global_root = self.global();
         let global_ref = global_root.r();
         global_ref.get_url()
     }
 
     fn get_storage_thread(&self) -> StorageThread {
-        let global_root = self.global.root();
+        let global_root = self.global();
         let global_ref = global_root.r();
         global_ref.as_window().storage_thread()
     }
 
 }
 
 impl StorageMethods for Storage {
     // https://html.spec.whatwg.org/multipage/#dom-storage-length
@@ -149,17 +147,17 @@ impl StorageMethods for Storage {
     }
 }
 
 
 impl Storage {
     /// https://html.spec.whatwg.org/multipage/#send-a-storage-notification
     fn broadcast_change_notification(&self, key: Option<String>, old_value: Option<String>,
                                      new_value: Option<String>) {
-        let global_root = self.global.root();
+        let global_root = self.global();
         let global_ref = global_root.r();
         let main_script_chan = global_ref.as_window().main_thread_script_chan();
         let script_chan = global_ref.dom_manipulation_thread_source();
         let trusted_storage = Trusted::new(self, script_chan);
         main_script_chan.send(MainThreadScriptMsg::MainThreadRunnableMsg(
             box StorageEventRunnable::new(trusted_storage, key, old_value, new_value))).unwrap();
     }
 }
@@ -178,17 +176,17 @@ impl StorageEventRunnable {
     }
 }
 
 impl MainThreadRunnable for StorageEventRunnable {
     fn handler(self: Box<StorageEventRunnable>, script_thread: &ScriptThread) {
         let this = *self;
         let storage_root = this.element.root();
         let storage = storage_root.r();
-        let global_root = storage.global.root();
+        let global_root = storage.global();
         let global_ref = global_root.r();
         let ev_window = global_ref.as_window();
         let ev_url = storage.get_url();
 
         let storage_event = StorageEvent::new(
             global_ref,
             atom!("storage"),
             EventBubbles::DoesNotBubble, EventCancelable::NotCancelable,
--- a/servo/components/script/dom/testbinding.rs
+++ b/servo/components/script/dom/testbinding.rs
@@ -5,20 +5,20 @@
 // check-tidy: no specs after this line
 
 use dom::bindings::codegen::Bindings::EventListenerBinding::EventListener;
 use dom::bindings::codegen::Bindings::FunctionBinding::Function;
 use dom::bindings::codegen::Bindings::TestBindingBinding::{self, TestBindingMethods, TestEnum};
 use dom::bindings::codegen::UnionTypes::{BlobOrString, EventOrString};
 use dom::bindings::codegen::UnionTypes::{EventOrUSVString, HTMLElementOrLong};
 use dom::bindings::error::Fallible;
-use dom::bindings::global::{GlobalRef, global_root_from_reflector};
+use dom::bindings::global::GlobalRef;
 use dom::bindings::js::Root;
 use dom::bindings::num::Finite;
-use dom::bindings::reflector::{Reflector, reflect_dom_object};
+use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
 use dom::bindings::str::{ByteString, USVString};
 use dom::bindings::weakref::MutableWeakRef;
 use dom::blob::Blob;
 use dom::url::URL;
 use js::jsapi::{HandleValue, JSContext, JSObject};
 use js::jsval::{JSVal, NullValue};
 use std::borrow::ToOwned;
 use std::ptr;
@@ -80,17 +80,17 @@ impl TestBindingMethods for TestBinding 
     fn SetStringAttribute(&self, _: DOMString) {}
     fn UsvstringAttribute(&self) -> USVString { USVString("".to_owned()) }
     fn SetUsvstringAttribute(&self, _: USVString) {}
     fn ByteStringAttribute(&self) -> ByteString { ByteString::new(vec!()) }
     fn SetByteStringAttribute(&self, _: ByteString) {}
     fn EnumAttribute(&self) -> TestEnum { TestEnum::_empty }
     fn SetEnumAttribute(&self, _: TestEnum) {}
     fn InterfaceAttribute(&self) -> Root<Blob> {
-        Blob::new(global_root_from_reflector(self).r(), Vec::new(), "")
+        Blob::new(self.global().r(), Vec::new(), "")
     }
     fn SetInterfaceAttribute(&self, _: &Blob) {}
     fn UnionAttribute(&self) -> HTMLElementOrLong { HTMLElementOrLong::eLong(0) }
     fn SetUnionAttribute(&self, _: HTMLElementOrLong) {}
     fn Union2Attribute(&self) -> EventOrString { EventOrString::eString(DOMString::new()) }
     fn SetUnion2Attribute(&self, _: EventOrString) {}
     fn Union3Attribute(&self) -> EventOrUSVString {
         EventOrUSVString::eUSVString(USVString("".to_owned()))
@@ -138,17 +138,17 @@ impl TestBindingMethods for TestBinding 
     fn ForwardedAttribute(&self) -> Root<TestBinding> { Root::from_ref(self) }
     fn BinaryRenamedAttribute(&self) -> DOMString { DOMString::new() }
     fn SetBinaryRenamedAttribute2(&self, _: DOMString) {}
     fn BinaryRenamedAttribute2(&self) -> DOMString { DOMString::new() }
     fn Attr_to_automatically_rename(&self) -> DOMString { DOMString::new() }
     fn SetAttr_to_automatically_rename(&self, _: DOMString) {}
     fn GetEnumAttributeNullable(&self) -> Option<TestEnum> { Some(TestEnum::_empty) }
     fn GetInterfaceAttributeNullable(&self) -> Option<Root<Blob>> {
-        Some(Blob::new(global_root_from_reflector(self).r(), Vec::new(), ""))
+        Some(Blob::new(self.global().r(), Vec::new(), ""))
     }
     fn SetInterfaceAttributeNullable(&self, _: Option<&Blob>) {}
     fn GetInterfaceAttributeWeak(&self) -> Option<Root<URL>> {
         self.url.root()
     }
     fn SetInterfaceAttributeWeak(&self, url: Option<&URL>) {
         self.url.set(url);
     }
@@ -177,17 +177,17 @@ impl TestBindingMethods for TestBinding 
     fn ReceiveFloat(&self) -> Finite<f32> { Finite::wrap(0.) }
     fn ReceiveUnrestrictedDouble(&self) -> f64 { 0. }
     fn ReceiveDouble(&self) -> Finite<f64> { Finite::wrap(0.) }
     fn ReceiveString(&self) -> DOMString { DOMString::new() }
     fn ReceiveUsvstring(&self) -> USVString { USVString("".to_owned()) }
     fn ReceiveByteString(&self) -> ByteString { ByteString::new(vec!()) }
     fn ReceiveEnum(&self) -> TestEnum { TestEnum::_empty }
     fn ReceiveInterface(&self) -> Root<Blob> {
-        Blob::new(global_root_from_reflector(self).r(), Vec::new(), "")
+        Blob::new(self.global().r(), Vec::new(), "")
     }
     fn ReceiveAny(&self, _: *mut JSContext) -> JSVal { NullValue() }
     fn ReceiveObject(&self, _: *mut JSContext) -> *mut JSObject { panic!() }
     fn ReceiveUnion(&self) -> HTMLElementOrLong { HTMLElementOrLong::eLong(0) }
     fn ReceiveUnion2(&self) -> EventOrString { EventOrString::eString(DOMString::new()) }
 
     fn ReceiveNullableBoolean(&self) -> Option<bool> { Some(false) }
     fn ReceiveNullableByte(&self) -> Option<i8> { Some(0) }
@@ -202,17 +202,17 @@ impl TestBindingMethods for TestBinding 
     fn ReceiveNullableFloat(&self) -> Option<Finite<f32>> { Some(Finite::wrap(0.)) }
     fn ReceiveNullableUnrestrictedDouble(&self) -> Option<f64> { Some(0.) }
     fn ReceiveNullableDouble(&self) -> Option<Finite<f64>> { Some(Finite::wrap(0.)) }
     fn ReceiveNullableString(&self) -> Option<DOMString> { Some(DOMString::new()) }
     fn ReceiveNullableUsvstring(&self) -> Option<USVString> { Some(USVString("".to_owned())) }
     fn ReceiveNullableByteString(&self) -> Option<ByteString> { Some(ByteString::new(vec!())) }
     fn ReceiveNullableEnum(&self) -> Option<TestEnum> { Some(TestEnum::_empty) }
     fn ReceiveNullableInterface(&self) -> Option<Root<Blob>> {
-        Some(Blob::new(global_root_from_reflector(self).r(), Vec::new(), ""))
+        Some(Blob::new(self.global().r(), Vec::new(), ""))
     }
     fn ReceiveNullableObject(&self, _: *mut JSContext) -> *mut JSObject { ptr::null_mut() }
     fn ReceiveNullableUnion(&self) -> Option<HTMLElementOrLong> {
         Some(HTMLElementOrLong::eLong(0))
     }
     fn ReceiveNullableUnion2(&self) -> Option<EventOrString> {
         Some(EventOrString::eString(DOMString::new()))
     }
--- a/servo/components/script/dom/webglrenderingcontext.rs
+++ b/servo/components/script/dom/webglrenderingcontext.rs
@@ -5,20 +5,20 @@
 use canvas_traits::WebGLError::*;
 use canvas_traits::{CanvasCommonMsg, CanvasMsg, CanvasWebGLMsg, WebGLError};
 use canvas_traits::{WebGLFramebufferBindingRequest, WebGLParameter};
 use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
 use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::{WebGLRenderingContextMethods};
 use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::{self, WebGLContextAttributes};
 use dom::bindings::codegen::UnionTypes::ImageDataOrHTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement;
 use dom::bindings::conversions::{ToJSValConvertible, array_buffer_view_to_vec_checked, array_buffer_view_to_vec};
-use dom::bindings::global::{GlobalField, GlobalRef};
+use dom::bindings::global::GlobalRef;
 use dom::bindings::inheritance::Castable;
 use dom::bindings::js::{JS, LayoutJS, MutNullableHeap, Root};
-use dom::bindings::reflector::{Reflector, reflect_dom_object};
+use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object};
 use dom::event::{Event, EventBubbles, EventCancelable};
 use dom::htmlcanvaselement::HTMLCanvasElement;
 use dom::htmlcanvaselement::utils as canvas_utils;
 use dom::node::{Node, NodeDamage, window_from_node};
 use dom::webglbuffer::WebGLBuffer;
 use dom::webglcontextevent::WebGLContextEvent;
 use dom::webglframebuffer::WebGLFramebuffer;
 use dom::webglprogram::WebGLProgram;
@@ -64,17 +64,16 @@ bitflags! {
         const PREMULTIPLY_ALPHA = 0x02,
         const CONVERT_COLORSPACE = 0x04,
     }
 }
 
 #[dom_struct]
 pub struct WebGLRenderingContext {
     reflector_: Reflector,
-    global: GlobalField,
     renderer_id: usize,
     #[ignore_heap_size_of = "Defined in ipc-channel"]
     ipc_renderer: IpcSender<CanvasMsg>,
     canvas: JS<HTMLCanvasElement>,
     last_error: Cell<Option<WebGLError>>,
     texture_unpacking_settings: Cell<TextureUnpacking>,
     bound_texture_2d: MutNullableHeap<JS<WebGLTexture>>,
     bound_texture_cube_map: MutNullableHeap<JS<WebGLTexture>>,
@@ -93,17 +92,16 @@ impl WebGLRenderingContext {
         constellation_chan.0
                           .send(ConstellationMsg::CreateWebGLPaintThread(size, attrs, sender))
                           .unwrap();
         let result = receiver.recv().unwrap();
 
         result.map(|(ipc_renderer, renderer_id)| {
             WebGLRenderingContext {
                 reflector_: Reflector::new(),
-                global: GlobalField::from_rooted(&global),
                 renderer_id: renderer_id,
                 ipc_renderer: ipc_renderer,
                 canvas: JS::from_ref(canvas),
                 last_error: Cell::new(None),
                 texture_unpacking_settings: Cell::new(CONVERT_COLORSPACE),
                 bound_texture_2d: MutNullableHeap::new(None),
                 bound_texture_cube_map: MutNullableHeap::new(None),
                 bound_buffer_array: MutNullableHeap::new(None),
@@ -612,44 +610,44 @@ impl WebGLRenderingContextMethods for We
             shader.compile()
         }
     }
 
     // TODO(ecoal95): Probably in the future we should keep track of the
     // generated objects, either here or in the webgl thread
     // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5
     fn CreateBuffer(&self) -> Option<Root<WebGLBuffer>> {
-        WebGLBuffer::maybe_new(self.global.root().r(), self.ipc_renderer.clone())
+        WebGLBuffer::maybe_new(self.global().r(), self.ipc_renderer.clone())
     }
 
     // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6
     fn CreateFramebuffer(&self) -> Option<Root<WebGLFramebuffer>> {
-        WebGLFramebuffer::maybe_new(self.global.root().r(), self.ipc_renderer.clone())
+        WebGLFramebuffer::maybe_new(self.global().r(), self.ipc_renderer.clone())
     }
 
     // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7
     fn CreateRenderbuffer(&self) -> Option<Root<WebGLRenderbuffer>> {
-        WebGLRenderbuffer::maybe_new(self.global.root().r(), self.ipc_renderer.clone())
+        WebGLRenderbuffer::maybe_new(self.global().r(), self.ipc_renderer.clone())
     }
 
     // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8
     fn CreateTexture(&self) -> Option<Root<WebGLTexture>> {
-        WebGLTexture::maybe_new(self.global.root().r(), self.ipc_renderer.clone())
+        WebGLTexture::maybe_new(self.global().r(), self.ipc_renderer.clone())
     }
 
     // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
     fn CreateProgram(&self) -> Option<Root<WebGLProgram>> {
-        WebGLProgram::maybe_new(self.global.root().r(), self.ipc_renderer.clone())
+        WebGLProgram::maybe_new(self.global().r(), self.ipc_renderer.clone())
     }
 
     // TODO(ecoal95): Check if constants are cross-platform or if we must make a translation
     // between WebGL constants and native ones.
     // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9
     fn CreateShader(&self, shader_type: u32) -> Option<Root<WebGLShader>> {
-        WebGLShader::maybe_new(self.global.root().r(), self.ipc_renderer.clone(), shader_type)
+        WebGLShader::maybe_new(self.global().r(), self.ipc_renderer.clone(), shader_type)
     }
 
     // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5
     fn DeleteBuffer(&self, buffer: Option<&WebGLBuffer>) {
         if let Some(buffer) = buffer {
             buffer.delete()
         }
     }
@@ -801,17 +799,17 @@ impl WebGLRenderingContextMethods for We
     }
 
     // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.10
     fn GetUniformLocation(&self,
                           program: Option<&WebGLProgram>,
                           name: DOMString) -> Option<Root<WebGLUniformLocation>> {
         if let Some(program) = program {
             handle_potential_webgl_error!(self, program.get_uniform_location(name), None)
-                .map(|location| WebGLUniformLocation::new(self.global.root().r(), location))
+                .map(|location| WebGLUniformLocation::new(self.global().r(), location))
         } else {
             None
         }
     }
 
     // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.3
     fn Hint(&self, target: u32, mode: u32) {
         if target != constants::GENERATE_MIPMAP_HINT {
@@ -1078,17 +1076,17 @@ impl WebGLRenderingContextMethods for We
 
         let source = match source {
             Some(s) => s,
             None => return,
         };
 
         let (pixels, size) = match source {
             ImageDataOrHTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement::eImageData(image_data) => {
-                let global = self.global.root();
+                let global = self.global();
                 (image_data.get_data_array(&global.r()), image_data.get_size())
             },
             ImageDataOrHTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement::eHTMLImageElement(image) => {
                 let img_url = match image.get_url() {
                     Some(url) => url,
                     None => return,
                 };
 
--- a/servo/components/script/dom/websocket.rs
+++ b/servo/components/script/dom/websocket.rs
@@ -4,17 +4,17 @@
 
 use dom::bindings::cell::DOMRefCell;
 use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
 use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
 use dom::bindings::codegen::Bindings::WebSocketBinding;
 use dom::bindings::codegen::Bindings::WebSocketBinding::{BinaryType, WebSocketMethods};
 use dom::bindings::conversions::{ToJSValConvertible};
 use dom::bindings::error::{Error, Fallible};
-use dom::bindings::global::{GlobalField, GlobalRef};
+use dom::bindings::global::GlobalRef;
 use dom::bindings::inheritance::Castable;
 use dom::bindings::js::Root;
 use dom::bindings::refcounted::Trusted;
 use dom::bindings::reflector::{Reflectable, reflect_dom_object};
 use dom::bindings::str::USVString;
 use dom::bindings::trace::JSTraceable;
 use dom::blob::Blob;
 use dom::closeevent::CloseEvent;
@@ -131,54 +131,51 @@ mod close_code {
     pub const INTERNAL_ERROR: u16 = 1011;
     pub const TLS_FAILED: u16 = 1015;
 }
 
 #[dom_struct]
 pub struct WebSocket {
     eventtarget: EventTarget,
     url: Url,
-    global: GlobalField,
     ready_state: Cell<WebSocketRequestState>,
     buffered_amount: Cell<u64>,
     clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount
     #[ignore_heap_size_of = "Defined in std"]
     sender: DOMRefCell<Option<IpcSender<WebSocketDomAction>>>,
     failed: Cell<bool>, //Flag to tell if websocket was closed due to failure
     full: Cell<bool>, //Flag to tell if websocket queue is full
     clean_close: Cell<bool>, //Flag to tell if the websocket closed cleanly (not due to full or fail)
     code: Cell<u16>, //Closing code
     reason: DOMRefCell<String>, //Closing reason
     binary_type: Cell<BinaryType>,
     protocol: DOMRefCell<String>, //Subprotocol selected by server
 }
 
 impl WebSocket {
-    fn new_inherited(global: GlobalRef, url: Url) -> WebSocket {
+    fn new_inherited(url: Url) -> WebSocket {
         WebSocket {
             eventtarget: EventTarget::new_inherited(),
             url: url,
-            global: GlobalField::from_rooted(&global),
             ready_state: Cell::new(WebSocketRequestState::Connecting),
             buffered_amount: Cell::new(0),
             clearing_buffer: Cell::new(false),
             failed: Cell::new(false),
             sender: DOMRefCell::new(None),
             full: Cell::new(false),
             clean_close: Cell::new(true),
             code: Cell::new(0),
             reason: DOMRefCell::new("".to_owned()),
             binary_type: Cell::new(BinaryType::Blob),
             protocol: DOMRefCell::new("".to_owned()),
         }
-
     }
 
     fn new(global: GlobalRef, url: Url) -> Root<WebSocket> {
-        reflect_dom_object(box WebSocket::new_inherited(global, url),
+        reflect_dom_object(box WebSocket::new_inherited(url),
                            global, WebSocketBinding::Wrap)
     }
 
     pub fn Constructor(global: GlobalRef,
                        url: DOMString,
                        protocols: Option<DOMString>)
                        -> Fallible<Root<WebSocket>> {
         // Step 1.
@@ -290,17 +287,17 @@ impl WebSocket {
         let return_after_buffer = match self.ready_state.get() {
             WebSocketRequestState::Connecting => {
                 return Err(Error::InvalidState);
             },
             WebSocketRequestState::Open => false,
             WebSocketRequestState::Closing | WebSocketRequestState::Closed => true,
         };
 
-        let global = self.global.root();
+        let global = self.global();
         let chan = global.r().networking_thread_source();
         let address = Trusted::new(self, chan.clone());
 
         match data_byte_len.checked_add(self.buffered_amount.get()) {
             None => panic!(),
             Some(new_amount) => self.buffered_amount.set(new_amount)
         };
 
@@ -458,17 +455,17 @@ struct ConnectionEstablishedTask {
     addr: Trusted<WebSocket>,
     protocols: Vec<String>,
     headers: Headers,
 }
 
 impl Runnable for ConnectionEstablishedTask {
     fn handler(self: Box<Self>) {
         let ws = self.addr.root();
-        let global = ws.global.root();
+        let global = ws.r().global();
 
         // Step 1: Protocols.
         if !self.protocols.is_empty() && self.headers.get::<WebSocketProtocol>().is_none() {
             ws.failed.set(true);
             ws.ready_state.set(WebSocketRequestState::Closing);
             let thread = box CloseTask {
                 addr: self.addr,
             };
@@ -517,17 +514,17 @@ impl Runnable for BufferedAmountTask {
 struct CloseTask {
     addr: Trusted<WebSocket>,
 }
 
 impl Runnable for CloseTask {
     fn handler(self: Box<Self>) {
         let ws = self.addr.root();
         let ws = ws.r();
-        let global = ws.global.root();
+        let global = ws.global();
         ws.ready_state.set(WebSocketRequestState::Closed);
         //If failed or full, fire error event
         if ws.failed.get() || ws.full.get() {
             ws.failed.set(false);
             ws.full.set(false);
             //A Bad close
             ws.clean_close.set(false);
             ws.upcast().fire_event("error",
@@ -563,17 +560,17 @@ impl Runnable for MessageReceivedTask {
                ws.ready_state.get());
 
         // Step 1.
         if ws.ready_state.get() != WebSocketRequestState::Open {
             return;
         }
 
         // Step 2-5.
-        let global = ws.global.root();
+        let global = ws.r().global();
         // global.get_cx() returns a valid `JSContext` pointer, so this is safe.
         unsafe {
             let cx = global.r().get_cx();
             let _ar = JSAutoRequest::new(cx);
             let _ac = JSAutoCompartment::new(cx, ws.reflector().get_jsobject().get());
             let mut message = RootedValue::new(cx, UndefinedValue());
             match self.message {
                 MessageData::Text(text) => text.to_jsval(cx, message.handle_mut()),
--- a/servo/components/script/dom/window.rs
+++ b/servo/components/script/dom/window.rs
@@ -7,17 +7,17 @@ use devtools_traits::{ScriptToDevtoolsCo
 use dom::bindings::callback::ExceptionHandling;
 use dom::bindings::cell::DOMRefCell;
 use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, DocumentReadyState};
 use dom::bindings::codegen::Bindings::EventHandlerBinding::{EventHandlerNonNull, OnErrorEventHandlerNonNull};
 use dom::bindings::codegen::Bindings::FunctionBinding::Function;
 use dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOptions};
 use dom::bindings::codegen::Bindings::WindowBinding::{self, FrameRequestCallback, WindowMethods};
 use dom::bindings::error::{Error, Fallible, report_pending_exception};
-use dom::bindings::global::{GlobalRef, global_root_from_reflector};
+use dom::bindings::global::GlobalRef;
 use dom::bindings::inheritance::Castable;
 use dom::bindings::js::RootedReference;
 use dom::bindings::js::{JS, MutNullableHeap, Root};
 use dom::bindings::num::Finite;
 use dom::bindings::reflector::Reflectable;
 use dom::bindings::utils::{GlobalStaticData, WindowProxyHandler};
 use dom::browsingcontext::BrowsingContext;
 use dom::console::Console;
@@ -799,17 +799,17 @@ impl<'a, T: Reflectable> ScriptHelpers f
     fn evaluate_js_on_global_with_result(self, code: &str,
                                          rval: MutableHandleValue) {
         self.evaluate_script_on_global_with_result(code, "", rval)
     }
 
     #[allow(unsafe_code)]
     fn evaluate_script_on_global_with_result(self, code: &str, filename: &str,
                                              rval: MutableHandleValue) {
-        let global = global_root_from_reflector(self);
+        let global = self.global();
         let cx = global.r().get_cx();
         let _ar = JSAutoRequest::new(cx);
         let globalhandle = global.r().reflector().get_jsobject();
         let code: Vec<u16> = code.utf16_units().collect();
         let filename = CString::new(filename).unwrap();
 
         let _ac = JSAutoCompartment::new(cx, globalhandle.get());
         let options = CompileOptionsWrapper::new(cx, filename.as_ptr(), 0);
--- a/servo/components/script/dom/worker.rs
+++ b/servo/components/script/dom/worker.rs
@@ -2,17 +2,17 @@
  * 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/. */
 
 use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg};
 use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
 use dom::bindings::codegen::Bindings::WorkerBinding;
 use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods;
 use dom::bindings::error::{Error, ErrorResult, Fallible};
-use dom::bindings::global::{GlobalField, GlobalRef};
+use dom::bindings::global::GlobalRef;
 use dom::bindings::inheritance::Castable;
 use dom::bindings::js::Root;
 use dom::bindings::refcounted::Trusted;
 use dom::bindings::reflector::{Reflectable, reflect_dom_object};
 use dom::bindings::structuredclone::StructuredCloneData;
 use dom::bindings::trace::JSTraceable;
 use dom::dedicatedworkerglobalscope::{DedicatedWorkerGlobalScope, WorkerScriptMsg};
 use dom::errorevent::ErrorEvent;
@@ -29,38 +29,35 @@ use std::sync::mpsc::{Sender, channel};
 use util::str::DOMString;
 
 pub type TrustedWorkerAddress = Trusted<Worker>;
 
 // https://html.spec.whatwg.org/multipage/#worker
 #[dom_struct]
 pub struct Worker {
     eventtarget: EventTarget,
-    global: GlobalField,
     #[ignore_heap_size_of = "Defined in std"]
     /// Sender to the Receiver associated with the DedicatedWorkerGlobalScope
     /// this Worker created.
     sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
 }
 
 impl Worker {
-    fn new_inherited(global: GlobalRef,
-                     sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>)
+    fn new_inherited(sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>)
                      -> Worker {
         Worker {
             eventtarget: EventTarget::new_inherited(),
-            global: GlobalField::from_rooted(&global),
             sender: sender,
         }
     }
 
     pub fn new(global: GlobalRef,
                sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>)
                -> Root<Worker> {
-        reflect_dom_object(box Worker::new_inherited(global, sender),
+        reflect_dom_object(box Worker::new_inherited(sender),
                            global,
                            WorkerBinding::Wrap)
     }
 
     // https://html.spec.whatwg.org/multipage/#dom-worker
     pub fn Constructor(global: GlobalRef, script_url: DOMString) -> Fallible<Root<Worker>> {
         // Step 2-4.
         let worker_url = match global.get_url().join(&script_url) {
@@ -109,48 +106,48 @@ impl Worker {
 
         Ok(worker)
     }
 
     pub fn handle_message(address: TrustedWorkerAddress,
                           data: StructuredCloneData) {
         let worker = address.root();
 
-        let global = worker.r().global.root();
+        let global = worker.r().global();
         let target = worker.upcast();
         let _ar = JSAutoRequest::new(global.r().get_cx());
         let _ac = JSAutoCompartment::new(global.r().get_cx(), target.reflector().get_jsobject().get());
         let mut message = RootedValue::new(global.r().get_cx(), UndefinedValue());
         data.read(global.r(), message.handle_mut());
         MessageEvent::dispatch_jsval(target, global.r(), message.handle());
     }
 
     pub fn dispatch_simple_error(address: TrustedWorkerAddress) {
         let worker = address.root();
-        let global = worker.r().global.root();
+        let global = worker.r().global();
         worker.upcast().fire_simple_event("error", global.r());
     }
 
     pub fn handle_error_message(address: TrustedWorkerAddress, message: DOMString,
                                 filename: DOMString, lineno: u32, colno: u32) {
         let worker = address.root();
-        let global = worker.r().global.root();
+        let global = worker.r().global();
         let error = RootedValue::new(global.r().get_cx(), UndefinedValue());
         let errorevent = ErrorEvent::new(global.r(), atom!("error"),
                                          EventBubbles::Bubbles, EventCancelable::Cancelable,
                                          message, filename, lineno, colno, error.handle());
         errorevent.upcast::<Event>().fire(worker.upcast());
     }
 }
 
 impl WorkerMethods for Worker {
     // https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage
     fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult {
         let data = try!(StructuredCloneData::write(cx, message));
-        let address = Trusted::new(self, self.global.root().r().dom_manipulation_thread_source());
+        let address = Trusted::new(self, self.global().r().dom_manipulation_thread_source());
         self.sender.send((address, WorkerScriptMsg::DOMMessage(data))).unwrap();
         Ok(())
     }
 
     // https://html.spec.whatwg.org/multipage/#handler-dedicatedworkerglobalscope-onmessage
     event_handler!(message, GetOnmessage, SetOnmessage);
 
     // https://html.spec.whatwg.org/multipage/#handler-workerglobalscope-onerror
--- a/servo/components/script/dom/xmlhttprequest.rs
+++ b/servo/components/script/dom/xmlhttprequest.rs
@@ -11,17 +11,17 @@ use dom::bindings::codegen::Bindings::Wi
 use dom::bindings::codegen::Bindings::XMLHttpRequestBinding;
 use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestMethods;
 use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestResponseType;
 use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestResponseType::{Json, Text, _empty};
 use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams;
 use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams::{eString, eURLSearchParams};
 use dom::bindings::conversions::{ToJSValConvertible};
 use dom::bindings::error::{Error, ErrorResult, Fallible};
-use dom::bindings::global::{GlobalField, GlobalRef, GlobalRoot};
+use dom::bindings::global::{GlobalRef, GlobalRoot};
 use dom::bindings::inheritance::Castable;
 use dom::bindings::js::{JS, MutNullableHeap};
 use dom::bindings::js::{Root, RootedReference};
 use dom::bindings::refcounted::Trusted;
 use dom::bindings::reflector::{Reflectable, reflect_dom_object};
 use dom::bindings::str::ByteString;
 use dom::document::DocumentSource;
 use dom::document::{Document, IsHTMLDocument};
@@ -136,17 +136,16 @@ pub struct XMLHttpRequest {
     #[ignore_heap_size_of = "Defined in hyper"]
     request_headers: DOMRefCell<Headers>,
     request_body_len: Cell<usize>,
     sync: Cell<bool>,
     upload_complete: Cell<bool>,
     upload_events: Cell<bool>,
     send_flag: Cell<bool>,
 
-    global: GlobalField,
     timeout_cancel: DOMRefCell<Option<TimerHandle>>,
     fetch_time: Cell<i64>,
     generation_id: Cell<GenerationId>,
     response_status: Cell<Result<(), ()>>,
 }
 
 impl XMLHttpRequest {
     fn new_inherited(global: GlobalRef) -> XMLHttpRequest {
@@ -170,17 +169,16 @@ impl XMLHttpRequest {
             request_url: DOMRefCell::new(None),
             request_headers: DOMRefCell::new(Headers::new()),
             request_body_len: Cell::new(0),
             sync: Cell::new(false),
             upload_complete: Cell::new(false),
             upload_events: Cell::new(false),
             send_flag: Cell::new(false),
 
-            global: GlobalField::from_rooted(&global),
             timeout_cancel: DOMRefCell::new(None),
             fetch_time: Cell::new(0),
             generation_id: Cell::new(GenerationId(0)),
             response_status: Cell::new(Ok(())),
         }
     }
     pub fn new(global: GlobalRef) -> Root<XMLHttpRequest> {
         reflect_dom_object(box XMLHttpRequest::new_inherited(global),
@@ -320,17 +318,17 @@ impl XMLHttpRequestMethods for XMLHttpRe
                 // Step 3
                 if !method.is_token() {
                     return Err(Error::Syntax)
                 }
 
                 *self.request_method.borrow_mut() = parsed_method;
 
                 // Step 6
-                let base = self.global.root().r().get_url();
+                let base = self.global().r().get_url();
                 let parsed_url = match base.join(&url) {
                     Ok(parsed) => parsed,
                     Err(_) => return Err(Error::Syntax) // Step 7
                 };
                 // XXXManishearth Do some handling of username/passwords
                 if self.sync.get() {
                     // FIXME: This should only happen if the global environment is a document environment
                     if self.timeout.get() != 0 || self.with_credentials.get() || self.response_type.get() != _empty {
@@ -452,17 +450,17 @@ impl XMLHttpRequestMethods for XMLHttpRe
 
     // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials
     fn SetWithCredentials(&self, with_credentials: bool) -> ErrorResult {
         match self.ready_state.get() {
             XMLHttpRequestState::HeadersReceived |
             XMLHttpRequestState::Loading |
             XMLHttpRequestState::Done => Err(Error::InvalidState),
             _ if self.send_flag.get() => Err(Error::InvalidState),
-            _ => match self.global.root() {
+            _ => match self.global() {
                 GlobalRoot::Window(_) if self.sync.get() => Err(Error::InvalidAccess),
                 _ => {
                     self.with_credentials.set(with_credentials);
                     Ok(())
                 },
             },
         }
     }
@@ -514,17 +512,17 @@ impl XMLHttpRequestMethods for XMLHttpRe
                 self.dispatch_upload_progress_event(atom!("loadstart"), Some(0));
                 if self.generation_id.get() != gen_id {
                     return Ok(());
                 }
             }
 
         }
 
-        let global = self.global.root();
+        let global = self.global();
         let pipeline_id = global.r().pipeline();
         let mut load_data =
             LoadData::new(LoadContext::Browsing,
                           self.request_url.borrow().clone().unwrap(),
                           Some(pipeline_id));
         if load_data.url.origin().ne(&global.r().get_url().origin()) {
             load_data.credentials_flag = self.WithCredentials();
         }
@@ -557,18 +555,18 @@ impl XMLHttpRequestMethods for XMLHttpRe
         if !load_data.preserved_headers.has::<Accept>() {
             let mime = Mime(mime::TopLevel::Star, mime::SubLevel::Star, vec![]);
             load_data.preserved_headers.set(Accept(vec![qitem(mime)]));
         }
 
         load_data.method = (*self.request_method.borrow()).clone();
 
         // CORS stuff
-        let global = self.global.root();
-        let referer_url = self.global.root().r().get_url();
+        let global = self.global();
+        let referer_url = self.global().r().get_url();
         let mode = if self.upload_events.get() {
             RequestMode::ForcedPreflight
         } else {
             RequestMode::CORS
         };
         let mut combined_headers = load_data.headers.clone();
         combined_headers.extend(load_data.preserved_headers.iter());
         let cors_request = CORSRequest::maybe_new(referer_url.clone(),
@@ -681,17 +679,17 @@ impl XMLHttpRequestMethods for XMLHttpRe
 
     // https://xhr.spec.whatwg.org/#the-responsetype-attribute
     fn ResponseType(&self) -> XMLHttpRequestResponseType {
         self.response_type.get()
     }
 
     // https://xhr.spec.whatwg.org/#the-responsetype-attribute
     fn SetResponseType(&self, response_type: XMLHttpRequestResponseType) -> ErrorResult {
-        match self.global.root() {
+        match self.global() {
             GlobalRoot::Worker(_) if response_type == XMLHttpRequestResponseType::Document
             => return Ok(()),
             _ => {}
         }
         match self.ready_state.get() {
             XMLHttpRequestState::Loading | XMLHttpRequestState::Done => Err(Error::InvalidState),
             _ if self.sync.get() => Err(Error::InvalidAccess),
             _ => {
@@ -784,17 +782,17 @@ impl XMLHttpRequestMethods for XMLHttpRe
 
 pub type TrustedXHRAddress = Trusted<XMLHttpRequest>;
 
 
 impl XMLHttpRequest {
     fn change_ready_state(&self, rs: XMLHttpRequestState) {
         assert!(self.ready_state.get() != rs);
         self.ready_state.set(rs);
-        let global = self.global.root();
+        let global = self.global();
         let event = Event::new(global.r(),
                                atom!("readystatechange"),
                                EventBubbles::DoesNotBubble,
                                EventCancelable::Cancelable);
         event.fire(self.upcast());
     }
 
     fn process_headers_available(&self, cors_request: Option<CORSRequest>,
@@ -965,17 +963,17 @@ impl XMLHttpRequest {
 
     fn insert_trusted_header(&self, name: String, value: String) {
         // Insert a header without checking spec-compliance
         // Use for hardcoded headers
         self.request_headers.borrow_mut().set_raw(name, vec![value.into_bytes()]);
     }
 
     fn dispatch_progress_event(&self, upload: bool, type_: Atom, loaded: u64, total: Option<u64>) {
-        let global = self.global.root();
+        let global = self.global();
         let progressevent = ProgressEvent::new(global.r(),
                                                type_,
                                                EventBubbles::DoesNotBubble,
                                                EventCancelable::NotCancelable,
                                                total.is_some(), loaded,
                                                total.unwrap_or(0));
         let target = if upload {
             self.upload.upcast()
@@ -1019,28 +1017,28 @@ impl XMLHttpRequest {
                     xhr: self.xhr.clone(),
                     generation_id: self.generation_id,
                 }
             }
         }
 
         // Sets up the object to timeout in a given number of milliseconds
         // This will cancel all previous timeouts
-        let global = self.global.root();
+        let global = self.global();
         let callback = ScheduledXHRTimeout {
             xhr: Trusted::new(self, global.r().networking_thread_source()),
             generation_id: self.generation_id.get(),
         };
         let duration = Length::new(duration_ms as u64);
         *self.timeout_cancel.borrow_mut() = Some(global.r().schedule_callback(box callback, duration));
     }
 
     fn cancel_timeout(&self) {
         if let Some(handle) = self.timeout_cancel.borrow_mut().take() {
-            let global = self.global.root();
+            let global = self.global();
             global.r().unschedule_callback(handle);
         }
     }
 
     //FIXME: add support for XML encoding guess stuff using XML spec
     fn text_response(&self) -> String {
         let encoding = self.final_charset().unwrap_or(UTF_8);
 
@@ -1079,44 +1077,44 @@ impl XMLHttpRequest {
             _ => { return None; }
         }
         temp_doc.set_encoding_name(DOMString::from(charset.name()));
         Some(temp_doc)
     }
 
     fn document_text_html(&self) -> Root<Document>{
         let charset = self.final_charset().unwrap_or(UTF_8);
-        let wr = self.global.root();
+        let wr = self.global();
         let wr = wr.r();
         let decoded = charset.decode(&self.response.borrow(), DecoderTrap::Replace).unwrap().to_owned();
         let document = self.new_doc(IsHTMLDocument::HTMLDocument);
         // TODO: Disable scripting while parsing
         parse_html(document.r(), DOMString::from(decoded), wr.get_url(), ParseContext::Owner(Some(wr.pipeline())));
         document
     }
 
     fn handle_xml(&self) -> Root<Document> {
         let charset = self.final_charset().unwrap_or(UTF_8);
-        let wr = self.global.root();
+        let wr = self.global();
         let wr = wr.r();
         let decoded = charset.decode(&self.response.borrow(), DecoderTrap::Replace).unwrap().to_owned();
         let document = self.new_doc(IsHTMLDocument::NonHTMLDocument);
         // TODO: Disable scripting while parsing
         parse_xml(document.r(), DOMString::from(decoded), wr.get_url(), xml::ParseContext::Owner(Some(wr.pipeline())));
         document
     }
 
     fn new_doc(&self, is_html_document: IsHTMLDocument) -> Root<Document> {
-        let wr = self.global.root();
+        let wr = self.global();
         let wr = wr.r();
         let win = wr.as_window();
         let doc = win.Document();
         let doc = doc.r();
         let docloader = DocumentLoader::new(&*doc.loader());
-        let base = self.global.root().r().get_url();
+        let base = self.global().r().get_url();
         let parsed_url = match base.join(&self.ResponseURL()) {
             Ok(parsed) => Some(parsed),
             Err(_) => None // Step 7
         };
         let mime_type = self.final_mime_type();
         let content_type = mime_type.map(|mime|{
             DOMString::from(format!("{}", mime))
         });
--- a/servo/components/script/timers.rs
+++ b/servo/components/script/timers.rs
@@ -1,16 +1,15 @@
 /* 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/. */
 
 use dom::bindings::callback::ExceptionHandling::Report;
 use dom::bindings::cell::DOMRefCell;
 use dom::bindings::codegen::Bindings::FunctionBinding::Function;
-use dom::bindings::global::global_root_from_reflector;
 use dom::bindings::reflector::Reflectable;
 use dom::bindings::trace::JSTraceable;
 use dom::window::ScriptHelpers;
 use euclid::length::Length;
 use ipc_channel::ipc::IpcSender;
 use js::jsapi::{HandleValue, Heap, RootedValue};
 use js::jsval::{JSVal, UndefinedValue};
 use num::traits::Saturating;
@@ -284,17 +283,17 @@ impl ActiveTimers {
                 timer.nesting_level += 1;
                 timer.next_call = base_time + timer.duration;
                 self.insert_timer(timer);
             }
 
             // step 14
             match callback {
                 InternalTimerCallback::StringTimerCallback(code_str) => {
-                    let cx = global_root_from_reflector(this).r().get_cx();
+                    let cx = this.global().r().get_cx();
                     let mut rval = RootedValue::new(cx, UndefinedValue());
 
                     this.evaluate_js_on_global_with_result(&code_str, rval.handle_mut());
                 },
                 InternalTimerCallback::FunctionTimerCallback(function, arguments) => {
                     let arguments: Vec<JSVal> = arguments.iter().map(|arg| arg.get()).collect();
                     let arguments = arguments.iter().by_ref().map(|arg| unsafe {
                         HandleValue::from_marked_location(arg)