Merge inbound to m-c.
authorRyan VanderMeulen <ryanvm@gmail.com>
Mon, 22 Jul 2013 21:47:13 -0400
changeset 151767 5ceea82a79c7d05d20d42445e55bee610c71a054
parent 151719 eee6188bec4167dd8ad64eccea8a8c7e185b4a7b (current diff)
parent 151766 3794beed0e342017fa80d5a0158492f72598822b (diff)
child 151768 fb4bf993a58a153a1d63302ccd2aa3103975f850
child 151770 1fdb491eee10b8676346e8630af1a5f5e1931bad
child 151787 47298789df93060230c315b329bfc494b3f83a7c
child 151817 2e57ec157214a1a6f24224e97a2c109f2b3226b6
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
5ceea82a79c7 / 25.0a1 / 20130723030205 / files
nightly linux64
5ceea82a79c7 / 25.0a1 / 20130723030205 / files
nightly mac
5ceea82a79c7 / 25.0a1 / 20130723030205 / files
nightly win32
5ceea82a79c7 / 25.0a1 / 20130723030205 / files
nightly win64
5ceea82a79c7 / 25.0a1 / 20130723030205 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge inbound to m-c.
--- a/accessible/src/generic/DocAccessible.cpp
+++ b/accessible/src/generic/DocAccessible.cpp
@@ -1260,29 +1260,53 @@ DocAccessible::GetAccessibleByUniqueIDIn
     if (child)
       return child;
   }
 
   return nullptr;
 }
 
 Accessible*
-DocAccessible::GetAccessibleOrContainer(nsINode* aNode)
+DocAccessible::GetAccessibleOrContainer(nsINode* aNode) const
 {
   if (!aNode || !aNode->IsInDoc())
     return nullptr;
 
   nsINode* currNode = aNode;
   Accessible* accessible = nullptr;
   while (!(accessible = GetAccessible(currNode)) &&
          (currNode = currNode->GetParentNode()));
 
   return accessible;
 }
 
