Merge mozilla-central and inbound
authorEd Morley <emorley@mozilla.com>
Mon, 22 Jul 2013 16:52:23 +0100
changeset 151752 f155634c57b98af2c60a4fb813690fb667e295c6
parent 151701 308e3cf5ba75fdf8ed3bdd3dc766410b708b98ef (current diff)
parent 151751 582a0b8558d17aeba214fa2b4a8d86e77f9f497a (diff)
child 151753 b4b9e91729d369d62fd7651839cffc9cc24e6807
push id2859
push userakeybl@mozilla.com
push dateMon, 16 Sep 2013 19:14:59 +0000
treeherdermozilla-beta@87d3c51cd2bf [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone25.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge mozilla-central and inbound
--- a/accessible/src/windows/sdn/sdnTextAccessible.cpp
+++ b/accessible/src/windows/sdn/sdnTextAccessible.cpp
@@ -29,17 +29,17 @@ IMPL_IUNKNOWN_QUERY_TAIL_AGGREGATED(mAcc
 
 STDMETHODIMP
 sdnTextAccessible::get_domText(BSTR __RPC_FAR* aText)
 {
   A11Y_TRYBLOCK_BEGIN
 
   if (!aText)
     return E_INVALIDARG;
-  *aText = NULL;
+  *aText = nullptr;
 
   if (mAccessible->IsDefunct())
     return CO_E_OBJNOTCONNECTED;
 
   nsAutoString nodeValue;
 
   nsCOMPtr<nsIDOMNode> DOMNode(do_QueryInterface(mAccessible->GetContent()));
   DOMNode->GetNodeValue(nodeValue);
@@ -165,17 +165,17 @@ sdnTextAccessible::scrollToSubstring(uns
 
 STDMETHODIMP
 sdnTextAccessible::get_fontFamily(BSTR __RPC_FAR* aFontFamily)
 {
   A11Y_TRYBLOCK_BEGIN
 
   if (!aFontFamily)
     return E_INVALIDARG;
-  *aFontFamily = NULL;
+  *aFontFamily = nullptr;
 
   if (mAccessible->IsDefunct())
     return CO_E_OBJNOTCONNECTED;
 
   nsIFrame* frame = mAccessible->GetFrame();
   if (!frame)
     return E_FAIL;
 
--- a/browser/base/content/browser-plugins.js
+++ b/browser/base/content/browser-plugins.js
@@ -340,18 +340,18 @@ var gPluginHandler = {
     // if this isn't a known plugin, we can't activate it
     // (this also guards pluginHost.getPermissionStringForType against
     // unexpected input)
     if (!gPluginHandler.isKnownPlugin(objLoadingContent))
       return false;
 
     let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);
     let permissionString = pluginHost.getPermissionStringForType(objLoadingContent.actualType);
-    let browser = gBrowser.getBrowserForDocument(objLoadingContent.ownerDocument.defaultView.top.document);
-    let pluginPermission = Services.perms.testPermission(browser.currentURI, permissionString);
+    let principal = objLoadingContent.ownerDocument.defaultView.top.document.nodePrincipal;
+    let pluginPermission = Services.perms.testPermissionFromPrincipal(principal, permissionString);
 
     let isFallbackTypeValid =
       objLoadingContent.pluginFallbackType >= Ci.nsIObjectLoadingContent.PLUGIN_CLICK_TO_PLAY &&
       objLoadingContent.pluginFallbackType <= Ci.nsIObjectLoadingContent.PLUGIN_VULNERABLE_NO_UPDATE;
 
     if (objLoadingContent.pluginFallbackType == Ci.nsIObjectLoadingContent.PLUGIN_PLAY_PREVIEW) {
       // checking if play preview is subject to CTP rules
       let playPreviewInfo = pluginHost.getPlayPreviewInfo(objLoadingContent.actualType);
@@ -506,17 +506,18 @@ var gPluginHandler = {
     let browser = gBrowser.getBrowserForDocument(doc.defaultView.top.document);
     let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);
     let objLoadingContent = aPlugin.QueryInterface(Ci.nsIObjectLoadingContent);
     // guard against giving pluginHost.getPermissionStringForType a type
     // not associated with any known plugin
     if (!gPluginHandler.isKnownPlugin(objLoadingContent))
       return;
     let permissionString = pluginHost.getPermissionStringForType(objLoadingContent.actualType);
-    let pluginPermission = Services.perms.testPermission(browser.currentURI, permissionString);
+    let principal = doc.defaultView.top.document.nodePrincipal;
+    let pluginPermission = Services.perms.testPermissionFromPrincipal(principal, permissionString);
 
     let overlay = doc.getAnonymousElementByAttribute(aPlugin, "class", "mainBox");
 
     if (pluginPermission == Ci.nsIPermissionManager.DENY_ACTION) {
       if (overlay)
         overlay.style.visibility = "hidden";
       return;
     }
@@ -625,23 +626,38 @@ var gPluginHandler = {
     }
     else if (event == "dismissed") {
       // Once the popup is dismissed, clicking the icon should show the full
       // list again
       this.options.primaryPlugin = null;
     }
   },
 
+  // Match the behaviour of nsPermissionManager
+  _getHostFromPrincipal: function PH_getHostFromPrincipal(principal) {
+    if (!principal.URI || principal.URI.schemeIs("moz-nullprincipal")) {
+      return "(null)";
+    }
+
+    try {
+      if (principal.URI.host)
+        return principal.URI.host;
+    } catch (e) {}
+
+    return principal.origin;
+  },
+
   _makeCenterActions: function PH_makeCenterActions(notification) {
-    let browser = notification.browser;
-    let contentWindow = browser.contentWindow;
+    let contentWindow = notification.browser.contentWindow;
     let cwu = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
                            .getInterface(Ci.nsIDOMWindowUtils);
 
-    let principal = Services.scriptSecurityManager.getNoAppCodebasePrincipal(browser.currentURI);
+    let principal = contentWindow.document.nodePrincipal;
+    // This matches the behavior of nsPermssionManager, used for display purposes only
+    let principalHost = this._getHostFromPrincipal(principal);
 
     let centerActions = [];
     let pluginsFound = new Set();
     for (let plugin of cwu.plugins) {
       plugin.QueryInterface(Ci.nsIObjectLoadingContent);
       if (plugin.getContentTypeForMIMEType(plugin.actualType) != Ci.nsIObjectLoadingContent.TYPE_PLUGIN) {
         continue;
       }
@@ -661,17 +677,17 @@ var gPluginHandler = {
       // the tighter loop above.
       let permissionObj = Services.perms.
         getPermissionObject(principal, pluginInfo.permissionString, false);
       if (permissionObj) {
         pluginInfo.pluginPermissionHost = permissionObj.host;
         pluginInfo.pluginPermissionType = permissionObj.expireType;
       }
       else {
-        pluginInfo.pluginPermissionHost = browser.currentURI.host;
+        pluginInfo.pluginPermissionHost = principalHost;
         pluginInfo.pluginPermissionType = undefined;
       }
 
       let url;
       // TODO: allow the blocklist to specify a better link, bug 873093
       if (pluginInfo.blocklistState == Ci.nsIBlocklistService.STATE_VULNERABLE_UPDATE_AVAILABLE) {
         url = Services.urlFormatter.formatURLPref("plugins.update.url");
       }
@@ -724,28 +740,29 @@ var gPluginHandler = {
       case "continue":
         break;
       default:
         Cu.reportError(Error("Unexpected plugin state: " + aNewState));
         return;
     }
 
     let browser = aNotification.browser;
+    let contentWindow = browser.contentWindow;
     if (aNewState != "continue") {
-      Services.perms.add(browser.currentURI, aPluginInfo.permissionString,
-                         permission, expireType, expireTime);
+      let principal = contentWindow.document.nodePrincipal;
+      Services.perms.addFromPrincipal(principal, aPluginInfo.permissionString,
+                                      permission, expireType, expireTime);
 
       if (aNewState == "block") {
         return;
       }
     }
 
     // Manually activate the plugins that would have been automatically
     // activated.
-    let contentWindow = browser.contentWindow;
     let cwu = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
                            .getInterface(Ci.nsIDOMWindowUtils);
     let plugins = cwu.plugins;
     let pluginHost = Cc["@mozilla.org/plugin/host;1"].getService(Ci.nsIPluginHost);
 
     for (let plugin of plugins) {
       plugin.QueryInterface(Ci.nsIObjectLoadingContent);
       // canActivatePlugin will return false if this isn't a known plugin type,
--- a/browser/base/content/test/Makefile.in
+++ b/browser/base/content/test/Makefile.in
@@ -187,16 +187,17 @@ MOCHITEST_BROWSER_FILES = \
                  browser_bug887515.js \
                  browser_canonizeURL.js \
                  browser_clearplugindata_noage.html \
                  browser_clearplugindata.html \
                  browser_clearplugindata.js \
                  browser_contentAreaClick.js \
                  browser_contextSearchTabPosition.js \
                  browser_CTP_drag_drop.js \
+                 browser_CTP_data_urls.js \
                  browser_ctrlTab.js \
                  browser_customize_popupNotification.js \
                  browser_customize.js \
                  browser_disablechrome.js \
                  browser_discovery.js \
                  browser_duplicateIDs.js \
                  browser_findbarClose.js \
                  browser_fullscreen-window-open.js \
@@ -312,16 +313,17 @@ MOCHITEST_BROWSER_FILES = \
                  plugin_bug820497.html \
                  plugin_clickToPlayAllow.html \
                  plugin_clickToPlayDeny.html \
                  plugin_hidden_to_visible.html \
                  plugin_test.html \
                  plugin_test2.html \
                  plugin_test3.html \
                  plugin_two_types.html \
+                 plugin_data_url.html \
                  plugin_unknown.html \
                  pluginCrashCommentAndURL.html \
                  POSTSearchEngine.xml \
                  print_postdata.sjs \
                  redirect_bug623155.sjs \
                  test_bug435035.html \
                  test_bug462673.html \
                  test_bug628179.html \
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/browser_CTP_data_urls.js
@@ -0,0 +1,239 @@
+var rootDir = getRootDirectory(gTestPath);
+const gTestRoot = rootDir;
+const gHttpTestRoot = rootDir.replace("chrome://mochitests/content/", "http://127.0.0.1:8888/");
+
+var gTestBrowser = null;
+var gNextTest = null;
+var gPluginHost = Components.classes["@mozilla.org/plugin/host;1"].getService(Components.interfaces.nsIPluginHost);
+
+Components.utils.import("resource://gre/modules/Services.jsm");
+
+// This listens for the next opened tab and checks it is of the right url.
+// opencallback is called when the new tab is fully loaded
+// closecallback is called when the tab is closed
+function TabOpenListener(url, opencallback, closecallback) {
+  this.url = url;
+  this.opencallback = opencallback;
+  this.closecallback = closecallback;
+
+  gBrowser.tabContainer.addEventListener("TabOpen", this, false);
+}
+
+TabOpenListener.prototype = {
+  url: null,
+  opencallback: null,
+  closecallback: null,
+  tab: null,
+  browser: null,
+
+  handleEvent: function(event) {
+    if (event.type == "TabOpen") {
+      gBrowser.tabContainer.removeEventListener("TabOpen", this, false);
+      this.tab = event.originalTarget;
+      this.browser = this.tab.linkedBrowser;
+      gBrowser.addEventListener("pageshow", this, false);
+    } else if (event.type == "pageshow") {
+      if (event.target.location.href != this.url)
+        return;
+      gBrowser.removeEventListener("pageshow", this, false);
+      this.tab.addEventListener("TabClose", this, false);
+      var url = this.browser.contentDocument.location.href;
+      is(url, this.url, "Should have opened the correct tab");
+      this.opencallback(this.tab, this.browser.contentWindow);
+    } else if (event.type == "TabClose") {
+      if (event.originalTarget != this.tab)
+        return;
+      this.tab.removeEventListener("TabClose", this, false);
+      this.opencallback = null;
+      this.tab = null;
+      this.browser = null;
+      // Let the window close complete
+      executeSoon(this.closecallback);
+      this.closecallback = null;
+    }
+  }
+};
+
+function test() {
+  waitForExplicitFinish();
+  registerCleanupFunction(function() {
+    clearAllPluginPermissions();
+    Services.prefs.clearUserPref("extensions.blocklist.suppressUI");
+    getTestPlugin().enabledState = Ci.nsIPluginTag.STATE_ENABLED;
+    getTestPlugin("Second Test Plug-in").enabledState = Ci.nsIPluginTag.STATE_ENABLED;
+  });
+  Services.prefs.setBoolPref("extensions.blocklist.suppressUI", true);
+
+  var newTab = gBrowser.addTab();
+  gBrowser.selectedTab = newTab;
+  gTestBrowser = gBrowser.selectedBrowser;
+  gTestBrowser.addEventListener("load", pageLoad, true);
+
+  Services.prefs.setBoolPref("plugins.click_to_play", true);
+  getTestPlugin().enabledState = Ci.nsIPluginTag.STATE_CLICKTOPLAY;
+  getTestPlugin("Second Test Plug-in").enabledState = Ci.nsIPluginTag.STATE_CLICKTOPLAY;
+
+  prepareTest(test1a, gHttpTestRoot + "plugin_data_url.html");
+}
+
+function finishTest() {
+  clearAllPluginPermissions();
+  gTestBrowser.removeEventListener("load", pageLoad, true);
+  gBrowser.removeCurrentTab();
+  window.focus();
+  finish();
+}
+
+function pageLoad() {
+  // The plugin events are async dispatched and can come after the load event
+  // This just allows the events to fire before we then go on to test the states
+  executeSoon(gNextTest);
+}
+
+function prepareTest(nextTest, url) {
+  gNextTest = nextTest;
+  gTestBrowser.contentWindow.location = url;
+}
+
+// Test that the click-to-play doorhanger still works when navigating to data URLs
+function test1a() {
+  let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
+  ok(popupNotification, "Test 1a, Should have a click-to-play notification");
+
+  let plugin = gTestBrowser.contentDocument.getElementById("test");
+  let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
+  ok(!objLoadingContent.activated, "Test 1a, Plugin should not be activated");
+
+  gNextTest = test1b;
+  gTestBrowser.contentDocument.getElementById("data-link-1").click();
+}
+
+function test1b() {
+  let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
+  ok(popupNotification, "Test 1b, Should have a click-to-play notification");
+
+  let plugin = gTestBrowser.contentDocument.getElementById("test");
+  let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
+  ok(!objLoadingContent.activated, "Test 1b, Plugin should not be activated");
+
+  // Simulate clicking the "Allow Always" button.
+  popupNotification.reshow();
+  PopupNotifications.panel.firstChild._primaryButton.click();
+
+  let condition = function() objLoadingContent.activated;
+  waitForCondition(condition, test1c, "Test 1b, Waited too long for plugin to activate");
+}
+
+function test1c() {
+  clearAllPluginPermissions();
+  prepareTest(test2a, gHttpTestRoot + "plugin_data_url.html");
+}
+
+// Test that the click-to-play notification doesn't break when navigating to data URLs with multiple plugins
+function test2a() {
+  let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
+  ok(popupNotification, "Test 2a, Should have a click-to-play notification");
+  let plugin = gTestBrowser.contentDocument.getElementById("test");
+  let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
+  ok(!objLoadingContent.activated, "Test 2a, Plugin should not be activated");
+
+  gNextTest = test2b;
+  gTestBrowser.contentDocument.getElementById("data-link-2").click();
+}
+
+function test2b() {
+  let notification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
+  ok(notification, "Test 2b, Should have a click-to-play notification");
+
+  // Simulate choosing "Allow now" for the test plugin
+  notification.reshow();
+  is(notification.options.centerActions.length, 2, "Test 2b, Should have two types of plugin in the notification");
+
+  var centerAction = null;
+  for (var action of notification.options.centerActions) {
+    if (action.pluginName == "Test") {
+      centerAction = action;
+      break;
+    }
+  }
+  ok(centerAction, "Test 2b, found center action for the Test plugin");
+
+  var centerItem = null;
+  for (var item of PopupNotifications.panel.firstChild.childNodes) {
+    is(item.value, "block", "Test 2b, all plugins should start out blocked");
+    if (item.action == centerAction) {
+      centerItem = item;
+      break;
+    }
+  }
+  ok(centerItem, "Test 2b, found center item for the Test plugin");
+
+  // "click" the button to activate the Test plugin
+  centerItem.value = "allownow";
+  PopupNotifications.panel.firstChild._primaryButton.click();
+
+  let plugin = gTestBrowser.contentDocument.getElementById("test1");
+  let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
+  let condition = function() objLoadingContent.activated;
+  waitForCondition(condition, test2c, "Test 2b, Waited too long for plugin to activate");
+}
+
+function test2c() {
+  let plugin = gTestBrowser.contentDocument.getElementById("test1");
+  let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
+  ok(objLoadingContent.activated, "Test 2c, Plugin should be activated");
+
+  clearAllPluginPermissions();
+  prepareTest(test3a, gHttpTestRoot + "plugin_data_url.html");
+}
+
+// Test that when navigating to a data url, the plugin permission is inherited
+function test3a() {
+  let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
+  ok(popupNotification, "Test 3a, Should have a click-to-play notification");
+  let plugin = gTestBrowser.contentDocument.getElementById("test");
+  let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
+  ok(!objLoadingContent.activated, "Test 3a, Plugin should not be activated");
+
+  // Simulate clicking the "Allow Always" button.
+  popupNotification.reshow();
+  PopupNotifications.panel.firstChild._primaryButton.click();
+
+  let condition = function() objLoadingContent.activated;
+  waitForCondition(condition, test3b, "Test 3a, Waited too long for plugin to activate");
+}
+
+function test3b() {
+  gNextTest = test3c;
+  gTestBrowser.contentDocument.getElementById("data-link-1").click();
+}
+
+function test3c() {
+  let plugin = gTestBrowser.contentDocument.getElementById("test");
+  let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
+  ok(objLoadingContent.activated, "Test 3c, Plugin should be activated");
+
+  clearAllPluginPermissions();
+  prepareTest(test4b, 'data:text/html,<embed id="test" style="width: 200px; height: 200px" type="application/x-test"/>');
+}
+
+// Test that the click-to-play doorhanger still works when directly navigating to data URLs
+function test4a() {
+  let popupNotification = PopupNotifications.getNotification("click-to-play-plugins", gTestBrowser);
+  ok(popupNotification, "Test 4a, Should have a click-to-play notification");
+  let plugin = gTestBrowser.contentDocument.getElementById("test");
+  let objLoadingContent = plugin.QueryInterface(Ci.nsIObjectLoadingContent);
+  ok(!objLoadingContent.activated, "Test 4a, Plugin should not be activated");
+
+  // Simulate clicking the "Allow Always" button.
+  popupNotification.reshow();
+  PopupNotifications.panel.firstChild._primaryButton.click();
+
+  let condition = function() objLoadingContent.activated;
+  waitForCondition(condition, test4b, "Test 4a, Waited too long for plugin to activate");
+}
+
+function test4b() {
+  clearAllPluginPermissions();
+  finishTest();
+}
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/plugin_data_url.html
@@ -0,0 +1,11 @@
+<html>
+<body>
+  <a id="data-link-1" href='data:text/html,<embed id="test" style="width: 200px; height: 200px" type="application/x-test"/>'>
+    data: with one plugin
+  </a><br />
+  <a id="data-link-2" href='data:text/html,<embed id="test1" style="width: 200px; height: 200px" type="application/x-test"/><embed id="test2" style="width: 200px; height: 200px" type="application/x-second-test"/>'>
+    data: with two plugins
+  </a><br />
+  <object id="test" style="width: 200px; height: 200px" type="application/x-test"></object>
+</body>
+</html>
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -1595,17 +1595,18 @@
           var grid = document.getAnonymousElementByAttribute(this, "anonid", "click-to-play-plugins-notification-center-box");
 
           if (this._states.SINGLE == state) {
             grid.hidden = true;
             this._setupSingleState();
             return;
           }
 
-          this._setupDescription("pluginActivateMultiple.message");
+          let host = gPluginHandler._getHostFromPrincipal(this.notification.browser.contentWindow.document.nodePrincipal);
+          this._setupDescription("pluginActivateMultiple.message", null, host);
 
           var showBox = document.getAnonymousElementByAttribute(this, "anonid", "plugin-notification-showbox");
 
           var dialogStrings = Services.strings.createBundle("chrome://global/locale/dialog.properties");
           this._primaryButton.label = dialogStrings.GetStringFromName("button-accept");
           this._primaryButton.setAttribute("default", "true");
 
           this._secondaryButton.label = dialogStrings.GetStringFromName("button-cancel");
@@ -1758,19 +1759,16 @@
         <parameter name="host" />
         <body><![CDATA[
           var bsn = this._brandShortName;
           var span = document.getAnonymousElementByAttribute(this, "anonid", "click-to-play-plugins-notification-description");
           while (span.lastChild) {
             span.removeChild(span.lastChild);
           }
 
-          if (!host) {
-            host = this.notification.browser.currentURI.host;
-          }
           var args = ["__host__", this._brandShortName];
           if (pluginName) {
             args.unshift(pluginName);
           }
           var bases = gNavigatorBundle.getFormattedString(baseString, args).
             split("__host__", 2);
 
           span.appendChild(document.createTextNode(bases[0]));
--- a/content/base/public/Element.h
+++ b/content/base/public/Element.h
@@ -33,17 +33,16 @@
 #include "nsContentUtils.h"
 #include "nsIScrollableFrame.h"
 #include "mozilla/dom/Attr.h"
 #include "nsISMILAttr.h"
 #include "nsClientRect.h"
 #include "nsEvent.h"
 #include "nsAttrValue.h"
 #include "mozilla/dom/BindingDeclarations.h"
-#include "nsIHTMLCollection.h"
 #include "Units.h"
 
 class nsIDOMEventListener;
 class nsIFrame;
 class nsIDOMMozNamedAttrMap;
 class nsIDOMCSSStyleDeclaration;
 class nsIURI;
 class nsINodeInfo;
@@ -595,46 +594,16 @@ public:
   already_AddRefed<nsIHTMLCollection>
     GetElementsByTagName(const nsAString& aQualifiedName);
   already_AddRefed<nsIHTMLCollection>
     GetElementsByTagNameNS(const nsAString& aNamespaceURI,
                            const nsAString& aLocalName,
                            ErrorResult& aError);
   already_AddRefed<nsIHTMLCollection>
     GetElementsByClassName(const nsAString& aClassNames);
-  Element* GetFirstElementChild() const;
-  Element* GetLastElementChild() const;
-  Element* GetPreviousElementSibling() const
-  {
-    nsIContent* previousSibling = GetPreviousSibling();
-    while (previousSibling) {
-      if (previousSibling->IsElement()) {
-        return previousSibling->AsElement();
-      }
-      previousSibling = previousSibling->GetPreviousSibling();
-    }
-
-    return nullptr;
-  }
-  Element* GetNextElementSibling() const
-  {
-    nsIContent* nextSibling = GetNextSibling();
-    while (nextSibling) {
-      if (nextSibling->IsElement()) {
-        return nextSibling->AsElement();
-      }
-      nextSibling = nextSibling->GetNextSibling();
-    }
-
-    return nullptr;
-  }
-  uint32_t ChildElementCount()
-  {
-    return Children()->Length();
-  }
   bool MozMatchesSelector(const nsAString& aSelector,
                           ErrorResult& aError);
   void SetCapture(bool aRetargetToElement)
   {
     // If there is already an active capture, ignore this request. This would
     // occur if a splitter, frame resizer, etc had already captured and we don't
     // want to override those.
     if (!nsIPresShell::GetCapturingContent()) {
--- a/content/base/public/FragmentOrElement.h
+++ b/content/base/public/FragmentOrElement.h
@@ -18,26 +18,26 @@
 #include "nsCycleCollectionParticipant.h" // NS_DECL_CYCLE_*
 #include "nsIContent.h"                   // base class
 #include "nsIDOMTouchEvent.h"             // base class (nsITouchEventReceiver)
 #include "nsIDOMXPathNSResolver.h"        // base class
 #include "nsIInlineEventHandlers.h"       // base class
 #include "nsINodeList.h"                  // base class
 #include "nsIWeakReference.h"             // base class
 #include "nsNodeUtils.h"                  // class member nsNodeUtils::CloneNodeImpl
+#include "nsIHTMLCollection.h"
 
 class ContentUnbinder;
 class nsContentList;
 class nsDOMAttributeMap;
 class nsDOMTokenList;
 class nsIControllers;
 class nsICSSDeclaration;
 class nsIDocument;
 class nsDOMStringMap;
-class nsIHTMLCollection;
 class nsINodeInfo;
 class nsIURI;
 
 /**
  * Class that implements the nsIDOMNodeList interface (a list of children of
  * the content), by holding a reference to the content and delegating GetLength
  * and Item to its existing child list.
  * @see nsIDOMNodeList
@@ -224,16 +224,20 @@ public:
 
   virtual void DestroyContent() MOZ_OVERRIDE;
   virtual void SaveSubtreeState() MOZ_OVERRIDE;
 
   virtual const nsAttrValue* DoGetClasses() const MOZ_OVERRIDE;
   NS_IMETHOD WalkContentStyleRules(nsRuleWalker* aRuleWalker) MOZ_OVERRIDE;
 
   nsIHTMLCollection* Children();
+  uint32_t ChildElementCount()
+  {
+    return Children()->Length();
+  }
 
 public:
   /**
    * If there are listeners for DOMNodeInserted event, fires the event on all
    * aNodes
    */
   static void FireNodeInserted(nsIDocument* aDoc,
                                nsINode* aParent,
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -48,16 +48,17 @@ class nsIDocShell;
 class nsIDocumentObserver;
 class nsIDOMDocument;
 class nsIDOMDocumentFragment;
 class nsIDOMDocumentType;
 class nsIDOMElement;
 class nsIDOMNodeList;
 class nsIDOMXPathExpression;
 class nsIDOMXPathNSResolver;
+class nsIHTMLCollection;
 class nsILayoutHistoryState;
 class nsIObjectLoadingContent;
 class nsIObserver;
 class nsIPresShell;
 class nsIPrincipal;
 class nsIRequest;
 class nsIStreamListener;
 class nsIStyleRule;
@@ -2115,16 +2116,20 @@ public:
   {
     return mStyleSheetChangeEventsEnabled;
   }
 
   void ObsoleteSheet(nsIURI *aSheetURI, mozilla::ErrorResult& rv);
 
   void ObsoleteSheet(const nsAString& aSheetURI, mozilla::ErrorResult& rv);
 
+  // ParentNode
+  nsIHTMLCollection* Children();
+  uint32_t ChildElementCount();
+
   virtual nsHTMLDocument* AsHTMLDocument() { return nullptr; }
 
   virtual JSObject* WrapObject(JSContext *aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE;
 
 private:
   uint64_t mWarnedAbout;
 
@@ -2206,16 +2211,19 @@ protected:
 
   // SMIL Animation Controller, lazily-initialized in GetAnimationController
   nsRefPtr<nsSMILAnimationController> mAnimationController;
 
   // Table of element properties for this document.
   nsPropertyTable mPropertyTable;
   nsTArray<nsAutoPtr<nsPropertyTable> > mExtraPropertyTables;
 
+  // Our cached .children collection
+  nsCOMPtr<nsIHTMLCollection> mChildrenCollection;
+
   // Compatibility mode
   nsCompatibility mCompatMode;
 
   // Our readyState
   ReadyState mReadyState;
 
   // Our visibility state
   mozilla::dom::VisibilityState mVisibilityState;
--- a/content/base/public/nsINode.h
+++ b/content/base/public/nsINode.h
@@ -1585,21 +1585,28 @@ public:
   nsresult RemoveFromParent()
   {
     nsINode* parent = GetParentNode();
     mozilla::ErrorResult rv;
     parent->RemoveChild(*this, rv);
     return rv.ErrorCode();
   }
 
+  // ChildNode methods
+  mozilla::dom::Element* GetPreviousElementSibling() const;
+  mozilla::dom::Element* GetNextElementSibling() const;
   /**
    * Remove this node from its parent, if any.
    */
   void Remove();
 
+  // ParentNode methods
+  mozilla::dom::Element* GetFirstElementChild() const;
+  mozilla::dom::Element* GetLastElementChild() const;
+
 protected:
 
   // Override this function to create a custom slots class.
   // Must not return null.
   virtual nsINode::nsSlots* CreateSlots();
 
   bool HasSlots() const
   {
--- a/content/base/src/Element.cpp
+++ b/content/base/src/Element.cpp
@@ -411,44 +411,16 @@ Element::WrapObject(JSContext *aCx, JS::
       nsContentUtils::AddScriptRunner(
         NS_NewRunnableMethod(binding, &nsXBLBinding::ExecuteAttachedHandler));
     }
   }
 
   return obj;
 }
 
-Element*
-Element::GetFirstElementChild() const
-{
-  uint32_t i, count = mAttrsAndChildren.ChildCount();
-  for (i = 0; i < count; ++i) {
-    nsIContent* child = mAttrsAndChildren.ChildAt(i);
-    if (child->IsElement()) {
-      return child->AsElement();
-    }
-  }
-  
-  return nullptr;
-}
-
-Element*
-Element::GetLastElementChild() const
-{
-  uint32_t i = mAttrsAndChildren.ChildCount();
-  while (i > 0) {
-    nsIContent* child = mAttrsAndChildren.ChildAt(--i);
-    if (child->IsElement()) {
-      return child->AsElement();
-    }
-  }
-  
-  return nullptr;
-}
-
 nsDOMTokenList*
 Element::GetClassList()
 {
   Element::nsDOMSlots *slots = DOMSlots();
 
   if (!slots->mClassList) {
     nsIAtom* classAttr = GetClassAttributeName();
     if (classAttr) {
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -1788,16 +1788,17 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mFirstBaseNodeWithHref)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDOMImplementation)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mImageMaps)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOriginalDocument)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCachedEncoder)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStateObjectCached)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mUndoManager)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTemplateContentsOwner)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mChildrenCollection)
 
   // Traverse all our nsCOMArrays.
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStyleSheets)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCatalogSheets)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPreloadingImages)
 
   for (uint32_t i = 0; i < tmp->mFrameRequestCallbacks.Length(); ++i) {
     NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mFrameRequestCallbacks[i]");
@@ -1872,16 +1873,17 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(ns
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mDisplayDocument)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mFirstBaseNodeWithHref)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mDOMImplementation)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mImageMaps)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mOriginalDocument)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mCachedEncoder)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mUndoManager)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mTemplateContentsOwner)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK(mChildrenCollection)
 
   tmp->mParentDocument = nullptr;
 
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mPreloadingImages)
 
 
   if (tmp->mBoxObjectTable) {
    tmp->mBoxObjectTable->EnumerateRead(ClearAllBoxObjects, nullptr);
@@ -9470,16 +9472,35 @@ nsIDocument::ObsoleteSheet(const nsAStri
     return;
   }
   res = CSSLoader()->ObsoleteSheet(uri);
   if (NS_FAILED(res)) {
     rv.Throw(res);
   }
 }
 
+nsIHTMLCollection*
+nsIDocument::Children()
+{
+  if (!mChildrenCollection) {
+    mChildrenCollection = new nsContentList(this, kNameSpaceID_Wildcard,
+                                            nsGkAtoms::_asterix,
+                                            nsGkAtoms::_asterix,
+                                            false);
+  }
+
+  return mChildrenCollection;
+}
+
+uint32_t
+nsIDocument::ChildElementCount()
+{
+  return Children()->Length();
+}
+
 namespace mozilla {
 
 // Singleton class to manage the list of fullscreen documents which are the
 // root of a branch which contains fullscreen documents. We maintain this list
 // so that we can easily exit all windows from fullscreen when the user
 // presses the escape key.
 class FullscreenRoots {
 public:
--- a/content/base/src/nsINode.cpp
+++ b/content/base/src/nsINode.cpp
@@ -1399,31 +1399,87 @@ nsINode::doInsertChildAt(nsIContent* aKi
       mozAutoSubtreeModified subtree(OwnerDoc(), this);
       (new nsAsyncDOMEvent(aKid, mutation))->RunDOMEventWhenSafe();
     }
   }
 
   return NS_OK;
 }
 
+Element*
+nsINode::GetPreviousElementSibling() const
+{
+  nsIContent* previousSibling = GetPreviousSibling();
+  while (previousSibling) {
+    if (previousSibling->IsElement()) {
+      return previousSibling->AsElement();
+    }
+    previousSibling = previousSibling->GetPreviousSibling();
+  }
+
+  return nullptr;
+}
+
+Element*
+nsINode::GetNextElementSibling() const
+{
+  nsIContent* nextSibling = GetNextSibling();
+  while (nextSibling) {
+    if (nextSibling->IsElement()) {
+      return nextSibling->AsElement();
+    }
+    nextSibling = nextSibling->GetNextSibling();
+  }
+
+  return nullptr;
+}
+
 void
 nsINode::Remove()
 {
   nsCOMPtr<nsINode> parent = GetParentNode();
   if (!parent) {
     return;
   }
   int32_t index = parent->IndexOf(this);
   if (index < 0) {
     NS_WARNING("Ignoring call to nsINode::Remove on anonymous child.");
     return;
   }
   parent->RemoveChildAt(uint32_t(index), true);
 }
 
+Element*
+nsINode::GetFirstElementChild() const
+{
+  for (nsIContent* child = GetFirstChild();
+       child;
+       child = child->GetNextSibling()) {
+    if (child->IsElement()) {
+      return child->AsElement();
+    }
+  }
+
+  return nullptr;
+}
+
+Element*
+nsINode::GetLastElementChild() const
+{
+  for (nsIContent* child = GetLastChild();
+       child;
+       child = child->GetPreviousSibling()) {
+    if (child->IsElement()) {
+      return child->AsElement();
+    }
+  }
+
+  return nullptr;
+}
+
 void
 nsINode::doRemoveChildAt(uint32_t aIndex, bool aNotify,
                          nsIContent* aKid, nsAttrAndChildArray& aChildArray)
 {
   NS_PRECONDITION(aKid && aKid->GetParentNode() == this &&
                   aKid == GetChildAt(aIndex) &&
                   IndexOf(aKid) == (int32_t)aIndex, "Bogus aKid");
 
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -244,16 +244,17 @@ MOCHITEST_FILES_A = \
 		test_bug282547.html \
 		bug282547.sjs \
 		test_domparser_null_char.html \
 		test_bug811701.html \
 		test_bug811701.xhtml \
 		test_bug820909.html \
 		test_bug704063.html \
 		test_bug894874.html \
+		test_bug895974.html \
 		$(NULL)
 
 MOCHITEST_FILES_B = \
 		test_bug459424.html \
 		bug461735-redirect1.sjs \
 		bug461735-redirect2.sjs \
 		bug461735-post-redirect.js \
 		test_bug513194.html \
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_bug895974.html
@@ -0,0 +1,69 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=895974
+-->
+<head>
+  <meta charset="utf-8">
+  <title>Test for Bug 895974</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script type="application/javascript">
+
+  /** Test for Bug 895974 **/
+  SimpleTest.waitForExplicitFinish();
+
+  addLoadEvent(function() {
+  var frag = document.createDocumentFragment();
+  var span = document.createElement("span");
+  var div = document.createElement("div");
+  var text = document.createTextNode("help");
+  frag.appendChild(document.createTextNode("fail"));
+  frag.appendChild(span);
+  frag.appendChild(text);
+  frag.appendChild(div);
+  frag.appendChild(document.createTextNode("fail"));
+
+  is(text.nextElementSibling, div, "nextElementSibling should work on text");
+  is(text.previousElementSibling, span,
+    "previousElementSibling should work on text");
+
+  is(document.firstElementChild, document.documentElement,
+     "firstElementChild should work on document");
+  is(document.lastElementChild, document.documentElement,
+     "lastElementChild should work on document");
+  is(document.children.length, 1, "Document has one element kid");
+  is(document.children[0], document.documentElement,
+     "Document only element child is <html>");
+
+  is(frag.firstElementChild, span,
+     "firstElementChild should work on document fragment");
+  is(frag.lastElementChild, div,
+     "lastElementChild should work on document fragment");
+  is(frag.children.length, 2, "Document fragment has two element kids");
+  is(frag.children[0], span, "Document fragment first element child is span");
+  is(frag.children[1], div, "Document fragment second element child is div");
+
+  is(document.documentElement.firstElementChild, document.head,
+     "firstElementChild should work on element");
+  is(document.documentElement.lastElementChild, document.body,
+     "lastElementChild should work on element");
+  is(document.documentElement.children.length, 2, "<html> has two element kids");
+  is(document.documentElement.children[0], document.head,
+     "<html> first element child is head");
+  is(document.documentElement.children[1], document.body,
+     "<html>  second element child is body");
+  SimpleTest.finish();
+  });
+  </script>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=895974">Mozilla Bug 895974</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+
+</div>
+<pre id="test">
+</pre>
+</body>
+</html>
--- a/content/canvas/src/WebGLContext.h
+++ b/content/canvas/src/WebGLContext.h
@@ -517,17 +517,18 @@ public:
     void TexImage2D(WebGLenum target, WebGLint level,
                     WebGLenum internalformat, WebGLenum format, WebGLenum type,
                     dom::ImageData* pixels, ErrorResult& rv);
     // Allow whatever element types the bindings are willing to pass
     // us in TexImage2D
     template<class ElementType>
     void TexImage2D(WebGLenum target, WebGLint level,
                     WebGLenum internalformat, WebGLenum format, WebGLenum type,
-                    const ElementType& elt, ErrorResult& rv) {
+                    ElementType& elt, ErrorResult& rv)
+    {
         if (!IsContextStable())
             return;
         nsRefPtr<gfxImageSurface> isurf;
         WebGLTexelFormat srcFormat;
         nsLayoutUtils::SurfaceFromElementResult res = SurfaceFromElement(elt);
         rv = SurfaceFromElementResultToImageSurface(res, getter_AddRefs(isurf),
                                                     &srcFormat);
         if (rv.Failed())
@@ -554,17 +555,18 @@ public:
     void TexSubImage2D(WebGLenum target, WebGLint level,
                        WebGLint xoffset, WebGLint yoffset, WebGLenum format,
                        WebGLenum type, dom::ImageData* pixels, ErrorResult& rv);
     // Allow whatever element types the bindings are willing to pass
     // us in TexSubImage2D
     template<class ElementType>
     void TexSubImage2D(WebGLenum target, WebGLint level,
                        WebGLint xoffset, WebGLint yoffset, WebGLenum format,
-                       WebGLenum type, const ElementType& elt, ErrorResult& rv) {
+                       WebGLenum type, ElementType& elt, ErrorResult& rv)
+    {
         if (!IsContextStable())
             return;
         nsRefPtr<gfxImageSurface> isurf;
         WebGLTexelFormat srcFormat;
         nsLayoutUtils::SurfaceFromElementResult res = SurfaceFromElement(elt);
         rv = SurfaceFromElementResultToImageSurface(res, getter_AddRefs(isurf),
                                                     &srcFormat);
         if (rv.Failed())
@@ -971,18 +973,19 @@ protected:
 
         if (mPixelStoreColorspaceConversion == LOCAL_GL_NONE)
             flags |= nsLayoutUtils::SFE_NO_COLORSPACE_CONVERSION;
         if (!mPixelStorePremultiplyAlpha)
             flags |= nsLayoutUtils::SFE_NO_PREMULTIPLY_ALPHA;
         return nsLayoutUtils::SurfaceFromElement(aElement, flags);
     }
     template<class ElementType>
-    nsLayoutUtils::SurfaceFromElementResult SurfaceFromElement(const dom::NonNull<ElementType>& aElement) {
-      return SurfaceFromElement(aElement.get());
+    nsLayoutUtils::SurfaceFromElementResult SurfaceFromElement(ElementType& aElement)
+    {
+      return SurfaceFromElement(&aElement);
     }
 
     nsresult SurfaceFromElementResultToImageSurface(nsLayoutUtils::SurfaceFromElementResult& res,
                                                     gfxImageSurface **imageOut,
                                                     WebGLTexelFormat *format);
 
     void CopyTexSubImage2D_base(WebGLenum target,
                                 WebGLint level,
--- a/content/media/test/Makefile.in
+++ b/content/media/test/Makefile.in
@@ -110,16 +110,17 @@ MOCHITEST_FILES = \
 		test_seek_out_of_range.html \
 		test_source.html \
 		test_source_write.html \
 		test_source_null.html \
 		test_standalone.html \
 		test_volume.html \
 		test_video_to_canvas.html \
 		test_audiowrite.html \
+		test_mediarecorder_creation.html \
 		test_mozHasAudio.html \
 		test_source_media.html \
 		test_autoplay_contentEditable.html \
 		test_bug448534.html \
 		test_bug463162.xhtml \
 		test_decoder_disable.html \
 		test_media_selection.html \
 		test_playback.html \
--- a/content/media/test/manifest.js
+++ b/content/media/test/manifest.js
@@ -73,16 +73,22 @@ var gPausedAfterEndedTests = gSmallTests
 var gTrackTests = [
   { name:"big.wav", type:"audio/x-wav", duration:9.278981, size:102444, hasAudio:true, hasVideo:false },
   { name:"320x240.ogv", type:"video/ogg", width:320, height:240, duration:0.266, size:28942, hasAudio:false, hasVideo:true },
   { name:"short-video.ogv", type:"video/ogg", duration:1.081, hasAudio:true, hasVideo:true },
   { name:"seek.webm", type:"video/webm", duration:3.966, size:215529, hasAudio:false, hasVideo:true },
   { name:"bogus.duh", type:"bogus/duh" }
 ];
 
+// Used by any media recorder test. Need one test file per decoder backend
+// currently supported by the media encoder.
+var gMediaRecorderTests = [
+  { name:"detodos.opus", type:"audio/ogg; codecs=opus", duration:2.9135 }
+];
+
 // These are files that we want to make sure we can play through.  We can
 // also check metadata.  Put files of the same type together in this list so if
 // something crashes we have some idea of which backend is responsible.
 // Used by test_playback, which expects no error event and one ended event.
 var gPlayTests = [
   // 8-bit samples
   { name:"r11025_u8_c1.wav", type:"audio/x-wav", duration:1.0 },
   // 8-bit samples, file is truncated
new file mode 100644
--- /dev/null
+++ b/content/media/test/test_mediarecorder_creation.html
@@ -0,0 +1,45 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test MediaRecorder Creation</title>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+  <script type="text/javascript" src="manifest.js"></script>
+</head>
+<body>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+var manager = new MediaTestManager;
+
+/**
+ * Starts a test on every media recorder file included to check that
+ * a media recorder object created with a stream derived from a media
+ * element with that file produces the correct starting attribute values.
+ */
+function startTest(test, token) {
+  var element = document.createElement('audio');
+
+  element.token = token;
+  manager.started(token);
+
+  element.src = test.name;
+  element.test = test;
+  element.stream = element.mozCaptureStreamUntilEnded();
+
+  var mediaRecorder = new MediaRecorder(element.stream);
+
+  is(mediaRecorder.stream, element.stream,
+     'Stream should be provided stream on creation');
+  is(mediaRecorder.mimeType, '',
+     'mimeType should be an empty string on creation');
+  is(mediaRecorder.state, 'inactive',
+     'state should be inactive on creation');
+
+  manager.finished(token);
+}
+
+manager.runTests(gMediaRecorderTests, startTest);
+</script>
+</pre>
+</body>
+</html>
--- a/dom/bindings/BindingUtils.h
+++ b/dom/bindings/BindingUtils.h
@@ -2017,16 +2017,47 @@ struct JSBindingFinalized<T, true>
 
 // Helpers for creating a const version of a type.
 template<typename T>
 const T& Constify(T& arg)
 {
   return arg;
 }
 
+// Helper for turning (Owning)NonNull<T> into T&
+template<typename T>
+T& NonNullHelper(T& aArg)
+{
+  return aArg;
+}
+
+template<typename T>
+T& NonNullHelper(NonNull<T>& aArg)
+{
+  return aArg;
+}
+
+template<typename T>
+const T& NonNullHelper(const NonNull<T>& aArg)
+{
+  return aArg;
+}
+
+template<typename T>
+T& NonNullHelper(OwningNonNull<T>& aArg)
+{
+  return aArg;
+}
+
+template<typename T>
+const T& NonNullHelper(const OwningNonNull<T>& aArg)
+{
+  return aArg;
+}
+
 // Reparent the wrapper of aObj to whatever its native now thinks its
 // parent should be.
 nsresult
 ReparentWrapper(JSContext* aCx, JS::HandleObject aObj);
 
 /**
  * Used to implement the hasInstance hook of an interface object.
  *
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -4415,16 +4415,21 @@ class CGCallGenerator(CGThing):
                     # so doesn't need to be const just due to being optional.
                     # This also covers variadic arguments.
                     return True
                 if a.type.isUnion():
                     return True
                 return False
             if needsConst(a):
                 arg = CGWrapper(arg, pre="Constify(", post=")")
+            # And convert NonNull<T> to T&
+            if (((a.type.isInterface() or a.type.isCallback()) and
+                 not a.type.nullable()) or
+                a.type.isDOMString()):
+                arg = CGWrapper(arg, pre="NonNullHelper(", post=")")
             args.append(arg)
 
         # Return values that go in outparams go here
         if resultOutParam:
             args.append(CGGeneric("result"))
         if isFallible:
             args.append(CGGeneric("rv"))
 
--- a/dom/bindings/test/TestBindingHeader.h
+++ b/dom/bindings/test/TestBindingHeader.h
@@ -270,17 +270,16 @@ public:
                         double arg8);
 
   // Interface types
   already_AddRefed<TestInterface> ReceiveSelf();
   already_AddRefed<TestInterface> ReceiveNullableSelf();
   TestInterface* ReceiveWeakSelf();
   TestInterface* ReceiveWeakNullableSelf();
   void PassSelf(TestInterface&);
-  void PassSelf2(NonNull<TestInterface>&);
   void PassNullableSelf(TestInterface*);
   already_AddRefed<TestInterface> NonNullSelf();
   void SetNonNullSelf(TestInterface&);
   already_AddRefed<TestInterface> GetNullableSelf();
   void SetNullableSelf(TestInterface*);
   void PassOptionalSelf(const Optional<TestInterface*> &);
   void PassOptionalNonNullSelf(const Optional<NonNull<TestInterface> >&);
   void PassOptionalSelfWithDefault(TestInterface*);
@@ -292,47 +291,44 @@ public:
   void ReceiveNonWrapperCacheInterfaceNullableSequence(Nullable<nsTArray<nsRefPtr<TestNonWrapperCacheInterface> > >&);
   void ReceiveNullableNonWrapperCacheInterfaceNullableSequence(Nullable<nsTArray<nsRefPtr<TestNonWrapperCacheInterface> > >&);
 
   already_AddRefed<IndirectlyImplementedInterface> ReceiveOther();
   already_AddRefed<IndirectlyImplementedInterface> ReceiveNullableOther();
   IndirectlyImplementedInterface* ReceiveWeakOther();
   IndirectlyImplementedInterface* ReceiveWeakNullableOther();
   void PassOther(IndirectlyImplementedInterface&);
-  void PassOther2(NonNull<IndirectlyImplementedInterface>&);
   void PassNullableOther(IndirectlyImplementedInterface*);
   already_AddRefed<IndirectlyImplementedInterface> NonNullOther();
   void SetNonNullOther(IndirectlyImplementedInterface&);
   already_AddRefed<IndirectlyImplementedInterface> GetNullableOther();
   void SetNullableOther(IndirectlyImplementedInterface*);
   void PassOptionalOther(const Optional<IndirectlyImplementedInterface*>&);
   void PassOptionalNonNullOther(const Optional<NonNull<IndirectlyImplementedInterface> >&);
   void PassOptionalOtherWithDefault(IndirectlyImplementedInterface*);
 
   already_AddRefed<TestExternalInterface> ReceiveExternal();
   already_AddRefed<TestExternalInterface> ReceiveNullableExternal();
   TestExternalInterface* ReceiveWeakExternal();
   TestExternalInterface* ReceiveWeakNullableExternal();
   void PassExternal(TestExternalInterface*);
-  void PassExternal2(TestExternalInterface*);
   void PassNullableExternal(TestExternalInterface*);
   already_AddRefed<TestExternalInterface> NonNullExternal();
   void SetNonNullExternal(TestExternalInterface*);
   already_AddRefed<TestExternalInterface> GetNullableExternal();
   void SetNullableExternal(TestExternalInterface*);
   void PassOptionalExternal(const Optional<TestExternalInterface*>&);
   void PassOptionalNonNullExternal(const Optional<TestExternalInterface*>&);
   void PassOptionalExternalWithDefault(TestExternalInterface*);
 
   already_AddRefed<TestCallbackInterface> ReceiveCallbackInterface();
   already_AddRefed<TestCallbackInterface> ReceiveNullableCallbackInterface();
   TestCallbackInterface* ReceiveWeakCallbackInterface();
   TestCallbackInterface* ReceiveWeakNullableCallbackInterface();
   void PassCallbackInterface(TestCallbackInterface&);
-  void PassCallbackInterface2(OwningNonNull<TestCallbackInterface>);
   void PassNullableCallbackInterface(TestCallbackInterface*);
   already_AddRefed<TestCallbackInterface> NonNullCallbackInterface();
   void SetNonNullCallbackInterface(TestCallbackInterface&);
   already_AddRefed<TestCallbackInterface> GetNullableCallbackInterface();
   void SetNullableCallbackInterface(TestCallbackInterface*);
   void PassOptionalCallbackInterface(const Optional<nsRefPtr<TestCallbackInterface> >&);
   void PassOptionalNonNullCallbackInterface(const Optional<OwningNonNull<TestCallbackInterface> >&);
   void PassOptionalCallbackInterfaceWithDefault(TestCallbackInterface*);
@@ -803,16 +799,38 @@ private:
   void PassOptionalNullableDateWithDefaultValue(Nullable<Date>&) MOZ_DELETE;
   void PassDateSequence(Sequence<Date>&) MOZ_DELETE;
   void PassNullableDateSequence(Sequence<Nullable<Date> >&) MOZ_DELETE;
 
   // Make sure variadics are const as needed
   void PassVariadicAny(JSContext*, Sequence<JS::Value>&) MOZ_DELETE;
   void PassVariadicObject(JSContext*, Sequence<JSObject*>&) MOZ_DELETE;
   void PassVariadicNullableObject(JSContext*, Sequence<JSObject*>&) MOZ_DELETE;
+
+  // Ensure NonNull does not leak in
+  void PassSelf(NonNull<TestInterface>&) MOZ_DELETE;
+  void PassSelf(OwningNonNull<TestInterface>&) MOZ_DELETE;
+  void PassSelf(const NonNull<TestInterface>&) MOZ_DELETE;
+  void PassSelf(const OwningNonNull<TestInterface>&) MOZ_DELETE;
+  void PassOther(NonNull<IndirectlyImplementedInterface>&) MOZ_DELETE;
+  void PassOther(const NonNull<IndirectlyImplementedInterface>&) MOZ_DELETE;
+  void PassOther(OwningNonNull<IndirectlyImplementedInterface>&) MOZ_DELETE;
+  void PassOther(const OwningNonNull<IndirectlyImplementedInterface>&) MOZ_DELETE;
+  void PassCallbackInterface(OwningNonNull<TestCallbackInterface>&) MOZ_DELETE;
+  void PassCallbackInterface(const OwningNonNull<TestCallbackInterface>&) MOZ_DELETE;
+  void PassCallbackInterface(NonNull<TestCallbackInterface>&) MOZ_DELETE;
+  void PassCallbackInterface(const NonNull<TestCallbackInterface>&) MOZ_DELETE;
+  void PassCallback(OwningNonNull<TestCallback>&) MOZ_DELETE;
+  void PassCallback(const OwningNonNull<TestCallback>&) MOZ_DELETE;
+  void PassCallback(NonNull<TestCallback>&) MOZ_DELETE;
+  void PassCallback(const NonNull<TestCallback>&) MOZ_DELETE;
+  void PassString(const NonNull<nsAString>&) MOZ_DELETE;
+  void PassString(NonNull<nsAString>&) MOZ_DELETE;
+  void PassString(const OwningNonNull<nsAString>&) MOZ_DELETE;
+  void PassString(OwningNonNull<nsAString>&) MOZ_DELETE;
 };
 
 class TestIndexedGetterInterface : public nsISupports,
                                    public nsWrapperCache
 {
 public:
   NS_DECL_ISUPPORTS
 
--- a/dom/bindings/test/TestCodeGen.webidl
+++ b/dom/bindings/test/TestCodeGen.webidl
@@ -218,20 +218,17 @@ interface TestInterface {
                         optional unrestricted double arg8 = NaN);
 
   // Castable interface types
   // XXXbz add tests for throwing versions of all the castable interface stuff
   TestInterface receiveSelf();
   TestInterface? receiveNullableSelf();
   TestInterface receiveWeakSelf();
   TestInterface? receiveWeakNullableSelf();
-  // A verstion to test for casting to TestInterface&
   void passSelf(TestInterface arg);
-  // A version we can use to test for the exact type passed in
-  void passSelf2(TestInterface arg);
   void passNullableSelf(TestInterface? arg);
   attribute TestInterface nonNullSelf;
   attribute TestInterface? nullableSelf;
   // Optional arguments
   void passOptionalSelf(optional TestInterface? arg);
   void passOptionalNonNullSelf(optional TestInterface arg);
   void passOptionalSelfWithDefault(optional TestInterface? arg = null);
 
@@ -249,54 +246,45 @@ interface TestInterface {
   [Creator]
   sequence<TestNonWrapperCacheInterface?>? receiveNullableNonWrapperCacheInterfaceNullableSequence();
 
   // Non-castable interface types
   IndirectlyImplementedInterface receiveOther();
   IndirectlyImplementedInterface? receiveNullableOther();
   IndirectlyImplementedInterface receiveWeakOther();
   IndirectlyImplementedInterface? receiveWeakNullableOther();
-  // A verstion to test for casting to IndirectlyImplementedInterface&
   void passOther(IndirectlyImplementedInterface arg);
-  // A version we can use to test for the exact type passed in
-  void passOther2(IndirectlyImplementedInterface arg);
   void passNullableOther(IndirectlyImplementedInterface? arg);
   attribute IndirectlyImplementedInterface nonNullOther;
   attribute IndirectlyImplementedInterface? nullableOther;
   // Optional arguments
   void passOptionalOther(optional IndirectlyImplementedInterface? arg);
   void passOptionalNonNullOther(optional IndirectlyImplementedInterface arg);
   void passOptionalOtherWithDefault(optional IndirectlyImplementedInterface? arg = null);
 
   // External interface types
   TestExternalInterface receiveExternal();
   TestExternalInterface? receiveNullableExternal();
   TestExternalInterface receiveWeakExternal();
   TestExternalInterface? receiveWeakNullableExternal();
-  // A verstion to test for casting to TestExternalInterface&
   void passExternal(TestExternalInterface arg);
-  // A version we can use to test for the exact type passed in
-  void passExternal2(TestExternalInterface arg);
   void passNullableExternal(TestExternalInterface? arg);
   attribute TestExternalInterface nonNullExternal;
   attribute TestExternalInterface? nullableExternal;
   // Optional arguments
   void passOptionalExternal(optional TestExternalInterface? arg);
   void passOptionalNonNullExternal(optional TestExternalInterface arg);
   void passOptionalExternalWithDefault(optional TestExternalInterface? arg = null);
 
   // Callback interface types
   TestCallbackInterface receiveCallbackInterface();
   TestCallbackInterface? receiveNullableCallbackInterface();
   TestCallbackInterface receiveWeakCallbackInterface();
   TestCallbackInterface? receiveWeakNullableCallbackInterface();
-  // A verstion to test for casting to TestCallbackInterface&
   void passCallbackInterface(TestCallbackInterface arg);
-  // A version we can use to test for the exact type passed in
-  void passCallbackInterface2(TestCallbackInterface arg);
   void passNullableCallbackInterface(TestCallbackInterface? arg);
   attribute TestCallbackInterface nonNullCallbackInterface;
   attribute TestCallbackInterface? nullableCallbackInterface;
   // Optional arguments
   void passOptionalCallbackInterface(optional TestCallbackInterface? arg);
   void passOptionalNonNullCallbackInterface(optional TestCallbackInterface arg);
   void passOptionalCallbackInterfaceWithDefault(optional TestCallbackInterface? arg = null);
 
--- a/dom/bindings/test/TestExampleGen.webidl
+++ b/dom/bindings/test/TestExampleGen.webidl
@@ -114,20 +114,17 @@ interface TestExampleInterface {
   attribute double lenientDoubleAttr;
 
   // Castable interface types
   // XXXbz add tests for throwing versions of all the castable interface stuff
   TestInterface receiveSelf();
   TestInterface? receiveNullableSelf();
   TestInterface receiveWeakSelf();
   TestInterface? receiveWeakNullableSelf();
-  // A verstion to test for casting to TestInterface&
   void passSelf(TestInterface arg);
-  // A version we can use to test for the exact type passed in
-  void passSelf2(TestInterface arg);
   void passNullableSelf(TestInterface? arg);
   attribute TestInterface nonNullSelf;
   attribute TestInterface? nullableSelf;
   // Optional arguments
   void passOptionalSelf(optional TestInterface? arg);
   void passOptionalNonNullSelf(optional TestInterface arg);
   void passOptionalSelfWithDefault(optional TestInterface? arg = null);
 
@@ -145,54 +142,45 @@ interface TestExampleInterface {
   [Creator]
   sequence<TestNonWrapperCacheInterface?>? receiveNullableNonWrapperCacheInterfaceNullableSequence();
 
   // Non-castable interface types
   IndirectlyImplementedInterface receiveOther();
   IndirectlyImplementedInterface? receiveNullableOther();
   IndirectlyImplementedInterface receiveWeakOther();
   IndirectlyImplementedInterface? receiveWeakNullableOther();
-  // A verstion to test for casting to IndirectlyImplementedInterface&
   void passOther(IndirectlyImplementedInterface arg);
-  // A version we can use to test for the exact type passed in
-  void passOther2(IndirectlyImplementedInterface arg);
   void passNullableOther(IndirectlyImplementedInterface? arg);
   attribute IndirectlyImplementedInterface nonNullOther;
   attribute IndirectlyImplementedInterface? nullableOther;
   // Optional arguments
   void passOptionalOther(optional IndirectlyImplementedInterface? arg);
   void passOptionalNonNullOther(optional IndirectlyImplementedInterface arg);
   void passOptionalOtherWithDefault(optional IndirectlyImplementedInterface? arg = null);
 
   // External interface types
   TestExternalInterface receiveExternal();
   TestExternalInterface? receiveNullableExternal();
   TestExternalInterface receiveWeakExternal();
   TestExternalInterface? receiveWeakNullableExternal();
-  // A verstion to test for casting to TestExternalInterface&
   void passExternal(TestExternalInterface arg);
-  // A version we can use to test for the exact type passed in
-  void passExternal2(TestExternalInterface arg);
   void passNullableExternal(TestExternalInterface? arg);
   attribute TestExternalInterface nonNullExternal;
   attribute TestExternalInterface? nullableExternal;
   // Optional arguments
   void passOptionalExternal(optional TestExternalInterface? arg);
   void passOptionalNonNullExternal(optional TestExternalInterface arg);
   void passOptionalExternalWithDefault(optional TestExternalInterface? arg = null);
 
   // Callback interface types
   TestCallbackInterface receiveCallbackInterface();
   TestCallbackInterface? receiveNullableCallbackInterface();
   TestCallbackInterface receiveWeakCallbackInterface();
   TestCallbackInterface? receiveWeakNullableCallbackInterface();
-  // A verstion to test for casting to TestCallbackInterface&
   void passCallbackInterface(TestCallbackInterface arg);
-  // A version we can use to test for the exact type passed in
-  void passCallbackInterface2(TestCallbackInterface arg);
   void passNullableCallbackInterface(TestCallbackInterface? arg);
   attribute TestCallbackInterface nonNullCallbackInterface;
   attribute TestCallbackInterface? nullableCallbackInterface;
   // Optional arguments
   void passOptionalCallbackInterface(optional TestCallbackInterface? arg);
   void passOptionalNonNullCallbackInterface(optional TestCallbackInterface arg);
   void passOptionalCallbackInterfaceWithDefault(optional TestCallbackInterface? arg = null);
 
--- a/dom/bindings/test/TestJSImplGen.webidl
+++ b/dom/bindings/test/TestJSImplGen.webidl
@@ -131,18 +131,16 @@ interface TestJSImplInterface {
   TestJSImplInterface? receiveNullableSelf();
 
   // Callback interface ignores 'resultNotAddRefed'. See bug 843272.
   //TestJSImplInterface receiveWeakSelf();
   //TestJSImplInterface? receiveWeakNullableSelf();
 
   // A version to test for casting to TestJSImplInterface&
   void passSelf(TestJSImplInterface arg);
-  // A version we can use to test for the exact type passed in
-  void passSelf2(TestJSImplInterface arg);
   void passNullableSelf(TestJSImplInterface? arg);
   attribute TestJSImplInterface nonNullSelf;
   attribute TestJSImplInterface? nullableSelf;
   // Optional arguments
   void passOptionalSelf(optional TestJSImplInterface? arg);
   void passOptionalNonNullSelf(optional TestJSImplInterface arg);
   void passOptionalSelfWithDefault(optional TestJSImplInterface? arg = null);
 
@@ -163,56 +161,47 @@ interface TestJSImplInterface {
 
   // Non-castable interface types
   IndirectlyImplementedInterface receiveOther();
   IndirectlyImplementedInterface? receiveNullableOther();
   // Callback interface ignores 'resultNotAddRefed'. See bug 843272.
   //IndirectlyImplementedInterface receiveWeakOther();
   //IndirectlyImplementedInterface? receiveWeakNullableOther();
 
-  // A verstion to test for casting to IndirectlyImplementedInterface&
   void passOther(IndirectlyImplementedInterface arg);
-  // A version we can use to test for the exact type passed in
-  void passOther2(IndirectlyImplementedInterface arg);
   void passNullableOther(IndirectlyImplementedInterface? arg);
   attribute IndirectlyImplementedInterface nonNullOther;
   attribute IndirectlyImplementedInterface? nullableOther;
   // Optional arguments
   void passOptionalOther(optional IndirectlyImplementedInterface? arg);
   void passOptionalNonNullOther(optional IndirectlyImplementedInterface arg);
   void passOptionalOtherWithDefault(optional IndirectlyImplementedInterface? arg = null);
 
   // External interface types
   TestExternalInterface receiveExternal();
   TestExternalInterface? receiveNullableExternal();
   // Callback interface ignores 'resultNotAddRefed'. See bug 843272.
   //TestExternalInterface receiveWeakExternal();
   //TestExternalInterface? receiveWeakNullableExternal();
-  // A verstion to test for casting to TestExternalInterface&
   void passExternal(TestExternalInterface arg);
-  // A version we can use to test for the exact type passed in
-  void passExternal2(TestExternalInterface arg);
   void passNullableExternal(TestExternalInterface? arg);
   attribute TestExternalInterface nonNullExternal;
   attribute TestExternalInterface? nullableExternal;
   // Optional arguments
   void passOptionalExternal(optional TestExternalInterface? arg);
   void passOptionalNonNullExternal(optional TestExternalInterface arg);
   void passOptionalExternalWithDefault(optional TestExternalInterface? arg = null);
 
   // Callback interface types
   TestCallbackInterface receiveCallbackInterface();
   TestCallbackInterface? receiveNullableCallbackInterface();
   // Callback interface ignores 'resultNotAddRefed'. See bug 843272.
   //TestCallbackInterface receiveWeakCallbackInterface();
   //TestCallbackInterface? receiveWeakNullableCallbackInterface();
-  // A verstion to test for casting to TestCallbackInterface&
   void passCallbackInterface(TestCallbackInterface arg);
-  // A version we can use to test for the exact type passed in
-  void passCallbackInterface2(TestCallbackInterface arg);
   void passNullableCallbackInterface(TestCallbackInterface? arg);
   attribute TestCallbackInterface nonNullCallbackInterface;
   attribute TestCallbackInterface? nullableCallbackInterface;
   // Optional arguments
   void passOptionalCallbackInterface(optional TestCallbackInterface? arg);
   void passOptionalNonNullCallbackInterface(optional TestCallbackInterface arg);
   void passOptionalCallbackInterfaceWithDefault(optional TestCallbackInterface? arg = null);
 
--- a/dom/indexedDB/IDBEvents.h
+++ b/dom/indexedDB/IDBEvents.h
@@ -56,17 +56,17 @@ public:
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
     return mozilla::dom::IDBVersionChangeEventBinding::Wrap(aCx, aScope, this);
   }
 
   static already_AddRefed<IDBVersionChangeEvent>
   Constructor(const GlobalObject& aGlobal,
-              const NonNull<nsAString>& aType,
+              const nsAString& aType,
               const IDBVersionChangeEventInit& aOptions,
               ErrorResult& aRv)
   {
     uint64_t newVersion = 0;
     if (!aOptions.mNewVersion.IsNull()) {
       newVersion = aOptions.mNewVersion.Value();
     }
     nsCOMPtr<EventTarget> target = do_QueryInterface(aGlobal.Get());
--- a/dom/indexedDB/IDBFactory.cpp
+++ b/dom/indexedDB/IDBFactory.cpp
@@ -642,31 +642,31 @@ IDBFactory::Cmp(JSContext* aCx, JS::Hand
     return 0;
   }
 
   return Key::CompareKeys(first, second);
 }
 
 already_AddRefed<nsIIDBOpenDBRequest>
 IDBFactory::OpenForPrincipal(nsIPrincipal* aPrincipal,
-                             const NonNull<nsAString>& aName,
+                             const nsAString& aName,
                              const Optional<uint64_t>& aVersion,
                              ErrorResult& aRv)
 {
   // Just to be on the extra-safe side
   if (!nsContentUtils::IsCallerChrome()) {
     MOZ_CRASH();
   }
 
   return Open(aPrincipal, aName, aVersion, false, aRv);
 }
 
 already_AddRefed<nsIIDBOpenDBRequest>
 IDBFactory::DeleteForPrincipal(nsIPrincipal* aPrincipal,
-                               const NonNull<nsAString>& aName,
+                               const nsAString& aName,
                                ErrorResult& aRv)
 {
   // Just to be on the extra-safe side
   if (!nsContentUtils::IsCallerChrome()) {
     MOZ_CRASH();
   }
 
   return Open(aPrincipal, aName, Optional<uint64_t>(), true, aRv);
--- a/dom/indexedDB/IDBFactory.h
+++ b/dom/indexedDB/IDBFactory.h
@@ -136,38 +136,38 @@ public:
     return mWindow;
   }
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE;
 
   // WebIDL
   already_AddRefed<nsIIDBOpenDBRequest>
-  Open(const NonNull<nsAString>& aName, const Optional<uint64_t>& aVersion,
+  Open(const nsAString& aName, const Optional<uint64_t>& aVersion,
        ErrorResult& aRv)
   {
     return Open(nullptr, aName, aVersion, false, aRv);
   }
 
   already_AddRefed<nsIIDBOpenDBRequest>
-  DeleteDatabase(const NonNull<nsAString>& aName, ErrorResult& aRv)
+  DeleteDatabase(const nsAString& aName, ErrorResult& aRv)
   {
     return Open(nullptr, aName, Optional<uint64_t>(), true, aRv);
   }
 
   int16_t
   Cmp(JSContext* aCx, JS::Handle<JS::Value> aFirst,
       JS::Handle<JS::Value> aSecond, ErrorResult& aRv);
 
   already_AddRefed<nsIIDBOpenDBRequest>
-  OpenForPrincipal(nsIPrincipal* aPrincipal, const NonNull<nsAString>& aName,
+  OpenForPrincipal(nsIPrincipal* aPrincipal, const nsAString& aName,
                    const Optional<uint64_t>& aVersion, ErrorResult& aRv);
 
   already_AddRefed<nsIIDBOpenDBRequest>
-  DeleteForPrincipal(nsIPrincipal* aPrincipal, const NonNull<nsAString>& aName,
+  DeleteForPrincipal(nsIPrincipal* aPrincipal, const nsAString& aName,
                      ErrorResult& aRv);
 
 private:
   IDBFactory();
   ~IDBFactory();
 
   already_AddRefed<nsIIDBOpenDBRequest>
   Open(nsIPrincipal* aPrincipal, const nsAString& aName,
--- a/dom/media/tests/mochitest/pc.js
+++ b/dom/media/tests/mochitest/pc.js
@@ -603,26 +603,38 @@ DataChannelTest.prototype = Object.creat
 
       // Method to synchronize all asynchronous events.
       function check_next_test() {
         if (self.connected && localChannel && remoteChannel) {
           onSuccess(localChannel, remoteChannel);
         }
       }
 
-      // Register handlers for the remote peer
-      this.pcRemote.registerDataChannelOpenEvents(function (channel) {
-        remoteChannel = channel;
-        check_next_test();
-      });
+      if (!options.negotiated) {
+        // Register handlers for the remote peer
+        this.pcRemote.registerDataChannelOpenEvents(function (channel) {
+          remoteChannel = channel;
+          check_next_test();
+        });
+      }
 
-      // Creat the datachannel and handle the local 'onopen' event
+      // Create the datachannel and handle the local 'onopen' event
       this.pcLocal.createDataChannel(options, function (channel) {
         localChannel = channel;
-        check_next_test();
+
+        if (options.negotiated) {
+          // externally negotiated - we need to open from both ends
+          options.id = options.id || channel.id;  // allow for no id to let the impl choose
+          self.pcRemote.createDataChannel(options, function (channel) {
+            remoteChannel = channel;
+            check_next_test();
+          });
+        } else {
+          check_next_test();
+	}
       });
     }
   },
 
   send : {
     /**
      * Send data (message or blob) to the other peer
      *
@@ -821,16 +833,45 @@ DataChannelWrapper.prototype = {
    *
    * @returns {String} The label
    */
   get label() {
     return this._channel.label;
   },
 
   /**
+   * Returns the protocol of the underlying data channel
+   *
+   * @returns {String} The protocol
+   */
+  get protocol() {
+    return this._channel.protocol;
+  },
+
+  /**
+   * Returns the id of the underlying data channel
+   *
+   * @returns {number} The stream id
+   */
+  get id() {
+    return this._channel.id;
+  },
+
+  /**
+   * Returns the reliable state of the underlying data channel
+   *
+   * @returns {bool} The stream's reliable state
+   */
+  get reliable() {
+    return this._channel.reliable;
+  },
+
+  // ordered, maxRetransmits and maxRetransmitTime not exposed yet
+
+  /**
    * Returns the readyState bit of the data channel
    *
    * @returns {String} The state of the channel
    */
   get readyState() {
     return this._channel.readyState;
   },
 
--- a/dom/media/tests/mochitest/templates.js
+++ b/dom/media/tests/mochitest/templates.js
@@ -333,16 +333,87 @@ var commandsDataChannel = [
         is(test.pcRemote.dataChannels.indexOf(channel), 0, "1st channel used");
         is(data, message, "Received message has the correct content.");
 
         test.next();
       }, options);
     }
   ],
   [
+    'CREATE_NEGOTIATED_DATA_CHANNEL',
+    function (test) {
+      var options = {negotiated:true, id: 5, protocol:"foo/bar", ordered:false,
+		     maxRetransmits:500};
+      test.createDataChannel(options, function (sourceChannel2, targetChannel2) {
+        is(sourceChannel2.readyState, "open", sourceChannel2 + " is in state: 'open'");
+        is(targetChannel2.readyState, "open", targetChannel2 + " is in state: 'open'");
+
+        is(targetChannel2.binaryType, "blob", targetChannel2 + " is of binary type 'blob'");
+        is(targetChannel2.readyState, "open", targetChannel2 + " is in state: 'open'");
+
+        if (options.id != undefined) {
+          is(sourceChannel2.id, options.id, sourceChannel2 + " id is:" + sourceChannel2.id);
+	} else {
+	  options.id = sourceChannel2.id;
+	}
+	var reliable = !options.ordered ? false : (options.maxRetransmits || options.maxRetransmitTime);
+        is(sourceChannel2.protocol, options.protocol, sourceChannel2 + " protocol is:" + sourceChannel2.protocol);
+        is(sourceChannel2.reliable, reliable, sourceChannel2 + " reliable is:" + sourceChannel2.reliable);
+/*
+  These aren't exposed by IDL yet
+        is(sourceChannel2.ordered, options.ordered, sourceChannel2 + " ordered is:" + sourceChannel2.ordered);
+        is(sourceChannel2.maxRetransmits, options.maxRetransmits, sourceChannel2 + " maxRetransmits is:" +
+	   sourceChannel2.maxRetransmits);
+        is(sourceChannel2.maxRetransmitTime, options.maxRetransmitTime, sourceChannel2 + " maxRetransmitTime is:" +
+	   sourceChannel2.maxRetransmitTime);
+*/
+
+        is(targetChannel2.id, options.id, targetChannel2 + " id is:" + targetChannel2.id);
+        is(targetChannel2.protocol, options.protocol, targetChannel2 + " protocol is:" + targetChannel2.protocol);
+        is(targetChannel2.reliable, reliable, targetChannel2 + " reliable is:" + targetChannel2.reliable);
+/*
+  These aren't exposed by IDL yet
+       is(targetChannel2.ordered, options.ordered, targetChannel2 + " ordered is:" + targetChannel2.ordered);
+        is(targetChannel2.maxRetransmits, options.maxRetransmits, targetChannel2 + " maxRetransmits is:" +
+	   targetChannel2.maxRetransmits);
+        is(targetChannel2.maxRetransmitTime, options.maxRetransmitTime, targetChannel2 + " maxRetransmitTime is:" +
+	   targetChannel2.maxRetransmitTime);
+*/
+
+        test.next();
+      });
+    }
+  ],
+  [
+    'SEND_MESSAGE_THROUGH_LAST_OPENED_CHANNEL2',
+    function (test) {
+      var channels = test.pcRemote.dataChannels;
+      var message = "Lorem ipsum dolor sit amet";
+
+      test.send(message, function (channel, data) {
+        is(channels.indexOf(channel), channels.length - 1, "Last channel used");
+        is(data, message, "Received message has the correct content.");
+
+        test.next();
+      });
+    }
+  ],
+  [
+    'CLOSE_LAST_OPENED_DATA_CHANNEL2',
+    function (test) {
+      var channels = test.pcRemote.dataChannels;
+
+      test.closeDataChannel(channels.length - 1, function (channel) {
+        is(channel.readyState, "closed", "Channel is in state: 'closed'");
+
+        test.next();
+      });
+    }
+  ],
+  [
     'CLOSE_LAST_OPENED_DATA_CHANNEL',
     function (test) {
       var channels = test.pcRemote.dataChannels;
 
       test.closeDataChannel(channels.length - 1, function (channel) {
         is(channel.readyState, "closed", "Channel is in state: 'closed'");
 
         test.next();
--- a/dom/src/notification/DesktopNotification.h
+++ b/dom/src/notification/DesktopNotification.h
@@ -41,20 +41,24 @@ class DesktopNotificationCenter MOZ_FINA
                                             public nsWrapperCache
 {
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(DesktopNotificationCenter)
 
   DesktopNotificationCenter(nsPIDOMWindow *aWindow)
   {
+    MOZ_ASSERT(aWindow);
     mOwner = aWindow;
 
-    // Grab the uri of the document
-    mPrincipal = mOwner->GetDoc()->NodePrincipal();
+    nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(aWindow);
+    MOZ_ASSERT(sop);
+
+    mPrincipal = sop->GetPrincipal();
+    MOZ_ASSERT(mPrincipal);
 
     SetIsDOMBinding();
   }
 
   virtual ~DesktopNotificationCenter()
   {
   }
 
--- a/dom/webidl/ChildNode.webidl
+++ b/dom/webidl/ChildNode.webidl
@@ -4,18 +4,19 @@
  * You can obtain one at http://mozilla.org/MPL/2.0/.
  *
  * The origin of this IDL file is
  * http://dom.spec.whatwg.org/#interface-childnode
  */
 
 [NoInterfaceObject]
 interface ChildNode {
-// On Element:
-//  readonly attribute Element? previousElementSibling;
-//  readonly attribute Element? nextElementSibling;
+  [Pure]
+  readonly attribute Element? previousElementSibling;
+  [Pure]
+  readonly attribute Element? nextElementSibling;
 
 // Not implemented yet:
 //  void before((Node or DOMString)... nodes);
 //  void after((Node or DOMString)... nodes);
 //  void replace((Node or DOMString)... nodes);
   void remove();
 };
--- a/dom/webidl/Document.webidl
+++ b/dom/webidl/Document.webidl
@@ -329,8 +329,9 @@ partial interface Document {
 partial interface Document {
   [ChromeOnly] readonly attribute boolean isSrcdocDocument;
 };
 
 Document implements XPathEvaluator;
 Document implements GlobalEventHandlers;
 Document implements NodeEventHandlers;
 Document implements TouchEventHandlers;
+Document implements ParentNode;
--- a/dom/webidl/DocumentFragment.webidl
+++ b/dom/webidl/DocumentFragment.webidl
@@ -24,8 +24,10 @@ interface DocumentFragment : Node {
 
 // http://www.w3.org/TR/2012/WD-selectors-api-20120628/#interface-definitions
 partial interface DocumentFragment {
   [Throws]
   Element?  querySelector(DOMString selectors);
   [Throws]
   NodeList  querySelectorAll(DOMString selectors);
 };
+
+DocumentFragment implements ParentNode;
--- a/dom/webidl/Element.webidl
+++ b/dom/webidl/Element.webidl
@@ -50,29 +50,16 @@ interface Element : Node {
   boolean hasAttribute(DOMString name);
   boolean hasAttributeNS(DOMString? namespace, DOMString localName);
 
   HTMLCollection getElementsByTagName(DOMString localName);
   [Throws]
   HTMLCollection getElementsByTagNameNS(DOMString? namespace, DOMString localName);
   HTMLCollection getElementsByClassName(DOMString classNames);
 
-  [Constant]
-  readonly attribute HTMLCollection children;
-  [Pure]
-  readonly attribute Element? firstElementChild;
-  [Pure]
-  readonly attribute Element? lastElementChild;
-  [Pure]
-  readonly attribute Element? previousElementSibling;
-  [Pure]
-  readonly attribute Element? nextElementSibling;
-  [Pure]
-  readonly attribute unsigned long childElementCount;
-
   /**
    * The ratio of font-size-inflated text font size to computed font
    * size for this element. This will query the element for its primary frame,
    * and then use this to get font size inflation information about the frame.
    * This will be 1.0 if font size inflation is not enabled, and -1.0 if an
    * error occurred during the retrieval of the font size inflation.
    *
    * @note The font size inflation ratio that is returned is actually the
@@ -194,8 +181,9 @@ partial interface Element {
 partial interface Element {
   [Throws]
   Element?  querySelector(DOMString selectors);
   [Throws]
   NodeList  querySelectorAll(DOMString selectors);
 };
 
 Element implements ChildNode;
+Element implements ParentNode;
new file mode 100644
--- /dev/null
+++ b/dom/webidl/ParentNode.webidl
@@ -0,0 +1,24 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* 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 origin of this IDL file is
+ * http://dom.spec.whatwg.org/#interface-parentnode
+ */
+
+[NoInterfaceObject]
+interface ParentNode {
+  [Constant]
+  readonly attribute HTMLCollection children;
+  [Pure]
+  readonly attribute Element? firstElementChild;
+  [Pure]
+  readonly attribute Element? lastElementChild;
+  [Pure]
+  readonly attribute unsigned long childElementCount;
+
+  // Not implemented yet
+  // void prepend((Node or DOMString)... nodes);
+  // void append((Node or DOMString)... nodes);
+};
--- a/dom/webidl/WebIDL.mk
+++ b/dom/webidl/WebIDL.mk
@@ -204,16 +204,17 @@ webidl_files = \
   NotifyAudioAvailableEvent.webidl \
   NotifyPaintEvent.webidl \
   OfflineAudioCompletionEvent.webidl \
   OfflineAudioContext.webidl \
   OfflineResourceList.webidl \
   PaintRequest.webidl \
   PaintRequestList.webidl \
   PannerNode.webidl \
+  ParentNode.webidl \
   Performance.webidl \
   PerformanceNavigation.webidl \
   PerformanceTiming.webidl \
   PeriodicWave.webidl \
   Plugin.webidl \
   PluginArray.webidl \
   Position.webidl \
   PositionError.webidl \
--- a/gfx/2d/2D.h
+++ b/gfx/2d/2D.h
@@ -699,17 +699,17 @@ public:
 
   /*
    * Fill a series of clyphs on the draw target with a certain source pattern.
    */
   virtual void FillGlyphs(ScaledFont *aFont,
                           const GlyphBuffer &aBuffer,
                           const Pattern &aPattern,
                           const DrawOptions &aOptions = DrawOptions(),
-                          const GlyphRenderingOptions *aRenderingOptions = NULL) = 0;
+                          const GlyphRenderingOptions *aRenderingOptions = nullptr) = 0;
 
   /*
    * This takes a source pattern and a mask, and composites the source pattern
    * onto the destination surface using the alpha channel of the mask pattern
    * as a mask for the operation.
    *
    * aSource Source pattern
    * aMask Mask pattern
@@ -834,17 +834,17 @@ public:
   virtual void SetTransform(const Matrix &aTransform)
     { mTransform = aTransform; mTransformDirty = true; }
 
   SurfaceFormat GetFormat() { return mFormat; }
 
   /* Tries to get a native surface for a DrawTarget, this may fail if the
    * draw target cannot convert to this surface type.
    */
-  virtual void *GetNativeSurface(NativeSurfaceType aType) { return NULL; }
+  virtual void *GetNativeSurface(NativeSurfaceType aType) { return nullptr; }
 
   virtual bool IsDualDrawTarget() { return false; }
 
   void AddUserData(UserDataKey *key, void *userData, void (*destroy)(void*)) {
     mUserData.Add(key, userData, destroy);
   }
   void *GetUserData(UserDataKey *key) {
     return mUserData.Get(key);
--- a/gfx/2d/DrawEventRecorder.cpp
+++ b/gfx/2d/DrawEventRecorder.cpp
@@ -24,17 +24,17 @@ DrawEventRecorderPrivate::RecordEvent(co
   WriteElement(*mOutputStream, aEvent.mType);
 
   aEvent.RecordToStream(*mOutputStream);
 
   Flush();
 }
 
 DrawEventRecorderFile::DrawEventRecorderFile(const char *aFilename)
-  : DrawEventRecorderPrivate(NULL) 
+  : DrawEventRecorderPrivate(nullptr) 
   , mOutputFile(aFilename, ofstream::binary)
 {
   mOutputStream = &mOutputFile;
 
   WriteElement(*mOutputStream, kMagicInt);
   WriteElement(*mOutputStream, kMajorRevision);
   WriteElement(*mOutputStream, kMinorRevision);
 }
--- a/gfx/2d/DrawTargetD2D.cpp
+++ b/gfx/2d/DrawTargetD2D.cpp
@@ -1808,20 +1808,20 @@ DrawTargetD2D::GetClippedGeometry(IntRec
                                     D2D1::IdentityMatrix(), currentSink);
     }
 
     currentSink->Close();
 
     pathGeom = newGeom.forget();
   }
 
-  // For now we need mCurrentClippedGeometry to always be non-NULL. This method
-  // might seem a little strange but it is just fine, if pathGeom is NULL
-  // pathRect will always still contain 1 clip unaccounted for regardless of
-  // mCurrentClipBounds.
+  // For now we need mCurrentClippedGeometry to always be non-nullptr. This
+  // method might seem a little strange but it is just fine, if pathGeom is
+  // nullptr pathRect will always still contain 1 clip unaccounted for
+  // regardless of mCurrentClipBounds.
   if (!pathGeom) {
     pathGeom = ConvertRectToGeometry(pathRect);
   }
   mCurrentClippedGeometry = pathGeom.forget();
   *aClipBounds = mCurrentClipBounds;
   return mCurrentClippedGeometry;
 }
 
--- a/gfx/2d/DrawTargetD2D.h
+++ b/gfx/2d/DrawTargetD2D.h
@@ -202,17 +202,17 @@ private:
 
   TemporaryRef<ID3D10Texture2D> CreateGradientTexture(const GradientStopsD2D *aStops);
   TemporaryRef<ID3D10Texture2D> CreateTextureForAnalysis(IDWriteGlyphRunAnalysis *aAnalysis, const IntRect &aBounds);
 
   void SetupEffectForRadialGradient(const RadialGradientPattern *aPattern);
   void SetupStateForRendering();
 
   // Set the scissor rect to a certain IntRects, resets the scissor rect to
-  // surface bounds when NULL is specified.
+  // surface bounds when nullptr is specified.
   void SetScissorToRect(IntRect *aRect);
 
   void PushD2DLayer(ID2D1RenderTarget *aRT, ID2D1Geometry *aGeometry, ID2D1Layer *aLayer, const D2D1_MATRIX_3X2_F &aTransform);
 
   static const uint32_t test = 4;
 
   IntSize mSize;
 
@@ -237,17 +237,17 @@ private:
   RefPtr<ID3D10RenderTargetView> mTempRTView;
 
   // List of pushed clips.
   struct PushedClip
   {
     RefPtr<ID2D1Layer> mLayer;
     D2D1_RECT_F mBounds;
     union {
-      // If mPath is non-NULL, the mTransform member will be used, otherwise
+      // If mPath is non-nullptr, the mTransform member will be used, otherwise
       // the mIsPixelAligned member is valid.
       D2D1_MATRIX_3X2_F mTransform;
       bool mIsPixelAligned;
     };
     RefPtr<PathD2D> mPath;
   };
   std::vector<PushedClip> mPushedClips;
 
--- a/gfx/2d/DrawTargetRecording.cpp
+++ b/gfx/2d/DrawTargetRecording.cpp
@@ -72,17 +72,17 @@ GetGradientStops(GradientStops *aStops)
   }
 
   return static_cast<GradientStopsRecording*>(aStops)->mFinalGradientStops;
 }
 
 struct AdjustedPattern
 {
   AdjustedPattern(const Pattern &aPattern)
-    : mPattern(NULL)
+    : mPattern(nullptr)
   {
     mOrigPattern = const_cast<Pattern*>(&aPattern);
   }
 
   ~AdjustedPattern() {
     if (mPattern) {
       mPattern->~Pattern();
     }
@@ -181,17 +181,17 @@ DrawTargetRecording::StrokeLine(const Po
   mRecorder->RecordEvent(RecordedStrokeLine(this, aBegin, aEnd, aPattern, aStrokeOptions, aOptions));
   mFinalDT->StrokeLine(aBegin, aEnd, *AdjustedPattern(aPattern), aStrokeOptions, aOptions);
 }
 
 Path*
 DrawTargetRecording::GetPathForPathRecording(const Path *aPath) const
 {
   if (aPath->GetBackendType() != BACKEND_RECORDING) {
-    return NULL;
+    return nullptr;
   }
 
   return static_cast<const PathRecording*>(aPath)->mPath;
 }
 
 void
 DrawTargetRecording::Fill(const Path *aPath,
                           const Pattern &aPattern,
--- a/gfx/2d/DrawTargetRecording.h
+++ b/gfx/2d/DrawTargetRecording.h
@@ -152,17 +152,17 @@ public:
 
   /*
    * Fill a series of clyphs on the draw target with a certain source pattern.
    */
   virtual void FillGlyphs(ScaledFont *aFont,
                           const GlyphBuffer &aBuffer,
                           const Pattern &aPattern,
                           const DrawOptions &aOptions = DrawOptions(),
-                          const GlyphRenderingOptions *aRenderingOptions = NULL);
+                          const GlyphRenderingOptions *aRenderingOptions = nullptr);
 
   /*
    * This takes a source pattern and a mask, and composites the source pattern
    * onto the destination surface using the alpha channel of the mask pattern
    * as a mask for the operation.
    *
    * aSource Source pattern
    * aMask Mask pattern
--- a/gfx/2d/RecordedEvent.cpp
+++ b/gfx/2d/RecordedEvent.cpp
@@ -55,17 +55,17 @@ RecordedEvent::LoadEventFromStream(std::
     LOAD_EVENT_TYPE(SOURCESURFACEDESTRUCTION, RecordedSourceSurfaceDestruction);
     LOAD_EVENT_TYPE(GRADIENTSTOPSCREATION, RecordedGradientStopsCreation);
     LOAD_EVENT_TYPE(GRADIENTSTOPSDESTRUCTION, RecordedGradientStopsDestruction);
     LOAD_EVENT_TYPE(SNAPSHOT, RecordedSnapshot);
     LOAD_EVENT_TYPE(SCALEDFONTCREATION, RecordedScaledFontCreation);
     LOAD_EVENT_TYPE(SCALEDFONTDESTRUCTION, RecordedScaledFontDestruction);
     LOAD_EVENT_TYPE(MASKSURFACE, RecordedMaskSurface);
   default:
-    return NULL;
+    return nullptr;
   }
 }
 
 void
 RecordedEvent::RecordPatternData(std::ostream &aStream, const PatternStorage &aPattern) const
 {
   WriteElement(aStream, aPattern.mType);
 
@@ -337,17 +337,17 @@ void
 RecordedDrawTargetDestruction::OutputSimpleEventInfo(stringstream &aStringStream) const
 {
   aStringStream << "[" << mRefPtr << "] DrawTarget Destruction";
 }
 
 struct GenericPattern
 {
   GenericPattern(const PatternStorage &aStorage, Translator *aTranslator)
-    : mPattern(NULL), mTranslator(aTranslator)
+    : mPattern(nullptr), mTranslator(aTranslator)
   {
     mStorage = const_cast<PatternStorage*>(&aStorage);
   }
 
   ~GenericPattern() {
     if (mPattern) {
       mPattern->~Pattern();
     }
--- a/gfx/2d/RecordedEvent.h
+++ b/gfx/2d/RecordedEvent.h
@@ -810,17 +810,17 @@ private:
 class RecordedScaledFontCreation : public RecordedEvent {
 public:
   static void FontDataProc(const uint8_t *aData, uint32_t aSize, uint32_t aIndex, Float aGlyphSize, void* aBaton)
   {
     static_cast<RecordedScaledFontCreation*>(aBaton)->SetFontData(aData, aSize, aIndex, aGlyphSize);
   }
 
   RecordedScaledFontCreation(ReferencePtr aRefPtr, ScaledFont *aScaledFont)
-    : RecordedEvent(SCALEDFONTCREATION), mRefPtr(aRefPtr), mData(NULL)
+    : RecordedEvent(SCALEDFONTCREATION), mRefPtr(aRefPtr), mData(nullptr)
   {
     aScaledFont->GetFontFileData(&FontDataProc, this);
   }
 
   ~RecordedScaledFontCreation();
 
   virtual void PlayEvent(Translator *aTranslator) const;
 
--- a/gfx/2d/Rect.h
+++ b/gfx/2d/Rect.h
@@ -9,26 +9,30 @@
 #include "BaseRect.h"
 #include "BaseMargin.h"
 #include "Point.h"
 #include "Tools.h"
 
 namespace mozilla {
 namespace gfx {
 
-struct Margin :
-  public BaseMargin<Float, Margin> {
-  typedef BaseMargin<Float, Margin> Super;
+template<class units>
+struct MarginTyped:
+    public BaseMargin<Float, MarginTyped<units> >,
+    public units {
+    typedef BaseMargin<Float, MarginTyped<units> > Super;
 
-  // Constructors
-  Margin() : Super(0, 0, 0, 0) {}
-  Margin(const Margin& aMargin) : Super(aMargin) {}
-  Margin(Float aTop, Float aRight, Float aBottom, Float aLeft)
-    : Super(aTop, aRight, aBottom, aLeft) {}
+    MarginTyped() : Super(0, 0, 0, 0) {}
+    MarginTyped(const MarginTyped<units>& aMargin) :
+        Super(float(aMargin.top), float(aMargin.right),
+              float(aMargin.bottom), float(aMargin.left)) {}
+    MarginTyped(Float aTop, Float aRight, Float aBottom, Float aLeft) :
+        Super(aTop, aRight, aBottom, aLeft) {}
 };
+typedef MarginTyped<UnknownUnits> Margin;
 
 template<class units>
 struct IntRectTyped :
     public BaseRect<int32_t, IntRectTyped<units>, IntPointTyped<units>, IntSizeTyped<units>, Margin>,
     public units {
     typedef BaseRect<int32_t, IntRectTyped<units>, IntPointTyped<units>, IntSizeTyped<units>, Margin> Super;
 
     IntRectTyped() : Super() {}
--- a/gfx/2d/ScaledFontDWrite.cpp
+++ b/gfx/2d/ScaledFontDWrite.cpp
@@ -208,17 +208,17 @@ DoGrayscale(IDWriteFontFace *aDWFace, Fl
         break;
       }
     }
     aDWFace->ReleaseFontTable(tableContext);
   }
   return true;
 }
 
-IDWriteFontFileLoader* DWriteFontFileLoader::mInstance = NULL;
+IDWriteFontFileLoader* DWriteFontFileLoader::mInstance = nullptr;
 
 HRESULT STDMETHODCALLTYPE
 DWriteFontFileLoader::CreateStreamFromKey(const void *fontFileReferenceKey, 
                                           UINT32 fontFileReferenceKeySize, 
                                           IDWriteFontFileStream **fontFileStream)
 {
   if (!fontFileReferenceKey || !fontFileStream) {
     return E_POINTER;
@@ -270,17 +270,17 @@ DWriteFontFileStream::ReadFileFragment(c
     return E_FAIL;
   }
 
   // truncate the 64 bit fileOffset to size_t sized index into mData
   size_t index = static_cast<size_t>(fileOffset);
 
   // We should be alive for the duration of this.
   *fragmentStart = &mData[index];
-  *fragmentContext = NULL;
+  *fragmentContext = nullptr;
   return S_OK;
 }
 
 void STDMETHODCALLTYPE
 DWriteFontFileStream::ReleaseFileFragment(void *fragmentContext)
 {
 }
 
--- a/gfx/gl/GLContext.cpp
+++ b/gfx/gl/GLContext.cpp
@@ -136,194 +136,194 @@ GLContext::InitWithPrefix(const char *pr
     if (mInitialized) {
         reporter.SetSuccessful();
         return true;
     }
 
     mWorkAroundDriverBugs = gfxPlatform::GetPlatform()->WorkAroundDriverBugs();
 
     SymLoadStruct symbols[] = {
-        { (PRFuncPtr*) &mSymbols.fActiveTexture, { "ActiveTexture", "ActiveTextureARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fAttachShader, { "AttachShader", "AttachShaderARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fBindAttribLocation, { "BindAttribLocation", "BindAttribLocationARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fBindBuffer, { "BindBuffer", "BindBufferARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fBindTexture, { "BindTexture", "BindTextureARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fBlendColor, { "BlendColor", NULL } },
-        { (PRFuncPtr*) &mSymbols.fBlendEquation, { "BlendEquation", NULL } },
-        { (PRFuncPtr*) &mSymbols.fBlendEquationSeparate, { "BlendEquationSeparate", "BlendEquationSeparateEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fBlendFunc, { "BlendFunc", NULL } },
-        { (PRFuncPtr*) &mSymbols.fBlendFuncSeparate, { "BlendFuncSeparate", "BlendFuncSeparateEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fBufferData, { "BufferData", NULL } },
-        { (PRFuncPtr*) &mSymbols.fBufferSubData, { "BufferSubData", NULL } },
-        { (PRFuncPtr*) &mSymbols.fClear, { "Clear", NULL } },
-        { (PRFuncPtr*) &mSymbols.fClearColor, { "ClearColor", NULL } },
-        { (PRFuncPtr*) &mSymbols.fClearStencil, { "ClearStencil", NULL } },
-        { (PRFuncPtr*) &mSymbols.fColorMask, { "ColorMask", NULL } },
-        { (PRFuncPtr*) &mSymbols.fCompressedTexImage2D, {"CompressedTexImage2D", NULL} },
-        { (PRFuncPtr*) &mSymbols.fCompressedTexSubImage2D, {"CompressedTexSubImage2D", NULL} },
-        { (PRFuncPtr*) &mSymbols.fCullFace, { "CullFace", NULL } },
-        { (PRFuncPtr*) &mSymbols.fDetachShader, { "DetachShader", "DetachShaderARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fDepthFunc, { "DepthFunc", NULL } },
-        { (PRFuncPtr*) &mSymbols.fDepthMask, { "DepthMask", NULL } },
-        { (PRFuncPtr*) &mSymbols.fDisable, { "Disable", NULL } },
-        { (PRFuncPtr*) &mSymbols.fDisableVertexAttribArray, { "DisableVertexAttribArray", "DisableVertexAttribArrayARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fDrawArrays, { "DrawArrays", NULL } },
-        { (PRFuncPtr*) &mSymbols.fDrawElements, { "DrawElements", NULL } },
-        { (PRFuncPtr*) &mSymbols.fEnable, { "Enable", NULL } },
-        { (PRFuncPtr*) &mSymbols.fEnableVertexAttribArray, { "EnableVertexAttribArray", "EnableVertexAttribArrayARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fFinish, { "Finish", NULL } },
-        { (PRFuncPtr*) &mSymbols.fFlush, { "Flush", NULL } },
-        { (PRFuncPtr*) &mSymbols.fFrontFace, { "FrontFace", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetActiveAttrib, { "GetActiveAttrib", "GetActiveAttribARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetActiveUniform, { "GetActiveUniform", "GetActiveUniformARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetAttachedShaders, { "GetAttachedShaders", "GetAttachedShadersARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetAttribLocation, { "GetAttribLocation", "GetAttribLocationARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetIntegerv, { "GetIntegerv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetFloatv, { "GetFloatv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetBooleanv, { "GetBooleanv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetBufferParameteriv, { "GetBufferParameteriv", "GetBufferParameterivARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetError, { "GetError", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetProgramiv, { "GetProgramiv", "GetProgramivARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetProgramInfoLog, { "GetProgramInfoLog", "GetProgramInfoLogARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fTexParameteri, { "TexParameteri", NULL } },
-        { (PRFuncPtr*) &mSymbols.fTexParameteriv, { "TexParameteriv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fTexParameterf, { "TexParameterf", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetString, { "GetString", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetTexParameterfv, { "GetTexParameterfv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetTexParameteriv, { "GetTexParameteriv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetUniformfv, { "GetUniformfv", "GetUniformfvARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetUniformiv, { "GetUniformiv", "GetUniformivARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetUniformLocation, { "GetUniformLocation", "GetUniformLocationARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetVertexAttribfv, { "GetVertexAttribfv", "GetVertexAttribfvARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetVertexAttribiv, { "GetVertexAttribiv", "GetVertexAttribivARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetVertexAttribPointerv, { "GetVertexAttribPointerv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fHint, { "Hint", NULL } },
-        { (PRFuncPtr*) &mSymbols.fIsBuffer, { "IsBuffer", "IsBufferARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fIsEnabled, { "IsEnabled", NULL } },
-        { (PRFuncPtr*) &mSymbols.fIsProgram, { "IsProgram", "IsProgramARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fIsShader, { "IsShader", "IsShaderARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fIsTexture, { "IsTexture", "IsTextureARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fLineWidth, { "LineWidth", NULL } },
-        { (PRFuncPtr*) &mSymbols.fLinkProgram, { "LinkProgram", "LinkProgramARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fPixelStorei, { "PixelStorei", NULL } },
-        { (PRFuncPtr*) &mSymbols.fPolygonOffset, { "PolygonOffset", NULL } },
-        { (PRFuncPtr*) &mSymbols.fReadPixels, { "ReadPixels", NULL } },
-        { (PRFuncPtr*) &mSymbols.fSampleCoverage, { "SampleCoverage", NULL } },
-        { (PRFuncPtr*) &mSymbols.fScissor, { "Scissor", NULL } },
-        { (PRFuncPtr*) &mSymbols.fStencilFunc, { "StencilFunc", NULL } },
-        { (PRFuncPtr*) &mSymbols.fStencilFuncSeparate, { "StencilFuncSeparate", "StencilFuncSeparateEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fStencilMask, { "StencilMask", NULL } },
-        { (PRFuncPtr*) &mSymbols.fStencilMaskSeparate, { "StencilMaskSeparate", "StencilMaskSeparateEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fStencilOp, { "StencilOp", NULL } },
-        { (PRFuncPtr*) &mSymbols.fStencilOpSeparate, { "StencilOpSeparate", "StencilOpSeparateEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fTexImage2D, { "TexImage2D", NULL } },
-        { (PRFuncPtr*) &mSymbols.fTexSubImage2D, { "TexSubImage2D", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform1f, { "Uniform1f", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform1fv, { "Uniform1fv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform1i, { "Uniform1i", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform1iv, { "Uniform1iv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform2f, { "Uniform2f", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform2fv, { "Uniform2fv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform2i, { "Uniform2i", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform2iv, { "Uniform2iv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform3f, { "Uniform3f", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform3fv, { "Uniform3fv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform3i, { "Uniform3i", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform3iv, { "Uniform3iv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform4f, { "Uniform4f", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform4fv, { "Uniform4fv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform4i, { "Uniform4i", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniform4iv, { "Uniform4iv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniformMatrix2fv, { "UniformMatrix2fv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniformMatrix3fv, { "UniformMatrix3fv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUniformMatrix4fv, { "UniformMatrix4fv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fUseProgram, { "UseProgram", NULL } },
-        { (PRFuncPtr*) &mSymbols.fValidateProgram, { "ValidateProgram", NULL } },
-        { (PRFuncPtr*) &mSymbols.fVertexAttribPointer, { "VertexAttribPointer", NULL } },
-        { (PRFuncPtr*) &mSymbols.fVertexAttrib1f, { "VertexAttrib1f", NULL } },
-        { (PRFuncPtr*) &mSymbols.fVertexAttrib2f, { "VertexAttrib2f", NULL } },
-        { (PRFuncPtr*) &mSymbols.fVertexAttrib3f, { "VertexAttrib3f", NULL } },
-        { (PRFuncPtr*) &mSymbols.fVertexAttrib4f, { "VertexAttrib4f", NULL } },
-        { (PRFuncPtr*) &mSymbols.fVertexAttrib1fv, { "VertexAttrib1fv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fVertexAttrib2fv, { "VertexAttrib2fv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fVertexAttrib3fv, { "VertexAttrib3fv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fVertexAttrib4fv, { "VertexAttrib4fv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fViewport, { "Viewport", NULL } },
-        { (PRFuncPtr*) &mSymbols.fCompileShader, { "CompileShader", NULL } },
-        { (PRFuncPtr*) &mSymbols.fCopyTexImage2D, { "CopyTexImage2D", NULL } },
-        { (PRFuncPtr*) &mSymbols.fCopyTexSubImage2D, { "CopyTexSubImage2D", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetShaderiv, { "GetShaderiv", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetShaderInfoLog, { "GetShaderInfoLog", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetShaderSource, { "GetShaderSource", NULL } },
-        { (PRFuncPtr*) &mSymbols.fShaderSource, { "ShaderSource", NULL } },
-        { (PRFuncPtr*) &mSymbols.fVertexAttribPointer, { "VertexAttribPointer", NULL } },
-        { (PRFuncPtr*) &mSymbols.fBindFramebuffer, { "BindFramebuffer", "BindFramebufferEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fBindRenderbuffer, { "BindRenderbuffer", "BindRenderbufferEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fCheckFramebufferStatus, { "CheckFramebufferStatus", "CheckFramebufferStatusEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fFramebufferRenderbuffer, { "FramebufferRenderbuffer", "FramebufferRenderbufferEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fFramebufferTexture2D, { "FramebufferTexture2D", "FramebufferTexture2DEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGenerateMipmap, { "GenerateMipmap", "GenerateMipmapEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetFramebufferAttachmentParameteriv, { "GetFramebufferAttachmentParameteriv", "GetFramebufferAttachmentParameterivEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGetRenderbufferParameteriv, { "GetRenderbufferParameteriv", "GetRenderbufferParameterivEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fIsFramebuffer, { "IsFramebuffer", "IsFramebufferEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fIsRenderbuffer, { "IsRenderbuffer", "IsRenderbufferEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fRenderbufferStorage, { "RenderbufferStorage", "RenderbufferStorageEXT", NULL } },
-
-        { (PRFuncPtr*) &mSymbols.fGenBuffers, { "GenBuffers", "GenBuffersARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGenTextures, { "GenTextures", NULL } },
-        { (PRFuncPtr*) &mSymbols.fCreateProgram, { "CreateProgram", "CreateProgramARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fCreateShader, { "CreateShader", "CreateShaderARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGenFramebuffers, { "GenFramebuffers", "GenFramebuffersEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fGenRenderbuffers, { "GenRenderbuffers", "GenRenderbuffersEXT", NULL } },
-
-        { (PRFuncPtr*) &mSymbols.fDeleteBuffers, { "DeleteBuffers", "DeleteBuffersARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fDeleteTextures, { "DeleteTextures", "DeleteTexturesARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fDeleteProgram, { "DeleteProgram", "DeleteProgramARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fDeleteShader, { "DeleteShader", "DeleteShaderARB", NULL } },
-        { (PRFuncPtr*) &mSymbols.fDeleteFramebuffers, { "DeleteFramebuffers", "DeleteFramebuffersEXT", NULL } },
-        { (PRFuncPtr*) &mSymbols.fDeleteRenderbuffers, { "DeleteRenderbuffers", "DeleteRenderbuffersEXT", NULL } },
-
-        { NULL, { NULL } },
+        { (PRFuncPtr*) &mSymbols.fActiveTexture, { "ActiveTexture", "ActiveTextureARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fAttachShader, { "AttachShader", "AttachShaderARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fBindAttribLocation, { "BindAttribLocation", "BindAttribLocationARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fBindBuffer, { "BindBuffer", "BindBufferARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fBindTexture, { "BindTexture", "BindTextureARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fBlendColor, { "BlendColor", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fBlendEquation, { "BlendEquation", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fBlendEquationSeparate, { "BlendEquationSeparate", "BlendEquationSeparateEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fBlendFunc, { "BlendFunc", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fBlendFuncSeparate, { "BlendFuncSeparate", "BlendFuncSeparateEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fBufferData, { "BufferData", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fBufferSubData, { "BufferSubData", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fClear, { "Clear", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fClearColor, { "ClearColor", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fClearStencil, { "ClearStencil", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fColorMask, { "ColorMask", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fCompressedTexImage2D, {"CompressedTexImage2D", nullptr} },
+        { (PRFuncPtr*) &mSymbols.fCompressedTexSubImage2D, {"CompressedTexSubImage2D", nullptr} },
+        { (PRFuncPtr*) &mSymbols.fCullFace, { "CullFace", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fDetachShader, { "DetachShader", "DetachShaderARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fDepthFunc, { "DepthFunc", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fDepthMask, { "DepthMask", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fDisable, { "Disable", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fDisableVertexAttribArray, { "DisableVertexAttribArray", "DisableVertexAttribArrayARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fDrawArrays, { "DrawArrays", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fDrawElements, { "DrawElements", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fEnable, { "Enable", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fEnableVertexAttribArray, { "EnableVertexAttribArray", "EnableVertexAttribArrayARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fFinish, { "Finish", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fFlush, { "Flush", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fFrontFace, { "FrontFace", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetActiveAttrib, { "GetActiveAttrib", "GetActiveAttribARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetActiveUniform, { "GetActiveUniform", "GetActiveUniformARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetAttachedShaders, { "GetAttachedShaders", "GetAttachedShadersARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetAttribLocation, { "GetAttribLocation", "GetAttribLocationARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetIntegerv, { "GetIntegerv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetFloatv, { "GetFloatv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetBooleanv, { "GetBooleanv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetBufferParameteriv, { "GetBufferParameteriv", "GetBufferParameterivARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetError, { "GetError", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetProgramiv, { "GetProgramiv", "GetProgramivARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetProgramInfoLog, { "GetProgramInfoLog", "GetProgramInfoLogARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fTexParameteri, { "TexParameteri", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fTexParameteriv, { "TexParameteriv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fTexParameterf, { "TexParameterf", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetString, { "GetString", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetTexParameterfv, { "GetTexParameterfv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetTexParameteriv, { "GetTexParameteriv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetUniformfv, { "GetUniformfv", "GetUniformfvARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetUniformiv, { "GetUniformiv", "GetUniformivARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetUniformLocation, { "GetUniformLocation", "GetUniformLocationARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetVertexAttribfv, { "GetVertexAttribfv", "GetVertexAttribfvARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetVertexAttribiv, { "GetVertexAttribiv", "GetVertexAttribivARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetVertexAttribPointerv, { "GetVertexAttribPointerv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fHint, { "Hint", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fIsBuffer, { "IsBuffer", "IsBufferARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fIsEnabled, { "IsEnabled", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fIsProgram, { "IsProgram", "IsProgramARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fIsShader, { "IsShader", "IsShaderARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fIsTexture, { "IsTexture", "IsTextureARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fLineWidth, { "LineWidth", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fLinkProgram, { "LinkProgram", "LinkProgramARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fPixelStorei, { "PixelStorei", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fPolygonOffset, { "PolygonOffset", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fReadPixels, { "ReadPixels", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fSampleCoverage, { "SampleCoverage", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fScissor, { "Scissor", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fStencilFunc, { "StencilFunc", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fStencilFuncSeparate, { "StencilFuncSeparate", "StencilFuncSeparateEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fStencilMask, { "StencilMask", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fStencilMaskSeparate, { "StencilMaskSeparate", "StencilMaskSeparateEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fStencilOp, { "StencilOp", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fStencilOpSeparate, { "StencilOpSeparate", "StencilOpSeparateEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fTexImage2D, { "TexImage2D", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fTexSubImage2D, { "TexSubImage2D", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform1f, { "Uniform1f", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform1fv, { "Uniform1fv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform1i, { "Uniform1i", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform1iv, { "Uniform1iv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform2f, { "Uniform2f", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform2fv, { "Uniform2fv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform2i, { "Uniform2i", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform2iv, { "Uniform2iv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform3f, { "Uniform3f", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform3fv, { "Uniform3fv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform3i, { "Uniform3i", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform3iv, { "Uniform3iv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform4f, { "Uniform4f", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform4fv, { "Uniform4fv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform4i, { "Uniform4i", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniform4iv, { "Uniform4iv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniformMatrix2fv, { "UniformMatrix2fv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniformMatrix3fv, { "UniformMatrix3fv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUniformMatrix4fv, { "UniformMatrix4fv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fUseProgram, { "UseProgram", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fValidateProgram, { "ValidateProgram", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fVertexAttribPointer, { "VertexAttribPointer", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fVertexAttrib1f, { "VertexAttrib1f", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fVertexAttrib2f, { "VertexAttrib2f", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fVertexAttrib3f, { "VertexAttrib3f", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fVertexAttrib4f, { "VertexAttrib4f", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fVertexAttrib1fv, { "VertexAttrib1fv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fVertexAttrib2fv, { "VertexAttrib2fv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fVertexAttrib3fv, { "VertexAttrib3fv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fVertexAttrib4fv, { "VertexAttrib4fv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fViewport, { "Viewport", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fCompileShader, { "CompileShader", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fCopyTexImage2D, { "CopyTexImage2D", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fCopyTexSubImage2D, { "CopyTexSubImage2D", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetShaderiv, { "GetShaderiv", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetShaderInfoLog, { "GetShaderInfoLog", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetShaderSource, { "GetShaderSource", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fShaderSource, { "ShaderSource", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fVertexAttribPointer, { "VertexAttribPointer", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fBindFramebuffer, { "BindFramebuffer", "BindFramebufferEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fBindRenderbuffer, { "BindRenderbuffer", "BindRenderbufferEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fCheckFramebufferStatus, { "CheckFramebufferStatus", "CheckFramebufferStatusEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fFramebufferRenderbuffer, { "FramebufferRenderbuffer", "FramebufferRenderbufferEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fFramebufferTexture2D, { "FramebufferTexture2D", "FramebufferTexture2DEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGenerateMipmap, { "GenerateMipmap", "GenerateMipmapEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetFramebufferAttachmentParameteriv, { "GetFramebufferAttachmentParameteriv", "GetFramebufferAttachmentParameterivEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGetRenderbufferParameteriv, { "GetRenderbufferParameteriv", "GetRenderbufferParameterivEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fIsFramebuffer, { "IsFramebuffer", "IsFramebufferEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fIsRenderbuffer, { "IsRenderbuffer", "IsRenderbufferEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fRenderbufferStorage, { "RenderbufferStorage", "RenderbufferStorageEXT", nullptr } },
+
+        { (PRFuncPtr*) &mSymbols.fGenBuffers, { "GenBuffers", "GenBuffersARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGenTextures, { "GenTextures", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fCreateProgram, { "CreateProgram", "CreateProgramARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fCreateShader, { "CreateShader", "CreateShaderARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGenFramebuffers, { "GenFramebuffers", "GenFramebuffersEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fGenRenderbuffers, { "GenRenderbuffers", "GenRenderbuffersEXT", nullptr } },
+
+        { (PRFuncPtr*) &mSymbols.fDeleteBuffers, { "DeleteBuffers", "DeleteBuffersARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fDeleteTextures, { "DeleteTextures", "DeleteTexturesARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fDeleteProgram, { "DeleteProgram", "DeleteProgramARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fDeleteShader, { "DeleteShader", "DeleteShaderARB", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fDeleteFramebuffers, { "DeleteFramebuffers", "DeleteFramebuffersEXT", nullptr } },
+        { (PRFuncPtr*) &mSymbols.fDeleteRenderbuffers, { "DeleteRenderbuffers", "DeleteRenderbuffersEXT", nullptr } },
+
+        { nullptr, { nullptr } },
 
     };
 
     mInitialized = LoadSymbols(&symbols[0], trygl, prefix);
 
     // Load OpenGL ES 2.0 symbols, or desktop if we aren't using ES 2.
     if (mInitialized) {
         if (mIsGLES2) {
             SymLoadStruct symbols_ES2[] = {
-                { (PRFuncPtr*) &mSymbols.fGetShaderPrecisionFormat, { "GetShaderPrecisionFormat", NULL } },
-                { (PRFuncPtr*) &mSymbols.fClearDepthf, { "ClearDepthf", NULL } },
-                { (PRFuncPtr*) &mSymbols.fDepthRangef, { "DepthRangef", NULL } },
-                { NULL, { NULL } },
+                { (PRFuncPtr*) &mSymbols.fGetShaderPrecisionFormat, { "GetShaderPrecisionFormat", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fClearDepthf, { "ClearDepthf", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fDepthRangef, { "DepthRangef", nullptr } },
+                { nullptr, { nullptr } },
             };
 
             if (!LoadSymbols(&symbols_ES2[0], trygl, prefix)) {
                 NS_ERROR("OpenGL ES 2.0 supported, but symbols could not be loaded.");
                 mInitialized = false;
             }
         } else {
             SymLoadStruct symbols_desktop[] = {
-                { (PRFuncPtr*) &mSymbols.fClearDepth, { "ClearDepth", NULL } },
-                { (PRFuncPtr*) &mSymbols.fDepthRange, { "DepthRange", NULL } },
-                { (PRFuncPtr*) &mSymbols.fReadBuffer, { "ReadBuffer", NULL } },
-                { (PRFuncPtr*) &mSymbols.fMapBuffer, { "MapBuffer", NULL } },
-                { (PRFuncPtr*) &mSymbols.fUnmapBuffer, { "UnmapBuffer", NULL } },
-                { (PRFuncPtr*) &mSymbols.fPointParameterf, { "PointParameterf", NULL } },
-                { (PRFuncPtr*) &mSymbols.fBeginQuery, { "BeginQuery", NULL } },
-                { (PRFuncPtr*) &mSymbols.fGetQueryObjectuiv, { "GetQueryObjectuiv", NULL } },
-                { (PRFuncPtr*) &mSymbols.fGenQueries, { "GenQueries", NULL } },
-                { (PRFuncPtr*) &mSymbols.fDeleteQueries, { "DeleteQueries", NULL } },
-                { (PRFuncPtr*) &mSymbols.fGetQueryiv, { "GetQueryiv", NULL } },
-                { (PRFuncPtr*) &mSymbols.fGetQueryObjectiv, { "GetQueryObjectiv", NULL } },
-                { (PRFuncPtr*) &mSymbols.fEndQuery, { "EndQuery", NULL } },
-                { (PRFuncPtr*) &mSymbols.fDrawBuffer, { "DrawBuffer", NULL } },
-                { (PRFuncPtr*) &mSymbols.fDrawBuffers, { "DrawBuffers", NULL } },
-                { NULL, { NULL } },
+                { (PRFuncPtr*) &mSymbols.fClearDepth, { "ClearDepth", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fDepthRange, { "DepthRange", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fReadBuffer, { "ReadBuffer", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fMapBuffer, { "MapBuffer", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fUnmapBuffer, { "UnmapBuffer", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fPointParameterf, { "PointParameterf", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fBeginQuery, { "BeginQuery", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fGetQueryObjectuiv, { "GetQueryObjectuiv", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fGenQueries, { "GenQueries", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fDeleteQueries, { "DeleteQueries", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fGetQueryiv, { "GetQueryiv", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fGetQueryObjectiv, { "GetQueryObjectiv", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fEndQuery, { "EndQuery", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fDrawBuffer, { "DrawBuffer", nullptr } },
+                { (PRFuncPtr*) &mSymbols.fDrawBuffers, { "DrawBuffers", nullptr } },
+                { nullptr, { nullptr } },
             };
 
             if (!LoadSymbols(&symbols_desktop[0], trygl, prefix)) {
                 NS_ERROR("Desktop symbols failed to load.");
                 mInitialized = false;
             }
         }
     }
@@ -1576,18 +1576,18 @@ GLContext::ReadTextureImage(GLuint aText
     if (fCheckFramebufferStatus(LOCAL_GL_FRAMEBUFFER) !=
         LOCAL_GL_FRAMEBUFFER_COMPLETE)
     {
         goto cleanup;
     }
 
     vs = fCreateShader(LOCAL_GL_VERTEX_SHADER);
     fs = fCreateShader(LOCAL_GL_FRAGMENT_SHADER);
-    fShaderSource(vs, 1, (const GLchar**) &vShader, NULL);
-    fShaderSource(fs, 1, (const GLchar**) &fShader, NULL);
+    fShaderSource(vs, 1, (const GLchar**) &vShader, nullptr);
+    fShaderSource(fs, 1, (const GLchar**) &fShader, nullptr);
     fCompileShader(vs);
     fCompileShader(fs);
     prog = fCreateProgram();
     fAttachShader(prog, vs);
     fAttachShader(prog, fs);
     fBindAttribLocation(prog, 0, "aVertex");
     fBindAttribLocation(prog, 1, "aTexCoord");
     fLinkProgram(prog);
@@ -2007,18 +2007,18 @@ GLContext::BlitTextureImage(TextureImage
 
             fDisableVertexAttribArray(0);
             fDisableVertexAttribArray(1);
 
             PopViewportRect();
         } while (aSrc->NextTile());
     } while (aDst->NextTile());
 
-    fVertexAttribPointer(0, 2, LOCAL_GL_FLOAT, LOCAL_GL_FALSE, 0, NULL);
-    fVertexAttribPointer(1, 2, LOCAL_GL_FLOAT, LOCAL_GL_FALSE, 0, NULL);
+    fVertexAttribPointer(0, 2, LOCAL_GL_FLOAT, LOCAL_GL_FALSE, 0, nullptr);
+    fVertexAttribPointer(1, 2, LOCAL_GL_FLOAT, LOCAL_GL_FALSE, 0, nullptr);
 
     // unbind the previous texture from the framebuffer
     SetBlitFramebufferForDestTexture(0);
 
     fBindFramebuffer(LOCAL_GL_FRAMEBUFFER, savedFb);
 
     fEnable(LOCAL_GL_SCISSOR_TEST);
     fEnable(LOCAL_GL_BLEND);
@@ -2181,17 +2181,17 @@ GLContext::UploadSurfaceToTexture(gfxASu
                                   bool aOverwrite,
                                   const nsIntPoint& aSrcPoint,
                                   bool aPixelBuffer,
                                   GLenum aTextureUnit,
                                   GLenum aTextureTarget)
 {
 
     nsRefPtr<gfxImageSurface> imageSurface = aSurface->GetAsImageSurface();
-    unsigned char* data = NULL;
+    unsigned char* data = nullptr;
 
     if (!imageSurface ||
         (imageSurface->Format() != gfxASurface::ImageFormatARGB32 &&
          imageSurface->Format() != gfxASurface::ImageFormatRGB24 &&
          imageSurface->Format() != gfxASurface::ImageFormatRGB16_565 &&
          imageSurface->Format() != gfxASurface::ImageFormatA8)) {
         // We can't get suitable pixel data for the surface, make a copy
         nsIntRect bounds = aDstRegion.GetBounds();
@@ -2249,17 +2249,17 @@ GLContext::UploadSurfaceToTexture(gfx::D
                                   const nsIntRegion& aDstRegion,
                                   GLuint& aTexture,
                                   bool aOverwrite,
                                   const nsIntPoint& aSrcPoint,
                                   bool aPixelBuffer,
                                   GLenum aTextureUnit,
                                   GLenum aTextureTarget)
 {
-    unsigned char* data = aPixelBuffer ? NULL : aSurface->GetData();
+    unsigned char* data = aPixelBuffer ? nullptr : aSurface->GetData();
     int32_t stride = aSurface->Stride();
     gfxASurface::gfxImageFormat format =
         ImageFormatForSurfaceFormat(aSurface->GetFormat());
     data += DataOffset(aSrcPoint, stride, format);
     return UploadImageDataToTexture(data, stride, format,
                                     aDstRegion, aTexture, aOverwrite,
                                     aPixelBuffer, aTextureUnit,
                                     aTextureTarget);
@@ -2344,17 +2344,17 @@ GLContext::TexImage2D(GLenum target, GLi
             fTexImage2D(target,
                         border,
                         internalformat,
                         width,
                         height,
                         border,
                         format,
                         type,
-                        NULL);
+                        nullptr);
             TexSubImage2D(target,
                           level,
                           0,
                           0,
                           width,
                           height,
                           stride,
                           pixelsize,
@@ -2731,18 +2731,18 @@ GLContext::UseBlitProgram()
         "}";
     const char *blitFSSrc = "#ifdef GL_ES\nprecision mediump float;\n#endif\n"
         "uniform sampler2D uSrcTexture;"
         "varying vec2 vTexCoord;"
         "void main() {"
         "  gl_FragColor = texture2D(uSrcTexture, vTexCoord);"
         "}";
 
-    fShaderSource(shaders[0], 1, (const GLchar**) &blitVSSrc, NULL);
-    fShaderSource(shaders[1], 1, (const GLchar**) &blitFSSrc, NULL);
+    fShaderSource(shaders[0], 1, (const GLchar**) &blitVSSrc, nullptr);
+    fShaderSource(shaders[1], 1, (const GLchar**) &blitFSSrc, nullptr);
 
     for (int i = 0; i < 2; ++i) {
         GLint success, len = 0;
 
         fCompileShader(shaders[i]);
         fGetShaderiv(shaders[i], LOCAL_GL_COMPILE_STATUS, &success);
         NS_ASSERTION(success, "Shader compilation failed!");
 
@@ -2953,17 +2953,17 @@ ReportArrayContents(const char *title, c
     if (aArray.Length() == 0)
         return;
 
     printf_stderr("%s:\n", title);
 
     nsTArray<GLContext::NamedResource> copy(aArray);
     copy.Sort();
 
-    GLContext *lastContext = NULL;
+    GLContext *lastContext = nullptr;
     for (uint32_t i = 0; i < copy.Length(); ++i) {
         if (lastContext != copy[i].origin) {
             if (lastContext)
                 printf_stderr("\n");
             printf_stderr("  [%p - %s] ", copy[i].origin, copy[i].originDeleted ? "deleted" : "live");
             lastContext = copy[i].origin;
         }
         printf_stderr("%d ", copy[i].name);
--- a/gfx/gl/GLContext.h
+++ b/gfx/gl/GLContext.h
@@ -168,17 +168,17 @@ public:
     };
 
     virtual GLContextType GetContextType() { return ContextTypeUnknown; }
 
     virtual bool MakeCurrentImpl(bool aForce = false) = 0;
 
 #ifdef DEBUG
     static void StaticInit() {
-        PR_NewThreadPrivateIndex(&sCurrentGLContextTLS, NULL);
+        PR_NewThreadPrivateIndex(&sCurrentGLContextTLS, nullptr);
     }
 #endif
 
     bool MakeCurrent(bool aForce = false) {
 #ifdef DEBUG
     PR_SetThreadPrivate(sCurrentGLContextTLS, this);
 
     // XXX this assertion is disabled because it's triggering on Mac;
@@ -208,33 +208,33 @@ public:
         mUserData.Get(aKey, &result);
         return result;
     }
 
     void SetUserData(void *aKey, void *aValue) {
         mUserData.Put(aKey, aValue);
     }
 
-    // Mark this context as destroyed.  This will NULL out all
+    // Mark this context as destroyed.  This will nullptr out all
     // the GL function pointers!
     void MarkDestroyed();
 
     bool IsDestroyed() {
         // MarkDestroyed will mark all these as null.
         return mSymbols.fUseProgram == nullptr;
     }
 
     enum NativeDataType {
       NativeGLContext,
       NativeImageSurface,
       NativeThebesSurface,
       NativeDataTypeMax
     };
 
-    virtual void *GetNativeData(NativeDataType aType) { return NULL; }
+    virtual void *GetNativeData(NativeDataType aType) { return nullptr; }
     GLContext *GetSharedContext() { return mSharedContext; }
 
     bool IsGlobalSharedContext() { return mIsGlobalSharedContext; }
     void SetIsGlobalSharedContext(bool aIsOne) { mIsGlobalSharedContext = aIsOne; }
 
     /**
      * Returns true if the thread on which this context was created is the currently
      * executing thread.
@@ -781,17 +781,17 @@ public:
 
     /**
      * Return a valid, allocated TextureImage of |aSize| with
      * |aContentType|.  The TextureImage's texture is configured to
      * use |aWrapMode| (usually GL_CLAMP_TO_EDGE or GL_REPEAT) and by
      * default, GL_LINEAR filtering.  Specify
      * |aFlags=UseNearestFilter| for GL_NEAREST filtering. Specify
      * |aFlags=NeedsYFlip| if the image is flipped. Return
-     * NULL if creating the TextureImage fails.
+     * nullptr if creating the TextureImage fails.
      *
      * The returned TextureImage may only be used with this GLContext.
      * Attempting to use the returned TextureImage after this
      * GLContext is destroyed will result in undefined (and likely
      * crashy) behavior.
      */
     virtual already_AddRefed<TextureImage>
     CreateTextureImage(const nsIntSize& aSize,
@@ -977,17 +977,17 @@ public:
         // true.
         void addRect(GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1,
                      GLfloat tx0, GLfloat ty0, GLfloat tx1, GLfloat ty1,
                      bool flip_y = false);
 
         /**
          * these return a float pointer to the start of each array respectively.
          * Use it for glVertexAttribPointer calls.
-         * We can return NULL if we choose to use Vertex Buffer Objects here.
+         * We can return nullptr if we choose to use Vertex Buffer Objects here.
          */
         float* vertexPointer() {
             return &vertexCoords[0].x;
         }
 
         float* texCoordPointer() {
             return &texCoords[0].u;
         }
@@ -1495,17 +1495,17 @@ public:
 protected:
     GLenum mGLError;
 
 public:
 
     void BeforeGLCall(const char* glFunction) {
         MOZ_ASSERT(IsCurrent());
         if (DebugMode()) {
-            GLContext *currentGLContext = NULL;
+            GLContext *currentGLContext = nullptr;
 
             currentGLContext = (GLContext*)PR_GetThreadPrivate(sCurrentGLContextTLS);
 
             if (DebugMode() & DebugTrace)
                 printf_stderr("[gl:%p] > %s\n", this, glFunction);
             if (this != currentGLContext) {
                 printf_stderr("Fatal: %s called on non-current context %p. "
                               "The current context for this thread is %p.\n",
--- a/gfx/gl/GLContextProviderEGL.cpp
+++ b/gfx/gl/GLContextProviderEGL.cpp
@@ -62,34 +62,34 @@ using namespace android;
 #define WIN32_LEAN_AND_MEAN 1
 #endif
 
 #include <windows.h>
 
 // a little helper
 class AutoDestroyHWND {
 public:
-    AutoDestroyHWND(HWND aWnd = NULL)
+    AutoDestroyHWND(HWND aWnd = nullptr)
         : mWnd(aWnd)
     {
     }
 
     ~AutoDestroyHWND() {
         if (mWnd) {
             ::DestroyWindow(mWnd);
         }
     }
 
     operator HWND() {
         return mWnd;
     }
 
     HWND forget() {
         HWND w = mWnd;
-        mWnd = NULL;
+        mWnd = nullptr;
         return w;
     }
 
     HWND operator=(HWND aWnd) {
         if (mWnd && mWnd != aWnd) {
             ::DestroyWindow(mWnd);
         }
         mWnd = aWnd;
@@ -550,32 +550,32 @@ public:
 #ifdef MOZ_ANDROID_OMTC
             mSurface = mozilla::AndroidBridge::Bridge()->ProvideEGLSurface();
             if (!mSurface) {
                 return false;
             }
 #else
             EGLConfig config;
             CreateConfig(&config);
-            mSurface = CreateSurfaceForWindow(NULL, config);
+            mSurface = CreateSurfaceForWindow(nullptr, config);
 #endif
         }
         return sEGLLibrary.fMakeCurrent(EGL_DISPLAY(),
                                         mSurface, mSurface,
                                         mContext);
     }
 #endif
 
     virtual void
     ReleaseSurface() {
         if (mSurface && !mPlatformContext) {
             sEGLLibrary.fMakeCurrent(EGL_DISPLAY(), EGL_NO_SURFACE, EGL_NO_SURFACE,
                                      EGL_NO_CONTEXT);
             sEGLLibrary.fDestroySurface(EGL_DISPLAY(), mSurface);
-            mSurface = NULL;
+            mSurface = nullptr;
         }
     }
 
     bool SetupLookupFunction()
     {
         mLookupFunc = (PlatformLookupFunction)sEGLLibrary.mSymbols.fGetProcAddress;
         return true;
     }
@@ -1186,17 +1186,17 @@ public:
 
         // determine the region the client will need to repaint
         GetUpdateRegion(aRegion);
         mUpdateRect = aRegion.GetBounds();
 
         //printf_stderr("BeginUpdate with updateRect [%d %d %d %d]\n", mUpdateRect.x, mUpdateRect.y, mUpdateRect.width, mUpdateRect.height);
         if (!nsIntRect(nsIntPoint(0, 0), mSize).Contains(mUpdateRect)) {
             NS_ERROR("update outside of image");
-            return NULL;
+            return nullptr;
         }
 
         if (mBackingSurface) {
             mUpdateSurface = mBackingSurface;
             return mUpdateSurface;
         }
 
         //printf_stderr("creating image surface %dx%d format %d\n", mUpdateRect.width, mUpdateRect.height, mUpdateFormat);
@@ -1352,17 +1352,17 @@ public:
             mGLContext->fTexImage2D(LOCAL_GL_TEXTURE_2D,
                                     0,
                                     GLFormatForImage(mUpdateFormat),
                                     aSize.width,
                                     aSize.height,
                                     0,
                                     GLFormatForImage(mUpdateFormat),
                                     GLTypeForImage(mUpdateFormat),
-                                    NULL);
+                                    nullptr);
         }
 
         mTextureState = Allocated;
         mSize = aSize;
     }
 
     bool BindTexImage()
     {
--- a/gfx/gl/GLContextProviderGLX.cpp
+++ b/gfx/gl/GLContextProviderGLX.cpp
@@ -120,78 +120,78 @@ GLXLibrary::EnsureInitialized(LibType li
     }
 
     if (PR_GetEnv("MOZ_GLX_DEBUG")) {
         mDebug = true;
     }
 
     GLLibraryLoader::SymLoadStruct symbols[] = {
         /* functions that were in GLX 1.0 */
-        { (PRFuncPtr*) &xDestroyContextInternal, { "glXDestroyContext", NULL } },
-        { (PRFuncPtr*) &xMakeCurrentInternal, { "glXMakeCurrent", NULL } },
-        { (PRFuncPtr*) &xSwapBuffersInternal, { "glXSwapBuffers", NULL } },
-        { (PRFuncPtr*) &xQueryVersionInternal, { "glXQueryVersion", NULL } },
-        { (PRFuncPtr*) &xGetCurrentContextInternal, { "glXGetCurrentContext", NULL } },
-        { (PRFuncPtr*) &xWaitGLInternal, { "glXWaitGL", NULL } },
-        { (PRFuncPtr*) &xWaitXInternal, { "glXWaitX", NULL } },
+        { (PRFuncPtr*) &xDestroyContextInternal, { "glXDestroyContext", nullptr } },
+        { (PRFuncPtr*) &xMakeCurrentInternal, { "glXMakeCurrent", nullptr } },
+        { (PRFuncPtr*) &xSwapBuffersInternal, { "glXSwapBuffers", nullptr } },
+        { (PRFuncPtr*) &xQueryVersionInternal, { "glXQueryVersion", nullptr } },
+        { (PRFuncPtr*) &xGetCurrentContextInternal, { "glXGetCurrentContext", nullptr } },
+        { (PRFuncPtr*) &xWaitGLInternal, { "glXWaitGL", nullptr } },
+        { (PRFuncPtr*) &xWaitXInternal, { "glXWaitX", nullptr } },
         /* functions introduced in GLX 1.1 */
-        { (PRFuncPtr*) &xQueryExtensionsStringInternal, { "glXQueryExtensionsString", NULL } },
-        { (PRFuncPtr*) &xGetClientStringInternal, { "glXGetClientString", NULL } },
-        { (PRFuncPtr*) &xQueryServerStringInternal, { "glXQueryServerString", NULL } },
-        { NULL, { NULL } }
+        { (PRFuncPtr*) &xQueryExtensionsStringInternal, { "glXQueryExtensionsString", nullptr } },
+        { (PRFuncPtr*) &xGetClientStringInternal, { "glXGetClientString", nullptr } },
+        { (PRFuncPtr*) &xQueryServerStringInternal, { "glXQueryServerString", nullptr } },
+        { nullptr, { nullptr } }
     };
 
     GLLibraryLoader::SymLoadStruct symbols13[] = {
         /* functions introduced in GLX 1.3 */
-        { (PRFuncPtr*) &xChooseFBConfigInternal, { "glXChooseFBConfig", NULL } },
-        { (PRFuncPtr*) &xGetFBConfigAttribInternal, { "glXGetFBConfigAttrib", NULL } },
+        { (PRFuncPtr*) &xChooseFBConfigInternal, { "glXChooseFBConfig", nullptr } },
+        { (PRFuncPtr*) &xGetFBConfigAttribInternal, { "glXGetFBConfigAttrib", nullptr } },
         // WARNING: xGetFBConfigs not set in symbols13_ext
-        { (PRFuncPtr*) &xGetFBConfigsInternal, { "glXGetFBConfigs", NULL } },
+        { (PRFuncPtr*) &xGetFBConfigsInternal, { "glXGetFBConfigs", nullptr } },
         // WARNING: symbols13_ext sets xCreateGLXPixmapWithConfig instead
-        { (PRFuncPtr*) &xCreatePixmapInternal, { "glXCreatePixmap", NULL } },
-        { (PRFuncPtr*) &xDestroyPixmapInternal, { "glXDestroyPixmap", NULL } },
-        { (PRFuncPtr*) &xCreateNewContextInternal, { "glXCreateNewContext", NULL } },
-        { NULL, { NULL } }
+        { (PRFuncPtr*) &xCreatePixmapInternal, { "glXCreatePixmap", nullptr } },
+        { (PRFuncPtr*) &xDestroyPixmapInternal, { "glXDestroyPixmap", nullptr } },
+        { (PRFuncPtr*) &xCreateNewContextInternal, { "glXCreateNewContext", nullptr } },
+        { nullptr, { nullptr } }
     };
 
     GLLibraryLoader::SymLoadStruct symbols13_ext[] = {
         /* extension equivalents for functions introduced in GLX 1.3 */
         // GLX_SGIX_fbconfig extension
-        { (PRFuncPtr*) &xChooseFBConfigInternal, { "glXChooseFBConfigSGIX", NULL } },
-        { (PRFuncPtr*) &xGetFBConfigAttribInternal, { "glXGetFBConfigAttribSGIX", NULL } },
+        { (PRFuncPtr*) &xChooseFBConfigInternal, { "glXChooseFBConfigSGIX", nullptr } },
+        { (PRFuncPtr*) &xGetFBConfigAttribInternal, { "glXGetFBConfigAttribSGIX", nullptr } },
         // WARNING: no xGetFBConfigs equivalent in extensions
         // WARNING: different from symbols13:
-        { (PRFuncPtr*) &xCreateGLXPixmapWithConfigInternal, { "glXCreateGLXPixmapWithConfigSGIX", NULL } },
-        { (PRFuncPtr*) &xDestroyPixmapInternal, { "glXDestroyGLXPixmap", NULL } }, // not from ext
-        { (PRFuncPtr*) &xCreateNewContextInternal, { "glXCreateContextWithConfigSGIX", NULL } },
-        { NULL, { NULL } }
+        { (PRFuncPtr*) &xCreateGLXPixmapWithConfigInternal, { "glXCreateGLXPixmapWithConfigSGIX", nullptr } },
+        { (PRFuncPtr*) &xDestroyPixmapInternal, { "glXDestroyGLXPixmap", nullptr } }, // not from ext
+        { (PRFuncPtr*) &xCreateNewContextInternal, { "glXCreateContextWithConfigSGIX", nullptr } },
+        { nullptr, { nullptr } }
     };
 
     GLLibraryLoader::SymLoadStruct symbols14[] = {
         /* functions introduced in GLX 1.4 */
-        { (PRFuncPtr*) &xGetProcAddressInternal, { "glXGetProcAddress", NULL } },
-        { NULL, { NULL } }
+        { (PRFuncPtr*) &xGetProcAddressInternal, { "glXGetProcAddress", nullptr } },
+        { nullptr, { nullptr } }
     };
 
     GLLibraryLoader::SymLoadStruct symbols14_ext[] = {
         /* extension equivalents for functions introduced in GLX 1.4 */
         // GLX_ARB_get_proc_address extension
-        { (PRFuncPtr*) &xGetProcAddressInternal, { "glXGetProcAddressARB", NULL } },
-        { NULL, { NULL } }
+        { (PRFuncPtr*) &xGetProcAddressInternal, { "glXGetProcAddressARB", nullptr } },
+        { nullptr, { nullptr } }
     };
 
     GLLibraryLoader::SymLoadStruct symbols_texturefrompixmap[] = {
-        { (PRFuncPtr*) &xBindTexImageInternal, { "glXBindTexImageEXT", NULL } },
-        { (PRFuncPtr*) &xReleaseTexImageInternal, { "glXReleaseTexImageEXT", NULL } },
-        { NULL, { NULL } }
+        { (PRFuncPtr*) &xBindTexImageInternal, { "glXBindTexImageEXT", nullptr } },
+        { (PRFuncPtr*) &xReleaseTexImageInternal, { "glXReleaseTexImageEXT", nullptr } },
+        { nullptr, { nullptr } }
     };
 
     GLLibraryLoader::SymLoadStruct symbols_robustness[] = {
-        { (PRFuncPtr*) &xCreateContextAttribsInternal, { "glXCreateContextAttribsARB", NULL } },
-        { NULL, { NULL } }
+        { (PRFuncPtr*) &xCreateContextAttribsInternal, { "glXCreateContextAttribsARB", nullptr } },
+        { nullptr, { nullptr } }
     };
 
     if (!GLLibraryLoader::LoadSymbols(mOGLLibrary, &symbols[0])) {
         NS_WARNING("Couldn't find required entry point in OpenGL shared library");
         return false;
     }
 
     Display *display = DefaultXDisplay();
@@ -443,17 +443,17 @@ GLXLibrary::BindTexImage(GLXPixmap aPixm
     if (mClientIsMesa) {
         // Using XSync instead of Mesa's glXWaitX, because its glxWaitX is a
         // noop when direct rendering unless the current drawable is a
         // single-buffer window.
         FinishX(display);
     } else {
         xWaitX();
     }
-    xBindTexImage(display, aPixmap, GLX_FRONT_LEFT_EXT, NULL);
+    xBindTexImage(display, aPixmap, GLX_FRONT_LEFT_EXT, nullptr);
 }
 
 void
 GLXLibrary::ReleaseTexImage(GLXPixmap aPixmap)
 {
     if (!mUseTextureFromPixmap) {
         return;
     }
@@ -772,17 +772,17 @@ public:
         bool error;
 
         ScopedXErrorHandler xErrorHandler;
 
 TRY_AGAIN_NO_SHARING:
 
         error = false;
 
-        GLXContext glxContext = shareContext ? shareContext->mContext : NULL;
+        GLXContext glxContext = shareContext ? shareContext->mContext : nullptr;
         if (glx.HasRobustness()) {
             int attrib_list[] = {
                 LOCAL_GL_CONTEXT_FLAGS_ARB, LOCAL_GL_CONTEXT_ROBUST_ACCESS_BIT_ARB,
                 LOCAL_GL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB, LOCAL_GL_LOSE_CONTEXT_ON_RESET_ARB,
                 0,
             };
 
             context = glx.xCreateContextAttribs(
@@ -1349,17 +1349,17 @@ CreateOffscreenPixmapContext(const gfxIn
 
     // Handle slightly different signature between glXCreatePixmap and
     // its pre-GLX-1.3 extension equivalent (though given the ABI, we
     // might not need to).
     if (glx.GLXVersionCheck(1, 3)) {
         glxpixmap = glx.xCreatePixmap(display,
                                           cfgs[chosenIndex],
                                           xsurface->XDrawable(),
-                                          NULL);
+                                          nullptr);
     } else {
         glxpixmap = glx.xCreateGLXPixmapWithConfig(display,
                                                        cfgs[chosenIndex],
                                                        xsurface->
                                                        XDrawable());
     }
     if (glxpixmap == 0) {
         error = true;
--- a/gfx/gl/GLContextProviderWGL.cpp
+++ b/gfx/gl/GLContextProviderWGL.cpp
@@ -36,36 +36,37 @@ WGLLibrary::SelectLibrary(const GLContex
           ? WGLLibrary::MESA_LLVMPIPE_LIB
           : WGLLibrary::OPENGL_LIB;
 }
 
 HWND
 WGLLibrary::CreateDummyWindow(HDC *aWindowDC)
 {
     WNDCLASSW wc;
-    if (!GetClassInfoW(GetModuleHandle(NULL), L"GLContextWGLClass", &wc)) {
+    if (!GetClassInfoW(GetModuleHandle(nullptr), L"GLContextWGLClass", &wc)) {
         ZeroMemory(&wc, sizeof(WNDCLASSW));
         wc.style = CS_OWNDC;
-        wc.hInstance = GetModuleHandle(NULL);
+        wc.hInstance = GetModuleHandle(nullptr);
         wc.lpfnWndProc = DefWindowProc;
         wc.lpszClassName = L"GLContextWGLClass";
         if (!RegisterClassW(&wc)) {
             NS_WARNING("Failed to register GLContextWGLClass?!");
             // er. failed to register our class?
-            return NULL;
+            return nullptr;
         }
     }
 
     HWND win = CreateWindowW(L"GLContextWGLClass", L"GLContextWGL", 0,
                              0, 0, 16, 16,
-                             NULL, NULL, GetModuleHandle(NULL), NULL);
-    NS_ENSURE_TRUE(win, NULL);
+                             nullptr, nullptr, GetModuleHandle(nullptr),
+                             nullptr);
+    NS_ENSURE_TRUE(win, nullptr);
 
     HDC dc = GetDC(win);
-    NS_ENSURE_TRUE(dc, NULL);
+    NS_ENSURE_TRUE(dc, nullptr);
 
     if (mWindowPixelFormat == 0) {
         PIXELFORMATDESCRIPTOR pfd;
         ZeroMemory(&pfd, sizeof(PIXELFORMATDESCRIPTOR));
         pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
         pfd.nVersion = 1;
         pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
         if (mUseDoubleBufferedWindows)
@@ -78,21 +79,21 @@ WGLLibrary::CreateDummyWindow(HDC *aWind
         pfd.cAlphaBits = 8;
         pfd.cDepthBits = 0;
         pfd.iLayerType = PFD_MAIN_PLANE;
 
         mWindowPixelFormat = ChoosePixelFormat(dc, &pfd);
     }
 
     if (!mWindowPixelFormat ||
-        !SetPixelFormat(dc, mWindowPixelFormat, NULL))
+        !SetPixelFormat(dc, mWindowPixelFormat, nullptr))
     {
         NS_WARNING("SetPixelFormat failed!");
         DestroyWindow(win);
-        return NULL;
+        return nullptr;
     }
 
     if (aWindowDC) {
         *aWindowDC = dc;
     }
 
     return win;
 }
@@ -121,24 +122,24 @@ WGLLibrary::EnsureInitialized(bool aUseM
             NS_WARNING("Couldn't load OpenGL library.");
             return false;
         }
     }
 
     mUseDoubleBufferedWindows = PR_GetEnv("MOZ_WGL_DB") != nullptr;
 
     GLLibraryLoader::SymLoadStruct earlySymbols[] = {
-        { (PRFuncPtr*) &fCreateContext, { "wglCreateContext", NULL } },
-        { (PRFuncPtr*) &fMakeCurrent, { "wglMakeCurrent", NULL } },
-        { (PRFuncPtr*) &fGetProcAddress, { "wglGetProcAddress", NULL } },
-        { (PRFuncPtr*) &fDeleteContext, { "wglDeleteContext", NULL } },
-        { (PRFuncPtr*) &fGetCurrentContext, { "wglGetCurrentContext", NULL } },
-        { (PRFuncPtr*) &fGetCurrentDC, { "wglGetCurrentDC", NULL } },
-        { (PRFuncPtr*) &fShareLists, { "wglShareLists", NULL } },
-        { NULL, { NULL } }
+        { (PRFuncPtr*) &fCreateContext, { "wglCreateContext", nullptr } },
+        { (PRFuncPtr*) &fMakeCurrent, { "wglMakeCurrent", nullptr } },
+        { (PRFuncPtr*) &fGetProcAddress, { "wglGetProcAddress", nullptr } },
+        { (PRFuncPtr*) &fDeleteContext, { "wglDeleteContext", nullptr } },
+        { (PRFuncPtr*) &fGetCurrentContext, { "wglGetCurrentContext", nullptr } },
+        { (PRFuncPtr*) &fGetCurrentDC, { "wglGetCurrentDC", nullptr } },
+        { (PRFuncPtr*) &fShareLists, { "wglShareLists", nullptr } },
+        { nullptr, { nullptr } }
     };
 
     if (!GLLibraryLoader::LoadSymbols(mOGLLibrary, &earlySymbols[0])) {
         NS_WARNING("Couldn't find required entry points in OpenGL DLL (early init)");
         return false;
     }
 
     // This is ridiculous -- we have to actually create a context to
@@ -157,28 +158,28 @@ WGLLibrary::EnsureInitialized(bool aUseM
         NS_WARNING("wglMakeCurrent failed");
         return false;
     }
 
     // Now we can grab all the other symbols that we couldn't without having
     // a context current.
 
     GLLibraryLoader::SymLoadStruct pbufferSymbols[] = {
-        { (PRFuncPtr*) &fCreatePbuffer, { "wglCreatePbufferARB", "wglCreatePbufferEXT", NULL } },
-        { (PRFuncPtr*) &fDestroyPbuffer, { "wglDestroyPbufferARB", "wglDestroyPbufferEXT", NULL } },
-        { (PRFuncPtr*) &fGetPbufferDC, { "wglGetPbufferDCARB", "wglGetPbufferDCEXT", NULL } },
-        { (PRFuncPtr*) &fBindTexImage, { "wglBindTexImageARB", "wglBindTexImageEXT", NULL } },
-        { (PRFuncPtr*) &fReleaseTexImage, { "wglReleaseTexImageARB", "wglReleaseTexImageEXT", NULL } },
-        { NULL, { NULL } }
+        { (PRFuncPtr*) &fCreatePbuffer, { "wglCreatePbufferARB", "wglCreatePbufferEXT", nullptr } },
+        { (PRFuncPtr*) &fDestroyPbuffer, { "wglDestroyPbufferARB", "wglDestroyPbufferEXT", nullptr } },
+        { (PRFuncPtr*) &fGetPbufferDC, { "wglGetPbufferDCARB", "wglGetPbufferDCEXT", nullptr } },
+        { (PRFuncPtr*) &fBindTexImage, { "wglBindTexImageARB", "wglBindTexImageEXT", nullptr } },
+        { (PRFuncPtr*) &fReleaseTexImage, { "wglReleaseTexImageARB", "wglReleaseTexImageEXT", nullptr } },
+        { nullptr, { nullptr } }
     };
 
     GLLibraryLoader::SymLoadStruct pixFmtSymbols[] = {
-        { (PRFuncPtr*) &fChoosePixelFormat, { "wglChoosePixelFormatARB", "wglChoosePixelFormatEXT", NULL } },
-        { (PRFuncPtr*) &fGetPixelFormatAttribiv, { "wglGetPixelFormatAttribivARB", "wglGetPixelFormatAttribivEXT", NULL } },
-        { NULL, { NULL } }
+        { (PRFuncPtr*) &fChoosePixelFormat, { "wglChoosePixelFormatARB", "wglChoosePixelFormatEXT", nullptr } },
+        { (PRFuncPtr*) &fGetPixelFormatAttribiv, { "wglGetPixelFormatAttribivARB", "wglGetPixelFormatAttribivEXT", nullptr } },
+        { nullptr, { nullptr } }
     };
 
     if (!GLLibraryLoader::LoadSymbols(mOGLLibrary, &pbufferSymbols[0],
          (GLLibraryLoader::PlatformLookupFunction)fGetProcAddress))
     {
         // this isn't an error, just means that pbuffers aren't supported
         fCreatePbuffer = nullptr;
     }
@@ -186,23 +187,23 @@ WGLLibrary::EnsureInitialized(bool aUseM
     if (!GLLibraryLoader::LoadSymbols(mOGLLibrary, &pixFmtSymbols[0],
          (GLLibraryLoader::PlatformLookupFunction)fGetProcAddress))
     {
         // this isn't an error, just means that we don't have the pixel format extension
         fChoosePixelFormat = nullptr;
     }
 
     GLLibraryLoader::SymLoadStruct extensionsSymbols[] = {
-        { (PRFuncPtr *) &fGetExtensionsString, { "wglGetExtensionsStringARB", NULL} },
-        { NULL, { NULL } }
+        { (PRFuncPtr *) &fGetExtensionsString, { "wglGetExtensionsStringARB", nullptr} },
+        { nullptr, { nullptr } }
     };
 
     GLLibraryLoader::SymLoadStruct robustnessSymbols[] = {
-        { (PRFuncPtr *) &fCreateContextAttribs, { "wglCreateContextAttribsARB", NULL} },
-        { NULL, { NULL } }
+        { (PRFuncPtr *) &fCreateContextAttribs, { "wglCreateContextAttribsARB", nullptr} },
+        { nullptr, { nullptr } }
     };
 
     if (GLLibraryLoader::LoadSymbols(mOGLLibrary, &extensionsSymbols[0],
         (GLLibraryLoader::PlatformLookupFunction)fGetProcAddress)) {
         const char *wglExts = fGetExtensionsString(mWindowDC);
         if (wglExts && HasExtension(wglExts, "WGL_ARB_create_context")) {
             GLLibraryLoader::LoadSymbols(mOGLLibrary, &robustnessSymbols[0],
             (GLLibraryLoader::PlatformLookupFunction)fGetProcAddress);
@@ -219,17 +220,17 @@ WGLLibrary::EnsureInitialized(bool aUseM
         fDeleteContext(mWindowGLContext);
 
         int attribs[] = {
             LOCAL_WGL_CONTEXT_FLAGS_ARB, LOCAL_WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB,
             LOCAL_WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB, LOCAL_WGL_LOSE_CONTEXT_ON_RESET_ARB,
             0
         };
 
-        mWindowGLContext = fCreateContextAttribs(mWindowDC, NULL, attribs);
+        mWindowGLContext = fCreateContextAttribs(mWindowDC, nullptr, attribs);
         if (!mWindowGLContext) {
             mHasRobustness = false;
             mWindowGLContext = fCreateContext(mWindowDC);
         }
     }
 
     mInitialized = true;
 
@@ -261,17 +262,17 @@ public:
                  HDC aDC,
                  HGLRC aContext,
                  LibType aLibUsed,
                  HWND aWindow = nullptr)
         : GLContext(caps, sharedContext, isOffscreen),
           mDC(aDC),
           mContext(aContext),
           mWnd(aWindow),
-          mPBuffer(NULL),
+          mPBuffer(nullptr),
           mPixelFormat(0),
           mLibType(aLibUsed),
           mIsDoubleBuffered(false)
     {
     }
 
     // From PBuffer
     GLContextWGL(const SurfaceCaps& caps,
@@ -280,17 +281,17 @@ public:
                  HANDLE aPbuffer,
                  HDC aDC,
                  HGLRC aContext,
                  int aPixelFormat,
                  LibType aLibUsed)
         : GLContext(caps, sharedContext, isOffscreen),
           mDC(aDC),
           mContext(aContext),
-          mWnd(NULL),
+          mWnd(nullptr),
           mPBuffer(aPbuffer),
           mPixelFormat(aPixelFormat),
           mLibType(aLibUsed),
           mIsDoubleBuffered(false)
     {
     }
 
     ~GLContextWGL()
@@ -451,17 +452,17 @@ GLContextProviderWGL::CreateForWindow(ns
     /**
        * We need to make sure we call SetPixelFormat -after- calling 
        * EnsureInitialized, otherwise it can load/unload the dll and 
        * wglCreateContext will fail.
        */
 
     HDC dc = (HDC)aWidget->GetNativeData(NS_NATIVE_GRAPHIC);
 
-    SetPixelFormat(dc, sWGLLib[libToUse].GetWindowPixelFormat(), NULL);
+    SetPixelFormat(dc, sWGLLib[libToUse].GetWindowPixelFormat(), nullptr);
     HGLRC context;
 
     GLContextWGL *shareContext = GetGlobalContextWGL();
 
     if (sWGLLib[libToUse].HasRobustness()) {
         int attribs[] = {
             LOCAL_WGL_CONTEXT_FLAGS_ARB, LOCAL_WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB,
             LOCAL_WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB, LOCAL_WGL_LOSE_CONTEXT_ON_RESET_ARB,
@@ -540,17 +541,17 @@ CreatePBufferOffscreenContext(const gfxI
 #undef A1
 #undef A2
 
     // We only need one!
     UINT numFormats = 1;
     int formats[1];
     HDC windowDC = wgl.GetWindowDC();
     if (!wgl.fChoosePixelFormat(windowDC,
-                                attrs.Elements(), NULL,
+                                attrs.Elements(), nullptr,
                                 numFormats, formats, &numFormats)
         || numFormats == 0)
     {
         return nullptr;
     }
 
     // We don't care; just pick the first one.
     int chosenFormat = formats[0];
--- a/gfx/gl/GLLibraryEGL.cpp
+++ b/gfx/gl/GLLibraryEGL.cpp
@@ -27,17 +27,17 @@ static const char *sExtensionNames[] = {
     "EGL_KHR_fence_sync",
     nullptr
 };
 
 #if defined(ANDROID)
 
 static PRLibrary* LoadApitraceLibrary()
 {
-    static PRLibrary* sApitraceLibrary = NULL;
+    static PRLibrary* sApitraceLibrary = nullptr;
 
     if (sApitraceLibrary)
         return sApitraceLibrary;
 
     nsCString logFile = Preferences::GetCString("gfx.apitrace.logfile");
 
     if (logFile.IsEmpty()) {
         logFile = "firefox.trace";
@@ -140,17 +140,17 @@ GLLibraryEGL::EnsureInitialized()
     if (!mEGLLibrary) {
         NS_WARNING("Couldn't load EGL LIB.");
         return false;
     }
 
 #endif // !Windows
 
 #define SYMBOL(name) \
-{ (PRFuncPtr*) &mSymbols.f##name, { "egl" #name, NULL } }
+{ (PRFuncPtr*) &mSymbols.f##name, { "egl" #name, nullptr } }
 
     GLLibraryLoader::SymLoadStruct earlySymbols[] = {
         SYMBOL(GetDisplay),
         SYMBOL(GetCurrentSurface),
         SYMBOL(GetCurrentContext),
         SYMBOL(MakeCurrent),
         SYMBOL(DestroyContext),
         SYMBOL(CreateContext),
@@ -168,26 +168,26 @@ GLLibraryEGL::EnsureInitialized()
         SYMBOL(GetProcAddress),
         SYMBOL(SwapBuffers),
         SYMBOL(CopyBuffers),
         SYMBOL(QueryString),
         SYMBOL(QueryContext),
         SYMBOL(BindTexImage),
         SYMBOL(ReleaseTexImage),
         SYMBOL(QuerySurface),
-        { NULL, { NULL } }
+        { nullptr, { nullptr } }
     };
 
     if (!GLLibraryLoader::LoadSymbols(mEGLLibrary, &earlySymbols[0])) {
         NS_WARNING("Couldn't find required entry points in EGL library (early init)");
         return false;
     }
 
     mEGLDisplay = fGetDisplay(EGL_DEFAULT_DISPLAY);
-    if (!fInitialize(mEGLDisplay, NULL, NULL))
+    if (!fInitialize(mEGLDisplay, nullptr, nullptr))
         return false;
 
     const char *vendor = (const char*) fQueryString(mEGLDisplay, LOCAL_EGL_VENDOR);
     if (vendor && (strstr(vendor, "TransGaming") != 0 || strstr(vendor, "Google Inc.") != 0)) {
         mIsANGLE = true;
     }
     
     InitExtensions();
@@ -367,17 +367,17 @@ GLLibraryEGL::DumpEGLConfig(EGLConfig cf
 
 #undef ATTR
 }
 
 void
 GLLibraryEGL::DumpEGLConfigs()
 {
     int nc = 0;
-    fGetConfigs(mEGLDisplay, NULL, 0, &nc);
+    fGetConfigs(mEGLDisplay, nullptr, 0, &nc);
     EGLConfig *ec = new EGLConfig[nc];
     fGetConfigs(mEGLDisplay, ec, nc, &nc);
 
     for (int i = 0; i < nc; ++i) {
         printf_stderr ("========= EGL Config %d ========\n", i);
         DumpEGLConfig(ec[i]);
     }
 
--- a/gfx/gl/GLTextureImage.cpp
+++ b/gfx/gl/GLTextureImage.cpp
@@ -51,28 +51,28 @@ BasicTextureImage::BeginUpdate(nsIntRegi
         aRegion = nsIntRect(nsIntPoint(0, 0), mSize);
     }
 
     mUpdateRegion = aRegion;
 
     nsIntRect rgnSize = mUpdateRegion.GetBounds();
     if (!nsIntRect(nsIntPoint(0, 0), mSize).Contains(rgnSize)) {
         NS_ERROR("update outside of image");
-        return NULL;
+        return nullptr;
     }
 
     ImageFormat format =
         (GetContentType() == gfxASurface::CONTENT_COLOR) ?
         gfxASurface::ImageFormatRGB24 : gfxASurface::ImageFormatARGB32;
     mUpdateSurface =
         GetSurfaceForUpdate(gfxIntSize(rgnSize.width, rgnSize.height), format);
 
     if (!mUpdateSurface || mUpdateSurface->CairoStatus()) {
-        mUpdateSurface = NULL;
-        return NULL;
+        mUpdateSurface = nullptr;
+        return nullptr;
     }
 
     mUpdateSurface->SetDeviceOffset(gfxPoint(-rgnSize.x, -rgnSize.y));
 
     return mUpdateSurface;
 }
 
 void
@@ -177,17 +177,17 @@ BasicTextureImage::Resize(const nsIntSiz
     mGLContext->fTexImage2D(LOCAL_GL_TEXTURE_2D,
                             0,
                             LOCAL_GL_RGBA,
                             aSize.width,
                             aSize.height,
                             0,
                             LOCAL_GL_RGBA,
                             LOCAL_GL_UNSIGNED_BYTE,
-                            NULL);
+                            nullptr);
 
     mTextureState = Allocated;
     mSize = aSize;
 }
 
 TiledTextureImage::TiledTextureImage(GLContext* aGL,
                                      nsIntSize aSize,
                                      TextureImage::ContentType aContentType,
--- a/gfx/gl/GLTextureImage.h
+++ b/gfx/gl/GLTextureImage.h
@@ -61,20 +61,20 @@ public:
                        TextureImage::ContentType aContentType,
                        GLenum aWrapMode,
                        TextureImage::Flags aFlags = TextureImage::NoFlags);
 
     virtual ~TextureImage() {}
 
     /**
      * Returns a gfxASurface for updating |aRegion| of the client's
-     * image if successul, NULL if not.  |aRegion|'s bounds must fit
+     * image if successul, nullptr if not.  |aRegion|'s bounds must fit
      * within Size(); its coordinate space (if any) is ignored.  If
      * the update begins successfully, the returned gfxASurface is
-     * owned by this.  Otherwise, NULL is returned.
+     * owned by this.  Otherwise, nullptr is returned.
      *
      * |aRegion| is an inout param: the returned region is what the
      * client must repaint.  Category (1) regions above can
      * efficiently handle repaints to "scattered" regions, while (2)
      * can only efficiently handle repaints to rects.
      *
      * Painting the returned surface outside of |aRegion| results
      * in undefined behavior.
--- a/gfx/ipc/SharedDIBSurface.cpp
+++ b/gfx/ipc/SharedDIBSurface.cpp
@@ -45,17 +45,17 @@ SharedDIBSurface::InitSurface(uint32_t a
   long stride = long(aWidth * kBytesPerPixel);
   unsigned char* data = reinterpret_cast<unsigned char*>(mSharedDIB.GetBits());
 
   gfxImageFormat format = aTransparent ? ImageFormatARGB32 : ImageFormatRGB24;
 
   gfxImageSurface::InitWithData(data, gfxIntSize(aWidth, aHeight),
                                 stride, format);
 
-  cairo_surface_set_user_data(mSurface, &SHAREDDIB_KEY, this, NULL);
+  cairo_surface_set_user_data(mSurface, &SHAREDDIB_KEY, this, nullptr);
 }
 
 bool
 SharedDIBSurface::IsSharedDIBSurface(gfxASurface* aSurface)
 {
   return aSurface &&
     aSurface->GetType() == gfxASurface::SurfaceTypeImage &&
     aSurface->GetData(&SHAREDDIB_KEY);
--- a/gfx/ipc/SharedDIBWin.cpp
+++ b/gfx/ipc/SharedDIBWin.cpp
@@ -35,18 +35,18 @@ SharedDIBWin::Close()
     ::SelectObject(mSharedHdc, mOldObj);
 
   if (mSharedHdc)
     ::DeleteObject(mSharedHdc);
 
   if (mSharedBmp)
     ::DeleteObject(mSharedBmp);
 
-  mSharedHdc = NULL;
-  mOldObj = mSharedBmp = NULL;
+  mSharedHdc = nullptr;
+  mOldObj = mSharedBmp = nullptr;
 
   SharedDIB::Close();
 
   return NS_OK;
 }
 
 nsresult
 SharedDIBWin::Create(HDC aHdc, uint32_t aWidth, uint32_t aHeight,
@@ -78,17 +78,17 @@ SharedDIBWin::Attach(Handle aHandle, uin
 
   BITMAPV4HEADER bmih;
   SetupBitmapHeader(aWidth, aHeight, aTransparent, &bmih);
 
   nsresult rv = SharedDIB::Attach(aHandle, 0);
   if (NS_FAILED(rv))
     return rv;
 
-  if (NS_FAILED(SetupSurface(NULL, &bmih))) {
+  if (NS_FAILED(SetupSurface(nullptr, &bmih))) {
     Close();
     return NS_ERROR_FAILURE;
   }
 
   return NS_OK;
 }
 
 uint32_t
--- a/gfx/layers/D3D9SurfaceImage.cpp
+++ b/gfx/layers/D3D9SurfaceImage.cpp
@@ -34,17 +34,17 @@ D3D9SurfaceImage::SetData(const Data& aD
                                          D3DFMT_X8R8G8B8);
   NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
 
   // DXVA surfaces aren't created sharable, so we need to copy the surface
   // to a sharable texture to that it's accessible to the layer manager's
   // device.
   const nsIntRect& region = aData.mRegion;
   RefPtr<IDirect3DTexture9> texture;
-  HANDLE shareHandle = NULL;
+  HANDLE shareHandle = nullptr;
   hr = device->CreateTexture(region.width,
                              region.height,
                              1,
                              D3DUSAGE_RENDERTARGET,
                              D3DFMT_X8R8G8B8,
                              D3DPOOL_DEFAULT,
                              byRef(texture),
                              &shareHandle);
@@ -54,17 +54,17 @@ D3D9SurfaceImage::SetData(const Data& aD
   RefPtr<IDirect3DSurface9> textureSurface;
   hr = texture->GetSurfaceLevel(0, byRef(textureSurface));
   NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
 
   // Stash the surface description for later use.
   textureSurface->GetDesc(&mDesc);
 
   RECT src = { region.x, region.y, region.x+region.width, region.y+region.height };
-  hr = device->StretchRect(surface, &src, textureSurface, NULL, D3DTEXF_NONE);
+  hr = device->StretchRect(surface, &src, textureSurface, nullptr, D3DTEXF_NONE);
   NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
 
   // Flush the draw command now, so that by the time we come to draw this
   // image, we're less likely to need to wait for the draw operation to
   // complete.
   RefPtr<IDirect3DQuery9> query;
   hr = device->CreateQuery(D3DQUERYTYPE_EVENT, byRef(query));
   NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
@@ -82,17 +82,17 @@ D3D9SurfaceImage::SetData(const Data& aD
 void
 D3D9SurfaceImage::EnsureSynchronized()
 {
   if (!mQuery) {
     // Not setup, or already synchronized.
     return;
   }
   int iterations = 0;
-  while (iterations < 10 && S_FALSE == mQuery->GetData(NULL, 0, D3DGETDATA_FLUSH)) {
+  while (iterations < 10 && S_FALSE == mQuery->GetData(nullptr, 0, D3DGETDATA_FLUSH)) {
     Sleep(1);
     iterations++;
   }
   mQuery = nullptr;
 }
 
 HANDLE
 D3D9SurfaceImage::GetShareHandle()
@@ -150,17 +150,17 @@ D3D9SurfaceImage::GetAsSurface()
                                            byRef(systemMemorySurface),
                                            0);
   NS_ENSURE_TRUE(SUCCEEDED(hr), nullptr);
 
   hr = device->GetRenderTargetData(textureSurface, systemMemorySurface);
   NS_ENSURE_TRUE(SUCCEEDED(hr), nullptr);
 
   D3DLOCKED_RECT rect;
-  hr = systemMemorySurface->LockRect(&rect, NULL, 0);
+  hr = systemMemorySurface->LockRect(&rect, nullptr, 0);
   NS_ENSURE_TRUE(SUCCEEDED(hr), nullptr);
 
   const unsigned char* src = (const unsigned char*)(rect.pBits);
   const unsigned srcPitch = rect.Pitch;
   for (int y = 0; y < mSize.height; y++) {
     memcpy(surface->Data() + surface->Stride() * y,
            (unsigned char*)(src) + srcPitch * y,
            mSize.width * 4);
--- a/gfx/layers/D3D9SurfaceImage.h
+++ b/gfx/layers/D3D9SurfaceImage.h
@@ -23,17 +23,17 @@ public:
 
   struct Data {
     Data(IDirect3DSurface9* aSurface, const nsIntRect& aRegion)
       : mSurface(aSurface), mRegion(aRegion) {}
     RefPtr<IDirect3DSurface9> mSurface;
     nsIntRect mRegion;
   };
 
-  D3D9SurfaceImage() : Image(NULL, D3D9_RGB32_TEXTURE), mSize(0, 0) {}
+  D3D9SurfaceImage() : Image(nullptr, D3D9_RGB32_TEXTURE), mSize(0, 0) {}
   virtual ~D3D9SurfaceImage() {}
 
   // Copies the surface into a sharable texture's surface, and initializes
   // the image.
   HRESULT SetData(const Data& aData);
 
   // Returns the description of the shared surface.
   const D3DSURFACE_DESC& GetDesc() const;
--- a/gfx/layers/GonkIOSurfaceImage.h
+++ b/gfx/layers/GonkIOSurfaceImage.h
@@ -50,17 +50,17 @@ class GonkIOSurfaceImage : public Image 
   typedef android::GraphicBuffer GraphicBuffer;
   static uint32_t sColorIdMap[];
 public:
   struct Data {
     nsRefPtr<GraphicBufferLocked> mGraphicBuffer;
     gfxIntSize mPicSize;
   };
   GonkIOSurfaceImage()
-    : Image(NULL, GONK_IO_SURFACE)
+    : Image(nullptr, GONK_IO_SURFACE)
     , mSize(0, 0)
     {}
 
   virtual ~GonkIOSurfaceImage()
   {
     mGraphicBuffer->Unlock();
   }
 
--- a/gfx/layers/ImageContainer.h
+++ b/gfx/layers/ImageContainer.h
@@ -533,17 +533,17 @@ protected:
   // this container can set an alternative image factory that will be used to
   // create images for this container.
   nsRefPtr<ImageFactory> mImageFactory;
 
   gfxIntSize mScaleHint;
 
   nsRefPtr<BufferRecycleBin> mRecycleBin;
 
-  // This contains the remote image data for this container, if this is NULL
+  // This contains the remote image data for this container, if this is nullptr
   // that means the container has no other process that may control its active
   // image.
   RemoteImageData *mRemoteData;
 
   // This cross-process mutex is used to synchronise access to mRemoteData.
   // When this mutex is held, we will always be inside the mReentrantMonitor
   // however the same is not true vice versa.
   CrossProcessMutex *mRemoteDataMutex;
@@ -777,25 +777,25 @@ public:
   {
     NS_ASSERTION(NS_IsMainThread(), "Must be main thread");
     nsRefPtr<gfxASurface> surface = mSurface.get();
     return surface.forget();
   }
 
   gfxIntSize GetSize() { return mSize; }
 
-  CairoImage() : Image(NULL, CAIRO_SURFACE) {}
+  CairoImage() : Image(nullptr, CAIRO_SURFACE) {}
 
   nsCountedRef<nsMainThreadSurfaceRef> mSurface;
   gfxIntSize mSize;
 };
 
 class RemoteBitmapImage : public Image {
 public:
-  RemoteBitmapImage() : Image(NULL, REMOTE_IMAGE_BITMAP) {}
+  RemoteBitmapImage() : Image(nullptr, REMOTE_IMAGE_BITMAP) {}
 
   already_AddRefed<gfxASurface> GetAsSurface();
 
   gfxIntSize GetSize() { return mSize; }
 
   unsigned char *mData;
   int mStride;
   gfxIntSize mSize;
--- a/gfx/layers/Layers.cpp
+++ b/gfx/layers/Layers.cpp
@@ -1137,17 +1137,17 @@ Layer::PrintInfo(nsACString& aTo, const 
   }
   if (GetContentFlags() & CONTENT_OPAQUE) {
     aTo += " [opaqueContent]";
   }
   if (GetContentFlags() & CONTENT_COMPONENT_ALPHA) {
     aTo += " [componentAlpha]";
   }
   if (GetIsFixedPosition()) {
-    aTo += " [isFixedPosition]";
+    aTo.AppendPrintf(" [isFixedPosition anchor=%f,%f]", mAnchor.x, mAnchor.y);
   }
 
   return aTo;
 }
 
 nsACString&
 ThebesLayer::PrintInfo(nsACString& aTo, const char* aPrefix)
 {
--- a/gfx/layers/Layers.h
+++ b/gfx/layers/Layers.h
@@ -486,22 +486,22 @@ public:
   // ifndef MOZ_LAYERS_HAVE_LOG builds, they only have trivial
   // definitions in Layers.cpp.
   virtual const char* Name() const { return "???"; }
 
   /**
    * Dump information about this layer manager and its managed tree to
    * aFile, which defaults to stderr.
    */
-  void Dump(FILE* aFile=NULL, const char* aPrefix="", bool aDumpHtml=false);
+  void Dump(FILE* aFile=nullptr, const char* aPrefix="", bool aDumpHtml=false);
   /**
    * Dump information about just this layer manager itself to aFile,
    * which defaults to stderr.
    */
-  void DumpSelf(FILE* aFile=NULL, const char* aPrefix="");
+  void DumpSelf(FILE* aFile=nullptr, const char* aPrefix="");
 
   /**
    * Log information about this layer manager and its managed tree to
    * the NSPR log (if enabled for "Layers").
    */
   void Log(const char* aPrefix="");
   /**
    * Log information about just this layer manager itself to the NSPR
@@ -854,17 +854,17 @@ public:
 
   /**
    * CONSTRUCTION PHASE ONLY
    * If a layer is "fixed position", this determines which point on the layer
    * is considered the "anchor" point, that is, the point which remains in the
    * same position when compositing the layer tree with a transformation
    * (such as when asynchronously scrolling and zooming).
    */
-  void SetFixedPositionAnchor(const gfxPoint& aAnchor)
+  void SetFixedPositionAnchor(const LayerPoint& aAnchor)
   {
     if (mAnchor != aAnchor) {
       MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) FixedPositionAnchor", this));
       mAnchor = aAnchor;
       Mutated();
     }
   }
 
@@ -874,17 +874,17 @@ public:
    * a document that has had fixed position element margins set on it, these
    * will be mirrored here. This allows for asynchronous animation of the
    * margins by reconciling the difference between this value and a value that
    * is updated more frequently.
    * If the left or top margins are negative, it means that the elements this
    * layer represents are auto-positioned, and so fixed position margins should
    * not have an effect on the corresponding axis.
    */
-  void SetFixedPositionMargins(const gfx::Margin& aMargins)
+  void SetFixedPositionMargins(const LayerMargin& aMargins)
   {
     if (mMargins != aMargins) {
       MOZ_LAYERS_LOG_IF_SHADOWABLE(this, ("Layer::Mutated(%p) FixedPositionMargins", this));
       mMargins = aMargins;
       Mutated();
     }
   }
 
@@ -900,18 +900,18 @@ public:
   const Layer* GetPrevSibling() const { return mPrevSibling; }
   virtual Layer* GetFirstChild() const { return nullptr; }
   virtual Layer* GetLastChild() const { return nullptr; }
   const gfx3DMatrix GetTransform() const;
   const gfx3DMatrix& GetBaseTransform() const { return mTransform; }
   float GetPostXScale() const { return mPostXScale; }
   float GetPostYScale() const { return mPostYScale; }
   bool GetIsFixedPosition() { return mIsFixedPosition; }
-  gfxPoint GetFixedPositionAnchor() { return mAnchor; }
-  const gfx::Margin& GetFixedPositionMargins() { return mMargins; }
+  LayerPoint GetFixedPositionAnchor() { return mAnchor; }
+  const LayerMargin& GetFixedPositionMargins() { return mMargins; }
   Layer* GetMaskLayer() const { return mMaskLayer; }
 
   // Note that all lengths in animation data are either in CSS pixels or app
   // units and must be converted to device pixels by the compositor.
   AnimationArray& GetAnimations() { return mAnimations; }
   InfallibleTArray<AnimData>& GetAnimationData() { return mAnimationData; }
 
   uint64_t GetAnimationGeneration() { return mAnimationGeneration; }
@@ -1113,22 +1113,22 @@ public:
   void SetParent(ContainerLayer* aParent) { mParent = aParent; }
   void SetNextSibling(Layer* aSibling) { mNextSibling = aSibling; }
   void SetPrevSibling(Layer* aSibling) { mPrevSibling = aSibling; }
 
   /**
    * Dump information about this layer manager and its managed tree to
    * aFile, which defaults to stderr.
    */
-  void Dump(FILE* aFile=NULL, const char* aPrefix="", bool aDumpHtml=false);
+  void Dump(FILE* aFile=nullptr, const char* aPrefix="", bool aDumpHtml=false);
   /**
    * Dump information about just this layer manager itself to aFile,
    * which defaults to stderr.
    */
-  void DumpSelf(FILE* aFile=NULL, const char* aPrefix="");
+  void DumpSelf(FILE* aFile=nullptr, const char* aPrefix="");
 
   /**
    * Log information about this layer manager and its managed tree to
    * the NSPR log (if enabled for "Layers").
    */
   void Log(const char* aPrefix="");
   /**
    * Log information about just this layer manager itself to the NSPR
@@ -1255,18 +1255,18 @@ protected:
   float mOpacity;
   nsIntRect mClipRect;
   nsIntRect mTileSourceRect;
   nsIntRegion mInvalidRegion;
   uint32_t mContentFlags;
   bool mUseClipRect;
   bool mUseTileSourceRect;
   bool mIsFixedPosition;
-  gfxPoint mAnchor;
-  gfx::Margin mMargins;
+  LayerPoint mAnchor;
+  LayerMargin mMargins;
   DebugOnly<uint32_t> mDebugColorIndex;
   // If this layer is used for OMTA, then this counter is used to ensure we
   // stay in sync with the animation manager
   uint64_t mAnimationGeneration;
 };
 
 /**
  * A Layer which we can draw into using Thebes. It is a conceptually
--- a/gfx/layers/RenderTrace.cpp
+++ b/gfx/layers/RenderTrace.cpp
@@ -13,17 +13,17 @@
 namespace mozilla {
 namespace layers {
 
 static int colorId = 0;
 
 static gfx3DMatrix GetRootTransform(Layer *aLayer) {
   gfx3DMatrix layerTrans = aLayer->GetTransform();
   layerTrans.ProjectTo2D();
-  if (aLayer->GetParent() != NULL) {
+  if (aLayer->GetParent() != nullptr) {
     return GetRootTransform(aLayer->GetParent()) * layerTrans;
   }
   return layerTrans;
 }
 
 void RenderTraceLayers(Layer *aLayer, const char *aColor, const gfx3DMatrix aRootTransform, bool aReset) {
   if (!aLayer)
     return;
--- a/gfx/layers/SharedTextureImage.h
+++ b/gfx/layers/SharedTextureImage.h
@@ -30,17 +30,17 @@ public:
   const Data* GetData() { return &mData; }
 
   gfxIntSize GetSize() { return mData.mSize; }
 
   virtual already_AddRefed<gfxASurface> GetAsSurface() { 
     return gl::GLContextProvider::GetSharedHandleAsSurface(mData.mShareType, mData.mHandle);
   }
 
-  SharedTextureImage() : Image(NULL, SHARED_TEXTURE) {}
+  SharedTextureImage() : Image(nullptr, SHARED_TEXTURE) {}
 
 private:
   Data mData;
 };
 
 } // layers
 } // mozilla
 
--- a/gfx/layers/composite/AsyncCompositionManager.cpp
+++ b/gfx/layers/composite/AsyncCompositionManager.cpp
@@ -104,104 +104,193 @@ AsyncCompositionManager::ComputeRotation
 {
   if (!mTargetConfig.naturalBounds().IsEmpty()) {
     mLayerManager->SetWorldTransform(
       ComputeTransformForRotation(mTargetConfig.naturalBounds(),
                                   mTargetConfig.rotation()));
   }
 }
 
-// Do a breadth-first search to find the first layer in the tree that is
-// scrollable.
+static bool
+GetBaseTransform2D(Layer* aLayer, gfxMatrix* aTransform)
+{
+  // Start with the animated transform if there is one
+  return (aLayer->AsLayerComposite()->GetShadowTransformSetByAnimation() ?
+          aLayer->GetLocalTransform() : aLayer->GetTransform()).Is2D(aTransform);
+}
+
 static void
-Translate2D(gfx3DMatrix& aTransform, const gfxPoint& aOffset)
+TranslateShadowLayer2D(Layer* aLayer,
+                       const gfxPoint& aTranslation)
 {
-  aTransform._41 += aOffset.x;
-  aTransform._42 += aOffset.y;
+  gfxMatrix layerTransform;
+  if (!GetBaseTransform2D(aLayer, &layerTransform)) {
+    return;
+  }
+
+  // Apply the 2D translation to the layer transform.
+  layerTransform.x0 += aTranslation.x;
+  layerTransform.y0 += aTranslation.y;
+
+  // The transform already takes the resolution scale into account.  Since we
+  // will apply the resolution scale again when computing the effective
+  // transform, we must apply the inverse resolution scale here.
+  gfx3DMatrix layerTransform3D = gfx3DMatrix::From2D(layerTransform);
+  if (ContainerLayer* c = aLayer->AsContainerLayer()) {
+    layerTransform3D.Scale(1.0f/c->GetPreXScale(),
+                           1.0f/c->GetPreYScale(),
+                           1);
+  }
+  layerTransform3D.ScalePost(1.0f/aLayer->GetPostXScale(),
+                             1.0f/aLayer->GetPostYScale(),
+                             1);
+
+  LayerComposite* layerComposite = aLayer->AsLayerComposite();
+  layerComposite->SetShadowTransform(layerTransform3D);
+  layerComposite->SetShadowTransformSetByAnimation(false);
+
+  const nsIntRect* clipRect = aLayer->GetClipRect();
+  if (clipRect) {
+    nsIntRect transformedClipRect(*clipRect);
+    transformedClipRect.MoveBy(aTranslation.x, aTranslation.y);
+    layerComposite->SetShadowClipRect(&transformedClipRect);
+  }
+}
+
+static bool
+AccumulateLayerTransforms2D(Layer* aLayer,
+                            Layer* aAncestor,
+                            gfxMatrix& aMatrix)
+{
+  // Accumulate the transforms between this layer and the subtree root layer.
+  for (Layer* l = aLayer; l && l != aAncestor; l = l->GetParent()) {
+    gfxMatrix l2D;
+    if (!GetBaseTransform2D(l, &l2D)) {
+      return false;
+    }
+    aMatrix.Multiply(l2D);
+  }
+
+  return true;
+}
+
+static LayerPoint
+GetLayerFixedMarginsOffset(Layer* aLayer,
+                           const LayerMargin& aFixedLayerMargins)
+{
+  // Work out the necessary translation, in root scrollable layer space.
+  // Because fixed layer margins are stored relative to the root scrollable
+  // layer, we can just take the difference between these values.
+  LayerPoint translation;
+  const LayerPoint& anchor = aLayer->GetFixedPositionAnchor();
+  const LayerMargin& fixedMargins = aLayer->GetFixedPositionMargins();
+
+  if (fixedMargins.left >= 0) {
+    if (anchor.x > 0) {
+      translation.x -= aFixedLayerMargins.right - fixedMargins.right;
+    } else {
+      translation.x += aFixedLayerMargins.left - fixedMargins.left;
+    }
+  }
+
+  if (fixedMargins.top >= 0) {
+    if (anchor.y > 0) {
+      translation.y -= aFixedLayerMargins.bottom - fixedMargins.bottom;
+    } else {
+      translation.y += aFixedLayerMargins.top - fixedMargins.top;
+    }
+  }
+
+  return translation;
 }
 
 void
-AsyncCompositionManager::TransformFixedLayers(Layer* aLayer,
-                                              const gfxPoint& aTranslation,
-                                              const gfxSize& aScaleDiff,
-                                              const gfx::Margin& aFixedLayerMargins)
+AsyncCompositionManager::AlignFixedLayersForAnchorPoint(Layer* aLayer,
+                                                        Layer* aTransformedSubtreeRoot,
+                                                        const gfx3DMatrix& aPreviousTransformForRoot,
+                                                        const LayerMargin& aFixedLayerMargins)
 {
-  if (aLayer->GetIsFixedPosition() &&
+  if (aLayer != aTransformedSubtreeRoot && aLayer->GetIsFixedPosition() &&
       !aLayer->GetParent()->GetIsFixedPosition()) {
-    // When a scale has been applied to a layer, it focuses around (0,0).
-    // The anchor position is used here as a scale focus point (assuming that
-    // aScaleDiff has already been applied) to re-focus the scale.
-    const gfxPoint& anchor = aLayer->GetFixedPositionAnchor();
-    gfxPoint translation(aTranslation - (anchor - anchor / aScaleDiff));
+    // Insert a translation so that the position of the anchor point is the same
+    // before and after the change to the transform of aTransformedSubtreeRoot.
+    // This currently only works for fixed layers with 2D transforms.
 
-    // Offset this translation by the fixed layer margins, depending on what
-    // side of the viewport the layer is anchored to, reconciling the
-    // difference between the current fixed layer margins and the Gecko-side
-    // fixed layer margins.
-    // aFixedLayerMargins are the margins we expect to be at at the current
-    // time, obtained via SyncViewportInfo, and fixedMargins are the margins
-    // that were used during layout.
-    // If top/left of fixedMargins are negative, that indicates that this layer
-    // represents auto-positioned elements, and should not be affected by
-    // fixed margins at all.
-    const gfx::Margin& fixedMargins = aLayer->GetFixedPositionMargins();
-    if (fixedMargins.left >= 0) {
-      if (anchor.x > 0) {
-        translation.x -= aFixedLayerMargins.right - fixedMargins.right;
-      } else {
-        translation.x += aFixedLayerMargins.left - fixedMargins.left;
-      }
+    // Accumulate the transforms between this layer and the subtree root layer.
+    gfxMatrix ancestorTransform;
+    if (!AccumulateLayerTransforms2D(aLayer->GetParent(), aTransformedSubtreeRoot,
+                                     ancestorTransform)) {
+      return;
+    }
+
+    gfxMatrix oldRootTransform;
+    gfxMatrix newRootTransform;
+    if (!aPreviousTransformForRoot.Is2D(&oldRootTransform) ||
+        !aTransformedSubtreeRoot->GetLocalTransform().Is2D(&newRootTransform)) {
+      return;
     }
 
-    if (fixedMargins.top >= 0) {
-      if (anchor.y > 0) {
-        translation.y -= aFixedLayerMargins.bottom - fixedMargins.bottom;
-      } else {
-        translation.y += aFixedLayerMargins.top - fixedMargins.top;
-      }
+    // Calculate the cumulative transforms between the subtree root with the
+    // old transform and the current transform.
+    gfxMatrix oldCumulativeTransform = ancestorTransform * oldRootTransform;
+    gfxMatrix newCumulativeTransform = ancestorTransform * newRootTransform;
+    if (newCumulativeTransform.IsSingular()) {
+      return;
+    }
+    gfxMatrix newCumulativeTransformInverse = newCumulativeTransform;
+    newCumulativeTransformInverse.Invert();
+
+    // Now work out the translation necessary to make sure the layer doesn't
+    // move given the new sub-tree root transform.
+    gfxMatrix layerTransform;
+    if (!GetBaseTransform2D(aLayer, &layerTransform)) {
+      return;
     }
 
-    // The transform already takes the resolution scale into account.  Since we
-    // will apply the resolution scale again when computing the effective
-    // transform, we must apply the inverse resolution scale here.
-    LayerComposite* layerComposite = aLayer->AsLayerComposite();
-    gfx3DMatrix layerTransform;
-    if (layerComposite->GetShadowTransformSetByAnimation()) {
-      // Start with the animated transform
-      layerTransform = aLayer->GetLocalTransform();
-    } else {
-      layerTransform = aLayer->GetTransform();
-    }
-    Translate2D(layerTransform, translation);
-    if (ContainerLayer* c = aLayer->AsContainerLayer()) {
-      layerTransform.Scale(1.0f/c->GetPreXScale(),
-                           1.0f/c->GetPreYScale(),
-                           1);
-    }
-    layerTransform.ScalePost(1.0f/aLayer->GetPostXScale(),
-                             1.0f/aLayer->GetPostYScale(),
-                             1);
-    layerComposite->SetShadowTransform(layerTransform);
-    layerComposite->SetShadowTransformSetByAnimation(false);
+    // Calculate any offset necessary, in previous transform sub-tree root
+    // space. This is used to make sure fixed position content respects
+    // content document fixed position margins.
+    LayerPoint offsetInOldSubtreeLayerSpace = GetLayerFixedMarginsOffset(aLayer, aFixedLayerMargins);
+
+    // Add the above offset to the anchor point so we can offset the layer by
+    // and amount that's specified in old subtree layer space.
+    const LayerPoint& anchorInOldSubtreeLayerSpace = aLayer->GetFixedPositionAnchor();
+    LayerPoint offsetAnchorInOldSubtreeLayerSpace = anchorInOldSubtreeLayerSpace + offsetInOldSubtreeLayerSpace;
 
-    const nsIntRect* clipRect = aLayer->GetClipRect();
-    if (clipRect) {
-      nsIntRect transformedClipRect(*clipRect);
-      transformedClipRect.MoveBy(translation.x, translation.y);
-      layerComposite->SetShadowClipRect(&transformedClipRect);
-    }
+    // Add the local layer transform to the two points to make the equation
+    // below this section more convenient.
+    gfxPoint anchor(anchorInOldSubtreeLayerSpace.x, anchorInOldSubtreeLayerSpace.y);
+    gfxPoint offsetAnchor(offsetAnchorInOldSubtreeLayerSpace.x, offsetAnchorInOldSubtreeLayerSpace.y);
+    gfxPoint locallyTransformedAnchor = layerTransform.Transform(anchor);
+    gfxPoint locallyTransformedOffsetAnchor = layerTransform.Transform(offsetAnchor);
+
+    // Transforming the locallyTransformedAnchor by oldCumulativeTransform
+    // returns the layer's anchor point relative to the parent of
+    // aTransformedSubtreeRoot, before the new transform was applied.
+    // Then, applying newCumulativeTransformInverse maps that point relative
+    // to the layer's parent, which is the same coordinate space as
+    // locallyTransformedAnchor again, allowing us to subtract them and find
+    // out the offset necessary to make sure the layer stays stationary.
+    gfxPoint oldAnchorPositionInNewSpace =
+      newCumulativeTransformInverse.Transform(
+        oldCumulativeTransform.Transform(locallyTransformedOffsetAnchor));
+    gfxPoint translation = oldAnchorPositionInNewSpace - locallyTransformedAnchor;
+
+    // Finally, apply the 2D translation to the layer transform.
+    TranslateShadowLayer2D(aLayer, translation);
 
     // The transform has now been applied, so there's no need to iterate over
     // child layers.
     return;
   }
 
   for (Layer* child = aLayer->GetFirstChild();
        child; child = child->GetNextSibling()) {
-    TransformFixedLayers(child, aTranslation, aScaleDiff, aFixedLayerMargins);
+    AlignFixedLayersForAnchorPoint(child, aTransformedSubtreeRoot,
+                                   aPreviousTransformForRoot, aFixedLayerMargins);
   }
 }
 
 static void
 SampleValue(float aPortion, Animation& aAnimation, nsStyleAnimation::Value& aStart,
             nsStyleAnimation::Value& aEnd, Animatable* aValue)
 {
   nsStyleAnimation::Value interpolatedValue;
@@ -337,16 +426,17 @@ AsyncCompositionManager::ApplyAsyncConte
 
   ContainerLayer* container = aLayer->AsContainerLayer();
   if (!container) {
     return appliedTransform;
   }
 
   if (AsyncPanZoomController* controller = container->GetAsyncPanZoomController()) {
     LayerComposite* layerComposite = aLayer->AsLayerComposite();
+    gfx3DMatrix oldTransform = aLayer->GetTransform();
 
     ViewTransform treeTransform;
     ScreenPoint scrollOffset;
     *aWantNextFrame |=
       controller->SampleContentTransformForFrame(aCurrentFrame,
                                                  container,
                                                  &treeTransform,
                                                  scrollOffset);
@@ -356,17 +446,17 @@ AsyncCompositionManager::ApplyAsyncConte
     // XXX We use rootTransform instead of metrics.mResolution here because on
     // Fennec the resolution is set on the root layer rather than the scrollable layer.
     // The SyncFrameMetrics call and the paintScale variable are used on Fennec only
     // so it doesn't affect any other platforms. See bug 732971.
     CSSToLayerScale paintScale = metrics.mDevPixelsPerCSSPixel
       / LayerToLayoutDeviceScale(rootTransform.GetXScale(), rootTransform.GetYScale());
     CSSRect displayPort(metrics.mCriticalDisplayPort.IsEmpty() ?
                         metrics.mDisplayPort : metrics.mCriticalDisplayPort);
-    gfx::Margin fixedLayerMargins(0, 0, 0, 0);
+    LayerMargin fixedLayerMargins(0, 0, 0, 0);
     ScreenPoint offset(0, 0);
     SyncFrameMetrics(scrollOffset, treeTransform.mScale.scale, metrics.mScrollableRect,
                      mLayersUpdated, displayPort, paintScale,
                      mIsFirstPaint, fixedLayerMargins, offset);
 
     mIsFirstPaint = false;
     mLayersUpdated = false;
 
@@ -382,21 +472,30 @@ AsyncCompositionManager::ApplyAsyncConte
                     1);
     transform.ScalePost(1.0f/aLayer->GetPostXScale(),
                         1.0f/aLayer->GetPostYScale(),
                         1);
     layerComposite->SetShadowTransform(transform);
     NS_ASSERTION(!layerComposite->GetShadowTransformSetByAnimation(),
                  "overwriting animated transform!");
 
-    TransformFixedLayers(
-      aLayer,
-      gfxPoint(-treeTransform.mTranslation.x, -treeTransform.mTranslation.y),
-      gfxSize(treeTransform.mScale.scale, treeTransform.mScale.scale),
-      fixedLayerMargins);
+    // Apply resolution scaling to the old transform - the layer tree as it is
+    // doesn't have the necessary transform to display correctly.
+#ifdef MOZ_WIDGET_ANDROID
+    // XXX We use rootTransform instead of the resolution on the individual layer's
+    // FrameMetrics on Fennec because the resolution is set on the root layer rather
+    // than the scrollable layer. See bug 732971. On non-Fennec we do the right thing.
+    LayoutDeviceToLayerScale resolution(1.0 / rootTransform.GetXScale(),
+                                        1.0 / rootTransform.GetYScale());
+#else
+    LayoutDeviceToLayerScale resolution = metrics.mResolution;
+#endif
+    oldTransform.Scale(resolution.scale, resolution.scale, 1);
+
+    AlignFixedLayersForAnchorPoint(aLayer, aLayer, oldTransform, fixedLayerMargins);
 
     appliedTransform = true;
   }
 
   return appliedTransform;
 }
 
 void
@@ -404,16 +503,17 @@ AsyncCompositionManager::TransformScroll
 {
   LayerComposite* layerComposite = aLayer->AsLayerComposite();
   ContainerLayer* container = aLayer->AsContainerLayer();
 
   const FrameMetrics& metrics = container->GetFrameMetrics();
   // We must apply the resolution scale before a pan/zoom transform, so we call
   // GetTransform here.
   const gfx3DMatrix& currentTransform = aLayer->GetTransform();
+  gfx3DMatrix oldTransform = currentTransform;
 
   gfx3DMatrix treeTransform;
 
   CSSToLayerScale geckoZoom = metrics.mDevPixelsPerCSSPixel * aResolution;
 
   LayerIntPoint scrollOffsetLayerPixels = RoundedToInt(metrics.mScrollOffset * geckoZoom);
 
   if (mIsFirstPaint) {
@@ -432,17 +532,17 @@ AsyncCompositionManager::TransformScroll
   // Calculate the absolute display port to send to Java
   LayerIntRect displayPort = RoundedToInt(
     (metrics.mCriticalDisplayPort.IsEmpty()
       ? metrics.mDisplayPort
       : metrics.mCriticalDisplayPort
     ) * geckoZoom);
   displayPort += scrollOffsetLayerPixels;
 
-  gfx::Margin fixedLayerMargins(0, 0, 0, 0);
+  LayerMargin fixedLayerMargins(0, 0, 0, 0);
   ScreenPoint offset(0, 0);
 
   // Ideally we would initialize userZoom to AsyncPanZoomController::CalculateResolution(metrics)
   // but this causes a reftest-ipc test to fail (see bug 883646 comment 27). The reason for this
   // appears to be that metrics.mZoom is poorly initialized in some scenarios. In these scenarios,
   // however, we can assume there is no async zooming in progress and so the following statement
   // works fine.
   CSSToScreenScale userZoom(metrics.mDevPixelsPerCSSPixel.scale * metrics.mResolution.scale);
@@ -466,57 +566,69 @@ AsyncCompositionManager::TransformScroll
   LayerIntPoint geckoScroll(0, 0);
   if (metrics.IsScrollable()) {
     geckoScroll = scrollOffsetLayerPixels;
   }
 
   LayerPoint translation = (userScroll / zoomAdjust) - geckoScroll;
   treeTransform = gfx3DMatrix(ViewTransform(-translation, userZoom / metrics.mDevPixelsPerCSSPixel));
 
-  // Translate fixed position layers so that they stay in the correct position
-  // when userScroll and geckoScroll differ.
-  gfxPoint fixedOffset;
-  gfxSize scaleDiff;
-
-  LayerRect content = mContentRect * geckoZoom;
-  // If the contents can fit entirely within the widget area on a particular
-  // dimension, we need to translate and scale so that the fixed layers remain
-  // within the page boundaries.
-  if (mContentRect.width * userZoom.scale < metrics.mCompositionBounds.width) {
-    fixedOffset.x = -geckoScroll.x;
-    scaleDiff.width = std::min(1.0f, metrics.mCompositionBounds.width / content.width);
-  } else {
-    fixedOffset.x = clamped(userScroll.x / zoomAdjust.scale, content.x,
-        content.XMost() - metrics.mCompositionBounds.width / zoomAdjust.scale) - geckoScroll.x;
-    scaleDiff.width = zoomAdjust.scale;
-  }
-
-  if (mContentRect.height * userZoom.scale < metrics.mCompositionBounds.height) {
-    fixedOffset.y = -geckoScroll.y;
-    scaleDiff.height = std::min(1.0f, metrics.mCompositionBounds.height / content.height);
-  } else {
-    fixedOffset.y = clamped(userScroll.y / zoomAdjust.scale, content.y,
-        content.YMost() - metrics.mCompositionBounds.height / zoomAdjust.scale) - geckoScroll.y;
-    scaleDiff.height = zoomAdjust.scale;
-  }
-
   // The transform already takes the resolution scale into account.  Since we
   // will apply the resolution scale again when computing the effective
   // transform, we must apply the inverse resolution scale here.
   gfx3DMatrix computedTransform = treeTransform * currentTransform;
   computedTransform.Scale(1.0f/container->GetPreXScale(),
                           1.0f/container->GetPreYScale(),
                           1);
   computedTransform.ScalePost(1.0f/container->GetPostXScale(),
                               1.0f/container->GetPostYScale(),
                               1);
   layerComposite->SetShadowTransform(computedTransform);
   NS_ASSERTION(!layerComposite->GetShadowTransformSetByAnimation(),
                "overwriting animated transform!");
-  TransformFixedLayers(aLayer, fixedOffset, scaleDiff, fixedLayerMargins);
+
+  // Apply resolution scaling to the old transform - the layer tree as it is
+  // doesn't have the necessary transform to display correctly.
+  oldTransform.Scale(aResolution.scale, aResolution.scale, 1);
+
+  // Make sure that overscroll and under-zoom are represented in the old
+  // transform so that fixed position content moves and scales accordingly.
+  // These calculations will effectively scale and offset fixed position layers
+  // in screen space when the compensatory transform is performed in
+  // AlignFixedLayersForAnchorPoint.
+  ScreenRect contentScreenRect = mContentRect * userZoom;
+  gfxPoint3D overscrollTranslation;
+  if (userScroll.x < contentScreenRect.x) {
+    overscrollTranslation.x = contentScreenRect.x - userScroll.x;
+  } else if (userScroll.x + metrics.mCompositionBounds.width > contentScreenRect.XMost()) {
+    overscrollTranslation.x = contentScreenRect.XMost() -
+      (userScroll.x + metrics.mCompositionBounds.width);
+  }
+  if (userScroll.y < contentScreenRect.y) {
+    overscrollTranslation.y = contentScreenRect.y - userScroll.y;
+  } else if (userScroll.y + metrics.mCompositionBounds.height > contentScreenRect.YMost()) {
+    overscrollTranslation.y = contentScreenRect.YMost() -
+      (userScroll.y + metrics.mCompositionBounds.height);
+  }
+  oldTransform.Translate(overscrollTranslation);
+
+  gfxSize underZoomScale(1.0f, 1.0f);
+  if (mContentRect.width * userZoom.scale < metrics.mCompositionBounds.width) {
+    underZoomScale.width = (mContentRect.width * userZoom.scale) /
+      metrics.mCompositionBounds.width;
+  }
+  if (mContentRect.height * userZoom.scale < metrics.mCompositionBounds.height) {
+    underZoomScale.height = (mContentRect.height * userZoom.scale) /
+      metrics.mCompositionBounds.height;
+  }
+  oldTransform.Scale(underZoomScale.width, underZoomScale.height, 1);
+
+  // Make sure fixed position layers don't move away from their anchor points
+  // when we're asynchronously panning or zooming
+  AlignFixedLayersForAnchorPoint(aLayer, aLayer, oldTransform, fixedLayerMargins);
 }
 
 bool
 AsyncCompositionManager::TransformShadowTree(TimeStamp aCurrentFrame)
 {
   Layer* root = mLayerManager->GetRoot();
 
   // NB: we must sample animations *before* sampling pan/zoom
@@ -582,17 +694,17 @@ AsyncCompositionManager::SetPageRect(con
 }
 
 void
 AsyncCompositionManager::SyncViewportInfo(const LayerIntRect& aDisplayPort,
                                           const CSSToLayerScale& aDisplayResolution,
                                           bool aLayersUpdated,
                                           ScreenPoint& aScrollOffset,
                                           CSSToScreenScale& aScale,
-                                          gfx::Margin& aFixedLayerMargins,
+                                          LayerMargin& aFixedLayerMargins,
                                           ScreenPoint& aOffset)
 {
 #ifdef MOZ_WIDGET_ANDROID
   AndroidBridge::Bridge()->SyncViewportInfo(aDisplayPort,
                                             aDisplayResolution,
                                             aLayersUpdated,
                                             aScrollOffset,
                                             aScale,
@@ -604,17 +716,17 @@ AsyncCompositionManager::SyncViewportInf
 void
 AsyncCompositionManager::SyncFrameMetrics(const ScreenPoint& aScrollOffset,
                                           float aZoom,
                                           const CSSRect& aCssPageRect,
                                           bool aLayersUpdated,
                                           const CSSRect& aDisplayPort,
                                           const CSSToLayerScale& aDisplayResolution,
                                           bool aIsFirstPaint,
-                                          gfx::Margin& aFixedLayerMargins,
+                                          LayerMargin& aFixedLayerMargins,
                                           ScreenPoint& aOffset)
 {
 #ifdef MOZ_WIDGET_ANDROID
   AndroidBridge::Bridge()->SyncFrameMetrics(aScrollOffset, aZoom, aCssPageRect,
                                             aLayersUpdated, aDisplayPort,
                                             aDisplayResolution, aIsFirstPaint,
                                             aFixedLayerMargins, aOffset);
 #endif
--- a/gfx/layers/composite/AsyncCompositionManager.h
+++ b/gfx/layers/composite/AsyncCompositionManager.h
@@ -126,39 +126,42 @@ private:
                              const CSSToLayerScale& aZoom,
                              const CSSRect& aCssPageRect);
   void SetPageRect(const CSSRect& aCssPageRect);
   void SyncViewportInfo(const LayerIntRect& aDisplayPort,
                         const CSSToLayerScale& aDisplayResolution,
                         bool aLayersUpdated,
                         ScreenPoint& aScrollOffset,
                         CSSToScreenScale& aScale,
-                        gfx::Margin& aFixedLayerMargins,
+                        LayerMargin& aFixedLayerMargins,
                         ScreenPoint& aOffset);
   void SyncFrameMetrics(const ScreenPoint& aScrollOffset,
                         float aZoom,
                         const CSSRect& aCssPageRect,
                         bool aLayersUpdated,
                         const CSSRect& aDisplayPort,
                         const CSSToLayerScale& aDisplayResolution,
                         bool aIsFirstPaint,
-                        gfx::Margin& aFixedLayerMargins,
+                        LayerMargin& aFixedLayerMargins,
                         ScreenPoint& aOffset);
 
   /**
-   * Recursively applies the given translation to all top-level fixed position
-   * layers that are descendants of the given layer.
-   * aScaleDiff is considered to be the scale transformation applied when
-   * displaying the layers, and is used to make sure the anchor points of
-   * fixed position layers remain in the same position.
+   * Adds a translation to the transform of any fixed-pos layer descendant of
+   * aTransformedSubtreeRoot whose parent layer is not fixed. The translation is
+   * chosen so that the layer's anchor point relative to aTransformedSubtreeRoot's
+   * parent layer is the same as it was when aTransformedSubtreeRoot's
+   * GetLocalTransform() was aPreviousTransformForRoot.
+   * This function will also adjust layers so that the given content document
+   * fixed position margins will be respected during asynchronous panning and
+   * zooming.
    */
-  void TransformFixedLayers(Layer* aLayer,
-                            const gfxPoint& aTranslation,
-                            const gfxSize& aScaleDiff,
-                            const gfx::Margin& aFixedLayerMargins);
+  void AlignFixedLayersForAnchorPoint(Layer* aLayer,
+                                      Layer* aTransformedSubtreeRoot,
+                                      const gfx3DMatrix& aPreviousTransformForRoot,
+                                      const LayerMargin& aFixedLayerMargins);
 
   /**
    * DRAWING PHASE ONLY
    *
    * For reach RefLayer in our layer tree, look up its referent and connect it
    * to the layer tree, if found.
    */
   void ResolveRefLayers();
--- a/gfx/layers/composite/CompositableHost.h
+++ b/gfx/layers/composite/CompositableHost.h
@@ -190,17 +190,17 @@ public:
     SetCompositor(aCompositor);
     SetLayer(aLayer);
   }
   void Detach() {
     SetLayer(nullptr);
     SetCompositor(nullptr);
   }
 
-  virtual void Dump(FILE* aFile=NULL,
+  virtual void Dump(FILE* aFile=nullptr,
                     const char* aPrefix="",
                     bool aDumpHtml=false) { }
   static void DumpDeprecatedTextureHost(FILE* aFile, DeprecatedTextureHost* aTexture);
 
 #ifdef MOZ_DUMP_PAINTING
   virtual already_AddRefed<gfxImageSurface> GetAsSurface() { return nullptr; }
 #endif
 
--- a/gfx/layers/composite/ContentHost.h
+++ b/gfx/layers/composite/ContentHost.h
@@ -92,17 +92,17 @@ public:
 
 #ifdef MOZ_DUMP_PAINTING
   virtual already_AddRefed<gfxImageSurface> GetAsSurface()
   {
     return mDeprecatedTextureHost->GetAsSurface();
   }
 #endif
 
-  virtual void Dump(FILE* aFile=NULL,
+  virtual void Dump(FILE* aFile=nullptr,
                     const char* aPrefix="",
                     bool aDumpHtml=false) MOZ_OVERRIDE;
 
   virtual DeprecatedTextureHost* GetDeprecatedTextureHost() MOZ_OVERRIDE;
 
   virtual void SetPaintWillResample(bool aResample) { mPaintWillResample = aResample; }
   // The client has destroyed its texture clients and we should destroy our
   // texture hosts and SurfaceDescriptors. Note that we don't immediately
@@ -154,17 +154,17 @@ public:
                             nsIntRegion* aUpdatedRegionBack);
 
   virtual void EnsureDeprecatedTextureHost(TextureIdentifier aTextureId,
                                  const SurfaceDescriptor& aSurface,
                                  ISurfaceAllocator* aAllocator,
                                  const TextureInfo& aTextureInfo) MOZ_OVERRIDE;
   virtual void DestroyTextures() MOZ_OVERRIDE;
 
-  virtual void Dump(FILE* aFile=NULL,
+  virtual void Dump(FILE* aFile=nullptr,
                     const char* aPrefix="",
                     bool aDumpHtml=false) MOZ_OVERRIDE;
 
 #ifdef MOZ_LAYERS_HAVE_LOG
   virtual void PrintInfo(nsACString& aTo, const char* aPrefix);
 #endif
 protected:
   nsIntRegion mValidRegionForNextBackBuffer;
--- a/gfx/layers/composite/ImageHost.h
+++ b/gfx/layers/composite/ImageHost.h
@@ -81,17 +81,17 @@ public:
     if (mDeprecatedTextureHost) {
       return mDeprecatedTextureHost->GetRenderState();
     }
     return LayerRenderState();
   }
 
   virtual void SetCompositor(Compositor* aCompositor) MOZ_OVERRIDE;
 
-  virtual void Dump(FILE* aFile=NULL,
+  virtual void Dump(FILE* aFile=nullptr,
                     const char* aPrefix="",
                     bool aDumpHtml=false) MOZ_OVERRIDE;
 
 #ifdef MOZ_LAYERS_HAVE_LOG
   virtual void PrintInfo(nsACString& aTo, const char* aPrefix);
 #endif
 
 #ifdef MOZ_DUMP_PAINTING
--- a/gfx/layers/composite/TiledContentHost.h
+++ b/gfx/layers/composite/TiledContentHost.h
@@ -197,17 +197,17 @@ public:
   {
     CompositableHost::SetCompositor(aCompositor);
     mVideoMemoryTiledBuffer.SetCompositor(aCompositor);
     mLowPrecisionVideoMemoryTiledBuffer.SetCompositor(aCompositor);
   }
 
   virtual void Attach(Layer* aLayer, Compositor* aCompositor) MOZ_OVERRIDE;
 
-  virtual void Dump(FILE* aFile=NULL,
+  virtual void Dump(FILE* aFile=nullptr,
                     const char* aPrefix="",
                     bool aDumpHtml=false) MOZ_OVERRIDE;
 
 #ifdef MOZ_LAYERS_HAVE_LOG
   virtual void PrintInfo(nsACString& aTo, const char* aPrefix);
 #endif
 
 private:
--- a/gfx/layers/d3d10/CanvasLayerD3D10.cpp
+++ b/gfx/layers/d3d10/CanvasLayerD3D10.cpp
@@ -63,17 +63,17 @@ CanvasLayerD3D10::Initialize(const Data&
 
     if (texture) {
       mTexture = static_cast<ID3D10Texture2D*>(texture);
 
       NS_ASSERTION(!aData.mGLContext && !aData.mSurface,
                    "CanvasLayer can't have both surface and WebGLContext/Surface");
 
       mBounds.SetRect(0, 0, aData.mSize.width, aData.mSize.height);
-      device()->CreateShaderResourceView(mTexture, NULL, getter_AddRefs(mSRView));
+      device()->CreateShaderResourceView(mTexture, nullptr, getter_AddRefs(mSRView));
       return;
     } 
     
     // XXX we should store mDrawTarget and use it directly in UpdateSurface,
     // bypassing Thebes
     mSurface = gfxPlatform::GetPlatform()->GetThebesSurfaceForDrawTarget(mDrawTarget);
   } else {
     NS_ERROR("CanvasLayer created without mSurface, mDrawTarget or mGLContext?");
@@ -81,37 +81,37 @@ CanvasLayerD3D10::Initialize(const Data&
 
   mBounds.SetRect(0, 0, aData.mSize.width, aData.mSize.height);
 
   if (mSurface && mSurface->GetType() == gfxASurface::SurfaceTypeD2D) {
     void *data = mSurface->GetData(&gKeyD3D10Texture);
     if (data) {
       mTexture = static_cast<ID3D10Texture2D*>(data);
       mIsD2DTexture = true;
-      device()->CreateShaderResourceView(mTexture, NULL, getter_AddRefs(mSRView));
+      device()->CreateShaderResourceView(mTexture, nullptr, getter_AddRefs(mSRView));
       mHasAlpha =
         mSurface->GetContentType() == gfxASurface::CONTENT_COLOR_ALPHA;
       return;
     }
   }
 
   mIsD2DTexture = false;
 
   // Create a texture in case we need to readback.
   CD3D10_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM, mBounds.width, mBounds.height, 1, 1);
   desc.Usage = D3D10_USAGE_DYNAMIC;
   desc.CPUAccessFlags = D3D10_CPU_ACCESS_WRITE;
 
-  HRESULT hr = device()->CreateTexture2D(&desc, NULL, getter_AddRefs(mTexture));
+  HRESULT hr = device()->CreateTexture2D(&desc, nullptr, getter_AddRefs(mTexture));
   if (FAILED(hr)) {
     NS_WARNING("Failed to create texture for CanvasLayer!");
     return;
   }
 
-  device()->CreateShaderResourceView(mTexture, NULL, getter_AddRefs(mUploadSRView));
+  device()->CreateShaderResourceView(mTexture, nullptr, getter_AddRefs(mUploadSRView));
 }
 
 void
 CanvasLayerD3D10::UpdateSurface()
 {
   if (!IsDirty())
     return;
   Painted();
--- a/gfx/layers/d3d10/CanvasLayerD3D10.h
+++ b/gfx/layers/d3d10/CanvasLayerD3D10.h
@@ -15,17 +15,17 @@
 namespace mozilla {
 namespace layers {
 
 class CanvasLayerD3D10 : public CanvasLayer,
                          public LayerD3D10
 {
 public:
   CanvasLayerD3D10(LayerManagerD3D10 *aManager)
-    : CanvasLayer(aManager, NULL)
+    : CanvasLayer(aManager, nullptr)
     , LayerD3D10(aManager)
     , mDataIsPremultiplied(false)
     , mNeedsYFlip(false)
     , mHasAlpha(true)
   {
       mImplData = static_cast<LayerD3D10*>(this);
       mForceReadback = Preferences::GetBool("webgl.force-layers-readback", false);
   }
--- a/gfx/layers/d3d10/ColorLayerD3D10.cpp
+++ b/gfx/layers/d3d10/ColorLayerD3D10.cpp
@@ -6,17 +6,17 @@
 #include "ColorLayerD3D10.h"
 
 #include "../d3d9/Nv3DVUtils.h"
 
 namespace mozilla {
 namespace layers {
 
 ColorLayerD3D10::ColorLayerD3D10(LayerManagerD3D10 *aManager)
-  : ColorLayer(aManager, NULL)
+  : ColorLayer(aManager, nullptr)
   , LayerD3D10(aManager)
 {
   mImplData = static_cast<LayerD3D10*>(this);
 }
 
 Layer*
 ColorLayerD3D10::GetLayer()
 {
--- a/gfx/layers/d3d10/ContainerLayerD3D10.cpp
+++ b/gfx/layers/d3d10/ContainerLayerD3D10.cpp
@@ -11,17 +11,17 @@
 #include "../d3d9/Nv3DVUtils.h"
 #include "ThebesLayerD3D10.h"
 #include "ReadbackProcessor.h"
 
 namespace mozilla {
 namespace layers {
 
 ContainerLayerD3D10::ContainerLayerD3D10(LayerManagerD3D10 *aManager)
-  : ContainerLayer(aManager, NULL)
+  : ContainerLayer(aManager, nullptr)
   , LayerD3D10(aManager)
 {
   mImplData = static_cast<LayerD3D10*>(this);
 }
 
 ContainerLayerD3D10::~ContainerLayerD3D10()
 {
   while (mFirstChild) {
@@ -210,37 +210,37 @@ ContainerLayerD3D10::RenderLayer()
   nsRefPtr<ID3D10Texture2D> renderTexture;
   nsRefPtr<ID3D10RenderTargetView> rtView;
   float previousRenderTargetOffset[2];
   nsIntSize previousViewportSize;
 
   gfx3DMatrix oldViewMatrix;
 
   if (useIntermediate) {
-    device()->OMGetRenderTargets(1, getter_AddRefs(previousRTView), NULL);
+    device()->OMGetRenderTargets(1, getter_AddRefs(previousRTView), nullptr);
  
     D3D10_TEXTURE2D_DESC desc;
     memset(&desc, 0, sizeof(D3D10_TEXTURE2D_DESC));
     desc.ArraySize = 1;
     desc.MipLevels = 1;
     desc.Width = visibleRect.width;
     desc.Height = visibleRect.height;
     desc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;
     desc.SampleDesc.Count = 1;
     desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
     HRESULT hr;
-    hr = device()->CreateTexture2D(&desc, NULL, getter_AddRefs(renderTexture));
+    hr = device()->CreateTexture2D(&desc, nullptr, getter_AddRefs(renderTexture));
 
     if (FAILED(hr)) {
       LayerManagerD3D10::ReportFailure(NS_LITERAL_CSTRING("Failed to create new texture for ContainerLayerD3D10!"), 
                                        hr);
       return;
     }
 
-    hr = device()->CreateRenderTargetView(renderTexture, NULL, getter_AddRefs(rtView));
+    hr = device()->CreateRenderTargetView(renderTexture, nullptr, getter_AddRefs(rtView));
     NS_ASSERTION(SUCCEEDED(hr), "Failed to create render target view for ContainerLayerD3D10!");
 
     effect()->GetVariableByName("vRenderTargetOffset")->
       GetRawValue(previousRenderTargetOffset, 0, 8);
 
     if (mVisibleRegion.GetNumRects() != 1 || !(GetContentFlags() & CONTENT_OPAQUE)) {
       const gfx3DMatrix& transform3D = GetEffectiveTransform();
       gfxMatrix transform;
@@ -272,17 +272,17 @@ ContainerLayerD3D10::RenderLayer()
                                         &srcBox);
       } else {
         float black[] = { 0, 0, 0, 0};
         device()->ClearRenderTargetView(rtView, black);
       }
     }
 
     ID3D10RenderTargetView *rtViewPtr = rtView;
-    device()->OMSetRenderTargets(1, &rtViewPtr, NULL);
+    device()->OMSetRenderTargets(1, &rtViewPtr, nullptr);
 
     renderTargetOffset[0] = (float)visibleRect.x;
     renderTargetOffset[1] = (float)visibleRect.y;
     effect()->GetVariableByName("vRenderTargetOffset")->
       SetRawValue(renderTargetOffset, 0, 8);
 
     previousViewportSize = mD3DManager->GetViewport();
     mD3DManager->SetViewport(nsIntSize(visibleRect.Size()));
@@ -327,17 +327,17 @@ ContainerLayerD3D10::RenderLayer()
     layerToRender->RenderLayer();
   }
 
   device()->RSSetScissorRects(1, &oldD3D10Scissor);
 
   if (useIntermediate) {
     mD3DManager->SetViewport(previousViewportSize);
     ID3D10RenderTargetView *rtView = previousRTView;
-    device()->OMSetRenderTargets(1, &rtView, NULL);
+    device()->OMSetRenderTargets(1, &rtView, nullptr);
     effect()->GetVariableByName("vRenderTargetOffset")->
       SetRawValue(previousRenderTargetOffset, 0, 8);
 
     SetEffectTransformAndOpacity();
 
     ID3D10EffectTechnique *technique;
     if (LoadMaskTexture()) {
       if (GetTransform().CanDraw2D()) {
@@ -355,17 +355,17 @@ ContainerLayerD3D10::RenderLayer()
         (float)visibleRect.y,
         (float)visibleRect.width,
         (float)visibleRect.height)
       );
 
     technique->GetPassByIndex(0)->Apply(0);
 
     ID3D10ShaderResourceView *view;
-    device()->CreateShaderResourceView(renderTexture, NULL, &view);
+    device()->CreateShaderResourceView(renderTexture, nullptr, &view);
     device()->PSSetShaderResources(0, 1, &view);    
     device()->Draw(4, 0);
     view->Release();
   }
 }
 
 void
 ContainerLayerD3D10::LayerManagerDestroyed()
--- a/gfx/layers/d3d10/ImageLayerD3D10.cpp
+++ b/gfx/layers/d3d10/ImageLayerD3D10.cpp
@@ -45,17 +45,17 @@ DataToTexture(ID3D10Device *aDevice,
 }
 
 static already_AddRefed<ID3D10Texture2D>
 SurfaceToTexture(ID3D10Device *aDevice,
                  gfxASurface *aSurface,
                  const gfxIntSize &aSize)
 {
   if (!aSurface) {
-    return NULL;
+    return nullptr;
   }
 
   if (aSurface->GetType() == gfxASurface::SurfaceTypeD2D) {
     void *data = aSurface->GetData(&gKeyD3D10Texture);
     if (data) {
       nsRefPtr<ID3D10Texture2D> texture = static_cast<ID3D10Texture2D*>(data);
       ID3D10Device *dev;
       texture->GetDevice(&dev);
@@ -101,17 +101,17 @@ ImageLayerD3D10::GetImageSRView(Image* a
     RemoteBitmapImage *remoteImage =
       static_cast<RemoteBitmapImage*>(aImage);
 
     if (!aImage->GetBackendData(mozilla::layers::LAYERS_D3D10)) {
       nsAutoPtr<TextureD3D10BackendData> dat(new TextureD3D10BackendData());
       dat->mTexture = DataToTexture(device(), remoteImage->mData, remoteImage->mStride, remoteImage->mSize);
 
       if (dat->mTexture) {
-        device()->CreateShaderResourceView(dat->mTexture, NULL, getter_AddRefs(dat->mSRView));
+        device()->CreateShaderResourceView(dat->mTexture, nullptr, getter_AddRefs(dat->mSRView));
         aImage->SetBackendData(mozilla::layers::LAYERS_D3D10, dat.forget());
       }
     }
 
     aHasAlpha = remoteImage->mFormat == RemoteImageData::BGRA32;
   } else if (aImage->GetFormat() == ImageFormat::REMOTE_IMAGE_DXGI_TEXTURE) {
     RemoteDXGITextureImage *remoteImage =
       static_cast<RemoteDXGITextureImage*>(aImage);
@@ -127,17 +127,17 @@ ImageLayerD3D10::GetImageSRView(Image* a
       return nullptr;
     }
 
     if (!aImage->GetBackendData(mozilla::layers::LAYERS_D3D10)) {
       nsAutoPtr<TextureD3D10BackendData> dat(new TextureD3D10BackendData());
       dat->mTexture = SurfaceToTexture(device(), cairoImage->mSurface, cairoImage->mSize);
 
       if (dat->mTexture) {
-        device()->CreateShaderResourceView(dat->mTexture, NULL, getter_AddRefs(dat->mSRView));
+        device()->CreateShaderResourceView(dat->mTexture, nullptr, getter_AddRefs(dat->mSRView));
         aImage->SetBackendData(mozilla::layers::LAYERS_D3D10, dat.forget());
       }
     }
 
     aHasAlpha = cairoImage->mSurface->GetContentType() == gfxASurface::CONTENT_COLOR_ALPHA;
   } else if (aImage->GetFormat() == ImageFormat::D3D9_RGB32_TEXTURE) {
     if (!aImage->GetBackendData(mozilla::layers::LAYERS_D3D10)) {
       // Use resource sharing to open the D3D9 texture as a D3D10 texture,
@@ -147,17 +147,17 @@ ImageLayerD3D10::GetImageSRView(Image* a
       hr = device()->OpenSharedResource(d3dImage->GetShareHandle(),
                                         IID_ID3D10Texture2D,
                                         (void**)getter_AddRefs(texture));
       NS_ENSURE_TRUE(SUCCEEDED(hr), nullptr);
 
       nsAutoPtr<TextureD3D10BackendData> dat(new TextureD3D10BackendData());
       dat->mTexture = texture;
 
-      hr = device()->CreateShaderResourceView(dat->mTexture, NULL, getter_AddRefs(dat->mSRView));
+      hr = device()->CreateShaderResourceView(dat->mTexture, nullptr, getter_AddRefs(dat->mSRView));
       NS_ENSURE_TRUE(SUCCEEDED(hr) && dat->mSRView, nullptr);
 
       aImage->SetBackendData(mozilla::layers::LAYERS_D3D10, dat.forget());
     }
     aHasAlpha = false;
   } else {
     NS_WARNING("Incorrect image type.");
     return nullptr;
@@ -302,17 +302,17 @@ ImageLayerD3D10::RenderLayer()
       }
 
       // Send control data even in mono case so driver knows to leave stereo mode.
       GetNv3DVUtils()->SendNv3DVControl(mode, true, FIREFOX_3DV_APP_HANDLE);
 
       if (yuvImage->GetData()->mStereoMode != STEREO_MODE_MONO) {
         // Dst resource is optional
         GetNv3DVUtils()->SendNv3DVMetaData((unsigned int)yuvImage->GetData()->mYSize.width,
-                                           (unsigned int)yuvImage->GetData()->mYSize.height, (HANDLE)(data->mYTexture), (HANDLE)(NULL));
+                                           (unsigned int)yuvImage->GetData()->mYSize.height, (HANDLE)(data->mYTexture), (HANDLE)(nullptr));
       }
     }
 
     effect()->GetVariableByName("vLayerQuad")->AsVector()->SetFloatVector(
       ShaderConstantRectD3D10(
         (float)0,
         (float)0,
         (float)size.width,
@@ -380,19 +380,19 @@ void ImageLayerD3D10::AllocateTexturesYC
   if (!FAILED(hr)) {
       hr = device()->CreateTexture2D(&descCbCr, &dataCr, getter_AddRefs(backendData->mCrTexture));
   }
   if (FAILED(hr)) {
     LayerManagerD3D10::ReportFailure(NS_LITERAL_CSTRING("PlanarYCbCrImageD3D10::AllocateTextures(): Failed to create texture"),
                                      hr);
     return;
   }
-  device()->CreateShaderResourceView(backendData->mYTexture, NULL, getter_AddRefs(backendData->mYView));
-  device()->CreateShaderResourceView(backendData->mCbTexture, NULL, getter_AddRefs(backendData->mCbView));
-  device()->CreateShaderResourceView(backendData->mCrTexture, NULL, getter_AddRefs(backendData->mCrView));
+  device()->CreateShaderResourceView(backendData->mYTexture, nullptr, getter_AddRefs(backendData->mYView));
+  device()->CreateShaderResourceView(backendData->mCbTexture, nullptr, getter_AddRefs(backendData->mCbView));
+  device()->CreateShaderResourceView(backendData->mCrTexture, nullptr, getter_AddRefs(backendData->mCrView));
 
   aImage->SetBackendData(mozilla::layers::LAYERS_D3D10, backendData.forget());
 }
 
 already_AddRefed<ID3D10ShaderResourceView>
 ImageLayerD3D10::GetAsTexture(gfxIntSize* aSize)
 {
   if (!GetContainer()) {
@@ -449,17 +449,17 @@ RemoteDXGITextureImage::GetAsSurface()
   data->mTexture->GetDesc(&desc);
 
   desc.CPUAccessFlags = D3D10_CPU_ACCESS_READ;
   desc.BindFlags = 0;
   desc.MiscFlags = 0;
   desc.Usage = D3D10_USAGE_STAGING;
 
   nsRefPtr<ID3D10Texture2D> softTexture;
-  HRESULT hr = device->CreateTexture2D(&desc, NULL, getter_AddRefs(softTexture));
+  HRESULT hr = device->CreateTexture2D(&desc, nullptr, getter_AddRefs(softTexture));
 
   if (FAILED(hr)) {
     NS_WARNING("Failed to create 2D staging texture.");
     return nullptr;
   }
 
   device->CopyResource(softTexture, data->mTexture);
   keyedMutex->ReleaseSync(0);
@@ -509,17 +509,17 @@ RemoteDXGITextureImage::GetD3D10TextureB
     NS_WARNING("Failed to get texture for shared texture handle.");
     return nullptr;
   }
 
   nsAutoPtr<TextureD3D10BackendData> data(new TextureD3D10BackendData());
 
   data->mTexture = texture;
 
-  aDevice->CreateShaderResourceView(texture, NULL, getter_AddRefs(data->mSRView));
+  aDevice->CreateShaderResourceView(texture, nullptr, getter_AddRefs(data->mSRView));
 
   SetBackendData(mozilla::layers::LAYERS_D3D10, data);
 
   return data.forget();
 }
 
 } /* layers */
 } /* mozilla */
--- a/gfx/layers/d3d10/ImageLayerD3D10.h
+++ b/gfx/layers/d3d10/ImageLayerD3D10.h
@@ -14,17 +14,17 @@
 namespace mozilla {
 namespace layers {
 
 class ImageLayerD3D10 : public ImageLayer,
                         public LayerD3D10
 {
 public:
   ImageLayerD3D10(LayerManagerD3D10 *aManager)
-    : ImageLayer(aManager, NULL)
+    : ImageLayer(aManager, nullptr)
     , LayerD3D10(aManager)
   {
     mImplData = static_cast<LayerD3D10*>(this);
   }
 
   // LayerD3D10 Implementation
   virtual Layer* GetLayer();
 
@@ -51,17 +51,17 @@ struct PlanarYCbCrD3D10BackendData : pub
 struct TextureD3D10BackendData : public ImageBackendData
 {
   nsRefPtr<ID3D10Texture2D> mTexture;
   nsRefPtr<ID3D10ShaderResourceView> mSRView;
 };
 
 class RemoteDXGITextureImage : public Image {
 public:
-  RemoteDXGITextureImage() : Image(NULL, REMOTE_IMAGE_DXGI_TEXTURE) {}
+  RemoteDXGITextureImage() : Image(nullptr, REMOTE_IMAGE_DXGI_TEXTURE) {}
 
   already_AddRefed<gfxASurface> GetAsSurface();
 
   gfxIntSize GetSize() { return mSize; }
 
   TextureD3D10BackendData *GetD3D10TextureBackendData(ID3D10Device *aDevice);
 
   gfxIntSize mSize;
--- a/gfx/layers/d3d10/LayerManagerD3D10.cpp
+++ b/gfx/layers/d3d10/LayerManagerD3D10.cpp
@@ -84,17 +84,17 @@ LayerManagerD3D10::~LayerManagerD3D10()
     mDevice->SetPrivateData(sLayerManagerCount, sizeof(referenceCount), &referenceCount);
 
     if (!referenceCount) {
       DeviceAttachments *attachments;
       size = sizeof(attachments);
       mDevice->GetPrivateData(sDeviceAttachments, &size, &attachments);
       // No LayerManagers left for this device. Clear out interfaces stored which
       // hold a reference to the device.
-      mDevice->SetPrivateData(sDeviceAttachments, 0, NULL);
+      mDevice->SetPrivateData(sDeviceAttachments, 0, nullptr);
 
       delete attachments;
     }
   }
 
   Destroy();
 }
 
@@ -131,17 +131,17 @@ LayerManagerD3D10::Initialize(bool force
       SetHRESULT(aHresultPtr, hr);
       return false;
   }
 
   /*
    * Do some post device creation setup
    */
   if (mNv3DVUtils) {
-    IUnknown* devUnknown = NULL;
+    IUnknown* devUnknown = nullptr;
     if (mDevice) {
       mDevice->QueryInterface(IID_IUnknown, (void **)&devUnknown);
     }
     mNv3DVUtils->SetDeviceInfo(devUnknown);
   }
 
   int referenceCount = 0;
   UINT size = sizeof(referenceCount);
@@ -163,17 +163,17 @@ LayerManagerD3D10::Initialize(bool force
       SetHRESULT(aHresultPtr, HRESULT_FROM_WIN32(GetLastError()));
       return false;
     }
 
     hr = createEffect((void*)g_main,
                       sizeof(g_main),
                       D3D10_EFFECT_SINGLE_THREADED,
                       mDevice,
-                      NULL,
+                      nullptr,
                       getter_AddRefs(mEffect));
     
     if (FAILED(hr)) {
       SetHRESULT(aHresultPtr, hr);
       return false;
     }
 
     attachments->mEffect = mEffect;
@@ -458,17 +458,17 @@ LayerManagerD3D10::CreateOptimalSurface(
   }
 
   nsRefPtr<ID3D10Texture2D> texture;
   
   CD3D10_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM, aSize.width, aSize.height, 1, 1);
   desc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;
   desc.MiscFlags = D3D10_RESOURCE_MISC_GDI_COMPATIBLE;
   
-  HRESULT hr = device()->CreateTexture2D(&desc, NULL, getter_AddRefs(texture));
+  HRESULT hr = device()->CreateTexture2D(&desc, nullptr, getter_AddRefs(texture));
 
   if (FAILED(hr)) {
     NS_WARNING("Failed to create new texture for CreateOptimalSurface!");
     return LayerManager::CreateOptimalSurface(aSize, aFormat);
   }
 
   nsRefPtr<gfxD2DSurface> surface =
     new gfxD2DSurface(texture, aFormat == gfxASurface::ImageFormatRGB24 ?
@@ -503,17 +503,17 @@ LayerManagerD3D10::CreateDrawTarget(cons
     return LayerManager::CreateDrawTarget(aSize, aFormat);
   }
 
   nsRefPtr<ID3D10Texture2D> texture;
   
   CD3D10_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM, aSize.width, aSize.height, 1, 1);
   desc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;
   
-  HRESULT hr = device()->CreateTexture2D(&desc, NULL, getter_AddRefs(texture));
+  HRESULT hr = device()->CreateTexture2D(&desc, nullptr, getter_AddRefs(texture));
 
   if (FAILED(hr)) {
     NS_WARNING("Failed to create new texture for CreateOptimalSurface!");
     return LayerManager::CreateDrawTarget(aSize, aFormat);
   }
 
   RefPtr<DrawTarget> surface =
     Factory::CreateDrawTargetForD3D10Texture(texture, aFormat);
@@ -594,17 +594,17 @@ LayerManagerD3D10::SetupPipeline()
     SetFloatVector(ShaderConstantRectD3D10(0, 0, 1.0f, 1.0f));
 
   if (FAILED(hr)) {
     NS_WARNING("Failed to set Texture Coordinates.");
     return;
   }
 
   ID3D10RenderTargetView *view = mRTView;
-  mDevice->OMSetRenderTargets(1, &view, NULL);
+  mDevice->OMSetRenderTargets(1, &view, nullptr);
 
   SetupInputAssembler();
 
   SetViewport(nsIntSize(rect.width, rect.height));
 }
 
 void
 LayerManagerD3D10::UpdateRenderTarget()
@@ -615,17 +615,17 @@ LayerManagerD3D10::UpdateRenderTarget()
 
   HRESULT hr;
 
   nsRefPtr<ID3D10Texture2D> backBuf;
   hr = mSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (void**)backBuf.StartAssignment());
   if (FAILED(hr)) {
     return;
   }
-  mDevice->CreateRenderTargetView(backBuf, NULL, getter_AddRefs(mRTView));
+  mDevice->CreateRenderTargetView(backBuf, nullptr, getter_AddRefs(mRTView));
 }
 
 void
 LayerManagerD3D10::VerifyBufferSize()
 {
   nsIntRect rect;
   mWidget->GetClientBounds(rect);
 
@@ -748,17 +748,17 @@ LayerManagerD3D10::PaintToTarget()
   CD3D10_TEXTURE2D_DESC softDesc(bbDesc.Format, bbDesc.Width, bbDesc.Height);
   softDesc.MipLevels = 1;
   softDesc.CPUAccessFlags = D3D10_CPU_ACCESS_READ;
   softDesc.Usage = D3D10_USAGE_STAGING;
   softDesc.BindFlags = 0;
 
   nsRefPtr<ID3D10Texture2D> readTexture;
 
-  HRESULT hr = device()->CreateTexture2D(&softDesc, NULL, getter_AddRefs(readTexture));
+  HRESULT hr = device()->CreateTexture2D(&softDesc, nullptr, getter_AddRefs(readTexture));
   if (FAILED(hr)) {
     ReportFailure(NS_LITERAL_CSTRING("LayerManagerD3D10::PaintToTarget(): Failed to create texture"),
                   hr);
     return;
   }
 
   device()->CopyResource(readTexture, backBuf);
 
--- a/gfx/layers/d3d10/LayerManagerD3D10.h
+++ b/gfx/layers/d3d10/LayerManagerD3D10.h
@@ -173,17 +173,17 @@ private:
   CallbackInfo mCurrentCallbackInfo;
 
   nsIntSize mViewport;
 
   /* Nv3DVUtils instance */ 
   nsAutoPtr<Nv3DVUtils> mNv3DVUtils; 
 
   /*
-   * Context target, NULL when drawing directly to our swap chain.
+   * Context target, nullptr when drawing directly to our swap chain.
    */
   nsRefPtr<gfxContext> mTarget;
 
   /*
    * Copies the content of our backbuffer to the set transaction target.
    */
   void PaintToTarget();
 };
--- a/gfx/layers/d3d10/ReadbackLayerD3D10.h
+++ b/gfx/layers/d3d10/ReadbackLayerD3D10.h
@@ -13,17 +13,17 @@ namespace mozilla {
 namespace layers {
 
 class ReadbackLayerD3D10 :
   public ReadbackLayer,
   public LayerD3D10
 {
 public:
     ReadbackLayerD3D10(LayerManagerD3D10 *aManager)
-    : ReadbackLayer(aManager, NULL),
+    : ReadbackLayer(aManager, nullptr),
       LayerD3D10(aManager)
   {
       mImplData = static_cast<LayerD3D10*>(this);
   }
 
   virtual Layer* GetLayer() { return this; }
   virtual void RenderLayer() {}
 };
--- a/gfx/layers/d3d10/ReadbackManagerD3D10.cpp
+++ b/gfx/layers/d3d10/ReadbackManagerD3D10.cpp
@@ -103,19 +103,19 @@ DWORD WINAPI StartTaskThread(void *aMana
 
   return 0;
 }
 
 ReadbackManagerD3D10::ReadbackManagerD3D10()
   : mRefCnt(0)
 {
   ::InitializeCriticalSection(&mTaskMutex);
-  mShutdownEvent = ::CreateEventA(NULL, FALSE, FALSE, NULL);
-  mTaskSemaphore = ::CreateSemaphoreA(NULL, 0, 1000000, NULL);
-  mTaskThread = ::CreateThread(NULL, 0, StartTaskThread, this, 0, 0);
+  mShutdownEvent = ::CreateEventA(nullptr, FALSE, FALSE, nullptr);
+  mTaskSemaphore = ::CreateSemaphoreA(nullptr, 0, 1000000, nullptr);
+  mTaskThread = ::CreateThread(nullptr, 0, StartTaskThread, this, 0, 0);
 }
 
 ReadbackManagerD3D10::~ReadbackManagerD3D10()
 {
   ::SetEvent(mShutdownEvent);
 
   // This shouldn't take longer than 5 seconds, if it does we're going to choose
   // to leak the thread and its synchronisation in favor of crashing or freezing
@@ -139,17 +139,17 @@ ReadbackManagerD3D10::PostTask(ID3D10Tex
   task->mOrigin = aOrigin;
   task->mLayer = task->mUpdate.mLayer;
   task->mBackgroundOffset = task->mLayer->GetBackgroundLayerOffset();
 
   ::EnterCriticalSection(&mTaskMutex);
   mPendingReadbackTasks.AppendElement(task);
   ::LeaveCriticalSection(&mTaskMutex);
 
-  ::ReleaseSemaphore(mTaskSemaphore, 1, NULL);
+  ::ReleaseSemaphore(mTaskSemaphore, 1, nullptr);
 }
 
 HRESULT
 ReadbackManagerD3D10::QueryInterface(REFIID riid, void **ppvObject)
 {
   if (!ppvObject) {
     return E_POINTER;
   }
--- a/gfx/layers/d3d10/ThebesLayerD3D10.cpp
+++ b/gfx/layers/d3d10/ThebesLayerD3D10.cpp
@@ -27,17 +27,17 @@
 #include "mozilla/gfx/2D.h"
 
 using namespace mozilla::gfx;
 
 namespace mozilla {
 namespace layers {
 
 ThebesLayerD3D10::ThebesLayerD3D10(LayerManagerD3D10 *aManager)
-  : ThebesLayer(aManager, NULL)
+  : ThebesLayer(aManager, nullptr)
   , LayerD3D10(aManager)
   , mCurrentSurfaceMode(SURFACE_OPAQUE)
 {
   mImplData = static_cast<LayerD3D10*>(this);
 }
 
 ThebesLayerD3D10::~ThebesLayerD3D10()
 {
@@ -245,17 +245,17 @@ ThebesLayerD3D10::Validate(ReadbackProce
 
     if (readbackUpdates.Length() > 0) {
       CD3D10_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM,
                                  newTextureRect.width, newTextureRect.height,
                                  1, 1, 0, D3D10_USAGE_STAGING,
                                  D3D10_CPU_ACCESS_READ);
 
       nsRefPtr<ID3D10Texture2D> readbackTexture;
-      HRESULT hr = device()->CreateTexture2D(&desc, NULL, getter_AddRefs(readbackTexture));
+      HRESULT hr = device()->CreateTexture2D(&desc, nullptr, getter_AddRefs(readbackTexture));
       if (FAILED(hr)) {
         LayerManagerD3D10::ReportFailure(NS_LITERAL_CSTRING("ThebesLayerD3D10::Validate(): Failed to create texture"),
                                          hr);
         return;
       }
 
       device()->CopyResource(readbackTexture, mTexture);
 
@@ -328,22 +328,22 @@ ThebesLayerD3D10::VerifyContentType(Surf
 void
 ThebesLayerD3D10::FillTexturesBlackWhite(const nsIntRegion& aRegion, const nsIntPoint& aOffset)
 {
   if (mTexture && mTextureOnWhite) {
     // It would be more optimal to draw the actual geometry, but more code
     // and probably not worth the win here as this will often be a single
     // rect.
     nsRefPtr<ID3D10RenderTargetView> oldRT;
-    device()->OMGetRenderTargets(1, getter_AddRefs(oldRT), NULL);
+    device()->OMGetRenderTargets(1, getter_AddRefs(oldRT), nullptr);
 
     nsRefPtr<ID3D10RenderTargetView> viewBlack;
     nsRefPtr<ID3D10RenderTargetView> viewWhite;
-    device()->CreateRenderTargetView(mTexture, NULL, getter_AddRefs(viewBlack));
-    device()->CreateRenderTargetView(mTextureOnWhite, NULL, getter_AddRefs(viewWhite));
+    device()->CreateRenderTargetView(mTexture, nullptr, getter_AddRefs(viewBlack));
+    device()->CreateRenderTargetView(mTextureOnWhite, nullptr, getter_AddRefs(viewWhite));
 
     D3D10_RECT oldScissor;
     UINT numRects = 1;
     device()->RSGetScissorRects(&numRects, &oldScissor);
 
     D3D10_TEXTURE2D_DESC desc;
     mTexture->GetDesc(&desc);
 
@@ -351,17 +351,17 @@ ThebesLayerD3D10::FillTexturesBlackWhite
     device()->RSSetScissorRects(1, &scissor);
 
     mD3DManager->SetupInputAssembler();
     nsIntSize oldVP = mD3DManager->GetViewport();
 
     mD3DManager->SetViewport(nsIntSize(desc.Width, desc.Height));
 
     ID3D10RenderTargetView *views[2] = { viewBlack, viewWhite };
-    device()->OMSetRenderTargets(2, views, NULL);
+    device()->OMSetRenderTargets(2, views, nullptr);
 
     gfx3DMatrix transform;
     transform.Translate(gfxPoint3D(-aOffset.x, -aOffset.y, 0));
     void* raw = &const_cast<gfx3DMatrix&>(transform)._11;
     effect()->GetVariableByName("mLayerTransform")->SetRawValue(raw, 0, 64);
 
     ID3D10EffectTechnique *technique =
       effect()->GetTechniqueByName("PrepareAlphaExtractionTextures");
@@ -378,17 +378,17 @@ ThebesLayerD3D10::FillTexturesBlackWhite
           (float)iterRect->height)
         );
 
       technique->GetPassByIndex(0)->Apply(0);
       device()->Draw(4, 0);
     }
 
     views[0] = oldRT;
-    device()->OMSetRenderTargets(1, views, NULL);
+    device()->OMSetRenderTargets(1, views, nullptr);
     mD3DManager->SetViewport(oldVP);
     device()->RSSetScissorRects(1, &oldScissor);
   }
 }
 
 void
 ThebesLayerD3D10::DrawRegion(nsIntRegion &aRegion, SurfaceMode aMode)
 {
@@ -459,52 +459,52 @@ ThebesLayerD3D10::CreateNewTextures(cons
   }
 
   CD3D10_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM, aSize.width, aSize.height, 1, 1);
   desc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;
   desc.MiscFlags = D3D10_RESOURCE_MISC_GDI_COMPATIBLE;
   HRESULT hr;
 
   if (!mTexture) {
-    hr = device()->CreateTexture2D(&desc, NULL, getter_AddRefs(mTexture));
+    hr = device()->CreateTexture2D(&desc, nullptr, getter_AddRefs(mTexture));
 
     if (FAILED(hr)) {
       NS_WARNING("Failed to create new texture for ThebesLayerD3D10!");
       return;
     }
 
-    hr = device()->CreateShaderResourceView(mTexture, NULL, getter_AddRefs(mSRView));
+    hr = device()->CreateShaderResourceView(mTexture, nullptr, getter_AddRefs(mSRView));
 
     if (FAILED(hr)) {
       NS_WARNING("Failed to create shader resource view for ThebesLayerD3D10.");
     }
 
     if (!gfxPlatform::GetPlatform()->SupportsAzureContent()) {
       mD2DSurface = new gfxD2DSurface(mTexture, aMode != SURFACE_SINGLE_CHANNEL_ALPHA ?
                                                 gfxASurface::CONTENT_COLOR : gfxASurface::CONTENT_COLOR_ALPHA);
 
       if (!mD2DSurface || mD2DSurface->CairoStatus()) {
         NS_WARNING("Failed to create surface for ThebesLayerD3D10.");
-        mD2DSurface = NULL;
+        mD2DSurface = nullptr;
         return;
       }
     } else {
       mDrawTarget = nullptr;
     }
   }
 
   if (aMode == SURFACE_COMPONENT_ALPHA && !mTextureOnWhite) {
-    hr = device()->CreateTexture2D(&desc, NULL, getter_AddRefs(mTextureOnWhite));
+    hr = device()->CreateTexture2D(&desc, nullptr, getter_AddRefs(mTextureOnWhite));
 
     if (FAILED(hr)) {
       NS_WARNING("Failed to create new texture for ThebesLayerD3D10!");
       return;
     }
 
-    hr = device()->CreateShaderResourceView(mTextureOnWhite, NULL, getter_AddRefs(mSRViewOnWhite));
+    hr = device()->CreateShaderResourceView(mTextureOnWhite, nullptr, getter_AddRefs(mSRViewOnWhite));
 
     if (FAILED(hr)) {
       NS_WARNING("Failed to create shader resource view for ThebesLayerD3D10.");
     }
 
     if (!gfxPlatform::GetPlatform()->SupportsAzureContent()) {
       mD2DSurfaceOnWhite = new gfxD2DSurface(mTextureOnWhite, gfxASurface::CONTENT_COLOR);
 
--- a/gfx/layers/d3d11/CompositorD3D11.cpp
+++ b/gfx/layers/d3d11/CompositorD3D11.cpp
@@ -75,17 +75,17 @@ CompositorD3D11::~CompositorD3D11()
     mDevice->SetPrivateData(sLayerManagerCount, sizeof(referenceCount), &referenceCount);
 
     if (!referenceCount) {
       DeviceAttachmentsD3D11 *attachments;
       size = sizeof(attachments);
       mDevice->GetPrivateData(sDeviceAttachmentsD3D11, &size, &attachments);
       // No LayerManagers left for this device. Clear out interfaces stored which
       // hold a reference to the device.
-      mDevice->SetPrivateData(sDeviceAttachmentsD3D11, 0, NULL);
+      mDevice->SetPrivateData(sDeviceAttachmentsD3D11, 0, nullptr);
 
       delete attachments;
     }
   }
 }
 
 bool
 CompositorD3D11::Initialize()
@@ -333,17 +333,17 @@ CompositorD3D11::GetMaxTextureSize() con
 TemporaryRef<CompositingRenderTarget>
 CompositorD3D11::CreateRenderTarget(const gfx::IntRect &aRect,
                                     SurfaceInitMode aInit)
 {
   CD3D11_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM, aRect.width, aRect.height, 1, 1,
                              D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET);
 
   RefPtr<ID3D11Texture2D> texture;
-  mDevice->CreateTexture2D(&desc, NULL, byRef(texture));
+  mDevice->CreateTexture2D(&desc, nullptr, byRef(texture));
 
   RefPtr<CompositingRenderTargetD3D11> rt = new CompositingRenderTargetD3D11(texture);
   rt->SetSize(IntSize(aRect.width, aRect.height));
 
   if (aInit == INIT_MODE_CLEAR) {
     FLOAT clear[] = { 0, 0, 0, 0 };
     mContext->ClearRenderTargetView(rt->mRTView, clear);
   }
@@ -355,17 +355,17 @@ CompositorD3D11::CreateRenderTarget(cons
 TemporaryRef<CompositingRenderTarget>
 CompositorD3D11::CreateRenderTargetFromSource(const gfx::IntRect &aRect,
                                               const CompositingRenderTarget *aSource)
 {
   CD3D11_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM, aRect.width, aRect.height, 1, 1,
                              D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET);
 
   RefPtr<ID3D11Texture2D> texture;
-  mDevice->CreateTexture2D(&desc, NULL, byRef(texture));
+  mDevice->CreateTexture2D(&desc, nullptr, byRef(texture));
 
   RefPtr<CompositingRenderTargetD3D11> rt = new CompositingRenderTargetD3D11(texture);
   rt->SetSize(IntSize(aRect.width, aRect.height));
 
   return rt;
 }
 
 void
@@ -653,17 +653,17 @@ CompositorD3D11::UpdateRenderTarget()
   nsRefPtr<ID3D11Texture2D> backBuf;
 
   hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)backBuf.StartAssignment());
   if (FAILED(hr)) {
     return;
   }
 
   mDefaultRT = new CompositingRenderTargetD3D11(nullptr);
-  mDevice->CreateRenderTargetView(backBuf, NULL, byRef(mDefaultRT->mRTView));
+  mDevice->CreateRenderTargetView(backBuf, nullptr, byRef(mDefaultRT->mRTView));
 }
 
 bool
 CompositorD3D11::CreateShaders()
 {
   HRESULT hr;
 
 
@@ -754,17 +754,17 @@ CompositorD3D11::PaintToTarget()
   CD3D11_TEXTURE2D_DESC softDesc(bbDesc.Format, bbDesc.Width, bbDesc.Height);
   softDesc.MipLevels = 1;
   softDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
   softDesc.Usage = D3D11_USAGE_STAGING;
   softDesc.BindFlags = 0;
 
   nsRefPtr<ID3D11Texture2D> readTexture;
 
-  HRESULT hr = mDevice->CreateTexture2D(&softDesc, NULL, getter_AddRefs(readTexture));
+  HRESULT hr = mDevice->CreateTexture2D(&softDesc, nullptr, getter_AddRefs(readTexture));
   mContext->CopyResource(readTexture, backBuf);
 
   D3D11_MAPPED_SUBRESOURCE map;
   mContext->Map(readTexture, 0, D3D11_MAP_READ, 0, &map);
 
   nsRefPtr<gfxImageSurface> tmpSurface =
     new gfxImageSurface((unsigned char*)map.pData,
                         gfxIntSize(bbDesc.Width, bbDesc.Height),
--- a/gfx/layers/d3d11/TextureD3D11.cpp
+++ b/gfx/layers/d3d11/TextureD3D11.cpp
@@ -45,17 +45,17 @@ CompositingRenderTargetD3D11::Compositin
     return;
   }
   
   mTextures[0] = aTexture;
 
   RefPtr<ID3D11Device> device;
   mTextures[0]->GetDevice(byRef(device));
 
-  HRESULT hr = device->CreateRenderTargetView(mTextures[0], NULL, byRef(mRTView));
+  HRESULT hr = device->CreateRenderTargetView(mTextures[0], nullptr, byRef(mRTView));
 
   if (FAILED(hr)) {
     LOGD3D11("Failed to create RenderTargetView.");
   }
 }
 
 IntSize
 CompositingRenderTargetD3D11::GetSize() const
@@ -244,17 +244,17 @@ DeprecatedTextureClientD3D11::ReleaseTex
 
   mutex->ReleaseSync(0);
   mIsLocked = false;
 }
 
 void
 DeprecatedTextureClientD3D11::ClearDT()
 {
-  // An Azure DrawTarget needs to be locked when it gets NULL'ed as this is
+  // An Azure DrawTarget needs to be locked when it gets nullptr'ed as this is
   // when it calls EndDraw. This EndDraw should not execute anything so it
   // shouldn't -really- need the lock but the debug layer chokes on this.
   //
   // Perhaps this should be debug only.
   if (mDrawTarget) {
     LockTexture();
     mDrawTarget = nullptr;
     ReleaseTexture();
--- a/gfx/layers/d3d9/CanvasLayerD3D9.cpp
+++ b/gfx/layers/d3d9/CanvasLayerD3D9.cpp
@@ -237,23 +237,23 @@ CanvasLayerD3D9::LayerManagerDestroyed()
 
 void
 CanvasLayerD3D9::CreateTexture()
 {
   HRESULT hr;
   if (mD3DManager->deviceManager()->HasDynamicTextures()) {
     hr = device()->CreateTexture(mBounds.width, mBounds.height, 1, D3DUSAGE_DYNAMIC,
                                  D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT,
-                                 getter_AddRefs(mTexture), NULL);
+                                 getter_AddRefs(mTexture), nullptr);
   } else {
     // D3DPOOL_MANAGED is fine here since we require Dynamic Textures for D3D9Ex
     // devices.
     hr = device()->CreateTexture(mBounds.width, mBounds.height, 1, 0,
                                  D3DFMT_A8R8G8B8, D3DPOOL_MANAGED,
-                                 getter_AddRefs(mTexture), NULL);
+                                 getter_AddRefs(mTexture), nullptr);
   }
   if (FAILED(hr)) {
     mD3DManager->ReportFailure(NS_LITERAL_CSTRING("CanvasLayerD3D9::CreateTexture() failed"),
                                  hr);
     return;
   }
 }
 
--- a/gfx/layers/d3d9/CanvasLayerD3D9.h
+++ b/gfx/layers/d3d9/CanvasLayerD3D9.h
@@ -15,17 +15,17 @@ namespace layers {
 
 
 class CanvasLayerD3D9 :
   public CanvasLayer,
   public LayerD3D9
 {
 public:
   CanvasLayerD3D9(LayerManagerD3D9 *aManager)
-    : CanvasLayer(aManager, NULL)
+    : CanvasLayer(aManager, nullptr)
     , LayerD3D9(aManager)
     , mDataIsPremultiplied(false)
     , mNeedsYFlip(false)
     , mHasAlpha(true)
   {
       mImplData = static_cast<LayerD3D9*>(this);
       aManager->deviceManager()->mLayersWithResources.AppendElement(this);
   }
--- a/gfx/layers/d3d9/ColorLayerD3D9.h
+++ b/gfx/layers/d3d9/ColorLayerD3D9.h
@@ -11,17 +11,17 @@
 namespace mozilla {
 namespace layers {
 
 class ColorLayerD3D9 : public ColorLayer,
                        public LayerD3D9
 {
 public:
   ColorLayerD3D9(LayerManagerD3D9 *aManager)
-    : ColorLayer(aManager, NULL)
+    : ColorLayer(aManager, nullptr)
     , LayerD3D9(aManager)
   {
     mImplData = static_cast<LayerD3D9*>(this);
   }
 
   // LayerD3D9 Implementation
   virtual Layer* GetLayer();
 
--- a/gfx/layers/d3d9/ContainerLayerD3D9.cpp
+++ b/gfx/layers/d3d9/ContainerLayerD3D9.cpp
@@ -186,17 +186,17 @@ ContainerRender(Container* aContainer,
   aContainer->mSupportsComponentAlphaChildren = false;
   if (useIntermediate) {
     nsRefPtr<IDirect3DSurface9> renderSurface;
     if (!aManager->CompositingDisabled()) {
       aManager->device()->GetRenderTarget(0, getter_AddRefs(previousRenderTarget));
       HRESULT hr = aManager->device()->CreateTexture(visibleRect.width, visibleRect.height, 1,
                                                      D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8,
                                                      D3DPOOL_DEFAULT, getter_AddRefs(renderTexture),
-                                                     NULL);
+                                                     nullptr);
       if (FAILED(hr)) {
         aManager->ReportFailure(NS_LITERAL_CSTRING("ContainerLayerD3D9::ContainerRender(): Failed to create texture"),
                                 hr);
         return;
       }
 
       nsRefPtr<IDirect3DSurface9> renderSurface;
       renderTexture->GetSurfaceLevel(0, getter_AddRefs(renderSurface));
@@ -319,17 +319,17 @@ ContainerRender(Container* aContainer,
     aManager->device()->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
   } else {
     aManager->device()->SetScissorRect(&containerD3D9ClipRect);
   }
 }
 
 
 ContainerLayerD3D9::ContainerLayerD3D9(LayerManagerD3D9 *aManager)
-  : ContainerLayer(aManager, NULL)
+  : ContainerLayer(aManager, nullptr)
   , LayerD3D9(aManager)
 {
   mImplData = static_cast<LayerD3D9*>(this);
 }
 
 ContainerLayerD3D9::~ContainerLayerD3D9()
 {
   while (mFirstChild) {
--- a/gfx/layers/d3d9/DeviceManagerD3D9.cpp
+++ b/gfx/layers/d3d9/DeviceManagerD3D9.cpp
@@ -165,30 +165,30 @@ NS_IMPL_ADDREF(DeviceManagerD3D9)
 NS_IMPL_RELEASE(DeviceManagerD3D9)
 
 bool
 DeviceManagerD3D9::Init()
 {
   WNDCLASSW wc;
   HRESULT hr;
 
-  if (!GetClassInfoW(GetModuleHandle(NULL), kClassName, &wc)) {
+  if (!GetClassInfoW(GetModuleHandle(nullptr), kClassName, &wc)) {
       ZeroMemory(&wc, sizeof(WNDCLASSW));
-      wc.hInstance = GetModuleHandle(NULL);
+      wc.hInstance = GetModuleHandle(nullptr);
       wc.lpfnWndProc = ::DefWindowProc;
       wc.lpszClassName = kClassName;
       if (!RegisterClassW(&wc)) {
           NS_WARNING("Failed to register window class for DeviceManager.");
           return false;
       }
   }
 
   mFocusWnd = ::CreateWindowW(kClassName, L"D3D9Window", WS_OVERLAPPEDWINDOW,
-                              CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL,
-                              NULL, GetModuleHandle(NULL), NULL);
+                              CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr,
+                              nullptr, GetModuleHandle(nullptr), nullptr);
 
   if (!mFocusWnd) {
     NS_WARNING("Failed to create DeviceManagerD3D9 Window.");
     return false;
   }
 
   /* Create an Nv3DVUtils instance */ 
   if (!mNv3DVUtils) { 
@@ -257,17 +257,17 @@ DeviceManagerD3D9::Init()
   if (mD3D9Ex) {
     hr = mD3D9Ex->CreateDeviceEx(D3DADAPTER_DEFAULT,
                                  D3DDEVTYPE_HAL,
                                  mFocusWnd,
                                  D3DCREATE_FPU_PRESERVE |
                                  D3DCREATE_MULTITHREADED |
                                  D3DCREATE_MIXED_VERTEXPROCESSING,
                                  &pp,
-                                 NULL,
+                                 nullptr,
                                  getter_AddRefs(mDeviceEx));
     if (SUCCEEDED(hr)) {
       mDevice = mDeviceEx;
     }
 
     D3DCAPS9 caps;
     if (mDeviceEx && mDeviceEx->GetDeviceCaps(&caps)) {
       if (LACKS_CAP(caps.Caps2, D3DCAPS2_DYNAMICTEXTURES)) {
@@ -308,17 +308,17 @@ DeviceManagerD3D9::Init()
     return false;
   mDeviceMonitor = mD3D9->GetAdapterMonitor(parameters.AdapterOrdinal);
 
 
   /* 
    * Do some post device creation setup 
    */ 
   if (mNv3DVUtils) { 
-    IUnknown* devUnknown = NULL; 
+    IUnknown* devUnknown = nullptr; 
     if (mDevice) { 
       mDevice->QueryInterface(IID_IUnknown, (void **)&devUnknown); 
     } 
     mNv3DVUtils->SetDeviceInfo(devUnknown); 
   } 
 
   hr = mDevice->CreateVertexShader((DWORD*)LayerQuadVS,
                                    getter_AddRefs(mLayerVS));
@@ -781,17 +781,17 @@ DeviceManagerD3D9::CreateVertexBuffer()
 {
   HRESULT hr;
 
   hr = mDevice->CreateVertexBuffer(sizeof(vertex) * 4,
                                    D3DUSAGE_WRITEONLY,
                                    0,
                                    D3DPOOL_DEFAULT,
                                    getter_AddRefs(mVB),
-                                   NULL);
+                                   nullptr);
 
   if (FAILED(hr)) {
     return false;
   }
 
   vertex *vertices;
   hr = mVB->Lock(0, 0, (void**)&vertices, 0);
   if (FAILED(hr)) {
--- a/gfx/layers/d3d9/ImageLayerD3D9.cpp
+++ b/gfx/layers/d3d9/ImageLayerD3D9.cpp
@@ -46,61 +46,61 @@ DataToTexture(IDirect3DDevice9 *aDevice,
   D3DLOCKED_RECT lockedRect;
   if (deviceEx) {
     // D3D9Ex doesn't support managed textures. We could use dynamic textures
     // here but since Images are immutable that probably isn't such a great
     // idea.
     if (FAILED(aDevice->
                CreateTexture(aSize.width, aSize.height,
                              1, 0, aFormat, D3DPOOL_DEFAULT,
-                             getter_AddRefs(texture), NULL)))
+                             getter_AddRefs(texture), nullptr)))
     {
-      return NULL;
+      return nullptr;
     }
 
     nsRefPtr<IDirect3DTexture9> tmpTexture;
     if (FAILED(aDevice->
                CreateTexture(aSize.width, aSize.height,
                              1, 0, aFormat, D3DPOOL_SYSTEMMEM,
-                             getter_AddRefs(tmpTexture), NULL)))
+                             getter_AddRefs(tmpTexture), nullptr)))
     {
-      return NULL;
+      return nullptr;
     }
 
     tmpTexture->GetSurfaceLevel(0, getter_AddRefs(surface));
-    surface->LockRect(&lockedRect, NULL, 0);
+    surface->LockRect(&lockedRect, nullptr, 0);
     NS_ASSERTION(lockedRect.pBits, "Could not lock surface");
   } else {
     if (FAILED(aDevice->
                CreateTexture(aSize.width, aSize.height,
                              1, 0, aFormat, D3DPOOL_MANAGED,
-                             getter_AddRefs(texture), NULL)))
+                             getter_AddRefs(texture), nullptr)))
     {
-      return NULL;
+      return nullptr;
     }
 
     /* lock the entire texture */
-    texture->LockRect(0, &lockedRect, NULL, 0);
+    texture->LockRect(0, &lockedRect, nullptr, 0);
   }
 
   uint32_t width = aSize.width;
   if (aFormat == D3DFMT_A8R8G8B8) {
     width *= 4;
   }
   for (int y = 0; y < aSize.height; y++) {
     memcpy((char*)lockedRect.pBits + lockedRect.Pitch * y,
             aData + aStride * y,
             width);
   }
 
   if (deviceEx) {
     surface->UnlockRect();
     nsRefPtr<IDirect3DSurface9> dstSurface;
     texture->GetSurfaceLevel(0, getter_AddRefs(dstSurface));
-    aDevice->UpdateSurface(surface, NULL, dstSurface, NULL);
+    aDevice->UpdateSurface(surface, nullptr, dstSurface, nullptr);
   } else {
     texture->UnlockRect(0);
   }
 
   return texture.forget();
 }
 
 static already_AddRefed<IDirect3DTexture9>
@@ -180,81 +180,81 @@ static void AllocateTexturesYCbCr(Planar
     nsRefPtr<IDirect3DTexture9> tmpCrTexture;
     // D3D9Ex does not support the managed pool, could use dynamic textures
     // here. But since an Image is immutable static textures are probably a
     // better idea.
 
     HRESULT hr;
     hr = aDevice->CreateTexture(data->mYSize.width, data->mYSize.height,
                                 1, 0, D3DFMT_L8, D3DPOOL_DEFAULT,
-                                getter_AddRefs(backendData->mYTexture), NULL);
+                                getter_AddRefs(backendData->mYTexture), nullptr);
     if (!FAILED(hr)) {
       hr = aDevice->CreateTexture(data->mCbCrSize.width, data->mCbCrSize.height,
                                   1, 0, D3DFMT_L8, D3DPOOL_DEFAULT,
-                                  getter_AddRefs(backendData->mCbTexture), NULL);
+                                  getter_AddRefs(backendData->mCbTexture), nullptr);
     }
     if (!FAILED(hr)) {
       hr = aDevice->CreateTexture(data->mCbCrSize.width, data->mCbCrSize.height,
                                   1, 0, D3DFMT_L8, D3DPOOL_DEFAULT,
-                                  getter_AddRefs(backendData->mCrTexture), NULL);
+                                  getter_AddRefs(backendData->mCrTexture), nullptr);
     }
     if (!FAILED(hr)) {
       hr = aDevice->CreateTexture(data->mYSize.width, data->mYSize.height,
                                   1, 0, D3DFMT_L8, D3DPOOL_SYSTEMMEM,
-                                  getter_AddRefs(tmpYTexture), NULL);
+                                  getter_AddRefs(tmpYTexture), nullptr);
     }
     if (!FAILED(hr)) {
       hr = aDevice->CreateTexture(data->mCbCrSize.width, data->mCbCrSize.height,
                                   1, 0, D3DFMT_L8, D3DPOOL_SYSTEMMEM,
-                                  getter_AddRefs(tmpCbTexture), NULL);
+                                  getter_AddRefs(tmpCbTexture), nullptr);
     }
     if (!FAILED(hr)) {
       hr = aDevice->CreateTexture(data->mCbCrSize.width, data->mCbCrSize.height,
                                   1, 0, D3DFMT_L8, D3DPOOL_SYSTEMMEM,
-                                  getter_AddRefs(tmpCrTexture), NULL);
+                                  getter_AddRefs(tmpCrTexture), nullptr);
     }
 
     if (FAILED(hr)) {
       aManager->ReportFailure(NS_LITERAL_CSTRING("PlanarYCbCrImageD3D9::AllocateTextures(): Failed to create texture (isD3D9Ex)"),
                               hr);
       return;
     }
 
     tmpYTexture->GetSurfaceLevel(0, getter_AddRefs(tmpSurfaceY));
     tmpCbTexture->GetSurfaceLevel(0, getter_AddRefs(tmpSurfaceCb));
     tmpCrTexture->GetSurfaceLevel(0, getter_AddRefs(tmpSurfaceCr));
-    tmpSurfaceY->LockRect(&lockrectY, NULL, 0);
-    tmpSurfaceCb->LockRect(&lockrectCb, NULL, 0);
-    tmpSurfaceCr->LockRect(&lockrectCr, NULL, 0);
+    tmpSurfaceY->LockRect(&lockrectY, nullptr, 0);
+    tmpSurfaceCb->LockRect(&lockrectCb, nullptr, 0);
+    tmpSurfaceCr->LockRect(&lockrectCr, nullptr, 0);
   } else {
     HRESULT hr;
     hr = aDevice->CreateTexture(data->mYSize.width, data->mYSize.height,
                                 1, 0, D3DFMT_L8, D3DPOOL_MANAGED,
-                                getter_AddRefs(backendData->mYTexture), NULL);
+                                getter_AddRefs(backendData->mYTexture), nullptr);
     if (!FAILED(hr)) {
       aDevice->CreateTexture(data->mCbCrSize.width, data->mCbCrSize.height,
                              1, 0, D3DFMT_L8, D3DPOOL_MANAGED,
-                             getter_AddRefs(backendData->mCbTexture), NULL);
+                             getter_AddRefs(backendData->mCbTexture), nullptr);
     }
     if (!FAILED(hr)) {
       aDevice->CreateTexture(data->mCbCrSize.width, data->mCbCrSize.height,
                              1, 0, D3DFMT_L8, D3DPOOL_MANAGED,
-                             getter_AddRefs(backendData->mCrTexture), NULL);
+                             getter_AddRefs(backendData->mCrTexture), nullptr);
     }
 
     if (FAILED(hr)) {
       aManager->ReportFailure(NS_LITERAL_CSTRING("PlanarYCbCrImageD3D9::AllocateTextures(): Failed to create texture (!isD3D9Ex)"),
                               hr);
       return;
     }
 
     /* lock the entire texture */
-    backendData->mYTexture->LockRect(0, &lockrectY, NULL, 0);
-    backendData->mCbTexture->LockRect(0, &lockrectCb, NULL, 0);
-    backendData->mCrTexture->LockRect(0, &lockrectCr, NULL, 0);
+    backendData->mYTexture->LockRect(0, &lockrectY, nullptr, 0);
+    backendData->mCbTexture->LockRect(0, &lockrectCb, nullptr, 0);
+    backendData->mCrTexture->LockRect(0, &lockrectCr, nullptr, 0);
   }
 
   src  = data->mYChannel;
   //FIX cast
   dest = (uint8_t*)lockrectY.pBits;
 
   // copy over data
   for (int h=0; h<data->mYSize.height; h++) {
@@ -286,21 +286,21 @@ static void AllocateTexturesYCbCr(Planar
   }
 
   if (isD3D9Ex) {
     tmpSurfaceY->UnlockRect();
     tmpSurfaceCb->UnlockRect();
     tmpSurfaceCr->UnlockRect();
     nsRefPtr<IDirect3DSurface9> dstSurface;
     backendData->mYTexture->GetSurfaceLevel(0, getter_AddRefs(dstSurface));
-    aDevice->UpdateSurface(tmpSurfaceY, NULL, dstSurface, NULL);
+    aDevice->UpdateSurface(tmpSurfaceY, nullptr, dstSurface, nullptr);
     backendData->mCbTexture->GetSurfaceLevel(0, getter_AddRefs(dstSurface));
-    aDevice->UpdateSurface(tmpSurfaceCb, NULL, dstSurface, NULL);
+    aDevice->UpdateSurface(tmpSurfaceCb, nullptr, dstSurface, nullptr);
     backendData->mCrTexture->GetSurfaceLevel(0, getter_AddRefs(dstSurface));
-    aDevice->UpdateSurface(tmpSurfaceCr, NULL, dstSurface, NULL);
+    aDevice->UpdateSurface(tmpSurfaceCr, nullptr, dstSurface, nullptr);
   } else {
     backendData->mYTexture->UnlockRect(0);
     backendData->mCbTexture->UnlockRect(0);
     backendData->mCrTexture->UnlockRect(0);
   }
 
   aImage->SetBackendData(mozilla::layers::LAYERS_D3D9, backendData.forget());
 }
--- a/gfx/layers/d3d9/ImageLayerD3D9.h
+++ b/gfx/layers/d3d9/ImageLayerD3D9.h
@@ -14,17 +14,17 @@
 namespace mozilla {
 namespace layers {
 
 class ImageLayerD3D9 : public ImageLayer,
                        public LayerD3D9
 {
 public:
   ImageLayerD3D9(LayerManagerD3D9 *aManager)
-    : ImageLayer(aManager, NULL)
+    : ImageLayer(aManager, nullptr)
     , LayerD3D9(aManager)
   {
     mImplData = static_cast<LayerD3D9*>(this);
   }
 
   // LayerD3D9 Implementation
   virtual Layer* GetLayer();
 
--- a/gfx/layers/d3d9/LayerManagerD3D9.cpp
+++ b/gfx/layers/d3d9/LayerManagerD3D9.cpp
@@ -23,18 +23,18 @@ namespace mozilla {
 namespace layers {
 
 DeviceManagerD3D9 *LayerManagerD3D9::mDefaultDeviceManager = nullptr;
 
 LayerManagerD3D9::LayerManagerD3D9(nsIWidget *aWidget)
   : mWidget(aWidget)
   , mDeviceResetCount(0)
 {
-  mCurrentCallbackInfo.Callback = NULL;
-  mCurrentCallbackInfo.CallbackData = NULL;
+  mCurrentCallbackInfo.Callback = nullptr;
+  mCurrentCallbackInfo.CallbackData = nullptr;
 }
 
 LayerManagerD3D9::~LayerManagerD3D9()
 {
   Destroy();
 }
 
 bool
@@ -158,22 +158,22 @@ LayerManagerD3D9::EndTransaction(DrawThe
 
     // The results of our drawing always go directly into a pixel buffer,
     // so we don't need to pass any global transform here.
     mRoot->ComputeEffectiveTransforms(gfx3DMatrix());
 
     SetCompositingDisabled(aFlags & END_NO_COMPOSITE);
     Render();
     /* Clean this out for sanity */
-    mCurrentCallbackInfo.Callback = NULL;
-    mCurrentCallbackInfo.CallbackData = NULL;
+    mCurrentCallbackInfo.Callback = nullptr;
+    mCurrentCallbackInfo.CallbackData = nullptr;
   }
 
   // Clear mTarget, next transaction could have no target
-  mTarget = NULL;
+  mTarget = nullptr;
 }
 
 void
 LayerManagerD3D9::SetRoot(Layer *aLayer)
 {
   mRoot = aLayer;
 }
 
@@ -250,17 +250,17 @@ LayerManagerD3D9::Render()
   if (CompositingDisabled()) {
     static_cast<LayerD3D9*>(mRoot->ImplData())->RenderLayer();
     return;
   }
 
   nsIntRect rect;
   mWidget->GetClientBounds(rect);
 
-  device()->Clear(0, NULL, D3DCLEAR_TARGET, 0x00000000, 0, 0);
+  device()->Clear(0, nullptr, D3DCLEAR_TARGET, 0x00000000, 0, 0);
 
   device()->BeginScene();
 
   const nsIntRect *clipRect = mRoot->GetClipRect();
   RECT r;
   if (clipRect) {
     r.left = (LONG)clipRect->x;
     r.top = (LONG)clipRect->y;
@@ -336,22 +336,22 @@ LayerManagerD3D9::PaintToTarget()
   nsRefPtr<IDirect3DSurface9> destSurf;
   device()->GetRenderTarget(0, getter_AddRefs(backBuff));
 
   D3DSURFACE_DESC desc;
   backBuff->GetDesc(&desc);
 
   device()->CreateOffscreenPlainSurface(desc.Width, desc.Height,
                                        D3DFMT_A8R8G8B8, D3DPOOL_SYSTEMMEM,
-                                       getter_AddRefs(destSurf), NULL);
+                                       getter_AddRefs(destSurf), nullptr);
 
   device()->GetRenderTargetData(backBuff, destSurf);
 
   D3DLOCKED_RECT rect;
-  destSurf->LockRect(&rect, NULL, D3DLOCK_READONLY);
+  destSurf->LockRect(&rect, nullptr, D3DLOCK_READONLY);
 
   nsRefPtr<gfxImageSurface> imageSurface =
     new gfxImageSurface((unsigned char*)rect.pBits,
                         gfxIntSize(desc.Width, desc.Height),
                         rect.Pitch,
                         gfxASurface::ImageFormatARGB32);
 
   mTarget->SetSource(imageSurface);
--- a/gfx/layers/d3d9/LayerManagerD3D9.h
+++ b/gfx/layers/d3d9/LayerManagerD3D9.h
@@ -147,17 +147,17 @@ public:
     { mDeviceManager->SetShaderMode(aMode, aMask, aIs2D); }
 
   IDirect3DDevice9 *device() const { return mDeviceManager->device(); }
   DeviceManagerD3D9 *deviceManager() const { return mDeviceManager; }
 
   /** 
    * Return pointer to the Nv3DVUtils instance. Re-direct to mDeviceManager.
    */ 
-  Nv3DVUtils *GetNv3DVUtils()  { return mDeviceManager ? mDeviceManager->GetNv3DVUtils() : NULL; } 
+  Nv3DVUtils *GetNv3DVUtils() { return mDeviceManager ? mDeviceManager->GetNv3DVUtils() : nullptr; } 
 
   static void OnDeviceManagerDestroy(DeviceManagerD3D9 *aDeviceManager) {
     if(aDeviceManager == mDefaultDeviceManager)
       mDefaultDeviceManager = nullptr;
   }
 
 #ifdef MOZ_LAYERS_HAVE_LOG
   virtual const char* Name() const { return "D3D9"; }
@@ -177,17 +177,17 @@ private:
 
   /* Swap chain associated with this layer manager */
   nsRefPtr<SwapChainD3D9> mSwapChain;
 
   /* Widget associated with this layer manager */
   nsIWidget *mWidget;
 
   /*
-   * Context target, NULL when drawing directly to our swap chain.
+   * Context target, nullptr when drawing directly to our swap chain.
    */
   nsRefPtr<gfxContext> mTarget;
 
   /* Callback info for current transaction */
   CallbackInfo mCurrentCallbackInfo;
 
   /*
    * Region we're clipping our current drawing to.
@@ -293,17 +293,17 @@ protected:
  * RAII helper for locking D3D9 textures.
  */
 class LockTextureRectD3D9 
 {
 public:
   LockTextureRectD3D9(IDirect3DTexture9* aTexture) 
     : mTexture(aTexture)
   {
-    mLockResult = mTexture->LockRect(0, &mR, NULL, 0);
+    mLockResult = mTexture->LockRect(0, &mR, nullptr, 0);
   }
 
   ~LockTextureRectD3D9()
   {
     mTexture->UnlockRect(0);
   }
 
   bool HasLock() {
--- a/gfx/layers/d3d9/Nv3DVUtils.cpp
+++ b/gfx/layers/d3d9/Nv3DVUtils.cpp
@@ -18,17 +18,17 @@ 0xf98f9bb2, 0xb914, 0x4d44, 0x98, 0xfa, 
 
 namespace mozilla {
 namespace layers {
 
 /**
  * Constructor and Destructor
  */
 Nv3DVUtils::Nv3DVUtils()
-  : m3DVStreaming (NULL)
+  : m3DVStreaming (nullptr)
 {
 }
 
 Nv3DVUtils::~Nv3DVUtils()
 {
   UnInitialize();
 }
 
@@ -55,36 +55,36 @@ Nv3DVUtils::Initialize()
   if (m3DVStreaming) {
     WARNING("Nv3DVStreaming COM object already instantiated.\n");
     return;
   }
 
   /*
    * Create the COM object. If we fail at any stage, just return
    */
-  HRESULT hr = CoCreateInstance(CLSID_NV3DVStreaming, NULL, CLSCTX_INPROC_SERVER, IID_INV3DVStreaming, (void**)(getter_AddRefs(m3DVStreaming)));
+  HRESULT hr = CoCreateInstance(CLSID_NV3DVStreaming, nullptr, CLSCTX_INPROC_SERVER, IID_INV3DVStreaming, (void**)(getter_AddRefs(m3DVStreaming)));
   if (FAILED(hr) || !m3DVStreaming) {
     WARNING("Nv3DVStreaming CoCreateInstance failed (disabled).");
     return;
   }
 
   /*
-   * Initialize the object. Note that m3DVStreaming cannot be NULL at this point.
+   * Initialize the object. Note that m3DVStreaming cannot be nullptr at this point.
    */
   bool bRetVal = m3DVStreaming->Nv3DVInitialize();
 
   if (!bRetVal) {
     WARNING("Nv3DVStreaming Nv3DVInitialize failed!");
     return;
   }
 }
 
 /**
  * Release resources used by the COM Object, and then release 
- * the COM Object (nsRefPtr gets released by setting to NULL) 
+ * the COM Object (nsRefPtr gets released by setting to nullptr) 
  *
  */
 void
 Nv3DVUtils::UnInitialize()
 {
   if (m3DVStreaming) {
     m3DVStreaming->Nv3DVRelease();
   }
@@ -93,17 +93,17 @@ Nv3DVUtils::UnInitialize()
 /**
  * Sets the device info, along with any other initialization that is needed after device creation
  * Pass the D3D9 device pointer is an IUnknown input argument.
  */
 void 
 Nv3DVUtils::SetDeviceInfo(IUnknown *devUnknown)
 {
   if (!devUnknown) {
-    WARNING("D3D Device Pointer (IUnknown) is NULL.\n");
+    WARNING("D3D Device Pointer (IUnknown) is nullptr.\n");
     return;
   }
 
   if (!m3DVStreaming) {
       return;
   }
 
   bool rv = m3DVStreaming->Nv3DVSetDevice(devUnknown);
--- a/gfx/layers/d3d9/ReadbackLayerD3D9.h
+++ b/gfx/layers/d3d9/ReadbackLayerD3D9.h
@@ -13,17 +13,17 @@ namespace mozilla {
 namespace layers {
 
 class ReadbackLayerD3D9 :
   public ReadbackLayer,
   public LayerD3D9
 {
 public:
     ReadbackLayerD3D9(LayerManagerD3D9 *aManager)
-    : ReadbackLayer(aManager, NULL),
+    : ReadbackLayer(aManager, nullptr),
       LayerD3D9(aManager)
   {
       mImplData = static_cast<LayerD3D9*>(this);
   }
 
   virtual Layer* GetLayer() { return this; }
   virtual void RenderLayer() {}
 };
--- a/gfx/layers/d3d9/ThebesLayerD3D9.cpp
+++ b/gfx/layers/d3d9/ThebesLayerD3D9.cpp
@@ -19,17 +19,17 @@
 #include "gfxUtils.h"
 #include "ReadbackProcessor.h"
 #include "ReadbackLayer.h"
 
 namespace mozilla {
 namespace layers {
 
 ThebesLayerD3D9::ThebesLayerD3D9(LayerManagerD3D9 *aManager)
-  : ThebesLayer(aManager, NULL)
+  : ThebesLayer(aManager, nullptr)
   , LayerD3D9(aManager)
 {
   mImplData = static_cast<LayerD3D9*>(this);
   aManager->deviceManager()->mLayersWithResources.AppendElement(this);
 }
 
 ThebesLayerD3D9::~ThebesLayerD3D9()
 {
@@ -256,17 +256,17 @@ ThebesLayerD3D9::RenderThebesLayer(Readb
                                GetMaskLayer());
     device()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
     device()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
     RenderRegion(neededRegion);
 
     // Restore defaults
     device()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
     device()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
-    device()->SetTexture(1, NULL);
+    device()->SetTexture(1, nullptr);
   } else {
     mD3DManager->SetShaderMode(DeviceManagerD3D9::RGBALAYER,
                                GetMaskLayer());
     device()->SetTexture(0, mTexture);
     RenderRegion(neededRegion);
   }
 
   // Set back to default.
@@ -335,17 +335,17 @@ ThebesLayerD3D9::VerifyContentType(Surfa
   mTexture = nullptr;
   mTextureOnWhite = nullptr;
   mValidRegion.SetEmpty();
 }
 
 class OpaqueRenderer {
 public:
   OpaqueRenderer(const nsIntRegion& aUpdateRegion) :
-    mUpdateRegion(aUpdateRegion), mDC(NULL) {}
+    mUpdateRegion(aUpdateRegion), mDC(nullptr) {}
   ~OpaqueRenderer() { End(); }
   already_AddRefed<gfxWindowsSurface> Begin(LayerD3D9* aLayer);
   void End();
   IDirect3DTexture9* GetTexture() { return mTmpTexture; }
 
 private:
   const nsIntRegion& mUpdateRegion;
   nsRefPtr<IDirect3DTexture9> mTmpTexture;
@@ -355,17 +355,17 @@ private:
 
 already_AddRefed<gfxWindowsSurface>
 OpaqueRenderer::Begin(LayerD3D9* aLayer)
 {
   nsIntRect bounds = mUpdateRegion.GetBounds();
 
   HRESULT hr = aLayer->device()->
       CreateTexture(bounds.width, bounds.height, 1, 0, D3DFMT_X8R8G8B8,
-                    D3DPOOL_SYSTEMMEM, getter_AddRefs(mTmpTexture), NULL);
+                    D3DPOOL_SYSTEMMEM, getter_AddRefs(mTmpTexture), nullptr);
 
   if (FAILED(hr)) {
     aLayer->ReportFailure(NS_LITERAL_CSTRING("Failed to create temporary texture in system memory."), hr);
     return nullptr;
   }
 
   hr = mTmpTexture->GetSurfaceLevel(0, getter_AddRefs(mSurface));
 
@@ -385,18 +385,18 @@ OpaqueRenderer::Begin(LayerD3D9* aLayer)
   return result.forget();
 }
 
 void
 OpaqueRenderer::End()
 {
   if (mSurface && mDC) {
     mSurface->ReleaseDC(mDC);
-    mSurface = NULL;
-    mDC = NULL;
+    mSurface = nullptr;
+    mDC = nullptr;
   }
 }
 
 static void
 FillSurface(gfxASurface* aSurface, const nsIntRegion& aRegion,
             const nsIntPoint& aOffset, const gfxRGBA& aColor)
 {
   nsRefPtr<gfxContext> ctx = new gfxContext(aSurface);
@@ -423,17 +423,17 @@ ThebesLayerD3D9::DrawRegion(nsIntRegion 
   {
     case SURFACE_OPAQUE:
       destinationSurface = opaqueRenderer.Begin(this);
       break;
 
     case SURFACE_SINGLE_CHANNEL_ALPHA: {
       hr = device()->CreateTexture(bounds.width, bounds.height, 1,
                                    0, D3DFMT_A8R8G8B8,
-                                   D3DPOOL_SYSTEMMEM, getter_AddRefs(tmpTexture), NULL);
+                                   D3DPOOL_SYSTEMMEM, getter_AddRefs(tmpTexture), nullptr);
 
       if (FAILED(hr)) {
         ReportFailure(NS_LITERAL_CSTRING("Failed to create temporary texture in system memory."), hr);
         return;
       }
 
       // XXX - We may consider retaining a SYSTEMMEM texture texture the size
       // of our DEFAULT texture and then use UpdateTexture and add dirty rects
@@ -516,17 +516,17 @@ ThebesLayerD3D9::DrawRegion(nsIntRegion 
 
       if (destinationSurface) {
         nsRefPtr<gfxContext> context = new gfxContext(imgSurface);
         context->SetSource(destinationSurface);
         context->SetOperator(gfxContext::OPERATOR_SOURCE);
         context->Paint();
       }
 
-      imgSurface = NULL;
+      imgSurface = nullptr;
 
       srcTextures.AppendElement(tmpTexture);
       destTextures.AppendElement(mTexture);
       break;
     }
 
     case SURFACE_COMPONENT_ALPHA: {
       opaqueRenderer.End();
@@ -574,28 +574,28 @@ ThebesLayerD3D9::CreateNewTextures(const
     return;
   }
 
   mTexture = nullptr;
   mTextureOnWhite = nullptr;
   HRESULT hr = device()->CreateTexture(aSize.width, aSize.height, 1,
                                        D3DUSAGE_RENDERTARGET,
                                        aMode != SURFACE_SINGLE_CHANNEL_ALPHA ? D3DFMT_X8R8G8B8 : D3DFMT_A8R8G8B8,
-                                       D3DPOOL_DEFAULT, getter_AddRefs(mTexture), NULL);
+                                       D3DPOOL_DEFAULT, getter_AddRefs(mTexture), nullptr);
   if (FAILED(hr)) {
     ReportFailure(NS_LITERAL_CSTRING("ThebesLayerD3D9::CreateNewTextures(): Failed to create texture"),
                   hr);
     return;
   }
 
   if (aMode == SURFACE_COMPONENT_ALPHA) {
     hr = device()->CreateTexture(aSize.width, aSize.height, 1,
                                  D3DUSAGE_RENDERTARGET,
                                  D3DFMT_X8R8G8B8,
-                                 D3DPOOL_DEFAULT, getter_AddRefs(mTextureOnWhite), NULL);
+                                 D3DPOOL_DEFAULT, getter_AddRefs(mTextureOnWhite), nullptr);
     if (FAILED(hr)) {
       ReportFailure(NS_LITERAL_CSTRING("ThebesLayerD3D9::CreateNewTextures(): Failed to create texture (2)"),
                     hr);
       return;
     }
   }
 }
 
--- a/gfx/layers/ipc/CompositorChild.cpp
+++ b/gfx/layers/ipc/CompositorChild.cpp
@@ -26,17 +26,17 @@ CompositorChild::~CompositorChild()
 {
   MOZ_COUNT_DTOR(CompositorChild);
 }
 
 void
 CompositorChild::Destroy()
 {
   mLayerManager->Destroy();
-  mLayerManager = NULL;
+  mLayerManager = nullptr;
   while (size_t len = ManagedPLayerTransactionChild().Length()) {
     LayerTransactionChild* layers =
       static_cast<LayerTransactionChild*>(ManagedPLayerTransactionChild()[len - 1]);
     layers->Destroy();
   }
   SendStop();
 }
 
@@ -89,17 +89,17 @@ void
 CompositorChild::ActorDestroy(ActorDestroyReason aWhy)
 {
   MOZ_ASSERT(sCompositor == this);
 
   if (aWhy == AbnormalShutdown) {
     NS_RUNTIMEABORT("ActorDestroy by IPC channel failure at CompositorChild");
   }
 
-  sCompositor = NULL;
+  sCompositor = nullptr;
   // We don't want to release the ref to sCompositor here, during
   // cleanup, because that will cause it to be deleted while it's
   // still being used.  So defer the deletion to after it's not in
   // use.
   MessageLoop::current()->PostTask(
     FROM_HERE,
     NewRunnableMethod(this, &CompositorChild::Release));
 }
--- a/gfx/layers/ipc/CompositorParent.cpp
+++ b/gfx/layers/ipc/CompositorParent.cpp
@@ -127,17 +127,17 @@ MessageLoop* CompositorParent::Composito
 {
   return sCompositorThread ? sCompositorThread->message_loop() : sCompositorLoop;
 }
 
 CompositorParent::CompositorParent(nsIWidget* aWidget,
                                    bool aUseExternalSurfaceSize,
                                    int aSurfaceWidth, int aSurfaceHeight)
   : mWidget(aWidget)
-  , mCurrentCompositeTask(NULL)
+  , mCurrentCompositeTask(nullptr)
   , mIsTesting(false)
   , mPaused(false)
   , mUseExternalSurfaceSize(aUseExternalSurfaceSize)
   , mEGLSurfaceSize(aSurfaceWidth, aSurfaceHeight)
   , mPauseCompositionMonitor("PauseCompositionMonitor")
   , mResumeCompositionMonitor("ResumeCompositionMonitor")
   , mOverrideComposeReadiness(false)
   , mForceCompositionTask(nullptr)
@@ -522,17 +522,17 @@ SetShadowProperties(Layer* aLayer)
 void
 CompositorParent::ShadowLayersUpdated(LayerTransactionParent* aLayerTree,
                                       const TargetConfig& aTargetConfig,
                                       bool isFirstPaint)
 {
   if (!isFirstPaint &&
       !mCompositionManager->IsFirstPaint() &&
       mCompositionManager->RequiresReorientation(aTargetConfig.orientation())) {
-    if (mForceCompositionTask != NULL) {
+    if (mForceCompositionTask != nullptr) {
       mForceCompositionTask->Cancel();
     }
     mForceCompositionTask = NewRunnableMethod(this, &CompositorParent::ForceComposition);
     ScheduleTask(mForceCompositionTask, gfxPlatform::GetPlatform()->GetOrientationSyncMillis());
   }
 
   // Instruct the LayerManager to update its render bounds now. Since all the orientation
   // change, dimension change would be done at the stage, update the size here is free of
--- a/gfx/layers/ipc/LayerTransaction.ipdlh
+++ b/gfx/layers/ipc/LayerTransaction.ipdlh
@@ -24,17 +24,18 @@ using nscoord;
 using nsRect;
 using nsPoint;
 using mozilla::TimeDuration;
 using mozilla::TimeStamp;
 using mozilla::ScreenRotation;
 using nsCSSProperty;
 using mozilla::dom::ScreenOrientation;
 using mozilla::layers::TextureInfo;
-using mozilla::gfx::Margin;
+using mozilla::LayerMargin;
+using mozilla::LayerPoint;
 using mozilla::layers::ImageLayer::ScaleMode;
 
 namespace mozilla {
 namespace layers {
 
 struct TargetConfig {
   nsIntRect naturalBounds;
   ScreenRotation rotation;
@@ -181,18 +182,18 @@ struct CommonLayerAttributes {
   TransformMatrix transform;
   float postXScale;
   float postYScale;
   uint32_t contentFlags;
   float opacity;
   bool useClipRect;
   nsIntRect clipRect;
   bool isFixedPosition;
-  gfxPoint fixedPositionAnchor;
-  Margin fixedPositionMargin;
+  LayerPoint fixedPositionAnchor;
+  LayerMargin fixedPositionMargin;
   nullable PLayer maskLayer;
   // Animated colors will only honored for ColorLayers.
   Animation[] animations;
  };
 
 struct ThebesLayerAttributes {
   nsIntRegion validRegion;
 };
--- a/gfx/layers/ipc/LayerTransactionParent.cpp
+++ b/gfx/layers/ipc/LayerTransactionParent.cpp
@@ -180,17 +180,17 @@ LayerTransactionParent::RecvUpdate(const
   MOZ_LAYERS_LOG(("[ParentSide] received txn with %d edits", cset.Length()));
 
   if (mDestroyed || !layer_manager() || layer_manager()->IsDestroyed()) {
     return true;
   }
 
   EditReplyVector replyv;
 
-  layer_manager()->BeginTransactionWithTarget(NULL);
+  layer_manager()->BeginTransactionWithTarget(nullptr);
 
   for (EditArray::index_type i = 0; i < cset.Length(); ++i) {
     const Edit& edit = cset[i];
 
     switch (edit.type()) {
     // Create* ops
     case Edit::TOpCreateThebesLayer: {
       MOZ_LAYERS_LOG(("[ParentSide] CreateThebesLayer"));
@@ -246,26 +246,26 @@ LayerTransactionParent::RecvUpdate(const
       const OpSetLayerAttributes& osla = edit.get_OpSetLayerAttributes();
       Layer* layer = AsLayerComposite(osla)->AsLayer();
       const LayerAttributes& attrs = osla.attrs();
 
       const CommonLayerAttributes& common = attrs.common();
       layer->SetVisibleRegion(common.visibleRegion());
       layer->SetContentFlags(common.contentFlags());
       layer->SetOpacity(common.opacity());
-      layer->SetClipRect(common.useClipRect() ? &common.clipRect() : NULL);
+      layer->SetClipRect(common.useClipRect() ? &common.clipRect() : nullptr);
       layer->SetBaseTransform(common.transform().value());
       layer->SetPostScale(common.postXScale(), common.postYScale());
       layer->SetIsFixedPosition(common.isFixedPosition());
       layer->SetFixedPositionAnchor(common.fixedPositionAnchor());
       layer->SetFixedPositionMargins(common.fixedPositionMargin());
       if (PLayerParent* maskLayer = common.maskLayerParent()) {
         layer->SetMaskLayer(cast(maskLayer)->AsLayer());
       } else {
-        layer->SetMaskLayer(NULL);
+        layer->SetMaskLayer(nullptr);
       }
       layer->SetAnimations(common.animations());
 
       typedef SpecificLayerAttributes Specific;
       const SpecificLayerAttributes& specific = attrs.specific();
       switch (specific.type()) {
       case Specific::Tnull_t:
         break;
@@ -356,17 +356,17 @@ LayerTransactionParent::RecvUpdate(const
         ShadowChild(oia)->AsLayer(), ShadowAfter(oia)->AsLayer());
       break;
     }
     case Edit::TOpAppendChild: {
       MOZ_LAYERS_LOG(("[ParentSide] AppendChild"));
 
       const OpAppendChild& oac = edit.get_OpAppendChild();
       ShadowContainer(oac)->AsContainer()->InsertAfter(
-        ShadowChild(oac)->AsLayer(), NULL);
+        ShadowChild(oac)->AsLayer(), nullptr);
       break;
     }
     case Edit::TOpRemoveChild: {
       MOZ_LAYERS_LOG(("[ParentSide] RemoveChild"));
 
       const OpRemoveChild& orc = edit.get_OpRemoveChild();
       Layer* childLayer = ShadowChild(orc)->AsLayer();
       ShadowContainer(orc)->AsContainer()->RemoveChild(childLayer);
@@ -380,17 +380,17 @@ LayerTransactionParent::RecvUpdate(const
         ShadowChild(orc)->AsLayer(), ShadowAfter(orc)->AsLayer());
       break;
     }
     case Edit::TOpRaiseToTopChild: {
       MOZ_LAYERS_LOG(("[ParentSide] RaiseToTopChild"));
 
       const OpRaiseToTopChild& rtc = edit.get_OpRaiseToTopChild();
       ShadowContainer(rtc)->AsContainer()->RepositionChild(
-        ShadowChild(rtc)->AsLayer(), NULL);
+        ShadowChild(rtc)->AsLayer(), nullptr);
       break;
     }
     case Edit::TCompositableOperation: {
       ReceiveCompositableUpdate(edit.get_CompositableOperation(),
                                 replyv);
       break;
     }
     case Edit::TOpAttachCompositable: {
@@ -406,17 +406,17 @@ LayerTransactionParent::RecvUpdate(const
       compositableParent->SetCompositorID(mLayerManager->GetCompositor()->GetCompositorID());
       break;
     }
     default:
       NS_RUNTIMEABORT("not reached");
     }
   }
 
-  layer_manager()->EndTransaction(NULL, NULL, LayerManager::END_NO_IMMEDIATE_REDRAW);
+  layer_manager()->EndTransaction(nullptr, nullptr, LayerManager::END_NO_IMMEDIATE_REDRAW);
 
   if (reply) {
     reply->SetCapacity(replyv.size());
     if (replyv.size() > 0) {
       reply->AppendElements(&replyv.front(), replyv.size());
     }
   }
 
--- a/gfx/layers/ipc/ShadowLayerParent.cpp
+++ b/gfx/layers/ipc/ShadowLayerParent.cpp
@@ -9,17 +9,17 @@
 #include "ShadowLayerParent.h"
 #include "ShadowLayers.h"
 
 #include "BasicLayers.h"
 
 namespace mozilla {
 namespace layers {
 
-ShadowLayerParent::ShadowLayerParent() : mLayer(NULL)
+ShadowLayerParent::ShadowLayerParent() : mLayer(nullptr)
 {
 }
 
 ShadowLayerParent::~ShadowLayerParent()
 {
 }
 
 void
@@ -72,13 +72,13 @@ ShadowLayerParent::ActorDestroy(ActorDes
     // forth; our channel is disconnected anyway
     break;
 
   case FailedConstructor:
     NS_RUNTIMEABORT("FailedConstructor isn't possible in PLayerTransaction");
     return;                     // unreached
   }
 
-  mLayer = NULL;
+  mLayer = nullptr;
 }
 
 } // namespace layers
 } // namespace mozilla
--- a/gfx/layers/ipc/ShadowLayers.cpp
+++ b/gfx/layers/ipc/ShadowLayers.cpp
@@ -159,17 +159,17 @@ struct AutoTxnEnd {
 
 void
 CompositableForwarder::IdentifyTextureHost(const TextureFactoryIdentifier& aIdentifier)
 {
   mTextureFactoryIdentifier = aIdentifier;
 }
 
 ShadowLayerForwarder::ShadowLayerForwarder()
- : mShadowManager(NULL)
+ : mShadowManager(nullptr)
  , mIsFirstPaint(false)
  , mDrawColoredBorders(false)
  , mWindowOverlayChanged(false)
 {
   mTxn = new Transaction();
 }
 
 ShadowLayerForwarder::~ShadowLayerForwarder()
@@ -194,17 +194,17 @@ Shadow(ShadowableLayer* aLayer)
 {
   return aLayer->GetShadow();
 }
 
 template<typename OpCreateT>
 static void
 CreatedLayer(Transaction* aTxn, ShadowableLayer* aLayer)
 {
-  aTxn->AddEdit(OpCreateT(NULL, Shadow(aLayer)));
+  aTxn->AddEdit(OpCreateT(nullptr, Shadow(aLayer)));
 }
 
 void
 ShadowLayerForwarder::CreatedThebesLayer(ShadowableLayer* aThebes)
 {
   CreatedLayer<OpCreateThebesLayer>(mTxn, aThebes);
 }
 void
@@ -243,67 +243,67 @@ void
 ShadowLayerForwarder::Mutated(ShadowableLayer* aMutant)
 {
 mTxn->AddMutant(aMutant);
 }
 
 void
 ShadowLayerForwarder::SetRoot(ShadowableLayer* aRoot)
 {
-  mTxn->AddEdit(OpSetRoot(NULL, Shadow(aRoot)));
+  mTxn->AddEdit(OpSetRoot(nullptr, Shadow(aRoot)));
 }
 void
 ShadowLayerForwarder::InsertAfter(ShadowableLayer* aContainer,
                                   ShadowableLayer* aChild,
                                   ShadowableLayer* aAfter)
 {
   if (aAfter)
-    mTxn->AddEdit(OpInsertAfter(NULL, Shadow(aContainer),
-                                NULL, Shadow(aChild),
-                                NULL, Shadow(aAfter)));
+    mTxn->AddEdit(OpInsertAfter(nullptr, Shadow(aContainer),
+                                nullptr, Shadow(aChild),
+                                nullptr, Shadow(aAfter)));
   else
-    mTxn->AddEdit(OpAppendChild(NULL, Shadow(aContainer),
-                                NULL, Shadow(aChild)));
+    mTxn->AddEdit(OpAppendChild(nullptr, Shadow(aContainer),
+                                nullptr, Shadow(aChild)));
 }
 void
 ShadowLayerForwarder::RemoveChild(ShadowableLayer* aContainer,
                                   ShadowableLayer* aChild)
 {
   MOZ_LAYERS_LOG(("[LayersForwarder] OpRemoveChild container=%p child=%p\n",
                   aContainer->AsLayer(), aChild->AsLayer()));
 
-  mTxn->AddEdit(OpRemoveChild(NULL, Shadow(aContainer),
-                              NULL, Shadow(aChild)));
+  mTxn->AddEdit(OpRemoveChild(nullptr, Shadow(aContainer),
+                              nullptr, Shadow(aChild)));
 }
 void
 ShadowLayerForwarder::RepositionChild(ShadowableLayer* aContainer,
                                       ShadowableLayer* aChild,
                                       ShadowableLayer* aAfter)
 {
   if (aAfter) {
     MOZ_LAYERS_LOG(("[LayersForwarder] OpRepositionChild container=%p child=%p after=%p",
                    aContainer->AsLayer(), aChild->AsLayer(), aAfter->AsLayer()));
-    mTxn->AddEdit(OpRepositionChild(NULL, Shadow(aContainer),
-                                    NULL, Shadow(aChild),
-                                    NULL, Shadow(aAfter)));
+    mTxn->AddEdit(OpRepositionChild(nullptr, Shadow(aContainer),
+                                    nullptr, Shadow(aChild),
+                                    nullptr, Shadow(aAfter)));
   } else {
     MOZ_LAYERS_LOG(("[LayersForwarder] OpRaiseToTopChild container=%p child=%p",
                    aContainer->AsLayer(), aChild->AsLayer()));
-    mTxn->AddEdit(OpRaiseToTopChild(NULL, Shadow(aContainer),
-                                    NULL, Shadow(aChild)));
+    mTxn->AddEdit(OpRaiseToTopChild(nullptr, Shadow(aContainer),
+                                    nullptr, Shadow(aChild)));
   }
 }
 
 void
 ShadowLayerForwarder::PaintedTiledLayerBuffer(CompositableClient* aCompositable,
                                               BasicTiledLayerBuffer* aTiledLayerBuffer)
 {
   if (XRE_GetProcessType() != GeckoProcessType_Default)
     NS_RUNTIMEABORT("PaintedTiledLayerBuffer must be made IPC safe (not share pointers)");
-  mTxn->AddNoSwapPaint(OpPaintTiledLayerBuffer(NULL, aCompositable->GetIPDLActor(),
+  mTxn->AddNoSwapPaint(OpPaintTiledLayerBuffer(nullptr, aCompositable->GetIPDLActor(),
                                                uintptr_t(aTiledLayerBuffer)));
 }
 
 void
 ShadowLayerForwarder::UpdateTexture(CompositableClient* aCompositable,
                                     TextureIdentifier aTextureId,
                                     SurfaceDescriptor* aDescriptor)
 {
@@ -425,26 +425,26 @@ ShadowLayerForwarder::EndTransaction(Inf
     common.clipRect() = (common.useClipRect() ?
                          *mutant->GetClipRect() : nsIntRect());
     common.isFixedPosition() = mutant->GetIsFixedPosition();
     common.fixedPositionAnchor() = mutant->GetFixedPositionAnchor();
     common.fixedPositionMargin() = mutant->GetFixedPositionMargins();
     if (Layer* maskLayer = mutant->GetMaskLayer()) {
       common.maskLayerChild() = Shadow(maskLayer->AsShadowableLayer());
     } else {
-      common.maskLayerChild() = NULL;
+      common.maskLayerChild() = nullptr;
     }
-    common.maskLayerParent() = NULL;
+    common.maskLayerParent() = nullptr;
     common.animations() = mutant->GetAnimations();
     attrs.specific() = null_t();
     mutant->FillSpecificAttributes(attrs.specific());
 
     MOZ_LAYERS_LOG(("[LayersForwarder] OpSetLayerAttributes(%p)\n", mutant));
 
-    mTxn->AddEdit(OpSetLayerAttributes(NULL, Shadow(shadow), attrs));
+    mTxn->AddEdit(OpSetLayerAttributes(nullptr, Shadow(shadow), attrs));
   }
 
   AutoInfallibleTArray<Edit, 10> cset;
   size_t nCsets = mTxn->mCset.size() + mTxn->mPaints.size();
   NS_ABORT_IF_FALSE(nCsets > 0 || mWindowOverlayChanged, "should have bailed by now");
 
   cset.SetCapacity(nCsets);
   if (!mTxn->mCset.empty()) {
--- a/gfx/layers/ipc/ShadowLayers.h
+++ b/gfx/layers/ipc/ShadowLayers.h
@@ -223,27 +223,27 @@ public:
    * needs to sync to its shadow layer.  This initial implementation
    * forwards all attributes when any is mutated.
    */
   void Mutated(ShadowableLayer* aMutant);
 
   void SetRoot(ShadowableLayer* aRoot);
   /**
    * Insert |aChild| after |aAfter| in |aContainer|.  |aAfter| can be
-   * NULL to indicated that |aChild| should be appended to the end of
+   * nullptr to indicated that |aChild| should be appended to the end of
    * |aContainer|'s child list.
    */
   void InsertAfter(ShadowableLayer* aContainer,
                    ShadowableLayer* aChild,
-                   ShadowableLayer* aAfter=NULL);
+                   ShadowableLayer* aAfter = nullptr);
   void RemoveChild(ShadowableLayer* aContainer,
                    ShadowableLayer* aChild);
   void RepositionChild(ShadowableLayer* aContainer,
                        ShadowableLayer* aChild,
-                       ShadowableLayer* aAfter=NULL);
+                       ShadowableLayer* aAfter = nullptr);
 
   /**
    * Set aMaskLayer as the mask on aLayer.
    * Note that only image layers are properly supported
    * LayerTransactionParent::UpdateMask and accompanying ipdl
    * will need changing to update properties for other kinds
    * of mask layer.
    */
@@ -467,23 +467,23 @@ public:
 
   /**
    * True if this layer has a shadow in a parent process.
    */
   bool HasShadow() { return !!mShadow; }
 
   /**
    * Return the IPC handle to a Shadow*Layer referring to this if one
-   * exists, NULL if not.
+   * exists, nullptr if not.
    */
   PLayerChild* GetShadow() { return mShadow; }
 
   virtual CompositableClient* GetCompositableClient() { return nullptr; }
 protected:
-  ShadowableLayer() : mShadow(NULL) {}
+  ShadowableLayer() : mShadow(nullptr) {}
 
   PLayerChild* mShadow;
 };
 
 } // namespace layers
 } // namespace mozilla
 
 #endif // ifndef mozilla_layers_ShadowLayers_h
--- a/gfx/layers/opengl/CanvasLayerOGL.h
+++ b/gfx/layers/opengl/CanvasLayerOGL.h
@@ -21,17 +21,17 @@ namespace mozilla {
 namespace layers {
 
 class CanvasLayerOGL :
   public CanvasLayer,
   public LayerOGL
 {
 public:
   CanvasLayerOGL(LayerManagerOGL *aManager)
-    : CanvasLayer(aManager, NULL)
+    : CanvasLayer(aManager, nullptr)
     , LayerOGL(aManager)
     , mLayerProgram(RGBALayerProgramType)
     , mTexture(0)
     , mTextureTarget(LOCAL_GL_TEXTURE_2D)
     , mDelayedUpdates(false)
     , mIsGLAlphaPremult(false)
     , mUploadTexture(0)
 #if defined(GL_PROVIDER_GLX)
--- a/gfx/layers/opengl/ColorLayerOGL.h
+++ b/gfx/layers/opengl/ColorLayerOGL.h
@@ -14,17 +14,17 @@
 namespace mozilla {
 namespace layers {
 
 class ColorLayerOGL : public ColorLayer,
                       public LayerOGL
 {
 public:
   ColorLayerOGL(LayerManagerOGL *aManager)
-    : ColorLayer(aManager, NULL)
+    : ColorLayer(aManager, nullptr)
     , LayerOGL(aManager)
   { 
     mImplData = static_cast<LayerOGL*>(this);
   }
   ~ColorLayerOGL() { Destroy(); }
 
   // LayerOGL Implementation
   virtual Layer* GetLayer() { return this; }
--- a/gfx/layers/opengl/CompositorOGL.cpp
+++ b/gfx/layers/opengl/CompositorOGL.cpp
@@ -423,17 +423,17 @@ CompositorOGL::Initialize()
                                 LOCAL_GL_NEAREST);
       mGLContext->fTexImage2D(target,
                               0,
                               LOCAL_GL_RGBA,
                               5, 3, /* sufficiently NPOT */
                               0,
                               LOCAL_GL_RGBA,
                               LOCAL_GL_UNSIGNED_BYTE,
-                              NULL);
+                              nullptr);
 
       // unbind this texture, in preparation for binding it to the FBO
       mGLContext->fBindTexture(target, 0);
 
       mGLContext->fBindFramebuffer(LOCAL_GL_FRAMEBUFFER, testFBO);
       mGLContext->fFramebufferTexture2D(LOCAL_GL_FRAMEBUFFER,
                                         LOCAL_GL_COLOR_ATTACHMENT0,
                                         target,
@@ -906,17 +906,17 @@ CompositorOGL::CreateFBOWithTexture(cons
   } else {
     mGLContext->fTexImage2D(mFBOTextureTarget,
                             0,
                             LOCAL_GL_RGBA,
                             aRect.width, aRect.height,
                             0,
                             LOCAL_GL_RGBA,
                             LOCAL_GL_UNSIGNED_BYTE,
-                            NULL);
+                            nullptr);
   }
   mGLContext->fTexParameteri(mFBOTextureTarget, LOCAL_GL_TEXTURE_MIN_FILTER,
                              LOCAL_GL_LINEAR);
   mGLContext->fTexParameteri(mFBOTextureTarget, LOCAL_GL_TEXTURE_MAG_FILTER,
                              LOCAL_GL_LINEAR);
   mGLContext->fTexParameteri(mFBOTextureTarget, LOCAL_GL_TEXTURE_WRAP_S,
                              LOCAL_GL_CLAMP_TO_EDGE);
   mGLContext->fTexParameteri(mFBOTextureTarget, LOCAL_GL_TEXTURE_WRAP_T,
--- a/gfx/layers/opengl/ContainerLayerOGL.cpp
+++ b/gfx/layers/opengl/ContainerLayerOGL.cpp
@@ -342,17 +342,17 @@ ContainerRender(Container* aContainer,
       aContainer->gl()->fDeleteTextures(1, &containerSurface);
     }
   } else {
     aContainer->gl()->PopScissorRect();
   }
 }
 
 ContainerLayerOGL::ContainerLayerOGL(LayerManagerOGL *aManager)
-  : ContainerLayer(aManager, NULL)
+  : ContainerLayer(aManager, nullptr)
   , LayerOGL(aManager)
 {
   mImplData = static_cast<LayerOGL*>(this);
 }
 
 ContainerLayerOGL::~ContainerLayerOGL()
 {
   Destroy();
--- a/gfx/layers/opengl/ImageLayerOGL.cpp
+++ b/gfx/layers/opengl/ImageLayerOGL.cpp
@@ -390,17 +390,17 @@ UploadYUVToTexture(GLContext* gl, const 
   surf = new gfxImageSurface(aData.mCrChannel,
                              aData.mCbCrSize,
                              aData.mCbCrStride,
                              gfxASurface::ImageFormatA8);
   gl->UploadSurfaceToTexture(surf, size, texture, true);
 }
 
 ImageLayerOGL::ImageLayerOGL(LayerManagerOGL *aManager)
-  : ImageLayer(aManager, NULL)
+  : ImageLayer(aManager, nullptr)
   , LayerOGL(aManager)
   , mTextureRecycleBin(new TextureRecycleBin())
 { 
   mImplData = static_cast<LayerOGL*>(this);
 }
 
 void
 ImageLayerOGL::AllocateTexturesYCbCr(PlanarYCbCrImage *aImage)
--- a/gfx/layers/opengl/LayerManagerOGL.cpp
+++ b/gfx/layers/opengl/LayerManagerOGL.cpp
@@ -334,17 +334,17 @@ LayerManagerOGL::Initialize(bool force)
                                 LOCAL_GL_NEAREST);
       mGLContext->fTexImage2D(target,
                               0,
                               LOCAL_GL_RGBA,
                               5, 3, /* sufficiently NPOT */
                               0,
                               LOCAL_GL_RGBA,
                               LOCAL_GL_UNSIGNED_BYTE,
-                              NULL);
+                              nullptr);
 
       // unbind this texture, in preparation for binding it to the FBO
       mGLContext->fBindTexture(target, 0);
 
       mGLContext->fBindFramebuffer(LOCAL_GL_FRAMEBUFFER, mBackBufferFBO);
       mGLContext->fFramebufferTexture2D(LOCAL_GL_FRAMEBUFFER,
                                         LOCAL_GL_COLOR_ATTACHMENT0,
                                         target,
@@ -559,17 +559,17 @@ LayerManagerOGL::EndTransaction(DrawTheb
     if (needGLRender) {
       Render();
     }
 
     mThebesLayerCallback = nullptr;
     mThebesLayerCallbackData = nullptr;
   }
 
-  mTarget = NULL;
+  mTarget = nullptr;
 
 #ifdef MOZ_LAYERS_HAVE_LOG
   Log();
   MOZ_LAYERS_LOG(("]----- EndTransaction"));
 #endif
 }
 
 already_AddRefed<gfxASurface>
@@ -1073,17 +1073,17 @@ LayerManagerOGL::SetupBackBuffer(int aWi
   mGLContext->fBindTexture(mFBOTextureTarget, mBackBufferTexture);
   mGLContext->fTexImage2D(mFBOTextureTarget,
                           0,
                           LOCAL_GL_RGBA,
                           aWidth, aHeight,
                           0,
                           LOCAL_GL_RGBA,
                           LOCAL_GL_UNSIGNED_BYTE,
-                          NULL);
+                          nullptr);
   mGLContext->fBindTexture(mFBOTextureTarget, 0);
 
   mGLContext->fBindFramebuffer(LOCAL_GL_FRAMEBUFFER, mBackBufferFBO);
   mGLContext->fFramebufferTexture2D(LOCAL_GL_FRAMEBUFFER,
                                     LOCAL_GL_COLOR_ATTACHMENT0,
                                     mFBOTextureTarget,
                                     mBackBufferTexture,
                                     0);
@@ -1231,17 +1231,17 @@ LayerManagerOGL::CreateFBOWithTexture(co
   } else {
     mGLContext->fTexImage2D(mFBOTextureTarget,
                             0,
                             LOCAL_GL_RGBA,
                             aRect.width, aRect.height,
                             0,
                             LOCAL_GL_RGBA,
                             LOCAL_GL_UNSIGNED_BYTE,
-                            NULL);
+                            nullptr);
   }
   mGLContext->fTexParameteri(mFBOTextureTarget, LOCAL_GL_TEXTURE_MIN_FILTER,
                              LOCAL_GL_LINEAR);
   mGLContext->fTexParameteri(mFBOTextureTarget, LOCAL_GL_TEXTURE_MAG_FILTER,
                              LOCAL_GL_LINEAR);
   mGLContext->fTexParameteri(mFBOTextureTarget, LOCAL_GL_TEXTURE_WRAP_S, 
                              LOCAL_GL_CLAMP_TO_EDGE);
   mGLContext->fTexParameteri(mFBOTextureTarget, LOCAL_GL_TEXTURE_WRAP_T, 
--- a/gfx/layers/opengl/LayerManagerOGL.h
+++ b/gfx/layers/opengl/LayerManagerOGL.h
@@ -11,17 +11,17 @@
 
 #include "mozilla/TimeStamp.h"
 #include "nsPoint.h"
 
 #ifdef XP_WIN
 #include <windows.h>
 #endif
 
-#define BUFFER_OFFSET(i) ((char *)NULL + (i))
+#define BUFFER_OFFSET(i) ((char *)nullptr + (i))
 
 #include "gfxContext.h"
 #include "gfx3DMatrix.h"
 #include "nsIWidget.h"
 #include "GLContextTypes.h"
 #include "GLDefs.h"
 
 namespace mozilla {
@@ -316,17 +316,17 @@ private:
   /** Widget associated with this layer manager */
   nsIWidget *mWidget;
   nsIntSize mWidgetSize;
 
   /** The size of the surface we are rendering to */
   nsIntSize mSurfaceSize;
 
   /** 
-   * Context target, NULL when drawing directly to our swap chain.
+   * Context target, nullptr when drawing directly to our swap chain.
    */
   nsRefPtr<gfxContext> mTarget;
 
   nsRefPtr<GLContext> mGLContext;
 
   /** Our more efficient but less powerful alter ego, if one is available. */
   nsRefPtr<Composer2D> mComposer2D;
 
--- a/gfx/layers/opengl/LayerManagerOGLProgram.cpp
+++ b/gfx/layers/opengl/LayerManagerOGLProgram.cpp
@@ -324,17 +324,17 @@ ShaderProgramOGL::Initialize()
 }
 
 GLint
 ShaderProgramOGL::CreateShader(GLenum aShaderType, const char *aShaderSource)
 {
   GLint success, len = 0;
 
   GLint sh = mGL->fCreateShader(aShaderType);
-  mGL->fShaderSource(sh, 1, (const GLchar**)&aShaderSource, NULL);
+  mGL->fShaderSource(sh, 1, (const GLchar**)&aShaderSource, nullptr);
   mGL->fCompileShader(sh);
   mGL->fGetShaderiv(sh, LOCAL_GL_COMPILE_STATUS, &success);
   mGL->fGetShaderiv(sh, LOCAL_GL_INFO_LOG_LENGTH, (GLint*) &len);
   /* Even if compiling is successful, there may still be warnings.  Print them
    * in a debug build.  The > 10 is to catch silly compilers that might put
    * some whitespace in the log but otherwise leave it empty.
    */
   if (!success
--- a/gfx/layers/opengl/TexturePoolOGL.cpp
+++ b/gfx/layers/opengl/TexturePoolOGL.cpp
@@ -7,20 +7,20 @@
 #include "nsDeque.h"
 #include "mozilla/Monitor.h"
 
 #define TEXTURE_POOL_SIZE 10
 
 namespace mozilla {
 namespace gl {
 
-static GLContext* sActiveContext = NULL;
+static GLContext* sActiveContext = nullptr;
 
-static Monitor* sMonitor = NULL;
-static nsDeque* sTextures = NULL;
+static Monitor* sMonitor = nullptr;
+static nsDeque* sTextures = nullptr;
 
 GLuint TexturePoolOGL::AcquireTexture()
 {
   NS_ASSERTION(sMonitor, "not initialized");
 
   MonitorAutoLock lock(*sMonitor);
 
   if (!sActiveContext) {
@@ -84,17 +84,17 @@ void TexturePoolOGL::Fill(GLContext* aCo
     sActiveContext = aContext;
   }
 
   if (sTextures->GetSize() == TEXTURE_POOL_SIZE)
     return;
 
   sActiveContext->MakeCurrent();
 
-  GLuint* texture = NULL;
+  GLuint* texture = nullptr;
   while (sTextures->GetSize() < TEXTURE_POOL_SIZE) {
     texture = (GLuint*)malloc(sizeof(GLuint));
     sActiveContext->fGenTextures(1, texture);
     sTextures->Push((void*) texture);
   }
 
   sMonitor->NotifyAll();
 }
--- a/gfx/src/X11Util.h
+++ b/gfx/src/X11Util.h
@@ -39,18 +39,18 @@ DefaultXDisplay()
 #elif defined(MOZ_WIDGET_QT)
   return gfxQtPlatform::GetXDisplay();
 #endif
 }
 
 /**
  * Sets *aVisual to point to aDisplay's Visual struct corresponding to
  * aVisualID, and *aDepth to its depth.  When aVisualID is None, these are set
- * to NULL and 0 respectively.  Both out-parameter pointers are assumed
- * non-NULL.
+ * to nullptr and 0 respectively.  Both out-parameter pointers are assumed
+ * non-nullptr.
  */
 void
 FindVisualAndDepth(Display* aDisplay, VisualID aVisualID,
                    Visual** aVisual, int* aDepth);
 
 
 /**
  * Ensure that all X requests have been processed.
@@ -67,18 +67,18 @@ FinishX(Display* aDisplay);
 /**
  * Invoke XFree() on a pointer to memory allocated by Xlib (if the
  * pointer is nonnull) when this class goes out of scope.
  */
 template <typename T>
 struct ScopedXFreePtrTraits
 {
   typedef T *type;
-  static T *empty() { return NULL; }
-  static void release(T *ptr) { if (ptr!=NULL) XFree(ptr); }
+  static T *empty() { return nullptr; }
+  static void release(T *ptr) { if (ptr != nullptr) XFree(ptr); }
 };
 SCOPED_TEMPLATE(ScopedXFree, ScopedXFreePtrTraits)
 
 /**
  * On construction, set a graceful X error handler that doesn't crash the application and records X errors.
  * On destruction, restore the X error handler to what it was before construction.
  * 
  * The SyncAndGetError() method allows to know whether a X error occurred, optionally allows to get the full XErrorEvent,
--- a/gfx/src/nsDeviceContext.cpp
+++ b/gfx/src/nsDeviceContext.cpp
@@ -271,17 +271,17 @@ nsDeviceContext::FontMetricsDeleted(cons
         mFontCache->FontMetricsDeleted(aFontMetrics);
     }
     return NS_OK;
 }
 
 bool
 nsDeviceContext::IsPrinterSurface()
 {
-    return(mPrintingSurface != NULL);
+    return mPrintingSurface != nullptr;
 }
 
 void
 nsDeviceContext::SetDPI()
 {
     float dpi = -1.0f;
 
     // PostScript, PDF and Mac (when printing) all use 72 dpi
--- a/gfx/src/nsDeviceContext.h
+++ b/gfx/src/nsDeviceContext.h
@@ -158,17 +158,17 @@ public:
     nsresult GetClientRect(nsRect& aRect);
 
     /**
      * Inform the output device that output of a document is beginning
      * Used for print related device contexts. Must be matched 1:1 with
      * EndDocument() or AbortDocument().
      *
      * @param aTitle - title of Document
-     * @param aPrintToFileName - name of file to print to, if NULL
+     * @param aPrintToFileName - name of file to print to, if nullptr
      * then don't print to file
      * @param aStartPage - starting page number (must be greater than zero)
      * @param aEndPage - ending page number (must be less than or
      * equal to number of pages)
      *
      * @return error status
      */
     nsresult BeginDocument(PRUnichar  *aTitle,
--- a/gfx/src/nsScriptableRegion.cpp
+++ b/gfx/src/nsScriptableRegion.cpp
@@ -134,19 +134,19 @@ NS_IMETHODIMP nsScriptableRegion::GetRec
 
   *aRects = OBJECT_TO_JSVAL(destArray);
 
   uint32_t n = 0;
   nsIntRegionRectIterator iter(mRegion);
   const nsIntRect *rect;
 
   while ((rect = iter.Next())) {
-    if (!JS_DefineElement(aCx, destArray, n, INT_TO_JSVAL(rect->x), NULL, NULL, JSPROP_ENUMERATE) ||
-        !JS_DefineElement(aCx, destArray, n + 1, INT_TO_JSVAL(rect->y), NULL, NULL, JSPROP_ENUMERATE) ||
-        !JS_DefineElement(aCx, destArray, n + 2, INT_TO_JSVAL(rect->width), NULL, NULL, JSPROP_ENUMERATE) ||
-        !JS_DefineElement(aCx, destArray, n + 3, INT_TO_JSVAL(rect->height), NULL, NULL, JSPROP_ENUMERATE)) {
+    if (!JS_DefineElement(aCx, destArray, n, INT_TO_JSVAL(rect->x), nullptr, nullptr, JSPROP_ENUMERATE) ||
+        !JS_DefineElement(aCx, destArray, n + 1, INT_TO_JSVAL(rect->y), nullptr, nullptr, JSPROP_ENUMERATE) ||
+        !JS_DefineElement(aCx, destArray, n + 2, INT_TO_JSVAL(rect->width), nullptr, nullptr, JSPROP_ENUMERATE) ||
+        !JS_DefineElement(aCx, destArray, n + 3, INT_TO_JSVAL(rect->height), nullptr, nullptr, JSPROP_ENUMERATE)) {
       return NS_ERROR_FAILURE;
     }
     n += 4;
   }
 
   return NS_OK;
 }
--- a/gfx/src/nsThebesGfxFactory.cpp
+++ b/gfx/src/nsThebesGfxFactory.cpp
@@ -46,38 +46,38 @@ nsScriptableRegionConstructor(nsISupport
 
 NS_GENERIC_FACTORY_CONSTRUCTOR(GfxInitialization)
 
 NS_DEFINE_NAMED_CID(NS_FONT_ENUMERATOR_CID);
 NS_DEFINE_NAMED_CID(NS_SCRIPTABLE_REGION_CID);
 NS_DEFINE_NAMED_CID(NS_GFX_INITIALIZATION_CID);
 
 static const mozilla::Module::CIDEntry kThebesCIDs[] = {
-    { &kNS_FONT_ENUMERATOR_CID, false, NULL, nsThebesFontEnumeratorConstructor },
-    { &kNS_SCRIPTABLE_REGION_CID, false, NULL, nsScriptableRegionConstructor },
-    { &kNS_GFX_INITIALIZATION_CID, false, NULL, GfxInitializationConstructor },
-    { NULL }
+    { &kNS_FONT_ENUMERATOR_CID, false, nullptr, nsThebesFontEnumeratorConstructor },
+    { &kNS_SCRIPTABLE_REGION_CID, false, nullptr, nsScriptableRegionConstructor },
+    { &kNS_GFX_INITIALIZATION_CID, false, nullptr, GfxInitializationConstructor },
+    { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kThebesContracts[] = {
     { "@mozilla.org/gfx/fontenumerator;1", &kNS_FONT_ENUMERATOR_CID },
     { "@mozilla.org/gfx/region;1", &kNS_SCRIPTABLE_REGION_CID },
     { "@mozilla.org/gfx/init;1", &kNS_GFX_INITIALIZATION_CID },
-    { NULL }
+    { nullptr }
 };
 
 static void
 nsThebesGfxModuleDtor()
 {
     gfxPlatform::Shutdown();
 }
 
 static const mozilla::Module kThebesModule = {
     mozilla::Module::kVersion,
     kThebesCIDs,
     kThebesContracts,
-    NULL,
-    NULL,
-    NULL,
+    nullptr,
+    nullptr,
+    nullptr,
     nsThebesGfxModuleDtor
 };
 
 NSMODULE_DEFN(nsGfxModule) = &kThebesModule;
--- a/ipc/glue/IPCMessageUtils.h
+++ b/ipc/glue/IPCMessageUtils.h
@@ -919,16 +919,38 @@ struct ParamTraits<mozilla::gfx::Margin>
   {
     return (ReadParam(msg, iter, &result->top) &&
             ReadParam(msg, iter, &result->right) &&
             ReadParam(msg, iter, &result->bottom) &&
             ReadParam(msg, iter, &result->left));
   }
 };
 
+template<class T>
+struct ParamTraits< mozilla::gfx::MarginTyped<T> >
+{
+  typedef mozilla::gfx::MarginTyped<T> paramType;
+
+  static void Write(Message* msg, const paramType& param)
+  {
+    WriteParam(msg, param.top);
+    WriteParam(msg, param.right);
+    WriteParam(msg, param.bottom);
+    WriteParam(msg, param.left);
+  }
+
+  static bool Read(const Message* msg, void** iter, paramType* result)
+  {
+    return (ReadParam(msg, iter, &result->top) &&
+            ReadParam(msg, iter, &result->right) &&
+            ReadParam(msg, iter, &result->bottom) &&
+            ReadParam(msg, iter, &result->left));
+  }
+};
+
 template<>
 struct ParamTraits<nsRect>
 {
   typedef nsRect paramType;
 
   static void Write(Message* msg, const paramType& param)
   {
     WriteParam(msg, param.x);
--- a/js/src/ion/arm/CodeGenerator-arm.cpp
+++ b/js/src/ion/arm/CodeGenerator-arm.cpp
@@ -1850,30 +1850,60 @@ CodeGeneratorARM::visitAsmJSPassStackArg
             masm.ma_str(ToRegister(ins->arg()), dst);
         else
             masm.ma_vstr(ToFloatRegister(ins->arg()), dst);
     }
 
     return true;
 }
 
-
 bool
-CodeGeneratorARM::visitUDivOrMod(LUDivOrMod *ins)
+CodeGeneratorARM::visitUDiv(LUDiv *ins)
 {
-    //Register remainder = ToRegister(ins->remainder());
     Register lhs = ToRegister(ins->lhs());
     Register rhs = ToRegister(ins->rhs());
     Register output = ToRegister(ins->output());
 
-    //JS_ASSERT(remainder == edx);
-    //JS_ASSERT(lhs == eax);
+    masm.ma_udiv(lhs, rhs, output);
+    return true;
+}
+
+bool
+CodeGeneratorARM::visitUMod(LUMod *ins)
+{
+    Register lhs = ToRegister(ins->lhs());
+    Register rhs = ToRegister(ins->rhs());
+    Register output = ToRegister(ins->output());
+    Label notzero;
+    Label done;
+
+    masm.ma_cmp(rhs, Imm32(0));
+    masm.ma_b(&notzero, Assembler::NonZero);
+    masm.ma_mov(Imm32(0), output);
+    masm.ma_b(&done);
+
+    masm.bind(&notzero);
+    masm.ma_umod(lhs, rhs, output);
+
+    masm.bind(&done);
+    return true;
+}
+
+bool
+CodeGeneratorARM::visitSoftUDivOrMod(LSoftUDivOrMod *ins)
+{
+    Register lhs = ToRegister(ins->lhs());
+    Register rhs = ToRegister(ins->rhs());
+    Register output = ToRegister(ins->output());
+
+    JS_ASSERT(lhs == r0);
+    JS_ASSERT(rhs == r1);
     JS_ASSERT(ins->mirRaw()->isAsmJSUDiv() || ins->mirRaw()->isAsmJSUMod());
-    //JS_ASSERT_IF(ins->mirRaw()->isAsmUDiv(), output == eax);
-    //JS_ASSERT_IF(ins->mirRaw()->isAsmUMod(), output == edx);
+    JS_ASSERT_IF(ins->mirRaw()->isAsmJSUDiv(), output == r0);
+    JS_ASSERT_IF(ins->mirRaw()->isAsmJSUMod(), output == r1);
 
     Label afterDiv;
 
     masm.ma_cmp(rhs, Imm32(0));
     Label notzero;
     masm.ma_b(&notzero, Assembler::NonZero);
     masm.ma_mov(Imm32(0), output);
     masm.ma_b(&afterDiv);
--- a/js/src/ion/arm/CodeGenerator-arm.h
+++ b/js/src/ion/arm/CodeGenerator-arm.h
@@ -165,19 +165,21 @@ class CodeGeneratorARM : public CodeGene
   protected:
     void postAsmJSCall(LAsmJSCall *lir) {
 #if  !defined(JS_CPU_ARM_HARDFP)
         if (lir->mir()->type() == MIRType_Double) {
             masm.ma_vxfer(r0, r1, d0);
         }
 #endif
 }
- 
+
     bool visitEffectiveAddress(LEffectiveAddress *ins);
-    bool visitUDivOrMod(LUDivOrMod *ins);
+    bool visitUDiv(LUDiv *ins);
+    bool visitUMod(LUMod *ins);
+    bool visitSoftUDivOrMod(LSoftUDivOrMod *ins);
 };
 
 typedef CodeGeneratorARM CodeGeneratorSpecific;
 
 // An out-of-line bailout thunk.
 class OutOfLineBailout : public OutOfLineCodeBase<CodeGeneratorARM>
 {
     LSnapshot *snapshot_;
--- a/js/src/ion/arm/LIR-arm.h
+++ b/js/src/ion/arm/LIR-arm.h
@@ -354,34 +354,47 @@ class LMulI : public LBinaryMath<0>
   public:
     LIR_HEADER(MulI);
 
     MMul *mir() {
         return mir_->toMul();
     }
 };
 
+class LUDiv : public LBinaryMath<0>
+{
+  public:
+    LIR_HEADER(UDiv);
+};
+
+class LUMod : public LBinaryMath<0>
+{
+  public:
+    LIR_HEADER(UMod);
+};
+
 // This class performs a simple x86 'div', yielding either a quotient or remainder depending on
 // whether this instruction is defined to output eax (quotient) or edx (remainder).
-class LUDivOrMod : public LBinaryMath<2>
+class LSoftUDivOrMod : public LBinaryMath<2>
 {
   public:
-    LIR_HEADER(UDivOrMod);
+    LIR_HEADER(SoftUDivOrMod);
 
-    LUDivOrMod(const LAllocation &lhs, const LAllocation &rhs, const LDefinition &temp1, const LDefinition &temp2) {
+    LSoftUDivOrMod(const LAllocation &lhs, const LAllocation &rhs, const LDefinition &temp1, const LDefinition &temp2) {
         setOperand(0, lhs);
         setOperand(1, rhs);
         setTemp(0, temp1);
         setTemp(1, temp2);
     }
     // this is incorrect, it is returned in r1, getTemp(0) is r2.
     const LDefinition *remainder() {
         return getTemp(0);
     }
 };
+
 class LAsmJSLoadFuncPtr : public LInstructionHelper<1, 1, 1>
 {
   public:
     LIR_HEADER(AsmJSLoadFuncPtr);
     LAsmJSLoadFuncPtr(const LAllocation &index, const LDefinition &temp) {
         setOperand(0, index);
         setTemp(0, temp);
     }
--- a/js/src/ion/arm/LOpcodes-arm.h
+++ b/js/src/ion/arm/LOpcodes-arm.h
@@ -16,13 +16,14 @@
     _(SoftDivI)                 \
     _(DivPowTwoI)               \
     _(ModI)                     \
     _(SoftModI)                 \
     _(ModPowTwoI)               \
     _(ModMaskI)                 \
     _(PowHalfD)                 \
     _(UInt32ToDouble)           \
-    _(UDivOrMod)                \
+    _(UDiv)                     \
+    _(UMod)                     \
+    _(SoftUDivOrMod)            \
     _(AsmJSLoadFuncPtr)
 
-
 #endif /* ion_arm_LOpcodes_arm_h */
--- a/js/src/ion/arm/Lowering-arm.cpp
+++ b/js/src/ion/arm/Lowering-arm.cpp
@@ -444,35 +444,47 @@ LIRGeneratorARM::visitAsmJSNeg(MAsmJSNeg
 
     JS_ASSERT(ins->type() == MIRType_Double);
     return define(new LNegD(useRegisterAtStart(ins->input())), ins);
 }
 
 bool
 LIRGeneratorARM::lowerUDiv(MInstruction *div)
 {
-    LUDivOrMod *lir = new LUDivOrMod(useFixed(div->getOperand(0), r0),
-                                     useFixed(div->getOperand(1), r1),
-                                     tempFixed(r2), tempFixed(r3));
-    return defineFixed(lir, div, LAllocation(AnyRegister(r0)));
+    MDefinition *lhs = div->getOperand(0);
+    MDefinition *rhs = div->getOperand(1);
+
+    if (hasIDIV()) {
+        return lowerForALU(new LUDiv, div, lhs, rhs);
+    } else {
+        LSoftUDivOrMod *lir = new LSoftUDivOrMod(useFixed(lhs, r0), useFixed(rhs, r1),
+                                                 tempFixed(r2), tempFixed(r3));
+        return defineFixed(lir, div, LAllocation(AnyRegister(r0)));
+    }
 }
 
 bool
 LIRGeneratorARM::visitAsmJSUDiv(MAsmJSUDiv *div)
 {
     return lowerUDiv(div);
 }
 
 bool
 LIRGeneratorARM::lowerUMod(MInstruction *mod)
 {
-    LUDivOrMod *lir = new LUDivOrMod(useFixed(mod->getOperand(0), r0),
-                                     useFixed(mod->getOperand(1), r1),
-                                     tempFixed(r2), tempFixed(r3));
-    return defineFixed(lir, mod, LAllocation(AnyRegister(r1)));
+    MDefinition *lhs = mod->getOperand(0);
+    MDefinition *rhs = mod->getOperand(1);
+
+    if (hasIDIV()) {
+        return lowerForALU(new LUMod, mod, lhs, rhs);
+    } else {
+        LSoftUDivOrMod *lir = new LSoftUDivOrMod(useFixed(lhs, r0), useFixed(rhs, r1),
+                                                 tempFixed(r2), tempFixed(r3));
+        return defineFixed(lir, mod, LAllocation(AnyRegister(r1)));
+    }
 }
 
 bool
 LIRGeneratorARM::visitAsmJSUMod(MAsmJSUMod *mod)
 {
     return lowerUMod(mod);
 }
 
--- a/js/src/ion/arm/MacroAssembler-arm.cpp
+++ b/js/src/ion/arm/MacroAssembler-arm.cpp
@@ -884,23 +884,36 @@ MacroAssemblerARM::ma_mod_mask(Register 
 
 void
 MacroAssemblerARM::ma_smod(Register num, Register div, Register dest)
 {
     as_sdiv(ScratchRegister, num, div);
     as_mls(dest, num, ScratchRegister, div);
 }
 
+void
+MacroAssemblerARM::ma_umod(Register num, Register div, Register dest)
+{
+    as_udiv(ScratchRegister, num, div);
+    as_mls(dest, num, ScratchRegister, div);
+}
+
 // division
 void
 MacroAssemblerARM::ma_sdiv(Register num, Register div, Register dest, Condition cond)
 {
     as_sdiv(dest, num, div, cond);
 }
 
+void
+MacroAssemblerARM::ma_udiv(Register num, Register div, Register dest, Condition cond)
+{
+    as_udiv(dest, num, div, cond);
+}
+
 // Memory.
 // Shortcut for when we know we're transferring 32 bits of data.
 void
 MacroAssemblerARM::ma_dtr(LoadStore ls, Register rn, Imm32 offset, Register rt,
                           Index mode, Assembler::Condition cc)
 {
     ma_dataTransferN(ls, 32, true, rn, offset, rt, mode, cc);
 }
--- a/js/src/ion/arm/MacroAssembler-arm.h
+++ b/js/src/ion/arm/MacroAssembler-arm.h
@@ -233,21 +233,23 @@ class MacroAssemblerARM : public Assembl
     void ma_mul(Register src1, Imm32 imm, Register dest);
     Condition ma_check_mul(Register src1, Register src2, Register dest, Condition cond);
     Condition ma_check_mul(Register src1, Imm32 imm, Register dest, Condition cond);
 
     // fast mod, uses scratch registers, and thus needs to be in the assembler
     // implicitly assumes that we can overwrite dest at the beginning of the sequence
     void ma_mod_mask(Register src, Register dest, Register hold, int32_t shift);
 
-    // mod, depends on sdiv being supported
+    // mod, depends on integer divide instructions being supported
     void ma_smod(Register num, Register div, Register dest);
+    void ma_umod(Register num, Register div, Register dest);
 
-    // division
+    // division, depends on integer divide instructions being supported
     void ma_sdiv(Register num, Register div, Register dest, Condition cond = Always);
+    void ma_udiv(Register num, Register div, Register dest, Condition cond = Always);
 
     // memory
     // shortcut for when we know we're transferring 32 bits of data
     void ma_dtr(LoadStore ls, Register rn, Imm32 offset, Register rt,
                 Index mode = Offset, Condition cc = Always);
 
     void ma_dtr(LoadStore ls, Register rn, Register rm, Register rt,
                 Index mode = Offset, Condition cc = Always);
--- a/layout/base/Units.h
+++ b/layout/base/Units.h
@@ -20,37 +20,41 @@ struct LayerPixel;
 struct ScreenPixel;
 
 typedef gfx::PointTyped<CSSPixel> CSSPoint;
 typedef gfx::IntPointTyped<CSSPixel> CSSIntPoint;
 typedef gfx::SizeTyped<CSSPixel> CSSSize;
 typedef gfx::IntSizeTyped<CSSPixel> CSSIntSize;
 typedef gfx::RectTyped<CSSPixel> CSSRect;
 typedef gfx::IntRectTyped<CSSPixel> CSSIntRect;
+typedef gfx::MarginTyped<CSSPixel> CSSMargin;
 
 typedef gfx::PointTyped<LayoutDevicePixel> LayoutDevicePoint;
 typedef gfx::IntPointTyped<LayoutDevicePixel> LayoutDeviceIntPoint;
 typedef gfx::SizeTyped<LayoutDevicePixel> LayoutDeviceSize;
 typedef gfx::IntSizeTyped<LayoutDevicePixel> LayoutDeviceIntSize;
 typedef gfx::RectTyped<LayoutDevicePixel> LayoutDeviceRect;
 typedef gfx::IntRectTyped<LayoutDevicePixel> LayoutDeviceIntRect;
+typedef gfx::MarginTyped<LayoutDevicePixel> LayoutDeviceMargin;
 
 typedef gfx::PointTyped<LayerPixel> LayerPoint;
 typedef gfx::IntPointTyped<LayerPixel> LayerIntPoint;
 typedef gfx::SizeTyped<LayerPixel> LayerSize;
 typedef gfx::IntSizeTyped<LayerPixel> LayerIntSize;
 typedef gfx::RectTyped<LayerPixel> LayerRect;
 typedef gfx::IntRectTyped<LayerPixel> LayerIntRect;
+typedef gfx::MarginTyped<LayerPixel> LayerMargin;
 
 typedef gfx::PointTyped<ScreenPixel> ScreenPoint;
 typedef gfx::IntPointTyped<ScreenPixel> ScreenIntPoint;
 typedef gfx::SizeTyped<ScreenPixel> ScreenSize;
 typedef gfx::IntSizeTyped<ScreenPixel> ScreenIntSize;
 typedef gfx::RectTyped<ScreenPixel> ScreenRect;
 typedef gfx::IntRectTyped<ScreenPixel> ScreenIntRect;
+typedef gfx::MarginTyped<ScreenPixel> ScreenMargin;
 
 typedef gfx::ScaleFactor<CSSPixel, LayoutDevicePixel> CSSToLayoutDeviceScale;
 typedef gfx::ScaleFactor<LayoutDevicePixel, CSSPixel> LayoutDeviceToCSSScale;
 typedef gfx::ScaleFactor<CSSPixel, LayerPixel> CSSToLayerScale;
 typedef gfx::ScaleFactor<LayerPixel, CSSPixel> LayerToCSSScale;
 typedef gfx::ScaleFactor<CSSPixel, ScreenPixel> CSSToScreenScale;
 typedef gfx::ScaleFactor<ScreenPixel, CSSPixel> ScreenToCSSScale;
 typedef gfx::ScaleFactor<LayoutDevicePixel, LayerPixel> LayoutDeviceToLayerScale;
--- a/layout/base/nsDisplayList.cpp
+++ b/layout/base/nsDisplayList.cpp
@@ -3089,46 +3089,46 @@ nsDisplayFixedPosition::BuildLayer(nsDis
       GetScrollPositionClampingScrollPortSize();
   }
 
   // Find out the rect of the viewport frame relative to the reference frame.
   // This, in conjunction with the container scale, will correspond to the
   // coordinate-space of the built layer.
   float factor = presContext->AppUnitsPerDevPixel();
   nsPoint origin = viewportFrame->GetOffsetToCrossDoc(ReferenceFrame());
-  gfxRect anchorRect(NSAppUnitsToFloatPixels(origin.x, factor) *
-                       aContainerParameters.mXScale,
-                     NSAppUnitsToFloatPixels(origin.y, factor) *
-                       aContainerParameters.mYScale,
-                     NSAppUnitsToFloatPixels(containingBlockSize.width, factor) *
-                       aContainerParameters.mXScale,
-                     NSAppUnitsToFloatPixels(containingBlockSize.height, factor) *
-                       aContainerParameters.mYScale);
-
-  gfxPoint anchor(anchorRect.x, anchorRect.y);
+  LayerRect anchorRect(NSAppUnitsToFloatPixels(origin.x, factor) *
+                         aContainerParameters.mXScale,
+                       NSAppUnitsToFloatPixels(origin.y, factor) *
+                         aContainerParameters.mYScale,
+                       NSAppUnitsToFloatPixels(containingBlockSize.width, factor) *
+                         aContainerParameters.mXScale,
+                       NSAppUnitsToFloatPixels(containingBlockSize.height, factor) *
+                         aContainerParameters.mYScale);
+
+  LayerPoint anchor = anchorRect.TopLeft();
 
   const nsStylePosition* position = mFixedPosFrame->StylePosition();
   if (position->mOffset.GetRightUnit() != eStyleUnit_Auto)
     anchor.x = anchorRect.XMost();
   if (position->mOffset.GetBottomUnit() != eStyleUnit_Auto)
     anchor.y = anchorRect.YMost();
 
   layer->SetFixedPositionAnchor(anchor);
 
   // Also make sure the layer is aware of any fixed position margins that have
   // been set.
   nsMargin fixedMargins = presContext->PresShell()->GetContentDocumentFixedPositionMargins();
-  mozilla::gfx::Margin fixedLayerMargins(NSAppUnitsToFloatPixels(fixedMargins.top, factor) *
-                                           aContainerParameters.mYScale,
-                                         NSAppUnitsToFloatPixels(fixedMargins.right, factor) *
-                                           aContainerParameters.mXScale,
-                                         NSAppUnitsToFloatPixels(fixedMargins.bottom, factor) *
-                                           aContainerParameters.mYScale,
-                                         NSAppUnitsToFloatPixels(fixedMargins.left, factor) *
-                                           aContainerParameters.mXScale);
+  LayerMargin fixedLayerMargins(NSAppUnitsToFloatPixels(fixedMargins.top, factor) *
+                                  aContainerParameters.mYScale,
+                                NSAppUnitsToFloatPixels(fixedMargins.right, factor) *
+                                  aContainerParameters.mXScale,
+                                NSAppUnitsToFloatPixels(fixedMargins.bottom, factor) *
+                                  aContainerParameters.mYScale,
+                                NSAppUnitsToFloatPixels(fixedMargins.left, factor) *
+                                  aContainerParameters.mXScale);
 
   // If the frame is auto-positioned on either axis, set the top/left layer
   // margins to -1, to indicate to the compositor that this layer is
   // unaffected by fixed margins.
   if (position->mOffset.GetLeftUnit() == eStyleUnit_Auto &&
       position->mOffset.GetRightUnit() == eStyleUnit_Auto) {
     fixedLayerMargins.left = -1;
   }
--- a/layout/generic/test/plugin_clipping_helper_transformed.xhtml
+++ b/layout/generic/test/plugin_clipping_helper_transformed.xhtml
@@ -27,17 +27,16 @@
 <script class="testbody" type="application/javascript">
 <![CDATA[
 
 function runTests() {
   // p1 and p2 are both in a transformed context so they should be hidden.
   checkClipRegionNoBounds("p1", []);
   checkClipRegionNoBounds("p2", []);
 
-  window.opener.SimpleTest.finish();
-  window.close();
+  window.opener.childDone();
 }
 
 ]]>
 </script>
 
 </body>
 </html>
--- a/layout/generic/test/plugin_focus_helper.html
+++ b/layout/generic/test/plugin_focus_helper.html
@@ -2,53 +2,79 @@
 <head>
   <title>Test that clicking on plugins transfers focus correctly</title>
   <style>
   embed { width:200px; height:200px; }
   </style>
 </head>
 <body>
 
-<p><input type="text" id="input">
-<p><embed id="p1" type="application/x-test" wmode="window"></embed><embed id="p2" type="application/x-test"></embed>
+<p><input type="text" id="input"></input>
+<p><embed id="p1" type="application/x-test" wmode="window" paintscript="didPaint('p1')">
+   <embed id="p2" type="application/x-test" paintscript="didPaint('p2')"></p>
 
-<script>
+<script type="text/javascript">
 var SimpleTest = window.opener.SimpleTest;
 var is = window.opener.is;
 var ok = window.opener.ok;
 var todo = window.opener.todo;
+var info = window.opener.info;
 
-netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-var gWindowUtils = window.QueryInterface(Ci.nsIInterfaceRequestor).
-                     getInterface(Ci.nsIDOMWindowUtils);
+SimpleTest.waitForExplicitFinish();
+
+// We don't want to trigger native mouse events until the document is fully
+// loaded and each plugin has painted once.
+var expectPaints = 2;
+var loaded = false;
+function didPaint(id) {
+  ok(--expectPaints >= 0, "Got plugin painted event from "+id);
+  document.getElementById(id).setAttribute("paintscript", null);
+  if (expectPaints == 0) {
+    if (document.readyState == "complete") {
+      theTest();
+    } else {
+      info("Waiting for document load to continue");
+      window.addEventListener("load", function() { theTest(); });
+    }
+  }
+}
+
+//
+// Begin the test
+//
+function theTest() {
+
+const Cc = SpecialPowers.Cc;
+const Ci = SpecialPowers.Ci;
+var gWindowUtils = SpecialPowers.wrap(window)
+                                .QueryInterface(Ci.nsIInterfaceRequestor)
+                                .getInterface(Ci.nsIDOMWindowUtils);
 
 var nativeMouseDown;
 var nativeMouseUp;
 
-SimpleTest.waitForExplicitFinish();
-
 function activatePlugin(id) {
   return function() {
-    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
     var element = document.getElementById(id);
     var bounds = element.getBoundingClientRect();
     var x = (bounds.left + window.mozInnerScreenX + 10);
     var y = (bounds.top + window.mozInnerScreenY + 10);
 
-    gWindowUtils.sendNativeMouseEvent(x, y, nativeMouseDown, 0, element);
-    gWindowUtils.sendNativeMouseEvent(x, y, nativeMouseUp, 0, element);
+    SimpleTest.executeSoon(function () {
+      gWindowUtils.sendNativeMouseEvent(x, y, nativeMouseDown, 0, element);
+      SimpleTest.executeSoon(function () {
+        gWindowUtils.sendNativeMouseEvent(x, y, nativeMouseUp, 0, element);
+      });
+    });
   };
 }
 
 function done() {
-  SimpleTest.finish();
-  window.close();
+  window.opener.childDone();
 }
 
 var step = 0;
 var steps = [
   { event:"focus", id:"input", action:activatePlugin("p1") },
   { event:"blur", id:"input" },
   { event:"focus", id:"p1", action:activatePlugin("p2") },
   { event:"blur", id:"p1" },
@@ -59,18 +85,17 @@ function handleEvent(event) {
   if (step >= steps.length)
     return;
 
   var s = steps[step++];
   is(event.type, s.event, "Check event type");
   is(event.target.id, s.id, "Check event target");
 
   if (s.action) {
-    // Do the action after this event cycle is done
-    setTimeout(s.action, 1000);
+    SimpleTest.executeSoon(s.action);
   }
 }
 
 var elems = ["input", "p1", "p2"];
 for (var i = 0; i < elems.length; ++i) {
   var e = document.getElementById(elems[i]);
   e.addEventListener("focus", handleEvent, false);
   e.addEventListener("blur", handleEvent, false);
@@ -84,15 +109,18 @@ if (navigator.platform.indexOf("Mac") >=
   nativeMouseDown = 1; // NSLeftMouseDown
   nativeMouseUp = 2; // NSLeftMouseUp
   SimpleTest.waitForFocus(doTest, window);
 } else if (navigator.platform.indexOf("Win") >= 0) {
   nativeMouseDown = 2; // MOUSEEVENTF_LEFTDOWN
   nativeMouseUp = 4; // MOUSEEVENTF_LEFTUP
   SimpleTest.waitForFocus(doTest, window);
 } else {
+  // XXX(johns): our gtk2 sendNativeMouseEvent doesn't support clicks
   todo(false, "Platform not supported");
   done();
 }
+
+} // function theTest
 </script>
 
 </body>
 </html>
--- a/layout/generic/test/test_plugin_clipping_transformed.xhtml
+++ b/layout/generic/test/test_plugin_clipping_transformed.xhtml
@@ -3,19 +3,26 @@
 <html xmlns="http://www.w3.org/1999/xhtml" title="Test Plugin Clipping: Plugins in Transforms">
 <head>
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
 </head>
 <body>
 
 <script class="testbody" type="application/javascript">
 <![CDATA[
+
+var child;
+function childDone() {
+  child.close();
+  SimpleTest.executeSoon(SimpleTest.finish());
+}
+
 if (navigator.platform.indexOf("Mac") == 0) {
   todo(false, "Mac plugins do not run in windowed mode");
 } else {
-  window.open("plugin_clipping_helper_transformed.xhtml", "", "width=620,height=320");
   SimpleTest.waitForExplicitFinish();
+  child = window.open("plugin_clipping_helper_transformed.xhtml", "", "width=620,height=320");
 }
 ]]>
 </script>
 
 </body>
 </html>
--- a/layout/generic/test/test_plugin_focus.html
+++ b/layout/generic/test/test_plugin_focus.html
@@ -1,14 +1,21 @@
 <html title="Test plugin focus control">
 <head>
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
 </head>
 <body>
 
 <script class="testbody" type="application/javascript">
-window.open("plugin_focus_helper.html", "", "width=620,height=320");
+
+var child;
+function childDone() {
+  child.close();
+  SimpleTest.executeSoon(SimpleTest.finish());
+}
+
 SimpleTest.waitForExplicitFinish();
+child = window.open("plugin_focus_helper.html", "", "width=620,height=320");
 </script>
 
 </body>
 </html>
--- a/layout/reftests/border-radius/reftest.list
+++ b/layout/reftests/border-radius/reftest.list
@@ -58,18 +58,18 @@ fuzzy-if(true,1,33) fuzzy-if(cocoaWidget
 
 # Inheritance
 == inherit-1.html inherit-1-ref.html # border-radius shouldn't inherit
 
 # Table elements
 == table-collapse-1.html table-collapse-1-ref.html # border-radius is ignored on internal table elements
 # when border-collapse: collapse
 
-skip-if(B2G) == invalidate-1a.html invalidate-1-ref.html
-skip-if(B2G) == invalidate-1b.html invalidate-1-ref.html
+fuzzy-if(azureQuartz,1,3) skip-if(B2G) == invalidate-1a.html invalidate-1-ref.html
+fuzzy-if(azureQuartz,1,3) skip-if(B2G) == invalidate-1b.html invalidate-1-ref.html
 
 # test that border-radius is reduced for scrollbars
 skip-if(B2G) fails-if(Android) == scrollbar-clamping-1.html scrollbar-clamping-1-ref.html
 skip-if(B2G) fails-if(Android) == scrollbar-clamping-2.html scrollbar-clamping-2-ref.html
 
 # Test for bad corner joins.
 fuzzy-if(true,1,1) == corner-joins-1.xhtml corner-joins-1-ref.xhtml
 skip-if(B2G) random-if(winWidget) HTTP(..) == corner-joins-2.xhtml corner-joins-2-ref.xhtml
--- a/layout/reftests/bugs/reftest.list
+++ b/layout/reftests/bugs/reftest.list
@@ -1724,18 +1724,18 @@ fuzzy-if(true,17,5860) == 759036-2.html 
 == 776265-2a.html 776265-2-ref.html
 == 776265-2b.html 776265-2-ref.html
 == 776265-2c.html 776265-2-ref.html
 == 776265-2d.html 776265-2-ref.html
 == 776443-1.html 776443-1-ref.html
 == 776443-2.html 776443-2-ref.html
 == 787947-1.html 787947-1-ref.html
 == 796847-1.svg 796847-1-ref.svg
-fuzzy(40,850) == 797797-1.html 797797-1-ref.html # 'opacity:N' and rgba(,,,N) text don't match precisely
-fuzzy(40,850) == 797797-2.html 797797-2-ref.html # 'opacity:N' and rgba(,,,N) text don't match precisely
+fuzzy(40,850) fuzzy-if(azureQuartz,73,542) == 797797-1.html 797797-1-ref.html # 'opacity:N' and rgba(,,,N) text don't match precisely
+fuzzy(40,850) fuzzy-if(azureQuartz,68,586) == 797797-2.html 797797-2-ref.html # 'opacity:N' and rgba(,,,N) text don't match precisely
 == 801681-1.html 801681-1-ref.html
 == 801681-2.html 801681-2-ref.html
 == 801994-1.html 801994-1-ref.html
 == 804323-1.html 804323-1-ref.html
 fuzzy-if(Android,4,100) == 811301-1.html 811301-1-ref.html
 == 812824-1.html 812824-1-ref.html
 == 814677.html 814677-ref.html
 skip-if(B2G) == 814952-1.html 814952-1-ref.html
--- a/layout/reftests/css-gradients/reftest.list
+++ b/layout/reftests/css-gradients/reftest.list
@@ -1,31 +1,31 @@
-fuzzy-if(!contentSameGfxBackendAsCanvas,2,88500) fuzzy-if(azureSkiaGL,3,89700) == linear-1a.html linear-1-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,2,88500) fuzzy-if(azureSkiaGL,3,89700) == linear-1b.html linear-1-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,2,88500) fuzzy-if(azureSkiaGL,2,89997) == linear-keywords-1a.html linear-keywords-1-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,2,88500) fuzzy-if(azureSkiaGL,2,89997) == linear-keywords-1b.html linear-keywords-1-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,2,88500) == linear-percent.html linear-percent-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,92400) fuzzy-if(azureSkiaGL,2,143400) == linear-mix.html linear-mix-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,2,88500) fuzzy-if(azureSkiaGL,3,89700) fuzzy-if(azureQuartz,1,18) fuzzy-if(azureQuartz&&OSX==10.6,1,34792) == linear-1a.html linear-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,2,88500) fuzzy-if(azureSkiaGL,3,89700) fuzzy-if(azureQuartz,1,18) fuzzy-if(azureQuartz&&OSX==10.6,1,34792) == linear-1b.html linear-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,2,88500) fuzzy-if(azureSkiaGL,2,89997) fuzzy-if(azureQuartz&&OSX==10.6,1,11469) == linear-keywords-1a.html linear-keywords-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,2,88500) fuzzy-if(azureSkiaGL,2,89997) fuzzy-if(azureQuartz,1,11985) == linear-keywords-1b.html linear-keywords-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,2,88500) fuzzy-if(azureQuartz&&OSX==10.6,1,10230) == linear-percent.html linear-percent-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,92400) fuzzy-if(azureSkiaGL,2,143400) fuzzy-if(azureQuartz,1,18215) == linear-mix.html linear-mix-ref.html
 == linear-diagonal-1a.html linear-diagonal-1-ref.html
 == linear-diagonal-1b.html linear-diagonal-1-ref.html
 == linear-diagonal-1c.html linear-diagonal-1-ref.html
 == linear-diagonal-2a.html linear-diagonal-2-ref.html
 == linear-diagonal-2b.html linear-diagonal-2-ref.html
 == linear-diagonal-2c.html linear-diagonal-2-ref.html
 == linear-diagonal-3a.html linear-diagonal-3-ref.html
 == linear-diagonal-3b.html linear-diagonal-3-ref.html
 == linear-diagonal-3c.html linear-diagonal-3-ref.html
 == linear-diagonal-4a.html linear-diagonal-4-ref.html
 == linear-diagonal-4b.html linear-diagonal-4-ref.html
 == linear-diagonal-4c.html linear-diagonal-4-ref.html
-fuzzy(2,11356) == linear-diagonal-5a.html linear-diagonal-5-ref.html
-fuzzy(2,11657) == linear-diagonal-6a.html linear-diagonal-6-ref.html
-fuzzy(2,11298) == linear-diagonal-7a.html linear-diagonal-7-ref.html
-fuzzy(2,11443) == linear-diagonal-8a.html linear-diagonal-8-ref.html
-== linear-diagonal-9a.html linear-diagonal-9-ref.html
+fuzzy(2,11410) == linear-diagonal-5a.html linear-diagonal-5-ref.html
+fuzzy(2,11568) fuzzy-if(azureQuartz&&OSX==10.6,2,11657) == linear-diagonal-6a.html linear-diagonal-6-ref.html
+fuzzy(2,11605) == linear-diagonal-7a.html linear-diagonal-7-ref.html
+fuzzy(2,11407) fuzzy-if(azureQuartz&&OSX==10.6,2,11443) == linear-diagonal-8a.html linear-diagonal-8-ref.html
+fuzzy-if(azureQuartz,4,29373) == linear-diagonal-9a.html linear-diagonal-9-ref.html
 fuzzy(1,800000) == linear-flipped-1.html linear-flipped-1-ref.html
 == linear-position-1a.html linear-position-1-ref.html
 == linear-repeat-1a.html linear-repeat-1-ref.html
 fails-if(d2d) == linear-repeat-1b.html linear-repeat-1-ref.html # bug 582236
 == linear-repeat-1c.html linear-repeat-1-ref.html
 fails-if(d2d) == linear-repeat-1d.html linear-repeat-1-ref.html # bug 582236
 == linear-repeat-1e.html linear-repeat-1-ref.html
 fails-if(d2d) == linear-repeat-1f.html linear-repeat-1-ref.html # bug 582236
@@ -33,21 +33,21 @@ fails-if(d2d) == linear-repeat-1g.html l
 == linear-rotated-1.html linear-rotated-1-ref.html
 == linear-size-1a.html linear-size-1-ref.html
 == linear-stops-1a.html linear-stops-1-ref.html
 == linear-stops-1b.html linear-stops-1-ref.html
 == linear-stops-1c.html linear-stops-1-ref.html
 == linear-stops-1d.html linear-stops-1-ref.html
 == linear-stops-1e.html linear-stops-1-ref.html
 == linear-stops-1f.html linear-stops-1-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,88500) fuzzy-if(azureSkiaGL,2,89700) == linear-vertical-1a.html linear-vertical-1-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,88500) fuzzy-if(azureSkiaGL,2,89700) == linear-vertical-1b.html linear-vertical-1-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,88500) fuzzy-if(azureSkiaGL,2,89700) == linear-vertical-1c.html linear-vertical-1-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,88500) fuzzy-if(azureSkiaGL,2,89700) == linear-vertical-1d.html linear-vertical-1-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,88500) fuzzy-if(azureSkiaGL,2,89700) == linear-vertical-1e.html linear-vertical-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,88500) fuzzy-if(azureSkiaGL,2,89700) fuzzy-if(azureQuartz,1,22367) == linear-vertical-1a.html linear-vertical-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,88500) fuzzy-if(azureSkiaGL,2,89700) fuzzy-if(azureQuartz,1,22367) == linear-vertical-1b.html linear-vertical-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,88500) fuzzy-if(azureSkiaGL,2,89700) fuzzy-if(azureQuartz&&OSX==10.6,1,9627) == linear-vertical-1c.html linear-vertical-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,88500) fuzzy-if(azureSkiaGL,2,89700) fuzzy-if(azureQuartz&&OSX==10.6,1,9627) == linear-vertical-1d.html linear-vertical-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,88500) fuzzy-if(azureSkiaGL,2,89700) fuzzy-if(azureQuartz,1,22367) == linear-vertical-1e.html linear-vertical-1-ref.html
 == linear-vertical-subpixel-1.html linear-vertical-subpixel-1-ref.html
 == linear-viewport.html linear-viewport-ref.html
 == linear-zero-length-1a.html linear-zero-length-1-ref.html
 == linear-zero-length-1b.html linear-zero-length-1-ref.html
 == linear-zero-length-1c.html linear-zero-length-1-ref.html
 == nostops.html about:blank
 == onestop.html about:blank
 fuzzy-if(!contentSameGfxBackendAsCanvas,1,5884) fuzzy-if(cocoaWidget,9,87755) fuzzy-if(azureSkiaGL,2,88024) random-if(d2d) == radial-1a.html radial-1-ref.html
@@ -56,24 +56,24 @@ fuzzy-if(!contentSameGfxBackendAsCanvas,
 fuzzy(3,7860) fuzzy-if(cocoaWidget,5,89041) fuzzy-if(azureSkiaGL,2,90000) == radial-2a.html radial-2-ref.html
 fuzzy(3,7860) fuzzy-if(cocoaWidget,5,89041) fuzzy-if(azureSkiaGL,2,90000) == radial-2b.html radial-2-ref.html
 fuzzy(3,7860) fuzzy-if(cocoaWidget,5,89041) fuzzy-if(azureSkiaGL,2,90000) == radial-2c.html radial-2-ref.html
 fuzzy(3,7860) fuzzy-if(cocoaWidget,5,89041) fuzzy-if(azureSkiaGL,2,90000) == radial-2d.html radial-2-ref.html
 fuzzy(3,7860) fuzzy-if(cocoaWidget,5,89041) fuzzy-if(azureSkiaGL,2,90000) == radial-2e.html radial-2-ref.html
 fuzzy(3,7860) fuzzy-if(cocoaWidget,5,89041) fuzzy-if(azureSkiaGL,2,90000) == radial-2f.html radial-2-ref.html
 == radial-position-1a.html radial-position-1-ref.html
 == radial-position-1b.html radial-position-1-ref.html
-== radial-shape-closest-corner-1a.html radial-shape-closest-corner-1-ref.html
-fuzzy(1,190) fuzzy-if(cocoaWidget,3,460) == radial-shape-closest-corner-1b.html radial-shape-closest-corner-1-ref.html
-== radial-shape-closest-corner-1c.html radial-shape-closest-corner-1-ref.html
+fuzzy-if(azureQuartz,4,22317) == radial-shape-closest-corner-1a.html radial-shape-closest-corner-1-ref.html
+fuzzy(1,190) fuzzy-if(cocoaWidget,3,460) fuzzy-if(azureQuartz,4,22608) == radial-shape-closest-corner-1b.html radial-shape-closest-corner-1-ref.html
+fuzzy-if(azureQuartz,2,41171) == radial-shape-closest-corner-1c.html radial-shape-closest-corner-1-ref.html
 fuzzy-if(/^Windows\x20NT\x206\.2/.test(http.oscpu),1,5) fuzzy-if(Android,17,3880) == radial-shape-closest-side-1a.html radial-shape-closest-side-1-ref.html
 fuzzy-if(/^Windows\x20NT\x206\.2/.test(http.oscpu),1,5) fuzzy-if(Android,17,3880) == radial-shape-closest-side-1b.html radial-shape-closest-side-1-ref.html
 fuzzy-if(/^Windows\x20NT\x206\.2/.test(http.oscpu),1,5) fuzzy-if(Android,17,3880) == radial-shape-closest-side-1c.html radial-shape-closest-side-1-ref.html
 == radial-shape-farthest-corner-1a.html radial-shape-farthest-corner-1-ref.html
-fails-if(cocoaWidget&&/x86-/.test(xulRuntime.XPCOMABI)||gtk2Widget&&/x86_64-/.test(xulRuntime.XPCOMABI)) fuzzy(1,1561) fuzzy-if(cocoaWidget,3,1082) == radial-shape-farthest-corner-1b.html radial-shape-farthest-corner-1-ref.html
+fails-if(cocoaWidget&&/x86-/.test(xulRuntime.XPCOMABI)||gtk2Widget&&/x86_64-/.test(xulRuntime.XPCOMABI)) fuzzy(1,1561) fuzzy-if(cocoaWidget,3,1082) fuzzy-if(azureQuartz,2,41171) fuzzy-if(azureQuartz&&OSX==10.6,3,1082) == radial-shape-farthest-corner-1b.html radial-shape-farthest-corner-1-ref.html
 == radial-shape-farthest-corner-1c.html radial-shape-farthest-corner-1-ref.html
 fuzzy-if(Android,17,13320) == radial-shape-farthest-side-1a.html radial-shape-farthest-side-1-ref.html
 fuzzy-if(Android,17,13320) == radial-shape-farthest-side-1b.html radial-shape-farthest-side-1-ref.html
 fuzzy-if(Android,17,13320) == radial-shape-farthest-side-1c.html radial-shape-farthest-side-1-ref.html
 == radial-size-1a.html radial-size-1-ref.html
 == radial-size-1b.html radial-size-1-ref.html
 == radial-zero-length-1a.html radial-zero-length-1-ref.html
 == radial-zero-length-1b.html radial-zero-length-1-ref.html
@@ -100,33 +100,33 @@ fuzzy-if(d2d,124,2612) == repeating-radi
 == twostops-1b.html twostops-1-ref.html
 == twostops-1c.html twostops-1-ref.html
 == twostops-1d.html twostops-1-ref.html
 == twostops-1e.html twostops-1-ref.html
 == twostops-1f.html twostops-1-ref.html
 == twostops-1g.html twostops-1-ref.html
 
 # from http://www.xanthir.com/:4bhipd by way of http://a-ja.net/newgrad.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) == aja-linear-1a.html aja-linear-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) fuzzy-if(azureQuartz&&OSX==10.6,1,4646) == aja-linear-1a.html aja-linear-1-ref.html
 fails-if(!d2d) == aja-linear-1b.html aja-linear-1-ref.html # bug 526694
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) == aja-linear-1c.html aja-linear-1-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) == aja-linear-1d.html aja-linear-1-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) == aja-linear-1e.html aja-linear-1-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) == aja-linear-1f.html aja-linear-1-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) == aja-linear-1g.html aja-linear-1-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) == aja-linear-2a.html aja-linear-2-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) == aja-linear-2b.html aja-linear-2-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) fuzzy-if(azureQuartz&&OSX==10.6,1,4646) == aja-linear-1c.html aja-linear-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) fuzzy-if(azureQuartz&&OSX==10.6,1,4646) == aja-linear-1d.html aja-linear-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) fuzzy-if(azureQuartz&&OSX==10.6,1,4646) == aja-linear-1e.html aja-linear-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) fuzzy-if(azureQuartz&&OSX==10.6,1,4646) == aja-linear-1f.html aja-linear-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) fuzzy-if(azureQuartz&&OSX==10.6,1,4646) == aja-linear-1g.html aja-linear-1-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) fuzzy-if(azureQuartz&&OSX==10.6,1,4667) == aja-linear-2a.html aja-linear-2-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,20000) fuzzy-if(azureSkiaGL,8,20000) fuzzy-if(azureQuartz&&OSX==10.6,1,4667) == aja-linear-2b.html aja-linear-2-ref.html
 fails == aja-linear-2c.html aja-linear-2-ref.html # bug 522607
 fails-if(!d2d) == aja-linear-2d.html aja-linear-2-ref.html # bug 526694
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,19999) fuzzy-if(azureSkiaGL,8,20000) == aja-linear-3a.html aja-linear-3-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,1,19999) fuzzy-if(azureSkiaGL,8,20000) == aja-linear-3b.html aja-linear-3-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,2,20000) fuzzy-if(azureSkiaGL,8,20000) == aja-linear-4a.html aja-linear-4-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,2,20000) fuzzy-if(azureSkiaGL,8,20000) == aja-linear-4b.html aja-linear-4-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,2,20000) fuzzy-if(azureSkiaGL,8,20000) == aja-linear-5a.html aja-linear-5-ref.html
-fuzzy-if(!contentSameGfxBackendAsCanvas,2,16477) fuzzy-if(azureSkiaGL,8,20000) == aja-linear-6a.html aja-linear-6-ref.html # bug 526708
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,19999) fuzzy-if(azureSkiaGL,8,20000) fuzzy-if(azureQuartz,1,10553) == aja-linear-3a.html aja-linear-3-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,1,19999) fuzzy-if(azureSkiaGL,8,20000) fuzzy-if(azureQuartz,1,10553) == aja-linear-3b.html aja-linear-3-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,2,20000) fuzzy-if(azureSkiaGL,8,20000) fuzzy-if(azureQuartz&&OSX==10.6,1,8655) == aja-linear-4a.html aja-linear-4-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,2,20000) fuzzy-if(azureSkiaGL,8,20000) fuzzy-if(azureQuartz&&OSX==10.6,1,8655) == aja-linear-4b.html aja-linear-4-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,2,20000) fuzzy-if(azureSkiaGL,8,20000) fuzzy-if(azureQuartz&&OSX==10.6,2,7878) == aja-linear-5a.html aja-linear-5-ref.html
+fuzzy-if(!contentSameGfxBackendAsCanvas,2,16477) fuzzy-if(azureSkiaGL,8,20000) fuzzy-if(azureQuartz,2,10163) == aja-linear-6a.html aja-linear-6-ref.html # bug 526708
 fails == aja-linear-6b.html aja-linear-6-ref.html # bug 522607
 skip-if(B2G) == height-dependence-1.html height-dependence-1-ref.html
 skip-if(B2G) fuzzy-if(cocoaWidget,1,40000) == height-dependence-2.html height-dependence-2-ref.html
 skip-if(B2G) == height-dependence-3.html height-dependence-3-ref.html
 
 == linear-onestopposition-1.html linear-onestopposition-1-ref.html
 fuzzy-if(d2d,47,400) == linear-onestopposition-1.html linear-onestopposition-1-ref2.html # d2d interpolates the hard stop
 == radial-onestopposition-1a.html radial-onestopposition-1-ref.html
--- a/layout/reftests/image-element/reftest.list
+++ b/layout/reftests/image-element/reftest.list
@@ -34,13 +34,13 @@ skip-if(B2G) == element-paint-multiple-b
 == gradient-html-02.html gradient-html-02-ref.svg
 random-if(!cocoaWidget) == gradient-html-03.html gradient-html-03-ref.svg
 == gradient-html-04.html gradient-html-04-ref.html
 == gradient-html-05.html gradient-html-05-ref.html
 fuzzy(1,9674) random-if(!cocoaWidget) == gradient-html-06a.html gradient-html-06b.html
 fuzzy(1,9674) random-if(!cocoaWidget) == gradient-html-06b.html gradient-html-06c.html
 == gradient-html-06c.html gradient-html-06d.html
 == gradient-html-06d.html gradient-html-06e.html
-random-if(!cocoaWidget) == gradient-html-07a.html gradient-html-07b.html
-fuzzy-if(Android,9,23112) == gradient-html-07b.html gradient-html-07c.html
+random-if(!cocoaWidget) fuzzy-if(azureQuartz,1,11367) == gradient-html-07a.html gradient-html-07b.html
+fuzzy-if(Android,9,23112) fuzzy-if(azureQuartz,1,11367) == gradient-html-07b.html gradient-html-07c.html
 == pattern-html-01.html pattern-html-01-ref.svg
 == pattern-html-02.html pattern-html-02-ref.svg
 == referenced-from-binding-01.html referenced-from-binding-01-ref.html
--- a/layout/reftests/svg/reftest.list
+++ b/layout/reftests/svg/reftest.list
@@ -27,17 +27,17 @@ include svg-integration/reftest.list
 
 == altGlyph-01.svg altGlyph-01-ref.svg
 == border-radius-01.html pass.svg
 == cssComment-in-attribute-01.svg cssComment-in-attribute-01-ref.svg
 == clip-01.svg pass.svg
 == clip-02a.svg clip-02-ref.svg
 == clip-02b.svg clip-02-ref.svg
 == clipPath-advanced-01.svg pass.svg
-fuzzy-if(/^Windows\x20NT\x206\.[12]/.test(http.oscpu),1,5) == clipPath-and-shape-rendering-01.svg clipPath-and-shape-rendering-01-ref.svg # bug 614840
+fuzzy-if(/^Windows\x20NT\x206\.[12]/.test(http.oscpu),1,5) fuzzy-if(azureQuartz,1,6) == clipPath-and-shape-rendering-01.svg clipPath-and-shape-rendering-01-ref.svg # bug 614840
 == clipPath-and-transform-01.svg pass.svg
 == clipPath-basic-01.svg pass.svg
 == clipPath-basic-02.svg pass.svg
 == clipPath-basic-03.svg pass.svg
 == clipPath-basic-04.svg pass.svg
 == clipPath-basic-05.svg pass.svg
 == clipPath-basic-06.svg pass.svg
 == clipPath-winding-01.svg pass.svg
@@ -208,17 +208,17 @@ random-if(gtk2Widget) == objectBoundingB
 == objectBoundingBox-and-mask.svg pass.svg
 == objectBoundingBox-and-mask-02.svg pass.svg
 == objectBoundingBox-and-pattern-01a.svg objectBoundingBox-and-pattern-01-ref.svg
 == objectBoundingBox-and-pattern-01b.svg objectBoundingBox-and-pattern-01-ref.svg
 == objectBoundingBox-and-pattern-01c.svg objectBoundingBox-and-pattern-01-ref.svg
 == objectBoundingBox-and-pattern-02.svg pass.svg
 == objectBoundingBox-and-pattern-03.svg objectBoundingBox-and-pattern-03-ref.svg
 == opacity-and-gradient-01.svg pass.svg
-skip-if(d2d) == opacity-and-gradient-02.svg opacity-and-gradient-02-ref.svg
+skip-if(d2d) fuzzy-if(azureQuartz,1,99974) == opacity-and-gradient-02.svg opacity-and-gradient-02-ref.svg
 == opacity-and-pattern-01.svg pass.svg
 == opacity-and-transform-01.svg opacity-and-transform-01-ref.svg
 fuzzy-if(Android&&AndroidVersion>=15,8,200) == outer-svg-border-and-padding-01.svg outer-svg-border-and-padding-01-ref.svg 
 == overflow-on-outer-svg-01.svg overflow-on-outer-svg-01-ref.svg
 == overflow-on-outer-svg-02a.xhtml overflow-on-outer-svg-02-ref.xhtml
 == overflow-on-outer-svg-02b.xhtml overflow-on-outer-svg-02-ref.xhtml
 == overflow-on-outer-svg-02c.xhtml overflow-on-outer-svg-02-ref.xhtml
 == overflow-on-outer-svg-02d.xhtml overflow-on-outer-svg-02-ref.xhtml
@@ -305,17 +305,17 @@ fuzzy-if(OSX==10.7,6,2) fuzzy-if(OSX==10
 == text-layout-05.svg text-layout-05-ref.svg
 fuzzy-if(cocoaWidget&&layersGPUAccelerated,1,3) == text-layout-06.svg text-layout-06-ref.svg
 == text-layout-07.svg text-layout-07-ref.svg
 pref(svg.text.css-frames.enabled,true) == text-layout-08.svg text-layout-08-ref.svg
 == text-scale-01.svg text-scale-01-ref.svg
 HTTP(..) == text-scale-02.svg text-scale-02-ref.svg
 HTTP(..) == text-scale-03.svg text-scale-03-ref.svg
 == text-stroke-scaling-01.svg text-stroke-scaling-01-ref.svg
-== stroke-dasharray-01.svg stroke-dasharray-01-ref.svg
+fails-if(OSX==10.8) == stroke-dasharray-01.svg stroke-dasharray-01-ref.svg # bug 896487
 == stroke-dasharray-and-pathLength-01.svg pass.svg
 == stroke-dasharray-and-text-01.svg stroke-dasharray-and-text-01-ref.svg 
 == stroke-linecap-square-w-zero-length-segs-01.svg pass.svg
 == stroke-linecap-square-w-zero-length-segs-02.svg pass.svg
 == textPath-01.svg textPath-01-ref.svg
 == textPath-02.svg pass.svg
 == textPath-03.svg pass.svg
 == text-style-01a.svg text-style-01-ref.svg
--- a/layout/reftests/svg/text/reftest.list
+++ b/layout/reftests/svg/text/reftest.list
@@ -159,17 +159,17 @@ fuzzy-if(/^Windows\x20NT\x206\.[12]/.tes
 
 # dynamic document changes
 == dynamic-font-size.svg dynamic-font-size-ref.svg
 == dynamic-font-size-2.svg dynamic-font-size-2-ref.svg
 == dynamic-font-size-3.svg dynamic-font-size-3-ref.svg
 == dynamic-font-size-4.svg dynamic-font-size-4-ref.svg
 == dynamic-dominant-baseline.svg dynamic-dominant-baseline-ref.svg
 == dynamic-multiple-x.svg dynamic-multiple-x-ref.svg
-fuzzy-if(!d2d,14,2) == dynamic-non-scaling-stroke.svg dynamic-non-scaling-stroke-ref.svg #Bug 885316
+fuzzy-if(!d2d,14,2) fuzzy-if(azureQuartz,1,6) == dynamic-non-scaling-stroke.svg dynamic-non-scaling-stroke-ref.svg #Bug 885316
 
 # text and masks
 HTTP(../..) == mask-applied.svg mask-applied-ref.svg
 HTTP(../..) == mask-content.svg mask-content-ref.svg
 HTTP(../..) == mask-content-2.svg mask-content-2-ref.svg
 
 # text and clipPaths
 HTTP(../..) == clipPath-applied.svg clipPath-applied-ref.svg
--- a/media/mtransport/nr_socket_prsock.cpp
+++ b/media/mtransport/nr_socket_prsock.cpp
@@ -386,18 +386,20 @@ int NrSocket::sendto(const void *msg, si
     ABORT(r);
 
   if(fd_==nullptr)
     ABORT(R_EOD);
 
   // TODO: Convert flags?
   status = PR_SendTo(fd_, msg, len, flags, &naddr, PR_INTERVAL_NO_WAIT);
   if (status < 0 || (size_t)status != len) {
+    if (PR_GetError() == PR_WOULD_BLOCK_ERROR)
+      ABORT(R_WOULDBLOCK);
+
     r_log_e(LOG_GENERIC, LOG_INFO, "Error in sendto %s", to->as_string);
-
     ABORT(R_IO_ERROR);
   }
 
   _status=0;
 abort:
   return(_status);
 }
 
--- a/modules/libpref/src/init/all.js
+++ b/modules/libpref/src/init/all.js
@@ -314,17 +314,19 @@ pref("gfx.font_rendering.opentype_svg.en
 // comma separated list of backends to use in order of preference
 // e.g., pref("gfx.canvas.azure.backends", "direct2d,skia,cairo");
 pref("gfx.canvas.azure.backends", "direct2d,skia,cairo");
 pref("gfx.content.azure.backends", "direct2d");
 pref("gfx.content.azure.enabled", true);
 #else
 pref("gfx.content.azure.enabled", false);
 #ifdef XP_MACOSX
+pref("gfx.content.azure.backends", "cg");
 pref("gfx.canvas.azure.backends", "cg");
+pref("gfx.content.azure.enabled", true);
 // Accelerated cg canvas where available (10.7+)
 pref("gfx.canvas.azure.accelerated", false);
 #else
 pref("gfx.canvas.azure.backends", "cairo");
 pref("gfx.content.azure.backends", "cairo");
 #endif
 #endif
 
--- a/testing/marionette/client/marionette/tests/unit/test_elementState.py
+++ b/testing/marionette/client/marionette/tests/unit/test_elementState.py
@@ -39,15 +39,16 @@ class TestStateChrome(MarionetteTestCase
 
     def test_isEnabled(self):
         l = self.marionette.find_element("id", "textInput")
         self.assertTrue(l.is_enabled())
         self.marionette.execute_script("arguments[0].disabled = true;", [l])
         self.assertFalse(l.is_enabled())
         self.marionette.execute_script("arguments[0].disabled = false;", [l])
 
+    ''' Switched on in Bug 896043 to be turned on in Bug 896046
     def test_isDisplayed(self):
         l = self.marionette.find_element("id", "textInput")
         self.assertTrue(l.is_displayed())
         self.marionette.execute_script("arguments[0].hidden = true;", [l])
         self.assertFalse(l.is_displayed())
         self.marionette.execute_script("arguments[0].hidden = false;", [l])
-
+    '''
\ No newline at end of file
--- a/testing/marionette/client/marionette/tests/unit/test_text.py
+++ b/testing/marionette/client/marionette/tests/unit/test_text.py
@@ -23,16 +23,17 @@ class TestText(MarionetteTestCase):
     def test_sendKeys(self):
         test_html = self.marionette.absolute_url("test.html")
         self.marionette.navigate(test_html)
         l = self.marionette.find_element("name", "myInput")
         self.assertEqual("asdf", self.marionette.execute_script("return arguments[0].value;", [l]))
         l.send_keys("o")
         self.assertEqual("asdfo", self.marionette.execute_script("return arguments[0].value;", [l]))
 
+''' Disabled in bug 896043 and when working on Chrome code re-enable for bug 896046
 class TestTextChrome(MarionetteTestCase):
     def setUp(self):
         MarionetteTestCase.setUp(self)
         self.marionette.set_context("chrome")
         self.win = self.marionette.current_window_handle
         self.marionette.execute_script("window.open('chrome://marionette/content/test.xul', 'foo', 'chrome,centerscreen');")
         self.marionette.switch_to_window('foo')
         self.assertNotEqual(self.win, self.marionette.current_window_handle)
@@ -65,8 +66,9 @@ class TestTextChrome(MarionetteTestCase)
         wins = self.marionette.window_handles
         wins.remove(self.win)
         newWin = wins.pop()
         self.marionette.switch_to_window(newWin)
         box = self.marionette.find_element("id", "textInput")
         self.assertEqual("test", box.text)
         box.send_keys("at")
         self.assertEqual("attest", box.text)
+'''
\ No newline at end of file
--- a/widget/android/AndroidBridge.cpp
+++ b/widget/android/AndroidBridge.cpp
@@ -2156,30 +2156,30 @@ AndroidBridge::SetPageRect(const CSSRect
         return;
 
     client->SetPageRect(aCssPageRect);
 }
 
 void
 AndroidBridge::SyncViewportInfo(const LayerIntRect& aDisplayPort, const CSSToLayerScale& aDisplayResolution,
                                 bool aLayersUpdated, ScreenPoint& aScrollOffset, CSSToScreenScale& aScale,
-                                gfx::Margin& aFixedLayerMargins, ScreenPoint& aOffset)
+                                LayerMargin& aFixedLayerMargins, ScreenPoint& aOffset)
 {
     AndroidGeckoLayerClient *client = mLayerClient;
     if (!client)
         return;
 
     client->SyncViewportInfo(aDisplayPort, aDisplayResolution, aLayersUpdated,
                              aScrollOffset, aScale, aFixedLayerMargins,
                              aOffset);
 }
 
 void AndroidBridge::SyncFrameMetrics(const ScreenPoint& aScrollOffset, float aZoom, const CSSRect& aCssPageRect,
                                      bool aLayersUpdated, const CSSRect& aDisplayPort, const CSSToLayerScale& aDisplayResolution,
-                                     bool aIsFirstPaint, gfx::Margin& aFixedLayerMargins, ScreenPoint& aOffset)
+                                     bool aIsFirstPaint, LayerMargin& aFixedLayerMargins, ScreenPoint& aOffset)
 {
     AndroidGeckoLayerClient *client = mLayerClient;
     if (!client)
         return;
 
     client->SyncFrameMetrics(aScrollOffset, aZoom, aCssPageRect,
                              aLayersUpdated, aDisplayPort, aDisplayResolution,
                              aIsFirstPaint, aFixedLayerMargins, aOffset);
--- a/widget/android/AndroidBridge.h
+++ b/widget/android/AndroidBridge.h
@@ -371,20 +371,20 @@ public:
     void GetCurrentNetworkInformation(hal::NetworkInformation* aNetworkInfo);
     void EnableNetworkNotifications();
     void DisableNetworkNotifications();
 
     void SetFirstPaintViewport(const LayerIntPoint& aOffset, const CSSToLayerScale& aZoom, const CSSRect& aCssPageRect);
     void SetPageRect(const CSSRect& aCssPageRect);
     void SyncViewportInfo(const LayerIntRect& aDisplayPort, const CSSToLayerScale& aDisplayResolution,
                           bool aLayersUpdated, ScreenPoint& aScrollOffset, CSSToScreenScale& aScale,
-                          gfx::Margin& aFixedLayerMargins, ScreenPoint& aOffset);
+                          LayerMargin& aFixedLayerMargins, ScreenPoint& aOffset);
     void SyncFrameMetrics(const ScreenPoint& aScrollOffset, float aZoom, const CSSRect& aCssPageRect,
                           bool aLayersUpdated, const CSSRect& aDisplayPort, const CSSToLayerScale& aDisplayResolution,
-                          bool aIsFirstPaint, gfx::Margin& aFixedLayerMargins, ScreenPoint& aOffset);
+                          bool aIsFirstPaint, LayerMargin& aFixedLayerMargins, ScreenPoint& aOffset);
 
     void AddPluginView(jobject view, const gfxRect& rect, bool isFullScreen);
     void RemovePluginView(jobject view, bool isFullScreen);
 
     // These methods don't use a ScreenOrientation because it's an
     // enum and that would require including the header which requires
     // include IPC headers which requires including basictypes.h which
     // requires a lot of changes...
--- a/widget/android/AndroidJavaWrappers.cpp
+++ b/widget/android/AndroidJavaWrappers.cpp
@@ -944,17 +944,17 @@ AndroidGeckoLayerClient::SetPageRect(con
     AutoLocalJNIFrame jniFrame(env, 0);
     return env->CallVoidMethod(wrapped_obj, jSetPageRect,
                                aCssPageRect.x, aCssPageRect.y, aCssPageRect.XMost(), aCssPageRect.YMost());
 }
 
 void
 AndroidGeckoLayerClient::SyncViewportInfo(const LayerIntRect& aDisplayPort, const CSSToLayerScale& aDisplayResolution,
                                           bool aLayersUpdated, ScreenPoint& aScrollOffset, CSSToScreenScale& aScale,
-                                          gfx::Margin& aFixedLayerMargins, ScreenPoint& aOffset)
+                                          LayerMargin& aFixedLayerMargins, ScreenPoint& aOffset)
 {
     NS_ASSERTION(!isNull(), "SyncViewportInfo called on null layer client!");
     JNIEnv *env = GetJNIForThread();    // this is called on the compositor thread
     if (!env)
         return;
 
     AutoLocalJNIFrame jniFrame(env);
 
@@ -976,17 +976,17 @@ AndroidGeckoLayerClient::SyncViewportInf
 
     aOffset.x = viewTransform.GetOffsetX(env);
     aOffset.y = viewTransform.GetOffsetY(env);
 }
 
 void
 AndroidGeckoLayerClient::SyncFrameMetrics(const ScreenPoint& aScrollOffset, float aZoom, const CSSRect& aCssPageRect,
                                           bool aLayersUpdated, const CSSRect& aDisplayPort, const CSSToLayerScale& aDisplayResolution,
-                                          bool aIsFirstPaint, gfx::Margin& aFixedLayerMargins, ScreenPoint& aOffset)
+                                          bool aIsFirstPaint, LayerMargin& aFixedLayerMargins, ScreenPoint& aOffset)
 {
     NS_ASSERTION(!isNull(), "SyncFrameMetrics called on null layer client!");
     JNIEnv *env = GetJNIForThread();    // this is called on the compositor thread
     if (!env)
         return;
 
     AutoLocalJNIFrame jniFrame(env);
 
@@ -1253,17 +1253,17 @@ float
 AndroidViewTransform::GetScale(JNIEnv *env)
 {
     if (!env)
         return 0.0f;
     return env->GetFloatField(wrapped_obj, jScaleField);
 }
 
 void
-AndroidViewTransform::GetFixedLayerMargins(JNIEnv *env, gfx::Margin &aFixedLayerMargins)
+AndroidViewTransform::GetFixedLayerMargins(JNIEnv *env, LayerMargin &aFixedLayerMargins)
 {
     if (!env)
         return;
 
     aFixedLayerMargins.top = env->GetFloatField(wrapped_obj, jFixedLayerMarginTop);
     aFixedLayerMargins.right = env->GetFloatField(wrapped_obj, jFixedLayerMarginRight);
     aFixedLayerMargins.bottom = env->GetFloatField(wrapped_obj, jFixedLayerMarginBottom);
     aFixedLayerMargins.left = env->GetFloatField(wrapped_obj, jFixedLayerMarginLeft);
--- a/widget/android/AndroidJavaWrappers.h
+++ b/widget/android/AndroidJavaWrappers.h
@@ -192,17 +192,17 @@ public:
     void Init(jobject jobj);
 
     AndroidViewTransform() {}
     AndroidViewTransform(jobject jobj) { Init(jobj); }
 
     float GetX(JNIEnv *env);
     float GetY(JNIEnv *env);
     float GetScale(JNIEnv *env);
-    void GetFixedLayerMargins(JNIEnv *env, gfx::Margin &aFixedLayerMargins);
+    void GetFixedLayerMargins(JNIEnv *env, LayerMargin &aFixedLayerMargins);
     float GetOffsetX(JNIEnv *env);
     float GetOffsetY(JNIEnv *env);
 
 private:
     static jclass jViewTransformClass;
     static jfieldID jXField;
     static jfieldID jYField;
     static jfieldID jScaleField;
@@ -268,20 +268,20 @@ public:
 
     AndroidGeckoLayerClient() {}
     AndroidGeckoLayerClient(jobject jobj) { Init(jobj); }
 
     void SetFirstPaintViewport(const LayerIntPoint& aOffset, const CSSToLayerScale& aZoom, const CSSRect& aCssPageRect);
     void SetPageRect(const CSSRect& aCssPageRect);
     void SyncViewportInfo(const LayerIntRect& aDisplayPort, const CSSToLayerScale& aDisplayResolution,
                           bool aLayersUpdated, ScreenPoint& aScrollOffset, CSSToScreenScale& aScale,
-                          gfx::Margin& aFixedLayerMargins, ScreenPoint& aOffset);
+                          LayerMargin& aFixedLayerMargins, ScreenPoint& aOffset);
     void SyncFrameMetrics(const ScreenPoint& aScrollOffset, float aZoom, const CSSRect& aCssPageRect,
                           bool aLayersUpdated, const CSSRect& aDisplayPort, const CSSToLayerScale& aDisplayResolution,
-                          bool aIsFirstPaint, gfx::Margin& aFixedLayerMargins, ScreenPoint& aOffset);
+                          bool aIsFirstPaint, LayerMargin& aFixedLayerMargins, ScreenPoint& aOffset);
     bool ProgressiveUpdateCallback(bool aHasPendingNewThebesContent, const LayerRect& aDisplayPort, float aDisplayResolution, bool aDrawingCritical, gfx::Rect& aViewport, float& aScaleX, float& aScaleY);
     bool CreateFrame(AutoLocalJNIFrame *jniFrame, AndroidLayerRendererFrame& aFrame);
     bool ActivateProgram(AutoLocalJNIFrame *jniFrame);
     bool DeactivateProgram(AutoLocalJNIFrame *jniFrame);
     void GetDisplayPort(AutoLocalJNIFrame *jniFrame, bool aPageSizeUpdate, bool aIsBrowserContentDisplayed, int32_t tabId, nsIAndroidViewport* metrics, nsIAndroidDisplayport** displayPort);
     void ContentDocumentChanged(AutoLocalJNIFrame *jniFrame);
     bool IsContentDocumentDisplayed(AutoLocalJNIFrame *jniFrame);