+Accessible*
+DocAccessible::GetAccessibleOrDescendant(nsINode* aNode) const
+{
+  Accessible* acc = GetAccessible(aNode);
+  if (acc)
+    return acc;
+
+  acc = GetContainerAccessible(aNode);
+  if (acc) {
+    uint32_t childCnt = acc->ChildCount();
+    for (uint32_t idx = 0; idx < childCnt; idx++) {
+      Accessible* child = acc->GetChildAt(idx);
+      for (nsIContent* elm = child->GetContent();
+           elm && elm != acc->GetContent();
+           elm = elm->GetFlattenedTreeParent()) {
+        if (elm == aNode)
+          return child;
+      }
+    }
+  }
+
+  return nullptr;
+}
+
 bool
 DocAccessible::BindToDocument(Accessible* aAccessible,
                               nsRoleMapEntry* aRoleMapEntry)
 {
   if (!aAccessible)
     return false;
 
   // Put into DOM node cache.
--- a/accessible/src/generic/DocAccessible.h
+++ b/accessible/src/generic/DocAccessible.h
@@ -237,27 +237,32 @@ public:
    * this and nested documents.
    */
   Accessible* GetAccessibleByUniqueIDInSubtree(void* aUniqueID);
 
   /**
    * Return an accessible for the given DOM node or container accessible if
    * the node is not accessible.
    */
-  Accessible* GetAccessibleOrContainer(nsINode* aNode);
+  Accessible* GetAccessibleOrContainer(nsINode* aNode) const;
 
   /**
    * Return a container accessible for the given DOM node.
    */
-  Accessible* GetContainerAccessible(nsINode* aNode)
+  Accessible* GetContainerAccessible(nsINode* aNode) const
   {
     return aNode ? GetAccessibleOrContainer(aNode->GetParentNode()) : nullptr;
   }
 
   /**
+   * Return an accessible for the given node or its first accessible descendant.
+   */
+  Accessible* GetAccessibleOrDescendant(nsINode* aNode) const;
+
+  /**
    * Return true if the given ID is referred by relation attribute.
    *
    * @note Different elements may share the same ID if they are hosted inside
    *       XBL bindings. Be careful the result of this method may be  senseless
    *       while it's called for XUL elements (where XBL is used widely).
    */
   bool IsDependentID(const nsAString& aID) const
     { return mDependentIDsHash.Get(aID, nullptr); }
--- a/accessible/src/windows/msaa/AccessibleWrap.cpp
+++ b/accessible/src/windows/msaa/AccessibleWrap.cpp
@@ -1821,34 +1821,32 @@ AccessibleWrap::GetXPAccessibleFor(const
   // If lVal negative then it is treated as child ID and we should look for
   // accessible through whole accessible subtree including subdocuments.
   // Otherwise we treat lVal as index in parent.
 
   if (aVarChild.lVal < 0) {
     // Convert child ID to unique ID.
     void* uniqueID = reinterpret_cast<void*>(-aVarChild.lVal);
 
-    // Document.
+    DocAccessible* document = Document();
+    Accessible* child =
+      document->GetAccessibleByUniqueIDInSubtree(uniqueID);
+
+    // If it is a document then just return an accessible.
     if (IsDoc())
-      return AsDoc()->GetAccessibleByUniqueIDInSubtree(uniqueID);
+      return child;
 
-    // ARIA document and menu popups.
-    if (ARIARole() == roles::DOCUMENT || IsMenuPopup()) {
-      DocAccessible* document = Document();
-      Accessible* child =
-        document->GetAccessibleByUniqueIDInSubtree(uniqueID);
+    // Otherwise check whether the accessible is a child (this path works for
+    // ARIA documents and popups).
+    Accessible* parent = child;
+    while (parent && parent != document) {
+      if (parent == this)
+        return child;
 
-      // Check whether the accessible for the given ID is a child.
-      Accessible* parent = child ? child->Parent() : nullptr;
-      while (parent && parent != document) {
-        if (parent == this)
-          return child;
-
-        parent = parent->Parent();
-      }
+      parent = parent->Parent();
     }
 
     return nullptr;
   }
 
   // Gecko child indices are 0-based in contrast to indices used in MSAA.
   return GetChildAt(aVarChild.lVal - 1);
 }
--- 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/browser/metro/base/content/RemoteTabs.js
+++ b/browser/metro/base/content/RemoteTabs.js
@@ -126,19 +126,18 @@ let RemoteTabsStartView = {
 let RemoteTabsPanelView = {
   _view: null,
 
   get _grid() { return document.getElementById("remotetabs-list"); },
   get visible() { return PanelUI.isPaneVisible("remotetabs-container"); },
 
   init: function init() {
     //decks are fragile, don't hide the tab panel(bad things happen), hide link in menu.
-    let menuEntry = document.getElementById("menuitem-remotetabs");
     let snappedEntry = document.getElementById("snappedRemoteTabsLabel");
-    let uiList = [menuEntry, snappedEntry];
+    let uiList = [snappedEntry];
     this._view = new RemoteTabsView(this._grid, uiList);
   },
 
   show: function show() {
     this._grid.arrangeItems();
   },
 
   uninit: function uninit() {
--- a/browser/metro/base/content/browser-ui.js
+++ b/browser/metro/base/content/browser-ui.js
@@ -1206,17 +1206,16 @@ var StartUI = {
         aEvent.stopPropagation();
         break;
     }
   }
 };
 
 var PanelUI = {
   get _panels() { return document.getElementById("panel-items"); },
-  get _switcher() { return document.getElementById("panel-view-switcher"); },
 
   get isVisible() {
     return !Elements.panelUI.hidden;
   },
 
   views: {
     "bookmarks-container": "BookmarksPanelView",
     "console-container": "ConsolePanelView",
@@ -1254,17 +1253,16 @@ var PanelUI = {
   switchPane: function switchPane(aPanelId) {
     BrowserUI.blurFocusedElement();
 
     let panel = aPanelId ? document.getElementById(aPanelId) : this._panels.selectedPanel;
     let oldPanel = this._panels.selectedPanel;
 
     if (oldPanel != panel) {
       this._panels.selectedPanel = panel;
-      this._switcher.value = panel.id;
 
       this._fire("ToolPanelHidden", oldPanel);
     }
 
     this._fire("ToolPanelShown", panel);
   },
 
   isPaneVisible: function isPaneVisible(aPanelId) {
--- a/browser/metro/base/content/browser.xul
+++ b/browser/metro/base/content/browser.xul
@@ -297,25 +297,16 @@
           <toolbarbutton id="menu-button" class="appbar-primary" oncommand="Appbar.onMenuButton(event)"/>
         </toolbar>
       </vbox>
     </appbar>
 
     <vbox id="panel-container" hidden="true" class="window-width window-height meta" observes="bcast_windowState">
       <hbox id="panel-header">
         <toolbarbutton id="panel-close-button" command="cmd_panel"/>
-
-        <menulist id="panel-view-switcher" oncommand="PanelUI.switchPane(this.value);">
-          <menupopup>
-            <menuitem label="&bookmarksHeader.label;" value="bookmarks-container" id="menuitem-bookmarks"/>
-            <menuitem label="&startHistoryHeader.label;" value="history-container" id="menuitem-history"/>
-            <menuitem label="&startRemoteTabsHeader.label;" value="remotetabs-container" id="menuitem-remotetabs"/>
-            <menuitem label="&consoleHeader.label;" value="console-container" id="menuitem-console"/>
-          </menupopup>
-        </menulist>
       </hbox>
 
       <deck id="panel-items" selectedIndex="0" flex="1" >
         <scrollbox id="bookmarks-container" flex="1">
           <richgrid id="bookmarks-list" noun="bookmark" class="canSnapTiles" seltype="multiple" flex="1"/>
         </scrollbox>
         <scrollbox id="history-container" flex="1">
           <richgrid id="history-list" noun="history" class="canSnapTiles" seltype="multiple" flex="1"/>
--- a/browser/metro/base/content/console.js
+++ b/browser/metro/base/content/console.js
@@ -28,17 +28,16 @@ let ConsolePanelView = {
       // update users using the legacy pref
       if (Services.prefs.getBoolPref("browser.console.showInPanel")) {
         Services.prefs.setBoolPref(this._enabledPref, true);
         Services.prefs.clearUserPref("browser.console.showInPanel");
       }
     } catch(ex) {
       // likely don't have an old pref
     }
-    this.updateVisibility();
     Services.prefs.addObserver(this._enabledPref, this, false);
   },
 
   show: function show() {
     if (this._inited)
       return;
     this._inited = true;
 
@@ -63,24 +62,20 @@ let ConsolePanelView = {
 
     Services.prefs.removeObserver(this._enabledPref, this, false);
   },
 
   get enabled() {
     return Services.prefs.getBoolPref(this._enabledPref);
   },
 
-  updateVisibility: function ec_updateVisibility(aVal, aPref) {
-    let button = document.getElementById("menuitem-console");
-    button.hidden = !this.enabled;
-  },
-
   observe: function(aSubject, aTopic, aData) {
-    if (aTopic == "nsPref:changed")
-      this.updateVisibility();
+    if (aTopic == "nsPref:changed") {
+      // We may choose to create a new menu in v2
+      }
     else
       this.appendItem(aSubject);
   },
 
   showChromeErrors: function() {
     if (this._showChromeErrors != -1)
       return this._showChromeErrors;
 
--- a/browser/metro/base/tests/mochitest/browser_remotetabs.js
+++ b/browser/metro/base/tests/mochitest/browser_remotetabs.js
@@ -25,24 +25,19 @@ gTests.push({
     yield waitForCondition(() => StartUI.isStartPageVisible);
     yield hideContextUI();
 
     is(Weave.Status.checkSetup(), Weave.CLIENT_NOT_CONFIGURED, "Sync should be disabled on start");
 
     let vbox = document.getElementById("start-remotetabs");
     ok(vbox.hidden, "remote tabs in the start page should be hidden when sync is not enabled");
 
-    // check container link is hidden
-    let menulink = document.getElementById("menuitem-remotetabs");
-    ok(menulink.hidden, "link to container should be hidden when sync is not enabled");
-
     RemoteTabsStartView._view.setUIAccessVisible(true);
 
     // start page grid should be visible
     ok(vbox, "remote tabs grid is present on start page");
     is(vbox.hidden, false, "remote tabs should be visible in start page when sync is enabled");
 
     RemoteTabsStartView._view.setUIAccessVisible(false);
 
     ok(vbox.hidden, "remote tabs in the start page should be hidden when sync is not enabled");
-    ok(menulink.hidden, "link to container should be hidden when sync is not enabled");
   }
 });
--- a/browser/metro/theme/browser.css
+++ b/browser/metro/theme/browser.css
@@ -821,30 +821,16 @@ setting[type="radio"] > vbox {
     width: 40px;
   }
 }
 
 #panel-close-button[disabled] {
   opacity: .5;
 }
 
-#panel-view-switcher {
-  border: 0 none !important;
-  color: #000 !important;
-  background: transparent;
-  padding: 0;
-  font-size: @metro_font_xlarge@;
-  font-weight: 100;
-  margin: 0;
-}
-
-#panel-container[viewstate="snapped"] #panel-view-switcher {
-  font-size: @metro_font_large@;
-}
-
 #panel-items {
   padding-top: 20px;
   -moz-padding-start: 88px;
 }
 
 #panel-container[viewstate="snapped"] #panel-items {
   padding-left: 0px;
 }
--- a/content/canvas/src/WebGLContextVertexArray.cpp
+++ b/content/canvas/src/WebGLContextVertexArray.cpp
@@ -25,16 +25,18 @@ WebGLContext::BindVertexArray(WebGLVerte
          * generated if array is not a name returned from a previous call to
          * GenVertexArraysOES, or if such a name has since been deleted with
          * DeleteVertexArraysOES
          */
         ErrorInvalidOperation("bindVertexArray: can't bind a deleted array!");
         return;
     }
 
+    InvalidateCachedMinInUseAttribArrayLength();
+
     MakeContextCurrent();
 
     if (array) {
         gl->fBindVertexArray(array->GLName());
         array->SetHasEverBeenBound(true);
         mBoundVertexArray = array;
     }
     else {
--- a/content/canvas/src/WebGLExtensionVertexArray.cpp
+++ b/content/canvas/src/WebGLExtensionVertexArray.cpp
@@ -39,26 +39,19 @@ bool WebGLExtensionVertexArray::IsVertex
 
 void WebGLExtensionVertexArray::BindVertexArrayOES(WebGLVertexArray* array)
 {
     mContext->BindVertexArray(array);
 }
 
 bool WebGLExtensionVertexArray::IsSupported(const WebGLContext* context)
 {
-    /*
-     * Security leak with using Vertex Array Objects found while implementing
-     * WebGL 2.0 => Temporally disabled for fixing.
-     */
-    return false;
-/*
     gl::GLContext* gl = context->GL();
 
     if (gl->IsGLES2()) {
         return gl->IsExtensionSupported(gl::GLContext::OES_vertex_array_object);
     }
 
     return gl->IsExtensionSupported(gl::GLContext::ARB_vertex_array_object) ||
            gl->IsExtensionSupported(gl::GLContext::APPLE_vertex_array_object);
- */
 }
 
 IMPL_WEBGL_EXTENSION_GOOP(WebGLExtensionVertexArray)
--- a/content/canvas/test/webgl/conformance/extensions/00_test_list.txt
+++ b/content/canvas/test/webgl/conformance/extensions/00_test_list.txt
@@ -1,8 +1,9 @@
 oes-standard-derivatives.html
 ext-texture-filter-anisotropic.html
 oes-texture-float.html
+oes-vertex-array-object.html
 webgl-debug-renderer-info.html
 webgl-debug-shaders.html
 --min-version 1.0.2 webgl-compressed-texture-s3tc.html
 --min-version 1.0.2 webgl-depth-texture.html
 
--- 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/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/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/RestyleManager.cpp
+++ b/layout/base/RestyleManager.cpp
@@ -339,17 +339,17 @@ RestyleManager::RecomputePosition(nsIFra
         // table elements.  If we apply offsets to things we haven't
         // previously offset, we'll get confused.  So bail.
         return true;
       default:
         break;
     }
 
     nsIFrame* cb = aFrame->GetContainingBlock();
-    const nsSize size = cb->GetSize();
+    const nsSize size = cb->GetContentRectRelativeToSelf().Size();
     const nsPoint oldOffsets = aFrame->GetRelativeOffset();
     nsMargin newOffsets;
 
     // Move the frame
     nsHTMLReflowState::ComputeRelativeOffsets(
         cb->StyleVisibility()->mDirection,
         aFrame, size.width, size.height, newOffsets);
     NS_ASSERTION(newOffsets.left == -newOffsets.right &&
--- 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
@@ -1671,17 +1671,17 @@ fails-if(layersGPUAccelerated&&cocoaWidg
 != 656875.html about:blank
 == 658952.html 658952-ref.html
 == 660682-1.html 660682-1-ref.html
 == 664127-1.xul 664127-1-ref.xul
 skip-if(B2G) == 665597-1.html 665597-1-ref.html
 skip-if(B2G) == 665597-2.html 665597-2-ref.html
 == 668319-1.xul about:blank
 != 669015-1.xul 669015-1-notref.xul
-fuzzy-if(azureSkiaGL,14,2000) == 670442-1.html 670442-1-ref.html
+skip-if(azureSkiaGL) == 670442-1.html 670442-1-ref.html
 == 670467-1.html 670467-1-ref.html
 == 670467-2.html 670467-2-ref.html
 == 690164-1.html 690164-1-ref.html
 == 690643-1.html 690643-1-ref.html
 != 691087-1.html 691087-1-ref.html
 == 691571-1.html 691571-1-ref.html
 == 696307-1.html 696307-1-ref.html
 == 696739-1.html 696739-1-ref.html
@@ -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/canvas/reftest.list
+++ b/layout/reftests/canvas/reftest.list
@@ -67,17 +67,17 @@ fuzzy-if(azureSkiaGL,256,601) fails-if(a
 # this passes with cairo on 10.7 and 10.8 but not with azure for reasons unknown
 fails-if(azureSkiaGL||OSX==10.6||(azureQuartz&&(OSX==10.7||OSX==10.8))) == linear-gradient-1b.html linear-gradient-1-ref.html
 
 == zero-dimensions.html zero-dimensions-ref.html
 
 == evenodd-fill-sanity.html data:text/html,<body>Pass
 != evenodd-fill-1.html nonzero-fill-1.html
 == evenodd-fill-1.html evenodd-fill-ref.html
-== evenodd-fill-2.html evenodd-fill-ref.html
+random-if(azureSkiaGL) == evenodd-fill-2.html evenodd-fill-ref.html
 == evenodd-fill-3.html nonzero-fill-2.html
 
 == dash-sanity.html data:text/html,<body>Pass
 fuzzy-if(azureSkia,9,470) random-if(Android) == dash-1.html dash-1-ref.svg  # Bug 668412 (really is android-specific, not IPC-specific)
 
 == ctm-sanity.html data:text/html,<body>Pass
 == ctm-singular-sanity.html data:text/html,<body>Pass
 == ctm-1.html ctm-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
new file mode 100644
--- /dev/null
+++ b/layout/reftests/position-dynamic-changes/relative/percent-ref.html
@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<html>
+  <head>
+    <link rel="stylesheet" type="text/css" href="style.css">
+  </head>
+  <body>
+    <div id="container" style="border-width: 10px; padding: 50px"
+      >surrounding <span id="rel"
+        style="left: 50%; top: 50%;"
+        >position&#10;relative</span> text</div>
+  </body>
+</html>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/position-dynamic-changes/relative/percent.html
@@ -0,0 +1,20 @@
+<!DOCTYPE html>
+<html class="reftest-wait">
+  <head>
+    <link rel="stylesheet" type="text/css" href="style.css">
+  </head>
+  <body>
+    <div id="container" style="border-width: 10px; padding: 50px"
+      >surrounding <span id="rel"
+        style="left: 0; top: 0;"
+        >position&#10;relative</span> text</div>
+    <script>
+      document.addEventListener("MozReftestInvalidate", function() {
+        var rel = document.getElementById("rel");
+        rel.style.top = "50%";
+        rel.style.left = "50%";
+        document.documentElement.removeAttribute("class");
+      }, false);
+    </script>
+  </body>
+</html>
--- a/layout/reftests/position-dynamic-changes/relative/reftest.list
+++ b/layout/reftests/position-dynamic-changes/relative/reftest.list
@@ -1,4 +1,5 @@
 random-if(cocoaWidget) fuzzy-if(d2d,85,20) == move-right-bottom.html move-right-bottom-ref.html # Bug 742176
 random-if(cocoaWidget) fuzzy-if(d2d,85,20) == move-top-left.html move-top-left-ref.html # Bug 688545, bug 742176
 random-if(cocoaWidget) fuzzy-if(d2d,85,80) == move-right-bottom-table.html move-right-bottom-table-ref.html # Bug 742176
 random-if(cocoaWidget) fuzzy-if(d2d,85,80) == move-top-left-table.html move-top-left-table-ref.html # Bug 688545, bug 742176
+== percent.html percent-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/mobile/android/app/mobile.js
+++ b/mobile/android/app/mobile.js
@@ -757,8 +757,12 @@ pref("dom.payment.provider.0.type", "moz
 pref("dom.payment.provider.0.requestMethod", "GET");
 #endif
 
 // Support for the mozAudioChannel attribute on media elements is disabled in non-webapps
 pref("media.useAudioChannelService", false);
 
 // Turn on the CSP 1.0 parser for Content Security Policy headers
 pref("security.csp.speccompliant", true);
+
+// Enable hardware-accelerated Skia canvas
+pref("gfx.canvas.azure.backends", "skia");
+pref("gfx.canvas.azure.accelerated", true);
--- a/mobile/android/chrome/content/browser.js
+++ b/mobile/android/chrome/content/browser.js
@@ -538,16 +538,28 @@ var BrowserApp = {
       });
 
     NativeWindow.contextmenus.add(Strings.browser.GetStringFromName("contextmenu.fullScreen"),
       NativeWindow.contextmenus.SelectorContext("video:not(:-moz-full-screen)"),
       function(aTarget) {
         aTarget.mozRequestFullScreen();
       });
 
+    NativeWindow.contextmenus.add(Strings.browser.GetStringFromName("contextmenu.mute"),
+      NativeWindow.contextmenus.mediaContext("media-unmuted"),
+      function(aTarget) {
+        aTarget.muted = true;
+      });
+  
+    NativeWindow.contextmenus.add(Strings.browser.GetStringFromName("contextmenu.unmute"),
+      NativeWindow.contextmenus.mediaContext("media-muted"),
+      function(aTarget) {
+        aTarget.muted = false;
+      });
+
     NativeWindow.contextmenus.add(Strings.browser.GetStringFromName("contextmenu.copyImageLocation"),
       NativeWindow.contextmenus.imageLocationCopyableContext,
       function(aTarget) {
         let url = aTarget.src;
         NativeWindow.contextmenus._copyStringToDefaultClipboard(url);
       });
 
     NativeWindow.contextmenus.add(Strings.browser.GetStringFromName("contextmenu.shareImage"),
@@ -1937,16 +1949,22 @@ var NativeWindow = {
             let paused = aElt.paused || aElt.ended;
             if (paused && aMode == "media-paused")
               return true;
             if (!paused && aMode == "media-playing")
               return true;
             let controls = aElt.controls;
             if (!controls && aMode == "media-hidingcontrols")
               return true;
+
+            let muted = aElt.muted;
+            if (muted && aMode == "media-muted")
+              return true;
+            else if (!muted && aMode == "media-unmuted")
+              return true;
           }
           return false;
         }
       }
     },
 
     get _target() {
       if (this._targetRef)
--- a/mobile/android/locales/en-US/chrome/browser.properties
+++ b/mobile/android/locales/en-US/chrome/browser.properties
@@ -159,16 +159,18 @@ contextmenu.copyImageLocation=Copy Image
 contextmenu.shareImage=Share Image
 contextmenu.saveImage=Save Image
 contextmenu.setWallpaper=Set as Wallpaper
 contextmenu.addSearchEngine=Add Search Engine
 contextmenu.playMedia=Play
 contextmenu.pauseMedia=Pause
 contextmenu.shareMedia=Share Video
 contextmenu.showControls2=Show Controls
+contextmenu.mute=Mute
+contextmenu.unmute=Unmute
 contextmenu.saveVideo=Save Video
 contextmenu.saveAudio=Save Audio
 contextmenu.addToContacts=Add to Contacts
 
 contextmenu.copy=Copy
 contextmenu.copyAll=Copy All
 contextmenu.selectWord=Select Word
 contextmenu.selectAll=Select All
--- 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/services/common/modules-testing/bagheeraserver.js
+++ b/services/common/modules-testing/bagheeraserver.js
@@ -17,20 +17,22 @@ Cu.import("resource://testing-common/htt
  * This is an implementation of the Bagheera server.
  *
  * The purpose of the server is to facilitate testing of the Bagheera
  * client and the Firefox Health report. It is *not* meant to be a
  * production grade server.
  *
  * The Bagheera server is essentially a glorified document store.
  */
-this.BagheeraServer = function BagheeraServer() {
+this.BagheeraServer = function BagheeraServer(serverURI="http://localhost") {
   this._log = Log4Moz.repository.getLogger("metrics.BagheeraServer");
 
+  this.serverURI = serverURI;
   this.server = new HttpServer();
+  this.port = 8080;
   this.namespaces = {};
 
   this.allowAllNamespaces = false;
 }
 
 BagheeraServer.prototype = {
   /**
    * Whether this server has a namespace defined.
@@ -119,24 +121,25 @@ BagheeraServer.prototype = {
   createNamespace: function createNamespace(ns) {
     if (ns in this.namespaces) {
       throw new Error("Namespace already exists: " + ns);
     }
 
     this.namespaces[ns] = {};
   },
 
-  start: function start(port=-1) {
+  start: function start(port) {
+    if (!port) {
+      throw new Error("port argument must be specified.");
+    }
+
+    this.port = port;
+
     this.server.registerPrefixHandler("/", this._handleRequest.bind(this));
     this.server.start(port);
-    let i = this.server.identity;
-
-    this.serverURI = i.primaryScheme + "://" + i.primaryHost + ":" +
-                     i.primaryPort + "/";
-    this.port = i.primaryPort;
   },
 
   stop: function stop(cb) {
     let handler = {onStopped: cb};
 
     this.server.stop(handler);
   },
 
--- a/services/common/modules-testing/storageserver.js
+++ b/services/common/modules-testing/storageserver.js
@@ -877,50 +877,48 @@ this.StorageServer = function StorageSer
   // Install our own default handler. This allows us to mess around with the
   // whole URL space.
   let handler = this.server._handler;
   handler._handleDefault = this.handleDefault.bind(this, handler);
 }
 StorageServer.prototype = {
   DEFAULT_QUOTA: 1024 * 1024, // # bytes.
 
+  port:   8080,
   server: null,    // HttpServer.
   users:  null,    // Map of username => {collections, password}.
 
   /**
    * If true, the server will allow any arbitrary user to be used.
    *
    * No authentication will be performed. Whatever user is detected from the
    * URL or auth headers will be created (if needed) and used.
    */
   allowAllUsers: false,
 
   /**
    * Start the StorageServer's underlying HTTP server.
    *
    * @param port
-   *        The numeric port on which to start. A falsy value implies to
-   *        select any available port.
+   *        The numeric port on which to start. A falsy value implies the
+   *        default (8080).
    * @param cb
    *        A callback function (of no arguments) which is invoked after
    *        startup.
    */
   start: function start(port, cb) {
     if (this.started) {
       this._log.warn("Warning: server already started on " + this.port);
       return;
     }
-    if (!port) {
-      port = -1;
+    if (port) {
+      this.port = port;
     }
-    this.port = port;
-
     try {
       this.server.start(this.port);
-      this.port = this.server.identity.primaryPort;
       this.started = true;
       if (cb) {
         cb();
       }
     } catch (ex) {
       _("==========================================");
       _("Got exception starting Storage HTTP server on port " + this.port);
       _("Error: " + CommonUtils.exceptionStr(ex));
@@ -929,20 +927,20 @@ StorageServer.prototype = {
       do_throw(ex);
     }
   },
 
   /**
    * Start the server synchronously.
    *
    * @param port
-   *        The numeric port on which to start. The default is to choose
-   *        any available port.
+   *        The numeric port on which to start. A falsy value implies the
+   *        default (8080).
    */
-  startSynchronous: function startSynchronous(port=-1) {
+  startSynchronous: function startSynchronous(port) {
     let cb = Async.makeSpinningCallback();
     this.start(port, cb);
     cb.wait();
   },
 
   /**
    * Stop the StorageServer's HTTP server.
    *
--- a/services/common/tests/unit/head_global.js
+++ b/services/common/tests/unit/head_global.js
@@ -1,13 +1,16 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 const {classes: Cc, interfaces: Ci, results: Cr, utils: Cu, manager: Cm} = Components;
 
+// Where to bind test HTTP servers to.
+const TEST_SERVER_URL = "http://localhost:8080/";
+
 let gSyncProfile = do_get_profile();
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 
 let XULAppInfo = {
   vendor: "Mozilla",
   name: "XPCShell",
   ID: "xpcshell@tests.mozilla.org",
--- a/services/common/tests/unit/head_helpers.js
+++ b/services/common/tests/unit/head_helpers.js
@@ -41,36 +41,43 @@ function do_check_throws(aFunc, aResult,
  *
  * @param [arg0, arg1, arg2, ...]
  *        Any number of arguments to print out
  * @usage _("Hello World") -> prints "Hello World"
  * @usage _(1, 2, 3) -> prints "1 2 3"
  */
 let _ = function(some, debug, text, to) print(Array.slice(arguments).join(" "));
 
-function httpd_setup (handlers, port=-1) {
+/**
+ * Obtain a port number to run a server on.
+ *
+ * In the ideal world, this would be dynamic so multiple servers could be run
+ * in parallel.
+ */
+function get_server_port() {
+  return 8080;
+}
+
+function httpd_setup (handlers, port) {
+  let port   = port || 8080;
   let server = new HttpServer();
   for (let path in handlers) {
     server.registerPathHandler(path, handlers[path]);
   }
   try {
     server.start(port);
   } catch (ex) {
     _("==========================================");
     _("Got exception starting HTTP server on port " + port);
     _("Error: " + CommonUtils.exceptionStr(ex));
     _("Is there a process already listening on port " + port + "?");
     _("==========================================");
     do_throw(ex);
   }
 
-  // Set the base URI for convenience.
-  let i = server.identity;
-  server.baseURI = i.primaryScheme + "://" + i.primaryHost + ":" + i.primaryPort;
-
   return server;
 }
 
 function httpd_handler(statusCode, status, body) {
   return function handler(request, response) {
     _("Processing request");
     // Allow test functions to inspect the request.
     request.body = readBytesFromInputStream(request.bodyInputStream);
--- a/services/common/tests/unit/test_bagheera_client.js
+++ b/services/common/tests/unit/test_bagheera_client.js
@@ -4,38 +4,42 @@
 "use strict";
 
 Cu.import("resource://services-common/bagheeraclient.js");
 Cu.import("resource://services-common/rest.js");
 Cu.import("resource://testing-common/services-common/bagheeraserver.js");
 Cu.import("resource://gre/modules/Promise.jsm");
 Cu.import("resource://gre/modules/Task.jsm");
 
-function getClientAndServer() {
-  let server = new BagheeraServer();
-  server.start();
+const PORT = 8080;
 
-  let client = new BagheeraClient(server.serverURI);
+function getClientAndServer(port=PORT) {
+  let uri = "http://localhost";
+  let server = new BagheeraServer(uri);
+
+  server.start(port);
+
+  let client = new BagheeraClient(uri + ":" + port);
 
   return [client, server];
 }
 
 function run_test() {
   initTestLogging("Trace");
   run_next_test();
 }
 
 add_test(function test_constructor() {
-  let client = new BagheeraClient("http://localhost:1234/");
+  let client = new BagheeraClient("http://localhost:8080/");
 
   run_next_test();
 });
 
 add_test(function test_post_json_transport_failure() {
-  let client = new BagheeraClient("http://localhost:1234/");
+  let client = new BagheeraClient("http://localhost:8080/");
 
   client.uploadJSON("foo", "bar", {}).then(function onResult(result) {
     do_check_false(result.transportSuccess);
 
     run_next_test();
   });
 });
 
@@ -129,9 +133,9 @@ add_test(function test_delete_document()
   client.deleteDocument("foo", "bar").then(function onResult(result) {
     do_check_true(result.transportSuccess);
     do_check_true(result.serverSuccess);
 
     do_check_null(server.getDocument("foo", "bar"));
 
     server.stop(run_next_test);
   });
-});
+});
\ No newline at end of file
--- a/services/common/tests/unit/test_bagheera_server.js
+++ b/services/common/tests/unit/test_bagheera_server.js
@@ -1,15 +1,17 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 "use strict";
 
 Cu.import("resource://testing-common/services-common/bagheeraserver.js");
 
+const PORT = 8080;
+
 function run_test() {
   run_next_test();
 }
 
 add_test(function test_server_empty() {
   let server = new BagheeraServer();
 
   do_check_false(server.hasNamespace("foo"));
@@ -17,14 +19,27 @@ add_test(function test_server_empty() {
   do_check_null(server.getDocument("foo", "bar"));
 
   server.createNamespace("foo");
   do_check_true(server.hasNamespace("foo"));
 
   run_next_test();
 });
 
+add_test(function test_server_start_no_port() {
+  let server = new BagheeraServer();
+
+  try {
+    server.start();
+  } catch (ex) {
+    do_check_true(ex.message.startsWith("port argument must be"));
+  }
+
+  run_next_test();
+});
+
 add_test(function test_server_start() {
   let server = new BagheeraServer();
-  server.start();
+  server.start(PORT);
+
   server.stop(run_next_test);
 });
 
--- a/services/common/tests/unit/test_restrequest.js
+++ b/services/common/tests/unit/test_restrequest.js
@@ -1,16 +1,18 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 Cu.import("resource://gre/modules/NetUtil.jsm");
 Cu.import("resource://services-common/log4moz.js");
 Cu.import("resource://services-common/rest.js");
 Cu.import("resource://services-common/utils.js");
 
+const TEST_RESOURCE_URL = TEST_SERVER_URL + "resource";
+
 //DEBUG = true;
 
 function run_test() {
   Log4Moz.repository.getLogger("Services.Common.RESTRequest").level =
     Log4Moz.Level.Trace;
   initTestLogging("Trace");
 
   run_next_test();
@@ -67,20 +69,20 @@ add_test(function test_proxy_auth_redire
     response.setStatusLine(metadata.httpVersion, 200, "OK");
     response.bodyOutputStream.write(body, body.length);
   }
 
   let server = httpd_setup({
     "/original": original,
     "/pac3":     pacHandler
   });
-  PACSystemSettings.PACURI = server.baseURI + "/pac3";
+  PACSystemSettings.PACURI = "http://localhost:8080/pac3";
   installFakePAC();
 
-  let res = new RESTRequest(server.baseURI + "/original");
+  let res = new RESTRequest("http://localhost:8080/original");
   res.get(function (error) {
     do_check_true(pacFetched);
     do_check_true(fetched);
     do_check_true(!error);
     do_check_true(this.response.success);
     do_check_eq("TADA!", this.response.body);
     uninstallFakePAC();
     server.stop(run_next_test);
@@ -105,17 +107,18 @@ add_test(function test_forbidden_port() 
 
 /**
  * Demonstrate API short-hand: create a request and dispatch it immediately.
  */
 add_test(function test_simple_get() {
   let handler = httpd_handler(200, "OK", "Huzzah!");
   let server = httpd_setup({"/resource": handler});
 
-  let request = new RESTRequest(server.baseURI + "/resource").get(function (error) {
+  let uri = TEST_RESOURCE_URL;
+  let request = new RESTRequest(uri).get(function (error) {
     do_check_eq(error, null);
 
     do_check_eq(this.status, this.COMPLETED);
     do_check_true(this.response.success);
     do_check_eq(this.response.status, 200);
     do_check_eq(this.response.body, "Huzzah!");
 
     server.stop(run_next_test);
@@ -126,17 +129,17 @@ add_test(function test_simple_get() {
 
 /**
  * Test HTTP GET with all bells and whistles.
  */
 add_test(function test_get() {
   let handler = httpd_handler(200, "OK", "Huzzah!");
   let server = httpd_setup({"/resource": handler});
 
-  let request = new RESTRequest(server.baseURI + "/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
   do_check_eq(request.status, request.NOT_SENT);
 
   request.onProgress = request.onComplete = function () {
     do_throw("This function should have been overwritten!");
   };
 
   let onProgress_called = false;
   function onProgress() {
@@ -190,28 +193,28 @@ add_test(function test_get_utf8() {
     let converter = Cc["@mozilla.org/intl/converter-output-stream;1"]
                     .createInstance(Ci.nsIConverterOutputStream);
     converter.init(res.bodyOutputStream, "UTF-8", 0, 0x0000);
     converter.writeString(response);
     converter.close();
   }});
 
   // Check if charset in Content-Type is propertly interpreted.
-  let request1 = new RESTRequest(server.baseURI + "/resource");
+  let request1 = new RESTRequest(TEST_RESOURCE_URL);
   request1.get(function(error) {
     do_check_null(error);
 
     do_check_eq(request1.response.status, 200);
     do_check_eq(request1.response.body, response);
     do_check_eq(request1.response.headers["content-type"],
                 contentType + charsetSuffix);
 
     // Check that we default to UTF-8 if Content-Type doesn't have a charset.
     charset = false;
-    let request2 = new RESTRequest(server.baseURI + "/resource");
+    let request2 = new RESTRequest(TEST_RESOURCE_URL);
     request2.get(function(error) {
       do_check_null(error);
 
       do_check_eq(request2.response.status, 200);
       do_check_eq(request2.response.body, response);
       do_check_eq(request2.response.headers["content-type"], contentType);
       do_check_eq(request2.response.charset, "utf-8");
 
@@ -237,30 +240,30 @@ add_test(function test_charsets() {
     let converter = Cc["@mozilla.org/intl/converter-output-stream;1"]
                     .createInstance(Ci.nsIConverterOutputStream);
     converter.init(res.bodyOutputStream, "us-ascii", 0, 0x0000);
     converter.writeString(response);
     converter.close();
   }});
 
   // Check that provided charset overrides hint.
-  let request1 = new RESTRequest(server.baseURI + "/resource");
+  let request1 = new RESTRequest(TEST_RESOURCE_URL);
   request1.charset = "not-a-charset";
   request1.get(function(error) {
     do_check_null(error);
 
     do_check_eq(request1.response.status, 200);
     do_check_eq(request1.response.body, response);
     do_check_eq(request1.response.headers["content-type"],
                 contentType + charsetSuffix);
     do_check_eq(request1.response.charset, "us-ascii");
 
     // Check that hint is used if Content-Type doesn't have a charset.
     charset = false;
-    let request2 = new RESTRequest(server.baseURI + "/resource");
+    let request2 = new RESTRequest(TEST_RESOURCE_URL);
     request2.charset = "us-ascii";
     request2.get(function(error) {
       do_check_null(error);
 
       do_check_eq(request2.response.status, 200);
       do_check_eq(request2.response.body, response);
       do_check_eq(request2.response.headers["content-type"], contentType);
       do_check_eq(request2.response.charset, "us-ascii");
@@ -272,17 +275,17 @@ add_test(function test_charsets() {
 
 /**
  * Test HTTP PUT with a simple string argument and default Content-Type.
  */
 add_test(function test_put() {
   let handler = httpd_handler(200, "OK", "Got it!");
   let server = httpd_setup({"/resource": handler});
 
-  let request = new RESTRequest(server.baseURI + "/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
   do_check_eq(request.status, request.NOT_SENT);
 
   request.onProgress = request.onComplete = function () {
     do_throw("This function should have been overwritten!");
   };
 
   let onProgress_called = false;
   function onProgress() {
@@ -321,17 +324,17 @@ add_test(function test_put() {
 
 /**
  * Test HTTP POST with a simple string argument and default Content-Type.
  */
 add_test(function test_post() {
   let handler = httpd_handler(200, "OK", "Got it!");
   let server = httpd_setup({"/resource": handler});
 
-  let request = new RESTRequest(server.baseURI + "/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
   do_check_eq(request.status, request.NOT_SENT);
 
   request.onProgress = request.onComplete = function () {
     do_throw("This function should have been overwritten!");
   };
 
   let onProgress_called = false;
   function onProgress() {
@@ -370,17 +373,17 @@ add_test(function test_post() {
 
 /**
  * Test HTTP DELETE.
  */
 add_test(function test_delete() {
   let handler = httpd_handler(200, "OK", "Got it!");
   let server = httpd_setup({"/resource": handler});
 
-  let request = new RESTRequest(server.baseURI + "/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
   do_check_eq(request.status, request.NOT_SENT);
 
   request.onProgress = request.onComplete = function () {
     do_throw("This function should have been overwritten!");
   };
 
   let onProgress_called = false;
   function onProgress() {
@@ -416,17 +419,17 @@ add_test(function test_delete() {
 
 /**
  * Test an HTTP response with a non-200 status code.
  */
 add_test(function test_get_404() {
   let handler = httpd_handler(404, "Not Found", "Cannae find it!");
   let server = httpd_setup({"/resource": handler});
 
-  let request = new RESTRequest(server.baseURI + "/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
   request.get(function (error) {
     do_check_eq(error, null);
 
     do_check_eq(this.status, this.COMPLETED);
     do_check_false(this.response.success);
     do_check_eq(this.response.status, 404);
     do_check_eq(this.response.body, "Cannae find it!");
 
@@ -442,17 +445,17 @@ add_test(function test_put_json() {
   let handler = httpd_handler(200, "OK");
   let server = httpd_setup({"/resource": handler});
 
   let sample_data = {
     some: "sample_data",
     injson: "format",
     number: 42
   };
-  let request = new RESTRequest(server.baseURI + "/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
   request.put(sample_data, function (error) {
     do_check_eq(error, null);
 
     do_check_eq(this.status, this.COMPLETED);
     do_check_true(this.response.success);
     do_check_eq(this.response.status, 200);
     do_check_eq(this.response.body, "");
 
@@ -472,17 +475,17 @@ add_test(function test_post_json() {
   let handler = httpd_handler(200, "OK");
   let server = httpd_setup({"/resource": handler});
 
   let sample_data = {
     some: "sample_data",
     injson: "format",
     number: 42
   };
-  let request = new RESTRequest(server.baseURI + "/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
   request.post(sample_data, function (error) {
     do_check_eq(error, null);
 
     do_check_eq(this.status, this.COMPLETED);
     do_check_true(this.response.success);
     do_check_eq(this.response.status, 200);
     do_check_eq(this.response.body, "");
 
@@ -496,17 +499,17 @@ add_test(function test_post_json() {
 
 /**
  * HTTP PUT with a custom Content-Type header.
  */
 add_test(function test_put_override_content_type() {
   let handler = httpd_handler(200, "OK");
   let server = httpd_setup({"/resource": handler});
 
-  let request = new RESTRequest(server.baseURI + "/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
   request.setHeader("Content-Type", "application/lolcat");
   request.put("O HAI!!1!", function (error) {
     do_check_eq(error, null);
 
     do_check_eq(this.status, this.COMPLETED);
     do_check_true(this.response.success);
     do_check_eq(this.response.status, 200);
     do_check_eq(this.response.body, "");
@@ -521,17 +524,17 @@ add_test(function test_put_override_cont
 
 /**
  * HTTP POST with a custom Content-Type header.
  */
 add_test(function test_post_override_content_type() {
   let handler = httpd_handler(200, "OK");
   let server = httpd_setup({"/resource": handler});
 
-  let request = new RESTRequest(server.baseURI + "/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
   request.setHeader("Content-Type", "application/lolcat");
   request.post("O HAI!!1!", function (error) {
     do_check_eq(error, null);
 
     do_check_eq(this.status, this.COMPLETED);
     do_check_true(this.response.success);
     do_check_eq(this.response.status, 200);
     do_check_eq(this.response.body, "");
@@ -551,17 +554,17 @@ add_test(function test_get_no_headers() 
   let handler = httpd_handler(200, "OK");
   let server = httpd_setup({"/resource": handler});
 
   let ignore_headers = ["host", "user-agent", "accept", "accept-language",
                         "accept-encoding", "accept-charset", "keep-alive",
                         "connection", "pragma", "cache-control",
                         "content-length"];
 
-  new RESTRequest(server.baseURI + "/resource").get(function (error) {
+  new RESTRequest(TEST_RESOURCE_URL).get(function (error) {
     do_check_eq(error, null);
 
     do_check_eq(this.response.status, 200);
     do_check_eq(this.response.body, "");
 
     let server_headers = handler.request.headers;
     while (server_headers.hasMoreElements()) {
       let header = server_headers.getNext().toString();
@@ -576,33 +579,33 @@ add_test(function test_get_no_headers() 
 
 /**
  * Test changing the URI after having created the request.
  */
 add_test(function test_changing_uri() {
   let handler = httpd_handler(200, "OK");
   let server = httpd_setup({"/resource": handler});
 
-  let request = new RESTRequest("http://localhost:1234/the-wrong-resource");
-  request.uri = CommonUtils.makeURI(server.baseURI + "/resource");
+  let request = new RESTRequest("http://localhost:8080/the-wrong-resource");
+  request.uri = CommonUtils.makeURI(TEST_RESOURCE_URL);
   request.get(function (error) {
     do_check_eq(error, null);
     do_check_eq(this.response.status, 200);
     server.stop(run_next_test);
   });
 });
 
 /**
  * Test setting HTTP request headers.
  */
 add_test(function test_request_setHeader() {
   let handler = httpd_handler(200, "OK");
   let server = httpd_setup({"/resource": handler});
 
-  let request = new RESTRequest(server.baseURI + "/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
 
   request.setHeader("X-What-Is-Weave", "awesome");
   request.setHeader("X-WHAT-is-Weave", "more awesomer");
   request.setHeader("Another-Header", "Hello World");
 
   request.get(function (error) {
     do_check_eq(error, null);
 
@@ -621,17 +624,17 @@ add_test(function test_request_setHeader
  */
 add_test(function test_response_headers() {
   function handler(request, response) {
     response.setHeader("X-What-Is-Weave", "awesome");
     response.setHeader("Another-Header", "Hello World");
     response.setStatusLine(request.httpVersion, 200, "OK");
   }
   let server = httpd_setup({"/resource": handler});
-  let request = new RESTRequest(server.baseURI + "/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
 
   request.get(function (error) {
     do_check_eq(error, null);
 
     do_check_eq(this.response.status, 200);
     do_check_eq(this.response.body, "");
 
     do_check_eq(this.response.headers["x-what-is-weave"], "awesome");
@@ -641,17 +644,17 @@ add_test(function test_response_headers(
   });
 });
 
 /**
  * The onComplete() handler gets called in case of any network errors
  * (e.g. NS_ERROR_CONNECTION_REFUSED).
  */
 add_test(function test_connection_refused() {
-  let request = new RESTRequest("http://localhost:1234/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
   request.onProgress = function onProgress() {
     do_throw("Shouldn't have called request.onProgress()!");
   };
   request.get(function (error) {
     do_check_eq(error.result, Cr.NS_ERROR_CONNECTION_REFUSED);
     do_check_eq(error.message, "NS_ERROR_CONNECTION_REFUSED");
     do_check_eq(this.status, this.COMPLETED);
     run_next_test();
@@ -663,17 +666,17 @@ add_test(function test_connection_refuse
  * Abort a request that just sent off.
  */
 add_test(function test_abort() {
   function handler() {
     do_throw("Shouldn't have gotten here!");
   }
   let server = httpd_setup({"/resource": handler});
 
-  let request = new RESTRequest(server.baseURI + "/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
 
   // Aborting a request that hasn't been sent yet is pointless and will throw.
   do_check_throws(function () {
     request.abort();
   });
 
   request.onProgress = request.onComplete = function () {
     do_throw("Shouldn't have gotten here!");
@@ -701,22 +704,19 @@ add_test(function test_timeout() {
   let server_connection;
   server._handler.handleResponse = function(connection) {
     // This is a handler that doesn't do anything, just keeps the connection
     // open, thereby mimicking a timing out connection. We keep a reference to
     // the open connection for later so it can be properly disposed of. That's
     // why you really only want to make one HTTP request to this server ever.
     server_connection = connection;
   };
-  server.start();
-  let identity = server.identity;
-  let uri = identity.primaryScheme + "://" + identity.primaryHost + ":" +
-            identity.primaryPort;
+  server.start(8080);
 
-  let request = new RESTRequest(uri + "/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
   request.timeout = 0.1; // 100 milliseconds
   request.get(function (error) {
     do_check_eq(error.result, Cr.NS_ERROR_NET_TIMEOUT);
     do_check_eq(this.status, this.ABORTED);
 
     _("Closing connection.");
     server_connection.close();
     _("Shutting down server.");
@@ -726,17 +726,17 @@ add_test(function test_timeout() {
 
 /**
  * An exception thrown in 'onProgress' propagates to the 'onComplete' handler.
  */
 add_test(function test_exception_in_onProgress() {
   let handler = httpd_handler(200, "OK", "Foobar");
   let server = httpd_setup({"/resource": handler});
 
-  let request = new RESTRequest(server.baseURI + "/resource");
+  let request = new RESTRequest(TEST_RESOURCE_URL);
   request.onProgress = function onProgress() {
     it.does.not.exist();
   };
   request.get(function onComplete(error) {
     do_check_eq(error, "ReferenceError: it is not defined");
     do_check_eq(this.status, this.ABORTED);
 
     server.stop(run_next_test);
@@ -748,48 +748,46 @@ add_test(function test_new_channel() {
 
   function checkUA(metadata) {
     let ua = metadata.getHeader("User-Agent");
     _("User-Agent is " + ua);
     do_check_eq("foo bar", ua);
   }
 
   let redirectRequested = false;
-  let redirectURL;
   function redirectHandler(metadata, response) {
     checkUA(metadata);
     redirectRequested = true;
 
     let body = "Redirecting";
     response.setStatusLine(metadata.httpVersion, 307, "TEMPORARY REDIRECT");
-    response.setHeader("Location", redirectURL);
+    response.setHeader("Location", "http://localhost:8081/resource");
     response.bodyOutputStream.write(body, body.length);
   }
 
   let resourceRequested = false;
   function resourceHandler(metadata, response) {
     checkUA(metadata);
     resourceRequested = true;
 
     let body = "Test";
     response.setHeader("Content-Type", "text/plain");
     response.bodyOutputStream.write(body, body.length);
   }
 
-  let server1 = httpd_setup({"/redirect": redirectHandler});
-  let server2 = httpd_setup({"/resource": resourceHandler});
-  redirectURL = server2.baseURI + "/resource";
+  let server1 = httpd_setup({"/redirect": redirectHandler}, 8080);
+  let server2 = httpd_setup({"/resource": resourceHandler}, 8081);
 
   function advance() {
     server1.stop(function () {
       server2.stop(run_next_test);
     });
   }
 
-  let request = new RESTRequest(server1.baseURI + "/redirect");
+  let request = new RESTRequest("http://localhost:8080/redirect");
   request.setHeader("User-Agent", "foo bar");
 
   // Swizzle in our own fakery, because this redirect is neither
   // internal nor URI-preserving. RESTRequest's policy is to only
   // copy headers under certain circumstances.
   let protoMethod = request.shouldCopyOnRedirect;
   request.shouldCopyOnRedirect = function wrapped(o, n, f) {
     // Check the default policy.
@@ -815,19 +813,19 @@ add_test(function test_not_sending_cooki
     response.setStatusLine(metadata.httpVersion, 200, "OK");
     response.bodyOutputStream.write(body, body.length);
     do_check_false(metadata.hasHeader("Cookie"));
   }
   let server = httpd_setup({"/test": handler});
 
   let cookieSer = Cc["@mozilla.org/cookieService;1"]
                     .getService(Ci.nsICookieService);
-  let uri = CommonUtils.makeURI(server.baseURI);
+  let uri = CommonUtils.makeURI("http://localhost:8080");
   cookieSer.setCookieString(uri, null, "test=test; path=/;", null);
 
-  let res = new RESTRequest(server.baseURI + "/test");
+  let res = new RESTRequest("http://localhost:8080/test");
   res.get(function (error) {
     do_check_null(error);
     do_check_true(this.response.success);
     do_check_eq("COOKIE!", this.response.body);
     server.stop(run_next_test);
   });
 });
--- a/services/common/tests/unit/test_storage_server.js
+++ b/services/common/tests/unit/test_storage_server.js
@@ -1,27 +1,26 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 Cu.import("resource://services-common/async.js");
 Cu.import("resource://services-common/rest.js");
 Cu.import("resource://services-common/utils.js");
 Cu.import("resource://testing-common/services-common/storageserver.js");
 
+const PORT = 8080;
 const DEFAULT_USER = "123";
 const DEFAULT_PASSWORD = "password";
 
 /**
  * Helper function to prepare a RESTRequest against the server.
  */
-function localRequest(server, path, user=DEFAULT_USER, password=DEFAULT_PASSWORD) {
+function localRequest(path, user=DEFAULT_USER, password=DEFAULT_PASSWORD) {
   _("localRequest: " + path);
-  let identity = server.server.identity;
-  let url = identity.primaryScheme + "://" + identity.primaryHost + ":" +
-            identity.primaryPort + path;
+  let url = "http://127.0.0.1:" + PORT + path;
   _("url: " + url);
   let req = new RESTRequest(url);
 
   let header = basic_auth_header(user, password);
   req.setHeader("Authorization", header);
   req.setHeader("Accept", "application/json");
 
   return req;
@@ -116,27 +115,28 @@ add_test(function test_creation() {
   _("Ensure a simple server can be created.");
 
   // Explicit callback for this one.
   let server = new StorageServer({
     __proto__: StorageServerCallback,
   });
   do_check_true(!!server);
 
-  server.start(-1, function () {
+  server.start(PORT, function () {
     _("Started on " + server.port);
+    do_check_eq(server.port, PORT);
     server.stop(run_next_test);
   });
 });
 
 add_test(function test_synchronous_start() {
   _("Ensure starting using startSynchronous works.");
 
   let server = new StorageServer();
-  server.startSynchronous();
+  server.startSynchronous(PORT);
   server.stop(run_next_test);
 });
 
 add_test(function test_url_parsing() {
   _("Ensure server parses URLs properly.");
 
   let server = new StorageServer();
 
@@ -179,46 +179,46 @@ add_test(function test_url_parsing() {
 
   run_next_test();
 });
 
 add_test(function test_basic_http() {
   let server = new StorageServer();
   server.registerUser("345", "password");
   do_check_true(server.userExists("345"));
-  server.startSynchronous();
+  server.startSynchronous(PORT);
 
   _("Started on " + server.port);
   do_check_eq(server.requestCount, 0);
-  let req = localRequest(server, "/2.0/storage/crypto/keys");
+  let req = localRequest("/2.0/storage/crypto/keys");
   _("req is " + req);
   req.get(function (err) {
     do_check_eq(null, err);
     do_check_eq(server.requestCount, 1);
     server.stop(run_next_test);
   });
 });
 
 add_test(function test_info_collections() {
   let server = new StorageServer();
   server.registerUser("123", "password");
-  server.startSynchronous();
+  server.startSynchronous(PORT);
 
   let path = "/2.0/123/info/collections";
 
   _("info/collections on empty server should be empty object.");
-  let request = localRequest(server, path, "123", "password");
+  let request = localRequest(path, "123", "password");
   let error = doGetRequest(request);
   do_check_eq(error, null);
   do_check_eq(request.response.status, 200);
   do_check_eq(request.response.body, "{}");
 
   _("Creating an empty collection should result in collection appearing.");
   let coll = server.createCollection("123", "col1");
-  let request = localRequest(server, path, "123", "password");
+  let request = localRequest(path, "123", "password");
   let error = doGetRequest(request);
   do_check_eq(error, null);
   do_check_eq(request.response.status, 200);
   let info = JSON.parse(request.response.body);
   do_check_attribute_count(info, 1);
   do_check_true("col1" in info);
   do_check_eq(info.col1, coll.timestamp);
 
@@ -228,22 +228,21 @@ add_test(function test_info_collections(
 add_test(function test_bso_get_existing() {
   _("Ensure that BSO retrieval works.");
 
   let server = new StorageServer();
   server.registerUser("123", "password");
   server.createContents("123", {
     test: {"bso": {"foo": "bar"}}
   });
-  server.startSynchronous();
+  server.startSynchronous(PORT);
 
   let coll = server.user("123").collection("test");
 
-  let request = localRequest(server, "/2.0/123/storage/test/bso", "123",
-                             "password");
+  let request = localRequest("/2.0/123/storage/test/bso", "123", "password");
   let error = doGetRequest(request);
   do_check_eq(error, null);
   do_check_eq(request.response.status, 200);
   do_check_eq(request.response.headers["content-type"], "application/json");
   let bso = JSON.parse(request.response.body);
   do_check_attribute_count(bso, 3);
   do_check_eq(bso.id, "bso");
   do_check_eq(bso.modified, coll.bso("bso").modified);
@@ -254,24 +253,24 @@ add_test(function test_bso_get_existing(
   server.stop(run_next_test);
 });
 
 add_test(function test_percent_decoding() {
   _("Ensure query string arguments with percent encoded are handled.");
 
   let server = new StorageServer();
   server.registerUser("123", "password");
-  server.startSynchronous();
+  server.startSynchronous(PORT);
 
   let coll = server.user("123").createCollection("test");
   coll.insert("001", {foo: "bar"});
   coll.insert("002", {bar: "foo"});
 
-  let request = localRequest(server, "/2.0/123/storage/test?ids=001%2C002",
-                             "123", "password");
+  let request = localRequest("/2.0/123/storage/test?ids=001%2C002", "123",
+                             "password");
   let error = doGetRequest(request);
   do_check_null(error);
   do_check_eq(request.response.status, 200);
   let items = JSON.parse(request.response.body).items;
   do_check_attribute_count(items, 2);
 
   server.stop(run_next_test);
 });
@@ -279,19 +278,19 @@ add_test(function test_percent_decoding(
 add_test(function test_bso_404() {
   _("Ensure the server responds with a 404 if a BSO does not exist.");
 
   let server = new StorageServer();
   server.registerUser("123", "password");
   server.createContents("123", {
     test: {}
   });
-  server.startSynchronous();
+  server.startSynchronous(PORT);
 
-  let request = localRequest(server, "/2.0/123/storage/test/foo");
+  let request = localRequest("/2.0/123/storage/test/foo");
   let error = doGetRequest(request);
   do_check_eq(error, null);
 
   do_check_eq(request.response.status, 404);
   do_check_false("content-type" in request.response.headers);
 
   server.stop(run_next_test);
 });
@@ -299,36 +298,34 @@ add_test(function test_bso_404() {
 add_test(function test_bso_if_modified_since_304() {
   _("Ensure the server responds properly to X-If-Modified-Since for BSOs.");
 
   let server = new StorageServer();
   server.registerUser("123", "password");
   server.createContents("123", {
     test: {bso: {foo: "bar"}}
   });
-  server.startSynchronous();
+  server.startSynchronous(PORT);
 
   let coll = server.user("123").collection("test");
   do_check_neq(coll, null);
 
   // Rewind clock just in case.
   coll.timestamp -= 10000;
   coll.bso("bso").modified -= 10000;
 
-  let request = localRequest(server, "/2.0/123/storage/test/bso",
-                             "123", "password");
+  let request = localRequest("/2.0/123/storage/test/bso", "123", "password");
   request.setHeader("X-If-Modified-Since", "" + server.serverTime());
   let error = doGetRequest(request);
   do_check_eq(null, error);
 
   do_check_eq(request.response.status, 304);
   do_check_false("content-type" in request.response.headers);
 
-  let request = localRequest(server, "/2.0/123/storage/test/bso",
-                             "123", "password");
+  let request = localRequest("/2.0/123/storage/test/bso", "123", "password");
   request.setHeader("X-If-Modified-Since", "" + (server.serverTime() - 20000));
   let error = doGetRequest(request);
   do_check_eq(null, error);
   do_check_eq(request.response.status, 200);
   do_check_eq(request.response.headers["content-type"], "application/json");
 
   server.stop(run_next_test);
 });
@@ -336,228 +333,220 @@ add_test(function test_bso_if_modified_s
 add_test(function test_bso_if_unmodified_since() {
   _("Ensure X-If-Unmodified-Since works properly on BSOs.");
 
   let server = new StorageServer();
   server.registerUser("123", "password");
   server.createContents("123", {
     test: {bso: {foo: "bar"}}
   });
-  server.startSynchronous();
+  server.startSynchronous(PORT);
 
   let coll = server.user("123").collection("test");
   do_check_neq(coll, null);
 
   let time = coll.timestamp;
 
   _("Ensure we get a 412 for specified times older than server time.");
-  let request = localRequest(server, "/2.0/123/storage/test/bso",
-                             "123", "password");
+  let request = localRequest("/2.0/123/storage/test/bso", "123", "password");
   request.setHeader("X-If-Unmodified-Since", time - 5000);
   request.setHeader("Content-Type", "application/json");
   let payload = JSON.stringify({"payload": "foobar"});
   let error = doPutRequest(request, payload);
   do_check_eq(null, error);
   do_check_eq(request.response.status, 412);
 
   _("Ensure we get a 204 if update goes through.");
-  let request = localRequest(server, "/2.0/123/storage/test/bso",
-                             "123", "password");
+  let request = localRequest("/2.0/123/storage/test/bso", "123", "password");
   request.setHeader("Content-Type", "application/json");
   request.setHeader("X-If-Unmodified-Since", time + 1);
   let error = doPutRequest(request, payload);
   do_check_eq(null, error);
   do_check_eq(request.response.status, 204);
   do_check_true(coll.timestamp > time);
 
   // Not sure why a client would send X-If-Unmodified-Since if a BSO doesn't
   // exist. But, why not test it?
   _("Ensure we get a 201 if creation goes through.");
-  let request = localRequest(server, "/2.0/123/storage/test/none",
-                             "123", "password");
+  let request = localRequest("/2.0/123/storage/test/none", "123", "password");
   request.setHeader("Content-Type", "application/json");
   request.setHeader("X-If-Unmodified-Since", time);
   let error = doPutRequest(request, payload);
   do_check_eq(null, error);
   do_check_eq(request.response.status, 201);
 
   server.stop(run_next_test);
 });
 
 add_test(function test_bso_delete_not_exist() {
   _("Ensure server behaves properly when deleting a BSO that does not exist.");
 
   let server = new StorageServer();
   server.registerUser("123", "password");
   server.user("123").createCollection("empty");
-  server.startSynchronous();
+  server.startSynchronous(PORT);
 
   server.callback.onItemDeleted = function onItemDeleted(username, collection,
                                                          id) {
     do_throw("onItemDeleted should not have been called.");
   };
 
-  let request = localRequest(server, "/2.0/123/storage/empty/nada",
-                             "123", "password");
+  let request = localRequest("/2.0/123/storage/empty/nada", "123", "password");
   let error = doDeleteRequest(request);
   do_check_eq(error, null);
   do_check_eq(request.response.status, 404);
   do_check_false("content-type" in request.response.headers);
 
   server.stop(run_next_test);
 });
 
 add_test(function test_bso_delete_exists() {
   _("Ensure proper semantics when deleting a BSO that exists.");
 
   let server = new StorageServer();
   server.registerUser("123", "password");
-  server.startSynchronous();
+  server.startSynchronous(PORT);
 
   let coll = server.user("123").createCollection("test");
   let bso = coll.insert("myid", {foo: "bar"});
   let timestamp = coll.timestamp;
 
   server.callback.onItemDeleted = function onDeleted(username, collection, id) {
     delete server.callback.onItemDeleted;
     do_check_eq(username, "123");
     do_check_eq(collection, "test");
     do_check_eq(id, "myid");
   };
 
-  let request = localRequest(server, "/2.0/123/storage/test/myid",
-                             "123", "password");
+  let request = localRequest("/2.0/123/storage/test/myid", "123", "password");
   let error = doDeleteRequest(request);
   do_check_eq(error, null);
   do_check_eq(request.response.status, 204);
   do_check_eq(coll.bsos().length, 0);
   do_check_true(coll.timestamp > timestamp);
 
   _("On next request the BSO should not exist.");
-  let request = localRequest(server, "/2.0/123/storage/test/myid",
-                             "123", "password");
+  let request = localRequest("/2.0/123/storage/test/myid", "123", "password");
   let error = doGetRequest(request);
   do_check_eq(error, null);
   do_check_eq(request.response.status, 404);
 
   server.stop(run_next_test);
 });
 
 add_test(function test_bso_delete_unmodified() {
   _("Ensure X-If-Unmodified-Since works when deleting BSOs.");
 
   let server = new StorageServer();
-  server.startSynchronous();
+  server.startSynchronous(PORT);
   server.registerUser("123", "password");
   let coll = server.user("123").createCollection("test");
   let bso = coll.insert("myid", {foo: "bar"});
 
   let modified = bso.modified;
 
   _("Issuing a DELETE with an older time should fail.");
   let path = "/2.0/123/storage/test/myid";
-  let request = localRequest(server, path, "123", "password");
+  let request = localRequest(path, "123", "password");
   request.setHeader("X-If-Unmodified-Since", modified - 1000);
   let error = doDeleteRequest(request);
   do_check_eq(error, null);
   do_check_eq(request.response.status, 412);
   do_check_false("content-type" in request.response.headers);
   do_check_neq(coll.bso("myid"), null);
 
   _("Issuing a DELETE with a newer time should work.");
-  let request = localRequest(server, path, "123", "password");
+  let request = localRequest(path, "123", "password");
   request.setHeader("X-If-Unmodified-Since", modified + 1000);
   let error = doDeleteRequest(request);
   do_check_eq(error, null);
   do_check_eq(request.response.status, 204);
   do_check_true(coll.bso("myid").deleted);
 
   server.stop(run_next_test);
 });
 
 add_test(function test_collection_get_unmodified_since() {
   _("Ensure conditional unmodified get on collection works when it should.");
 
   let server = new StorageServer();
   server.registerUser("123", "password");
-  server.startSynchronous();
+  server.startSynchronous(PORT);
   let collection = server.user("123").createCollection("testcoll");
   collection.insert("bso0", {foo: "bar"});
 
   let serverModified = collection.timestamp;
 
-  let request1 = localRequest(server, "/2.0/123/storage/testcoll",
-                              "123", "password");
+  let request1 = localRequest("/2.0/123/storage/testcoll", "123", "password");
   request1.setHeader("X-If-Unmodified-Since", serverModified);
   let error = doGetRequest(request1);
   do_check_null(error);
   do_check_eq(request1.response.status, 200);
 
-  let request2 = localRequest(server, "/2.0/123/storage/testcoll",
-                              "123", "password");
+  let request2 = localRequest("/2.0/123/storage/testcoll", "123", "password");
   request2.setHeader("X-If-Unmodified-Since", serverModified - 1);
   let error = doGetRequest(request2);
   do_check_null(error);
   do_check_eq(request2.response.status, 412);
 
   server.stop(run_next_test);
 });
 
 add_test(function test_bso_get_unmodified_since() {
   _("Ensure conditional unmodified get on BSO works appropriately.");
 
   let server = new StorageServer();
   server.registerUser("123", "password");
-  server.startSynchronous();
+  server.startSynchronous(PORT);
   let collection = server.user("123").createCollection("testcoll");
   let bso = collection.insert("bso0", {foo: "bar"});
 
   let serverModified = bso.modified;
 
-  let request1 = localRequest(server, "/2.0/123/storage/testcoll/bso0",
-                              "123", "password");
+  let request1 = localRequest("/2.0/123/storage/testcoll/bso0", "123",
+                              "password");
   request1.setHeader("X-If-Unmodified-Since", serverModified);
   let error = doGetRequest(request1);
   do_check_null(error);
   do_check_eq(request1.response.status, 200);
 
-  let request2 = localRequest(server, "/2.0/123/storage/testcoll/bso0",
-                              "123", "password");
+  let request2 = localRequest("/2.0/123/storage/testcoll/bso0", "123",
+                              "password");
   request2.setHeader("X-If-Unmodified-Since", serverModified - 1);
   let error = doGetRequest(request2);
   do_check_null(error);
   do_check_eq(request2.response.status, 412);
 
   server.stop(run_next_test);
 });
 
 add_test(function test_missing_collection_404() {
   _("Ensure a missing collection returns a 404.");
 
   let server = new StorageServer();
   server.registerUser("123", "password");
-  server.startSynchronous();
+  server.startSynchronous(PORT);
 
-  let request = localRequest(server, "/2.0/123/storage/none", "123", "password");
+  let request = localRequest("/2.0/123/storage/none", "123", "password");
   let error = doGetRequest(request);
   do_check_eq(error, null);
   do_check_eq(request.response.status, 404);
   do_check_false("content-type" in request.response.headers);
 
   server.stop(run_next_test);
 });
 
 add_test(function test_get_storage_405() {
   _("Ensure that a GET on /storage results in a 405.");
 
   let server = new StorageServer();
   server.registerUser("123", "password");
-  server.startSynchronous();
+  server.startSynchronous(PORT);
 
-  let request = localRequest(server, "/2.0/123/storage", "123", "password");
+  let request = localRequest("/2.0/123/storage", "123", "password");
   let error = doGetRequest(request);
   do_check_eq(error, null);
   do_check_eq(request.response.status, 405);
   do_check_eq(request.response.headers["allow"], "DELETE");
 
   server.stop(run_next_test);
 });
 
@@ -566,108 +555,108 @@ add_test(function test_delete_storage() 
 
   let server = new StorageServer();
   server.registerUser("123", "password");
   server.createContents("123", {
     foo: {a: {foo: "bar"}, b: {bar: "foo"}},
     baz: {c: {bob: "law"}, blah: {law: "blog"}}
   });
 
-  server.startSynchronous();
+  server.startSynchronous(PORT);
 
-  let request = localRequest(server, "/2.0/123/storage", "123", "password");
+  let request = localRequest("/2.0/123/storage", "123", "password");
   let error = doDeleteRequest(request);
   do_check_eq(error, null);
   do_check_eq(request.response.status, 204);
   do_check_attribute_count(server.users["123"].collections, 0);
 
   server.stop(run_next_test);
 });
 
 add_test(function test_x_num_records() {
   let server = new StorageServer();
   server.registerUser("123", "password");
 
   server.createContents("123", {
     crypto: {foos: {foo: "bar"},
              bars: {foo: "baz"}}
   });
-  server.startSynchronous();
-  let bso = localRequest(server, "/2.0/123/storage/crypto/foos");
+  server.startSynchronous(PORT);
+  let bso = localRequest("/2.0/123/storage/crypto/foos");
   bso.get(function (err) {
     // BSO fetches don't have one.
     do_check_false("x-num-records" in this.response.headers);
-    let col = localRequest(server, "/2.0/123/storage/crypto");
+    let col = localRequest("/2.0/123/storage/crypto");
     col.get(function (err) {
       // Collection fetches do.
       do_check_eq(this.response.headers["x-num-records"], "2");
       server.stop(run_next_test);
     });
   });
 });
 
 add_test(function test_put_delete_put() {
   _("Bug 790397: Ensure BSO deleted flag is reset on PUT.");
 
   let server = new StorageServer();
   server.registerUser("123", "password");
   server.createContents("123", {
     test: {bso: {foo: "bar"}}
   });
-  server.startSynchronous();
+  server.startSynchronous(PORT);
 
   _("Ensure we can PUT an existing record.");
-  let request1 = localRequest(server, "/2.0/123/storage/test/bso", "123", "password");
+  let request1 = localRequest("/2.0/123/storage/test/bso", "123", "password");
   request1.setHeader("Content-Type", "application/json");
   let payload1 = JSON.stringify({"payload": "foobar"});
   let error1 = doPutRequest(request1, payload1);
   do_check_eq(null, error1);
   do_check_eq(request1.response.status, 204);
 
   _("Ensure we can DELETE it.");
-  let request2 = localRequest(server, "/2.0/123/storage/test/bso", "123", "password");
+  let request2 = localRequest("/2.0/123/storage/test/bso", "123", "password");
   let error2 = doDeleteRequest(request2);
   do_check_eq(error2, null);
   do_check_eq(request2.response.status, 204);
   do_check_false("content-type" in request2.response.headers);
 
   _("Ensure we can PUT a previously deleted record.");
-  let request3 = localRequest(server, "/2.0/123/storage/test/bso", "123", "password");
+  let request3 = localRequest("/2.0/123/storage/test/bso", "123", "password");
   request3.setHeader("Content-Type", "application/json");
   let payload3 = JSON.stringify({"payload": "foobar"});
   let error3 = doPutRequest(request3, payload3);
   do_check_eq(null, error3);
   do_check_eq(request3.response.status, 201);
 
   _("Ensure we can GET the re-uploaded record.");
-  let request4 = localRequest(server, "/2.0/123/storage/test/bso", "123", "password");
+  let request4 = localRequest("/2.0/123/storage/test/bso", "123", "password");
   let error4 = doGetRequest(request4);
   do_check_eq(error4, null);
   do_check_eq(request4.response.status, 200);
   do_check_eq(request4.response.headers["content-type"], "application/json");
 
   server.stop(run_next_test);
 });
 
 add_test(function test_collection_get_newer() {
   _("Ensure get with newer argument on collection works.");
 
   let server = new StorageServer();
   server.registerUser("123", "password");
-  server.startSynchronous();
+  server.startSynchronous(PORT);
 
   let coll = server.user("123").createCollection("test");
   let bso1 = coll.insert("001", {foo: "bar"});
   let bso2 = coll.insert("002", {bar: "foo"});
 
   // Don't want both records to have the same timestamp.
   bso2.modified = bso1.modified + 1000;
 
   function newerRequest(newer) {
-    return localRequest(server, "/2.0/123/storage/test?newer=" + newer,
+    return localRequest("/2.0/123/storage/test?newer=" + newer,
                         "123", "password");
   }
 
   let request1 = newerRequest(0);
   let error1 = doGetRequest(request1);
   do_check_null(error1);
   do_check_eq(request1.response.status, 200);
   let items1 = JSON.parse(request1.response.body).items;
@@ -683,9 +672,9 @@ add_test(function test_collection_get_ne
   let request3 = newerRequest(bso2.modified + 1);
   let error3 = doGetRequest(request3);
   do_check_null(error3);
   do_check_eq(request3.response.status, 200);
   let items3 = JSON.parse(request3.response.body).items;
   do_check_attribute_count(items3, 0);
 
   server.stop(run_next_test);
-});
+});
\ No newline at end of file
--- a/services/common/tests/unit/test_storageservice_client.js
+++ b/services/common/tests/unit/test_storageservice_client.js
@@ -1,14 +1,16 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 Cu.import("resource://services-common/storageservice.js");
 Cu.import("resource://testing-common/services-common/storageserver.js");
 
+const BASE_URI = "http://localhost:8080/2.0";
+
 function run_test() {
   initTestLogging("Trace");
 
   run_next_test();
 }
 
 function getRandomUser() {
   return "" + (Math.floor(Math.random() * 100000) + 1);
@@ -20,59 +22,56 @@ function getEmptyServer(user=getRandomUs
 
   return storageServerForUsers(users, {
     meta:    {},
     clients: {},
     crypto:  {},
   });
 }
 
-function getClient(server, user=getRandomUser(), password="password") {
-  let identity = server.server.identity;
-  let url = identity.primaryScheme + "://" + identity.primaryHost + ":" +
-            identity.primaryPort + "/2.0/" + user;
-  let client = new StorageServiceClient(url);
+function getClient(user=getRandomUser(), password="password") {
+  let client = new StorageServiceClient(BASE_URI + "/" + user);
   client.addListener({
     onDispatch: function onDispatch(request) {
       let up = user + ":" + password;
       request.request.setHeader("authorization", "Basic " + btoa(up));
     }
   });
 
   return client;
 }
 
 function getServerAndClient(user=getRandomUser(), password="password") {
   let server = getEmptyServer(user, password);
-  let client = getClient(server, user, password);
+  let client = getClient(user, password);
 
   return [server, client, user, password];
 }
 
 add_test(function test_auth_failure_listener() {
   _("Ensure the onAuthFailure listener is invoked.");
 
   let server = getEmptyServer();
-  let client = getClient(server, "324", "INVALID");
+  let client = getClient("324", "INVALID");
   client.addListener({
     onAuthFailure: function onAuthFailure(client, request) {
       _("onAuthFailure");
       server.stop(run_next_test);
     }
   });
 
   let request = client.getCollectionInfo();
   request.dispatch();
 });
 
 add_test(function test_duplicate_listeners() {
   _("Ensure that duplicate listeners aren't installed multiple times.");
 
   let server = getEmptyServer();
-  let client = getClient(server, "1234567", "BAD_PASSWORD");
+  let client = getClient("1234567", "BAD_PASSWORD");
 
   let invokeCount = 0;
   let listener = {
     onAuthFailure: function onAuthFailure() {
       invokeCount++;
     }
   };
 
@@ -582,19 +581,18 @@ add_test(function test_set_bso_condition
 
     server.stop(run_next_test);
   });
 });
 
 add_test(function test_set_bso_argument_errors() {
   _("Ensure BSO set detects invalid arguments.");
 
-  let server = getEmptyServer();
   let bso = new BasicStorageObject();
-  let client = getClient(server);
+  let client = getClient();
 
   let threw = false;
   try {
     client.setBSO(bso);
   } catch (ex) {
     threw = true;
     do_check_eq(ex.name, "Error");
     do_check_neq(ex.message.indexOf("does not have collection defined"), -1);
@@ -622,17 +620,17 @@ add_test(function test_set_bso_argument_
     threw = true;
     do_check_eq(ex.name, "Error");
     do_check_neq(ex.message.indexOf("does not have ID defined"), -1);
   } finally {
     do_check_true(threw);
     threw = false;
   }
 
-  server.stop(run_next_test);
+  run_next_test();
 });
 
 add_test(function test_set_bsos_simple() {
   _("Ensure setBSOs with basic options works.");
 
   let [server, client, username] = getServerAndClient();
   let user = server.user(username);
 
@@ -656,18 +654,17 @@ add_test(function test_set_bsos_simple()
 
     server.stop(run_next_test);
   });
 });
 
 add_test(function test_set_bsos_invalid_bso() {
   _("Ensure that adding an invalid BSO throws.");
 
-  let server = getEmptyServer();
-  let client = getClient(server);
+  let client = getClient();
   let request = client.setBSOs("testcoll");
 
   let threw = false;
 
   // Empty argument is invalid.
   try {
     request.addBSO(null);
   } catch (ex) {
@@ -682,17 +679,17 @@ add_test(function test_set_bsos_invalid_
     request.addBSO(bso);
   } catch (ex) {
     threw = true;
   } finally {
     do_check_true(threw);
     threw = false;
   }
 
-  server.stop(run_next_test);
+  run_next_test();
 });
 
 add_test(function test_set_bsos_newline() {
   _("Ensure that newlines in BSO payloads are formatted properly.");
 
   let [server, client, username] = getServerAndClient();
   let user = server.user(username);
 
--- a/services/common/tests/unit/test_tokenauthenticatedrequest.js
+++ b/services/common/tests/unit/test_tokenauthenticatedrequest.js
@@ -16,37 +16,36 @@ add_test(function test_authenticated_req
 
   let message = "Great Success!";
 
   // TODO: We use a preset key here, but use getTokenFromBrowserIDAssertion()
   // from TokenServerClient to get a real one when possible. (Bug 745800)
   let id = "eyJleHBpcmVzIjogMTM2NTAxMDg5OC4x";
   let key = "qTZf4ZFpAMpMoeSsX3zVRjiqmNs=";
   let method = "GET";
+  let uri = CommonUtils.makeURI(TEST_SERVER_URL + "foo");
 
   let nonce = btoa(CryptoUtils.generateRandomBytes(16));
   let ts = Math.floor(Date.now() / 1000);
   let extra = {ts: ts, nonce: nonce};
 
-  let auth;
+  let sig = CryptoUtils.computeHTTPMACSHA1(id, key, method, uri, extra);
+  let auth = sig.getHeader();
 
   let server = httpd_setup({"/foo": function(request, response) {
       do_check_true(request.hasHeader("Authorization"));
       do_check_eq(auth, request.getHeader("Authorization"));
 
       response.setStatusLine(request.httpVersion, 200, "OK");
       response.bodyOutputStream.write(message, message.length);
     }
   });
-  let uri = CommonUtils.makeURI(server.baseURI + "/foo");
-  let sig = CryptoUtils.computeHTTPMACSHA1(id, key, method, uri, extra);
-  auth = sig.getHeader();
 
   let req = new TokenAuthenticatedRESTRequest(uri, {id: id, key: key}, extra);
   let cb = Async.makeSpinningCallback();
   req.get(cb);
   let result = cb.wait();
 
   do_check_eq(null, result);
   do_check_eq(message, req.response.body);
 
   server.stop(run_next_test);
-});
+});
\ No newline at end of file
--- a/services/common/tests/unit/test_tokenserverclient.js
+++ b/services/common/tests/unit/test_tokenserverclient.js
@@ -31,17 +31,17 @@ add_test(function test_working_bid_excha
         uid:          "uid",
       });
       response.bodyOutputStream.write(body, body.length);
     }
   });
 
   let client = new TokenServerClient();
   let cb = Async.makeSpinningCallback();
-  let url = server.baseURI + "/1.0/foo/1.0";
+  let url = TEST_SERVER_URL + "1.0/foo/1.0";
   client.getTokenFromBrowserIDAssertion(url, "assertion", cb);
   let result = cb.wait();
   do_check_eq("object", typeof(result));
   do_check_attribute_count(result, 4);
   do_check_eq(service, result.endpoint);
   do_check_eq("id", result.id);
   do_check_eq("key", result.key);
   do_check_eq("uid", result.uid);
@@ -88,17 +88,17 @@ add_test(function test_conditions_requir
         errors: [{description: description, location: "body", name: ""}],
         urls: {tos: tosURL}
       });
       response.bodyOutputStream.write(body, body.length);
     }
   });
 
   let client = new TokenServerClient();
-  let url = server.baseURI + "/1.0/foo/1.0";
+  let url = TEST_SERVER_URL + "1.0/foo/1.0";
 
   function onResponse(error, token) {
     do_check_true(error instanceof TokenServerClientServerError);
     do_check_eq(error.cause, "conditions-required");
     do_check_null(token);
 
     do_check_eq(error.urls.tos, tosURL);
 
@@ -120,17 +120,17 @@ add_test(function test_invalid_403_no_co
         errors: [{description: "irrelevant", location: "body", name: ""}],
         urls: {foo: "http://bar"}
       });
       response.bodyOutputStream.write(body, body.length);
     }
   });
 
   let client = new TokenServerClient();
-  let url = server.baseURI + "/1.0/foo/1.0";
+  let url = TEST_SERVER_URL + "1.0/foo/1.0";
 
   function onResponse(error, token) {
     do_check_true(error instanceof TokenServerClientServerError);
     do_check_eq(error.cause, "malformed-response");
     do_check_null(token);
 
     do_check_null(error.urls);
 
@@ -151,17 +151,17 @@ add_test(function test_invalid_403_bad_j
       let body = JSON.stringify({
         foo: "bar"
       });
       response.bodyOutputStream.write(body, body.length);
     }
   });
 
   let client = new TokenServerClient();
-  let url = server.baseURI + "/1.0/foo/1.0";
+  let url = TEST_SERVER_URL + "1.0/foo/1.0";
 
   function onResponse(error, token) {
     do_check_true(error instanceof TokenServerClientServerError);
     do_check_eq(error.cause, "malformed-response");
     do_check_null(token);
     do_check_null(error.urls);
 
     server.stop(run_next_test);
@@ -179,17 +179,17 @@ add_test(function test_403_no_urls() {
       response.setHeader("Content-Type", "application/json; charset=utf-8");
 
       let body = "{}";
       response.bodyOutputStream.write(body, body.length);
     }
   });
 
   let client = new TokenServerClient();
-  let url = server.baseURI + "/1.0/foo/1.0";
+  let url = TEST_SERVER_URL + "1.0/foo/1.0";
 
   client.getTokenFromBrowserIDAssertion(url, "assertion",
                                         function onResponse(error, result) {
     do_check_true(error instanceof TokenServerClientServerError);
     do_check_eq(error.cause, "malformed-response");
     do_check_null(result);
 
     server.stop(run_next_test);
@@ -214,17 +214,17 @@ add_test(function test_send_conditions_a
         api_endpoint: "http://example.com/",
         uid:          "uid",
       });
       response.bodyOutputStream.write(body, body.length);
     }
   });
 
   let client = new TokenServerClient();
-  let url = server.baseURI + "/1.0/foo/1.0";
+  let url = TEST_SERVER_URL + "1.0/foo/1.0";
 
   function onResponse(error, token) {
     do_check_null(error);
 
     // Other tests validate other things.
 
     server.stop(run_next_test);
   }
@@ -233,17 +233,17 @@ add_test(function test_send_conditions_a
 });
 
 add_test(function test_error_404_empty() {
   _("Ensure that 404 responses without proper response are handled properly.");
 
   let server = httpd_setup();
 
   let client = new TokenServerClient();
-  let url = server.baseURI + "/foo";
+  let url = TEST_SERVER_URL + "foo";
   client.getTokenFromBrowserIDAssertion(url, "assertion", function(error, r) {
     do_check_true(error instanceof TokenServerClientServerError);
     do_check_eq(error.cause, "malformed-response");
 
     do_check_neq(null, error.response);
     do_check_null(r);
 
     server.stop(run_next_test);
@@ -271,17 +271,17 @@ add_test(function test_error_404_proper_
     do_check_true(error instanceof TokenServerClientServerError);
     do_check_eq(error.cause, "unknown-service");
     do_check_null(token);
 
     server.stop(run_next_test);
   }
 
   let client = new TokenServerClient();
-  let url = server.baseURI + "/1.0/foo/1.0";
+  let url = TEST_SERVER_URL + "1.0/foo/1.0";
   client.getTokenFromBrowserIDAssertion(url, "assertion", onResponse);
 });
 
 add_test(function test_bad_json() {
   _("Ensure that malformed JSON is handled properly.");
 
   let server = httpd_setup({
     "/1.0/foo/1.0": function(request, response) {
@@ -289,17 +289,17 @@ add_test(function test_bad_json() {
       response.setHeader("Content-Type", "application/json");
 
       let body = '{"id": "id", baz}'
       response.bodyOutputStream.write(body, body.length);
     }
   });
 
   let client = new TokenServerClient();
-  let url = server.baseURI + "/1.0/foo/1.0";
+  let url = TEST_SERVER_URL + "1.0/foo/1.0";
   client.getTokenFromBrowserIDAssertion(url, "assertion", function(error, r) {
     do_check_neq(null, error);
     do_check_eq("TokenServerClientServerError", error.name);
     do_check_eq(error.cause, "malformed-response");
     do_check_neq(null, error.response);
     do_check_eq(null, r);
 
     server.stop(run_next_test);
@@ -315,17 +315,17 @@ add_test(function test_400_response() {
       response.setHeader("Content-Type", "application/json; charset=utf-8");
 
       let body = "{}"; // Actual content may not be used.
       response.bodyOutputStream.write(body, body.length);
     }
   });
 
   let client = new TokenServerClient();
-  let url = server.baseURI + "/1.0/foo/1.0";
+  let url = TEST_SERVER_URL + "1.0/foo/1.0";
   client.getTokenFromBrowserIDAssertion(url, "assertion", function(error, r) {
     do_check_neq(null, error);
     do_check_eq("TokenServerClientServerError", error.name);
     do_check_neq(null, error.response);
     do_check_eq(error.cause, "malformed-request");
 
     server.stop(run_next_test);
   });
@@ -339,17 +339,17 @@ add_test(function test_unhandled_media_t
       response.setStatusLine(request.httpVersion, 200, "OK");
       response.setHeader("Content-Type", "text/plain");
 
       let body = "hello, world";
       response.bodyOutputStream.write(body, body.length);
     }
   });
 
-  let url = server.baseURI + "/1.0/foo/1.0";
+  let url = TEST_SERVER_URL + "1.0/foo/1.0";
   let client = new TokenServerClient();
   client.getTokenFromBrowserIDAssertion(url, "assertion", function(error, r) {
     do_check_neq(null, error);
     do_check_eq("TokenServerClientServerError", error.name);
     do_check_neq(null, error.response);
     do_check_eq(null, r);
 
     server.stop(run_next_test);
@@ -369,17 +369,17 @@ add_test(function test_rich_media_types(
         key:          "key",
         api_endpoint: "foo",
         uid:          "uid",
       });
       response.bodyOutputStream.write(body, body.length);
     }
   });
 
-  let url = server.baseURI + "/foo";
+  let url = TEST_SERVER_URL + "foo";
   let client = new TokenServerClient();
   client.getTokenFromBrowserIDAssertion(url, "assertion", function(error, r) {
     do_check_eq(null, error);
 
     server.stop(run_next_test);
   });
 });
 
@@ -396,17 +396,17 @@ add_test(function test_exception_during_
         key:          "key",
         api_endpoint: "foo",
         uid:          "uid",
       });
       response.bodyOutputStream.write(body, body.length);
     }
   });
 
-  let url = server.baseURI + "/foo";
+  let url = TEST_SERVER_URL + "foo";
   let client = new TokenServerClient();
   let cb = Async.makeSpinningCallback();
   let callbackCount = 0;
 
   client.getTokenFromBrowserIDAssertion(url, "assertion", function(error, r) {
     do_check_eq(null, error);
 
     cb();
--- a/services/healthreport/tests/xpcshell/test_healthreporter.js
+++ b/services/healthreport/tests/xpcshell/test_healthreporter.js
@@ -17,17 +17,19 @@ Cu.import("resource://gre/modules/servic
 Cu.import("resource://gre/modules/Services.jsm");
 Cu.import("resource://gre/modules/Task.jsm");
 Cu.import("resource://testing-common/httpd.js");
 Cu.import("resource://testing-common/services-common/bagheeraserver.js");
 Cu.import("resource://testing-common/services/metrics/mocks.jsm");
 Cu.import("resource://testing-common/services/healthreport/utils.jsm");
 
 
-const DUMMY_URI = "http://localhost:62013/";
+const SERVER_HOSTNAME = "localhost";
+const SERVER_PORT = 8080;
+const SERVER_URI = "http://" + SERVER_HOSTNAME + ":" + SERVER_PORT;
 const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;
 
 const HealthReporterState = bsp.HealthReporterState;
 
 
 function defineNow(policy, now) {
   print("Adjusting fake system clock to " + now);
   Object.defineProperty(policy, "now", {
@@ -47,22 +49,23 @@ function getReporter(name, uri, inspecte
       HealthReportProvider);
 
     throw new Task.Result(reporter);
   });
 }
 
 function getReporterAndServer(name, namespace="test") {
   return Task.spawn(function get() {
-    let server = new BagheeraServer();
+    let reporter = yield getReporter(name, SERVER_URI);
+    reporter.serverNamespace = namespace;
+
+    let server = new BagheeraServer(SERVER_URI);
     server.createNamespace(namespace);
-    server.start();
 
-    let reporter = yield getReporter(name, server.serverURI);
-    reporter.serverNamespace = namespace;
+    server.start(SERVER_PORT);
 
     throw new Task.Result([reporter, server]);
   });
 }
 
 function shutdownServer(server) {
   let deferred = Promise.defer();
   server.stop(deferred.resolve.bind(deferred));
@@ -129,17 +132,17 @@ add_task(function test_shutdown_normal()
 
   // We can't send "quit-application" notification because the xpcshell runner
   // will shut down!
   reporter._initiateShutdown();
   reporter._waitForShutdown();
 });
 
 add_task(function test_shutdown_storage_in_progress() {
-  let reporter = yield getHealthReporter("shutdown_storage_in_progress", DUMMY_URI, true);
+  let reporter = yield getHealthReporter("shutdown_storage_in_progress", SERVER_URI, true);
 
   reporter.onStorageCreated = function () {
     print("Faking shutdown during storage initialization.");
     reporter._initiateShutdown();
   };
 
   reporter.init();
 
@@ -147,17 +150,17 @@ add_task(function test_shutdown_storage_
   do_check_eq(reporter.providerManagerShutdownCount, 0);
   do_check_eq(reporter.storageCloseCount, 1);
 });
 
 // Ensure that a shutdown triggered while provider manager is initializing
 // results in shutdown and storage closure.
 add_task(function test_shutdown_provider_manager_in_progress() {
   let reporter = yield getHealthReporter("shutdown_provider_manager_in_progress",
-                                         DUMMY_URI, true);
+                                         SERVER_URI, true);
 
   reporter.onProviderManagerInitialized = function () {
     print("Faking shutdown during provider manager initialization.");
     reporter._initiateShutdown();
   };
 
   reporter.init();
 
@@ -165,17 +168,17 @@ add_task(function test_shutdown_provider
   reporter._waitForShutdown();
   do_check_eq(reporter.providerManagerShutdownCount, 1);
   do_check_eq(reporter.storageCloseCount, 1);
 });
 
 // Simulates an error during provider manager initialization and verifies we shut down.
 add_task(function test_shutdown_when_provider_manager_errors() {
   let reporter = yield getHealthReporter("shutdown_when_provider_manager_errors",
-                                       DUMMY_URI, true);
+                                       SERVER_URI, true);
 
   reporter.onInitializeProviderManagerFinished = function () {
     print("Throwing fake error.");
     throw new Error("Fake error during provider manager initialization.");
   };
 
   reporter.init();
 
@@ -548,17 +551,17 @@ add_task(function test_idle_daily() {
   } finally {
     reporter._shutdown();
   }
 });
 
 add_task(function test_data_submission_transport_failure() {
   let reporter = yield getReporter("data_submission_transport_failure");
   try {
-    reporter.serverURI = DUMMY_URI;
+    reporter.serverURI = "http://localhost:8080/";
     reporter.serverNamespace = "test00";
 
     let deferred = Promise.defer();
     let request = new DataSubmissionRequest(deferred, new Date(Date.now + 30000));
     reporter.requestDataUpload(request);
 
     yield deferred.promise;
     do_check_eq(request.state, request.SUBMISSION_FAILURE_SOFT);
@@ -835,20 +838,20 @@ add_task(function test_failure_if_not_in
     error = false;
   }
 
   // getJSONPayload always works (to facilitate error upload).
   yield reporter.getJSONPayload();
 });
 
 add_task(function test_upload_on_init_failure() {
-  let server = new BagheeraServer();
-  server.start();
-  let reporter = yield getHealthReporter("upload_on_init_failure", server.serverURI, true);
+  let reporter = yield getHealthReporter("upload_on_init_failure", SERVER_URI, true);
+  let server = new BagheeraServer(SERVER_URI);
   server.createNamespace(reporter.serverNamespace);
+  server.start(SERVER_PORT);
 
   reporter.onInitializeProviderManagerFinished = function () {
     throw new Error("Fake error during provider manager initialization.");
   };
 
   let deferred = Promise.defer();
 
   let oldOnResult = reporter._onBagheeraResult;
--- a/services/sync/modules-testing/utils.js
+++ b/services/sync/modules-testing/utils.js
@@ -1,29 +1,34 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 "use strict";
 
 this.EXPORTED_SYMBOLS = [
+  "TEST_CLUSTER_URL",
+  "TEST_SERVER_URL",
   "btoa", // It comes from a module import.
   "encryptPayload",
   "setBasicCredentials",
   "SyncTestingInfrastructure",
   "waitForZeroTimer",
 ];
 
 const {utils: Cu} = Components;
 
 Cu.import("resource://services-common/utils.js");
 Cu.import("resource://services-crypto/utils.js");
 Cu.import("resource://testing-common/services-common/logging.js");
 Cu.import("resource://testing-common/services/sync/fakeservices.js");
 
+this.TEST_SERVER_URL = "http://localhost:8080/";
+this.TEST_CLUSTER_URL = TEST_SERVER_URL;
+
 /**
  * First wait >100ms (nsITimers can take up to that much time to fire, so
  * we can account for the timer in delayedAutoconnect) and then two event
  * loop ticks (to account for the Utils.nextTick() in autoConnect).
  */
 this.waitForZeroTimer = function waitForZeroTimer(callback) {
   let ticks = 2;
   function wait() {
@@ -43,31 +48,28 @@ this.setBasicCredentials =
   Cu.import("resource://services-sync/service.js", ns);
 
   let auth = ns.Service.identity;
   auth.username = username;
   auth.basicPassword = password;
   auth.syncKey = syncKey;
 }
 
-this.SyncTestingInfrastructure = function (server, username, password, syncKey) {
+this.SyncTestingInfrastructure =
+ function SyncTestingInfrastructure(username, password, syncKey) {
   let ns = {};
   Cu.import("resource://services-sync/service.js", ns);
 
   let auth = ns.Service.identity;
   auth.account = username || "foo";
   auth.basicPassword = password || "password";
   auth.syncKey = syncKey || "abcdeabcdeabcdeabcdeabcdea";
 
-  let i = server.identity;
-  let uri = i.primaryScheme + "://" + i.primaryHost + ":" +
-            i.primaryPort + "/";
-
-  ns.Service.serverURL = uri;
-  ns.Service.clusterURL = uri;
+  ns.Service.serverURL = TEST_SERVER_URL;
+  ns.Service.clusterURL = TEST_CLUSTER_URL;
 
   this.logStats = initTestLogging();
   this.fakeFilesystem = new FakeFilesystemService({});
   this.fakeGUIDService = new FakeGUIDService();
   this.fakeCryptoService = new FakeCryptoService();
 }
 
 /**
--- a/services/sync/tests/unit/head_http_server.js
+++ b/services/sync/tests/unit/head_http_server.js
@@ -530,53 +530,52 @@ function SyncServer(callback) {
   this._log     = Log4Moz.repository.getLogger(SYNC_HTTP_LOGGER);
 
   // Install our own default handler. This allows us to mess around with the
   // whole URL space.
   let handler = this.server._handler;
   handler._handleDefault = this.handleDefault.bind(this, handler);
 }
 SyncServer.prototype = {
+  port:   8080,
   server: null,    // HttpServer.
   users:  null,    // Map of username => {collections, password}.
 
   /**
    * Start the SyncServer's underlying HTTP server.
    *
    * @param port
    *        The numeric port on which to start. A falsy value implies the
-   *        default, a randomly chosen port.
+   *        default (8080).
    * @param cb
    *        A callback function (of no arguments) which is invoked after
    *        startup.
    */
   start: function start(port, cb) {
     if (this.started) {
       this._log.warn("Warning: server already started on " + this.port);
       return;
     }
+    if (port) {
+      this.port = port;
+    }
     try {
-      this.server.start(port);
-      let i = this.server.identity;
-      this.port = i.primaryPort;
-      this.baseURI = i.primaryScheme + "://" + i.primaryHost + ":" +
-                     i.primaryPort + "/";
+      this.server.start(this.port);
       this.started = true;
       if (cb) {
         cb();
       }
     } catch (ex) {
       _("==========================================");
-      _("Got exception starting Sync HTTP server.");
+      _("Got exception starting Sync HTTP server on port " + this.port);
       _("Error: " + Utils.exceptionStr(ex));
-      _("Is there a process already listening on port " + port + "?");
+      _("Is there a process already listening on port " + this.port + "?");
       _("==========================================");
       do_throw(ex);
     }
-
   },
 
   /**
    * Stop the SyncServer's HTTP server.
    *
    * @param cb
    *        A callback function. Invoked after the server has been stopped.
    *
--- a/services/sync/tests/unit/test_addons_engine.js
+++ b/services/sync/tests/unit/test_addons_engine.js
@@ -153,31 +153,31 @@ add_test(function test_disabled_install_
 
   Svc.Prefs.set("addons.ignoreRepositoryChecking", true);
 
   const USER       = "foo";
   const PASSWORD   = "password";
   const PASSPHRASE = "abcdeabcdeabcdeabcdeabcdea";
   const ADDON_ID   = "addon1@tests.mozilla.org";
 
-  let server = new SyncServer();
-  server.start();
-  new SyncTestingInfrastructure(server.server, USER, PASSWORD, PASSPHRASE);
+  new SyncTestingInfrastructure(USER, PASSWORD, PASSPHRASE);
 
   generateNewKeys(Service.collectionKeys);
 
   let contents = {
     meta: {global: {engines: {addons: {version: engine.version,
                                       syncID:  engine.syncID}}}},
     crypto: {},
     addons: {}
   };
 
+  let server = new SyncServer();
   server.registerUser(USER, "password");
   server.createContents(USER, contents);
+  server.start();
 
   let amoServer = new HttpServer();
   amoServer.registerFile("/search/guid:addon1%40tests.mozilla.org",
                          do_get_file("addon1-search.xml"));
 
   let installXPI = ExtensionsTestPath("/addons/test_install1.xpi");
   amoServer.registerFile("/addon1.xpi", do_get_file(installXPI));
   amoServer.start(8888);
@@ -242,16 +242,18 @@ function run_test() {
   Log4Moz.repository.getLogger("Sync.Engine.Addons").level =
     Log4Moz.Level.Trace;
   Log4Moz.repository.getLogger("Sync.Store.Addons").level = Log4Moz.Level.Trace;
   Log4Moz.repository.getLogger("Sync.Tracker.Addons").level =
     Log4Moz.Level.Trace;
   Log4Moz.repository.getLogger("Sync.AddonsRepository").level =
     Log4Moz.Level.Trace;
 
+  new SyncTestingInfrastructure();
+
   reconciler.startListening();
 
   // Don't flush to disk in the middle of an event listener!
   // This causes test hangs on WinXP.
   reconciler._shouldPersist = false;
 
   advance_test();
 }
--- a/services/sync/tests/unit/test_bookmark_engine.js
+++ b/services/sync/tests/unit/test_bookmark_engine.js
@@ -8,21 +8,20 @@ Cu.import("resource://services-common/lo
 Cu.import("resource://services-sync/engines.js");
 Cu.import("resource://services-sync/engines/bookmarks.js");
 Cu.import("resource://services-sync/service.js");
 Cu.import("resource://services-sync/util.js");
 Cu.import("resource://testing-common/services/sync/utils.js");
 Cu.import("resource://gre/modules/Promise.jsm");
 
 Service.engineManager.register(BookmarksEngine);
+var syncTesting = new SyncTestingInfrastructure();
 
 add_test(function bad_record_allIDs() {
-  let server = new SyncServer();
-  server.start();
-  let syncTesting = new SyncTestingInfrastructure(server.server);
+  let syncTesting = new SyncTestingInfrastructure();
 
   _("Ensure that bad Places queries don't cause an error in getAllIDs.");
   let engine = new BookmarksEngine(Service);
   let store = engine._store;
   let badRecordID = PlacesUtils.bookmarks.insertBookmark(
       PlacesUtils.bookmarks.toolbarFolder,
       Utils.makeURI("place:folder=1138"),
       PlacesUtils.bookmarks.DEFAULT_INDEX,
@@ -39,23 +38,21 @@ add_test(function bad_record_allIDs() {
   let all = store.getAllIDs();
 
   _("All IDs: " + JSON.stringify(all));
   do_check_true("menu" in all);
   do_check_true("toolbar" in all);
 
   _("Clean up.");
   PlacesUtils.bookmarks.removeItem(badRecordID);
-  server.stop(run_next_test);
+  run_next_test();
 });
 
 add_test(function test_ID_caching() {
-  let server = new SyncServer();
-  server.start();
-  let syncTesting = new SyncTestingInfrastructure(server.server);
+  let syncTesting = new SyncTestingInfrastructure();
 
   _("Ensure that Places IDs are not cached.");
   let engine = new BookmarksEngine(Service);
   let store = engine._store;
   _("All IDs: " + JSON.stringify(store.getAllIDs()));
 
   let mobileID = store.idForGUID("mobile");
   _("Change the GUID for that item, and drop the mobile anno.");
@@ -81,34 +78,34 @@ add_test(function test_ID_caching() {
   _("New mobile ID: " + newMobileID);
   do_check_true(!!newMobileID);
   do_check_neq(newMobileID, mobileID);
 
   // And it's repeatable, even with creation enabled.
   do_check_eq(newMobileID, store.idForGUID("mobile", false));
 
   do_check_eq(store.GUIDForId(mobileID), "abcdefghijkl");
-  server.stop(run_next_test);
+  run_next_test();
 });
 
 function serverForFoo(engine) {
   return serverForUsers({"foo": "password"}, {
     meta: {global: {engines: {bookmarks: {version: engine.version,
                                           syncID: engine.syncID}}}},
     bookmarks: {}
   });
 }
 
 add_test(function test_processIncoming_error_orderChildren() {
   _("Ensure that _orderChildren() is called even when _processIncoming() throws an error.");
+  new SyncTestingInfrastructure();
 
   let engine = new BookmarksEngine(Service);
   let store  = engine._store;
   let server = serverForFoo(engine);
-  new SyncTestingInfrastructure(server.server);
 
   let collection = server.user("foo").collection("bookmarks");
 
   try {
 
     let folder1_id = PlacesUtils.bookmarks.createFolder(
       PlacesUtils.bookmarks.toolbarFolder, "Folder 1", 0);
     let folder1_guid = store.GUIDForId(folder1_id);
@@ -164,20 +161,21 @@ add_test(function test_processIncoming_e
     Svc.Prefs.resetBranch("");
     Service.recordManager.clearCache();
     server.stop(run_next_test);
   }
 });
 
 add_task(function test_restorePromptsReupload() {
   _("Ensure that restoring from a backup will reupload all records.");
+  new SyncTestingInfrastructure();
+
   let engine = new BookmarksEngine(Service);
   let store  = engine._store;
   let server = serverForFoo(engine);
-  new SyncTestingInfrastructure(server.server);
 
   let collection = server.user("foo").collection("bookmarks");
 
   Svc.Obs.notify("weave:engine:start-tracking");   // We skip usual startup...
 
   try {
 
     let folder1_id = PlacesUtils.bookmarks.createFolder(
@@ -330,20 +328,21 @@ add_test(function test_mismatched_types(
     "description":null,
     "children":
       ["HCRq40Rnxhrd", "YeyWCV1RVsYw", "GCceVZMhvMbP", "sYi2hevdArlF",
        "vjbZlPlSyGY8", "UtjUhVyrpeG6", "rVq8WMG2wfZI", "Lx0tcy43ZKhZ",
        "oT74WwV8_j4P", "IztsItWVSo3-"],
     "parentid": "toolbar"
   };
 
+  new SyncTestingInfrastructure();
+
   let engine = new BookmarksEngine(Service);
   let store  = engine._store;
   let server = serverForFoo(engine);
-  new SyncTestingInfrastructure(server.server);
 
   _("GUID: " + store.GUIDForId(6, true));
 
   try {
     let bms = PlacesUtils.bookmarks;
     let oldR = new FakeRecord(BookmarkFolder, oldRecord);
     let newR = new FakeRecord(Livemark, newRecord);
     oldR._parent = PlacesUtils.bookmarks.toolbarFolder;
@@ -372,23 +371,24 @@ add_test(function test_mismatched_types(
     Service.recordManager.clearCache();
     server.stop(run_next_test);
   }
 });
 
 add_test(function test_bookmark_guidMap_fail() {
   _("Ensure that failures building the GUID map cause early death.");
 
+  new SyncTestingInfrastructure();
+
   let engine = new BookmarksEngine(Service);
   let store = engine._store;
 
   let store  = engine._store;
   let server = serverForFoo(engine);
   let coll   = server.user("foo").collection("bookmarks");
-  new SyncTestingInfrastructure(server.server);
 
   // Add one item to the server.
   let itemID = PlacesUtils.bookmarks.createFolder(
     PlacesUtils.bookmarks.toolbarFolder, "Folder 1", 0);
   let itemGUID    = store.GUIDForId(itemID);
   let itemPayload = store.createRecord(itemGUID).cleartext;
   coll.insert(itemGUID, encryptPayload(itemPayload));
 
@@ -470,19 +470,20 @@ add_test(function test_bookmark_tag_but_
   store.update(record);
 
   run_next_test();
 });
 
 add_test(function test_misreconciled_root() {
   _("Ensure that we don't reconcile an arbitrary record with a root.");
 
+  new SyncTestingInfrastructure();
+
   let engine = new BookmarksEngine(Service);
   let store = engine._store;
-  let server = serverForFoo(engine);
 
   // Log real hard for this test.
   store._log.trace = store._log.debug;
   engine._log.trace = engine._log.debug;
 
   engine._syncStartup();
 
   // Let's find out where the toolbar is right now.
@@ -528,16 +529,16 @@ add_test(function test_misreconciled_roo
   // the real GUID, instead using a generated one. Sync does the translation.
   let toolbarAfter = store.createRecord("toolbar", "bookmarks");
   let parentGUIDAfter = toolbarAfter.parentid;
   let parentIDAfter = store.idForGUID(parentGUIDAfter);
   do_check_eq(store.GUIDForId(toolbarIDBefore), "toolbar");
   do_check_eq(parentGUIDBefore, parentGUIDAfter);
   do_check_eq(parentIDBefore, parentIDAfter);
 
-  server.stop(run_next_test);
+  run_next_test();
 });
 
 function run_test() {
   initTestLogging("Trace");
   generateNewKeys(Service.collectionKeys);
   run_next_test();
 }
--- a/services/sync/tests/unit/test_bookmark_smart_bookmarks.js
+++ b/services/sync/tests/unit/test_bookmark_smart_bookmarks.js
@@ -17,16 +17,18 @@ var IOService = Cc["@mozilla.org/network
 
 Service.engineManager.register(BookmarksEngine);
 let engine = Service.engineManager.get("bookmarks");
 let store = engine._store;
 
 // Clean up after other tests. Only necessary in XULRunner.
 store.wipe();
 
+var syncTesting = new SyncTestingInfrastructure();
+
 function newSmartBookmark(parent, uri, position, title, queryID) {
   let id = PlacesUtils.bookmarks.insertBookmark(parent, uri, position, title);
   PlacesUtils.annotations.setItemAnnotation(id, SMART_BOOKMARKS_ANNO,
                                             queryID, 0,
                                             PlacesUtils.annotations.EXPIRE_NEVER);
   return id;
 }
 
@@ -53,18 +55,17 @@ function serverForFoo(engine) {
                                           syncID: engine.syncID}}}},
     bookmarks: {}
   });
 }
 
 // Verify that Places smart bookmarks have their annotation uploaded and
 // handled locally.
 add_test(function test_annotation_uploaded() {
-  let server = serverForFoo(engine);
-  new SyncTestingInfrastructure(server.server);
+  new SyncTestingInfrastructure();
 
   let startCount = smartBookmarkCount();
 
   _("Start count is " + startCount);
 
   if (startCount > 0) {
     // This can happen in XULRunner.
     clearBookmarks();
@@ -102,16 +103,17 @@ add_test(function test_annotation_upload
 
   _("Make sure the new record carries with it the annotation.");
   do_check_eq("MostVisited", record.queryId);
 
   _("Our count has increased since we started.");
   do_check_eq(smartBookmarkCount(), startCount + 1);
 
   _("Sync record to the server.");
+  let server = serverForFoo(engine);
   let collection = server.user("foo").collection("bookmarks");
 
   try {
     engine.sync();
     let wbos = collection.keys(function (id) {
                  return ["menu", "toolbar", "mobile"].indexOf(id) == -1;
                });
     do_check_eq(wbos.length, 1);
@@ -168,31 +170,31 @@ add_test(function test_annotation_upload
     store.wipe();
     Svc.Prefs.resetBranch("");
     Service.recordManager.clearCache();
     server.stop(run_next_test);
   }
 });
 
 add_test(function test_smart_bookmarks_duped() {
-  let server = serverForFoo(engine);
-  new SyncTestingInfrastructure(server.server);
+  new SyncTestingInfrastructure();
 
   let parent = PlacesUtils.toolbarFolderId;
   let uri =
     Utils.makeURI("place:sort=" +
                   Ci.nsINavHistoryQueryOptions.SORT_BY_VISITCOUNT_DESCENDING +
                   "&maxResults=10");
   let title = "Most Visited";
   let mostVisitedID = newSmartBookmark(parent, uri, -1, title, "MostVisited");
   let mostVisitedGUID = store.GUIDForId(mostVisitedID);
 
   let record = store.createRecord(mostVisitedGUID);
 
   _("Prepare sync.");
+  let server = serverForFoo(engine);
   let collection = server.user("foo").collection("bookmarks");
 
   try {
     engine._syncStartup();
 
     _("Verify that mapDupe uses the anno, discovering a dupe regardless of URI.");
     do_check_eq(mostVisitedGUID, engine._mapDupe(record));
 
--- a/services/sync/tests/unit/test_clients_engine.js
+++ b/services/sync/tests/unit/test_clients_engine.js
@@ -53,17 +53,18 @@ add_test(function test_bad_hmac() {
     generateNewKeys(Service.collectionKeys);
     let serverKeys = Service.collectionKeys.asWBO("crypto", "keys");
     serverKeys.encrypt(Service.identity.syncKeyBundle);
     do_check_true(serverKeys.upload(Service.resource(Service.cryptoKeysURL)).success);
   }
 
   try {
     let passphrase     = "abcdeabcdeabcdeabcdeabcdea";
-    Service.serverURL  = server.baseURI;
+    Service.serverURL  = TEST_SERVER_URL;
+    Service.clusterURL = TEST_CLUSTER_URL;
     Service.login("foo", "ilovejane", passphrase);
 
     generateNewKeys(Service.collectionKeys);
 
     _("First sync, client record is uploaded");
     do_check_eq(engine.lastRecordUpload, 0);
     check_clients_count(0);
     engine._sync();
@@ -163,28 +164,28 @@ add_test(function test_properties() {
     Svc.Prefs.resetBranch("");
     run_next_test();
   }
 });
 
 add_test(function test_sync() {
   _("Ensure that Clients engine uploads a new client record once a week.");
 
+  new SyncTestingInfrastructure();
+  generateNewKeys(Service.collectionKeys);
+
   let contents = {
     meta: {global: {engines: {clients: {version: engine.version,
                                         syncID: engine.syncID}}}},
     clients: {},
     crypto: {}
   };
   let server = serverForUsers({"foo": "password"}, contents);
   let user   = server.user("foo");
 
-  new SyncTestingInfrastructure(server.server);
-  generateNewKeys(Service.collectionKeys);
-
   function clientWBO() {
     return user.collection("clients").wbo(engine.localID);
   }
 
   try {
 
     _("First sync. Client record is uploaded.");
     do_check_eq(clientWBO(), undefined);
@@ -401,28 +402,28 @@ add_test(function test_process_incoming_
 
   // logout command causes processIncomingCommands to return explicit false.
   do_check_false(engine.processIncomingCommands());
 });
 
 add_test(function test_command_sync() {
   _("Ensure that commands are synced across clients.");
 
+  new SyncTestingInfrastructure();
+
   engine._store.wipe();
   generateNewKeys(Service.collectionKeys);
 
   let contents = {
     meta: {global: {engines: {clients: {version: engine.version,
                                         syncID: engine.syncID}}}},
     clients: {},
     crypto: {}
   };
   let server   = serverForUsers({"foo": "password"}, contents);
-  new SyncTestingInfrastructure(server.server);
-
   let user     = server.user("foo");
   let remoteId = Utils.makeGUID();
 
   function clientWBO(id) {
     return user.collection("clients").wbo(id);
   }
 
   _("Create remote client record");
--- a/services/sync/tests/unit/test_collections_recovery.js
+++ b/services/sync/tests/unit/test_collections_recovery.js
@@ -20,30 +20,31 @@ add_test(function test_missing_crypto_co
         response.bodyOutputStream.write(body, body.length);
       } else {
         handler(request, response);
       }
     };
   }
 
   setBasicCredentials("johndoe", "ilovejane", "a-aaaaa-aaaaa-aaaaa-aaaaa-aaaaa");
+  Service.serverURL = TEST_SERVER_URL;
+  Service.clusterURL = TEST_CLUSTER_URL;
 
   let handlers = {
     "/1.1/johndoe/info/collections": maybe_empty(johnHelper.handler),
     "/1.1/johndoe/storage/crypto/keys": johnU("crypto", new ServerWBO("keys").handler()),
     "/1.1/johndoe/storage/meta/global": johnU("meta",   new ServerWBO("global").handler())
   };
   let collections = ["clients", "bookmarks", "forms", "history",
                      "passwords", "prefs", "tabs"];
   for each (let coll in collections) {
     handlers["/1.1/johndoe/storage/" + coll] =
       johnU(coll, new ServerCollection({}, true).handler());
   }
   let server = httpd_setup(handlers);
-  Service.serverURL = server.baseURI;
 
   try {
     let fresh = 0;
     let orig  = Service._freshStart;
     Service._freshStart = function() {
       _("Called _freshStart.");
       orig.call(Service);
       fresh++;